blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
e53ef3a51a14ccc8104cc867ed554b8adb9aed95
aad164e4efe1d55cc189c35956bfd435b14a0f52
/eve-8.21.494548/carbon/client/script/graphics/resourceConstructors/caustics.py
0b31954b427fc0133d1ad9e77edc5c4412a39c19
[]
no_license
Pluckyduck/eve
61cc41fe8fd4dca4fbdcc4761a37bcfeb27ed84f
9a277707ab1f162c6bd9618faf722c0be3ea93ad
refs/heads/master
2020-12-28T23:35:29.992875
2013-05-06T14:24:33
2013-05-06T14:24:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,938
py
#Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/carbon/client/script/graphics/resourceConstructors/caustics.py import blue import trinity import bluepy import re import decometaclass class CausticsRenderJob(object): __cid__ = 'trinity.TriRenderJob' __metaclass__ = decometaclass.BlueWrappedMetaclass def Initialize(self, size, speed, amplitude, tiling, texturePath): def TextureDestroyed(): self.Destroy() texture = trinity.Tr2RenderTarget(size, size, 1, trinity.PIXEL_FORMAT.B8G8R8A8_UNORM) self.name = 'Caustics' self.size = size self.texture = blue.BluePythonWeakRef(texture) self.texture.callback = TextureDestroyed self.steps.append(trinity.TriStepPushRenderTarget(texture)) self.steps.append(trinity.TriStepClear((0, 0, 0, 0))) self.steps.append(trinity.TriStepSetStdRndStates(trinity.RM_FULLSCREEN)) material = trinity.Tr2ShaderMaterial() material.highLevelShaderName = 'Caustics' param = trinity.TriTexture2DParameter() param.name = 'Texture' param.resourcePath = texturePath material.parameters['Texture'] = param param = trinity.Tr2FloatParameter() param.name = 'Speed' param.value = speed material.parameters['Speed'] = param param = trinity.Tr2FloatParameter() param.name = 'Amplitude' param.value = amplitude material.parameters['Amplitude'] = param param = trinity.Tr2FloatParameter() param.name = 'Tiling' param.value = tiling material.parameters['Tiling'] = param material.BindLowLevelShader([]) self.steps.append(trinity.TriStepRenderFullScreenShader(material)) self.steps.append(trinity.TriStepPopRenderTarget()) trinity.renderJobs.recurring.append(self) return trinity.TriTextureRes(texture) def Destroy(self): trinity.renderJobs.recurring.remove(self) self.texture = None def DoPrepareResources(self): for step in self.steps: if type(step) is trinity.TriStepPushRenderTarget: if self.texture is not None and self.texture.object is not None: self.texture.object.SetFromRenderTarget(step.renderTarget) def Caustics(paramString): params = {'size': 256, 'speed': 1, 'amplitude': 1, 'tiling': 1, 'texture': 'res:/Texture/Global/caustic.dds'} expr = re.compile('&?(\\w+)=([^&]*)') pos = 0 while True: match = expr.match(paramString, pos) if match is None: break params[match.group(1)] = match.group(2) pos = match.end() rj = CausticsRenderJob() return rj.Initialize(int(params['size']), float(params['speed']), float(params['amplitude']), float(params['tiling']), params['texture']) blue.resMan.RegisterResourceConstructor('caustics', Caustics)
a6b2d8ca57fdd5b6c2a3e5d15ae0a7de5aaa87d7
e67c27642a4b83b3560dc4bba7de7752278caa07
/example-seaexplorer/process_deploymentRealTime.py
390d934c8e720fa964bf4ca7e1f927624cb6a240
[]
no_license
c-burmaster/pyglider
3749661bfa367642bdd8cb453e8f14428785de46
76131e8419c30852150173a9994a88595cef52aa
refs/heads/master
2020-07-25T14:42:26.752105
2020-04-06T20:44:39
2020-04-06T20:44:39
208,326,724
0
0
null
2019-09-13T18:48:07
2019-09-13T18:48:07
null
UTF-8
Python
false
false
1,545
py
import logging import os import pyglider.seaexplorer as seaexplorer import pyglider.ncprocess as ncprocess import pyglider.plotting as pgplot logging.basicConfig(level='INFO') sourcedir = '~alseamar/Documents/SEA035/000012/000012/C-Csv/*' rawdir = './realtime_raw/' rawncdir = './realtime_rawnc/' deploymentyaml = './deploymentRealtime.yml' l1tsdir = './L1-timeseries/' profiledir = './L1-profiles/' griddir = './L2-gridfiles/' plottingyaml = './plottingconfig.yml' ## get the data and clean up derived #os.system('source synctodfo.sh') if 0: os.system('rsync -av ' + sourcedir + ' ' + rawdir) # clean last processing... os.system('rm ' + rawncdir + '* ' + l1tsdir + '* ' + profiledir + '* ' + griddir + '* ') if 1: # turn *.EBD and *.DBD into *.ebd.nc and *.dbd.nc netcdf files. seaexplorer.raw_to_rawnc(rawdir, rawncdir, deploymentyaml) # merge individual neetcdf files into single netcdf files *.ebd.nc and *.dbd.nc seaexplorer.merge_rawnc(rawncdir, rawncdir, deploymentyaml, kind='sub') # Make level-1 timeseries netcdf file from th raw files... outname = seaexplorer.raw_to_L1timeseries(rawncdir, l1tsdir, deploymentyaml, kind='sub') ncprocess.extract_L1timeseries_profiles(outname, profiledir, deploymentyaml) outname2 = ncprocess.make_L2_gridfiles(outname, griddir, deploymentyaml) if 1: # make profile netcdf files for ioos gdac... # make grid of dataset.... pgplot.timeseries_plots(outname, plottingyaml) pgplot.grid_plots(outname2, plottingyaml)
5c05c9569d485e314860849c7d2e6b419d5ec0fe
afa71330ff1b6b4d114993b39fea5f8e4b8fc210
/ensauction/abis.py
4334abe77636bbc1de06ea1eb341751a5cd0d3db
[ "MIT" ]
permissive
carver/ensauction.py
e556827e0c613d01ea94743e1527f279b1e92464
4f30d64ea7c470a53d133e7c8e43d8228b62732c
refs/heads/master
2018-12-20T18:28:07.237482
2018-09-17T22:15:14
2018-09-17T22:15:14
110,906,856
4
0
MIT
2018-09-17T20:49:09
2017-11-16T01:25:53
Python
UTF-8
Python
false
false
12,327
py
AUCTION_REGISTRAR = [ { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "releaseDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "getAllowedTime", "outputs": [ { "name": "timestamp", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "unhashedName", "type": "string" } ], "name": "invalidateName", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "hash", "type": "bytes32" }, { "name": "owner", "type": "address" }, { "name": "value", "type": "uint256" }, { "name": "salt", "type": "bytes32" } ], "name": "shaBid", "outputs": [ { "name": "sealedBid", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "bidder", "type": "address" }, { "name": "seal", "type": "bytes32" } ], "name": "cancelBid", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "entries", "outputs": [ { "name": "", "type": "uint8" }, { "name": "", "type": "address" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "ens", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "_value", "type": "uint256" }, { "name": "_salt", "type": "bytes32" } ], "name": "unsealBid", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "transferRegistrars", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "", "type": "address" }, { "name": "", "type": "bytes32" } ], "name": "sealedBids", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "state", "outputs": [ { "name": "", "type": "uint8" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "newOwner", "type": "address" } ], "name": "transfer", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "_hash", "type": "bytes32" }, { "name": "_timestamp", "type": "uint256" } ], "name": "isAllowed", "outputs": [ { "name": "allowed", "type": "bool" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "finalizeAuction", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "registryStarted", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "launchLength", "outputs": [ { "name": "", "type": "uint32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "sealedBid", "type": "bytes32" } ], "name": "newBid", "outputs": [], "payable": True, "type": "function" }, { "constant": False, "inputs": [ { "name": "labels", "type": "bytes32[]" } ], "name": "eraseNode", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hashes", "type": "bytes32[]" } ], "name": "startAuctions", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "hash", "type": "bytes32" }, { "name": "deed", "type": "address" }, { "name": "registrationDate", "type": "uint256" } ], "name": "acceptRegistrarTransfer", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "_hash", "type": "bytes32" } ], "name": "startAuction", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "rootNode", "outputs": [ { "name": "", "type": "bytes32" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "hashes", "type": "bytes32[]" }, { "name": "sealedBid", "type": "bytes32" } ], "name": "startAuctionsAndBid", "outputs": [], "payable": True, "type": "function" }, { "inputs": [ { "name": "_ens", "type": "address" }, { "name": "_rootNode", "type": "bytes32" }, { "name": "_startDate", "type": "uint256" } ], "payable": False, "type": "constructor" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "AuctionStarted", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "bidder", "type": "address" }, { "indexed": False, "name": "deposit", "type": "uint256" } ], "name": "NewBid", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "owner", "type": "address" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "status", "type": "uint8" } ], "name": "BidRevealed", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "owner", "type": "address" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "HashRegistered", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": False, "name": "value", "type": "uint256" } ], "name": "HashReleased", "type": "event" }, { "anonymous": False, "inputs": [ { "indexed": True, "name": "hash", "type": "bytes32" }, { "indexed": True, "name": "name", "type": "string" }, { "indexed": False, "name": "value", "type": "uint256" }, { "indexed": False, "name": "registrationDate", "type": "uint256" } ], "name": "HashInvalidated", "type": "event" } ] DEED = [ { "constant": True, "inputs": [], "name": "creationDate", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [], "name": "destroyDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newOwner", "type": "address" } ], "name": "setOwner", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "registrar", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "refundRatio", "type": "uint256" } ], "name": "closeDeed", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newRegistrar", "type": "address" } ], "name": "setRegistrar", "outputs": [], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "newValue", "type": "uint256" } ], "name": "setBalance", "outputs": [], "payable": True, "type": "function" }, { "inputs": [], "type": "constructor" }, { "payable": True, "type": "fallback" }, { "anonymous": False, "inputs": [ { "indexed": False, "name": "newOwner", "type": "address" } ], "name": "OwnerChanged", "type": "event" }, { "anonymous": False, "inputs": [], "name": "DeedClosed", "type": "event" } ] FIFS_REGISTRAR = [ { "constant": True, "inputs": [], "name": "ens", "outputs": [ { "name": "", "type": "address" } ], "payable": False, "type": "function" }, { "constant": True, "inputs": [ { "name": "", "type": "bytes32" } ], "name": "expiryTimes", "outputs": [ { "name": "", "type": "uint256" } ], "payable": False, "type": "function" }, { "constant": False, "inputs": [ { "name": "subnode", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "register", "outputs": [], "payable": False, "type": "function" }, { "constant": True, "inputs": [], "name": "rootNode", "outputs": [ { "name": "", "type": "bytes32" } ], "payable": False, "type": "function" }, { "inputs": [ { "name": "ensAddr", "type": "address" }, { "name": "node", "type": "bytes32" } ], "type": "constructor" } ]
217d85c42a5b1d3880ab3cbf52e36a73d6d5e6c9
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/response/AlipayFinancialnetAuthEcsignErrorQueryResponse.py
1e5c32e52d696f398ce156d029df7850935ce29a
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
1,115
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.ErrorLog import ErrorLog class AlipayFinancialnetAuthEcsignErrorQueryResponse(AlipayResponse): def __init__(self): super(AlipayFinancialnetAuthEcsignErrorQueryResponse, self).__init__() self._error_log_list = None @property def error_log_list(self): return self._error_log_list @error_log_list.setter def error_log_list(self, value): if isinstance(value, list): self._error_log_list = list() for i in value: if isinstance(i, ErrorLog): self._error_log_list.append(i) else: self._error_log_list.append(ErrorLog.from_alipay_dict(i)) def parse_response_content(self, response_content): response = super(AlipayFinancialnetAuthEcsignErrorQueryResponse, self).parse_response_content(response_content) if 'error_log_list' in response: self.error_log_list = response['error_log_list']
ac9a73f49e91af26961dc6a2016f1f3a3e02557b
68bad4b3d92872bb5b77b4ee503e588d20511a27
/python/scripts_inhibition/old_script/effect_beta_conn_index3.py
71c90589942dfe29b6b59fb06f211f42ddc7e0b9
[]
no_license
mickelindahl/bgmodel
647be626a7311a8f08f3dfc897c6dd4466fc0a92
78e6f2b73bbcbecd0dba25caf99f835313c914ee
refs/heads/master
2023-08-29T13:57:04.122115
2022-02-11T14:28:23
2022-02-11T14:28:23
17,148,386
7
3
null
null
null
null
UTF-8
Python
false
false
1,061
py
''' Created on Nov 13, 2014 @author: mikael ''' from scripts_inhibition import effect_conns from effect_conns import gs_builder_conn d=kw={'n_rows':8, 'n_cols':2, 'w':int(72/2.54*18), 'h':int(72/2.54*18)/3, 'fontsize':7, 'title_fontsize':7, 'gs_builder':gs_builder_conn} kwargs={'data_path':('/home/mikael/results/papers/inhibition/network/' +'milner/simulate_beta_ZZZ_conn_effect_perturb3/'), 'from_diks':0, 'script_name':(__file__.split('/')[-1][0:-3]+'/data'), 'title':'Activation (beta)', 'fontsize_x':7, 'fontsize_y':7, 'conn_fig_title_fontsize':7, 'title_flipped':True, # 'title_posy':0.2, 'do_plots':['index'], 'top_lables_fontsize':7, 'clim_raw': [[0,5], [0,50], [0,1]], 'kwargs_fig':d, 'oi_min':15., 'oi_max':25, 'oi_fs':256, 'psd':{'NFFT':128, 'fs':256., 'noverlap':128/2}} obj=effect_conns.Main(**kwargs) obj.do()
41371ec303f8bfca6e951551f8bc57780ee8392d
540bf8de2145644fa3549e507871d53352201df8
/Chapter_8/Lopez_TIY8.9.py
0f9c69bf23451d0fa200b8967c79b820adbb2d29
[]
no_license
lope512q09/Python
68d798d4c3135ac187b78db28b73047b2efdbde9
7fdb97da36fd3f7145bfb3c8a43518685b5f6d6d
refs/heads/master
2020-08-23T10:44:07.915389
2020-01-22T15:36:23
2020-01-22T15:36:23
216,598,365
0
0
null
null
null
null
UTF-8
Python
false
false
194
py
message_list = ["Hi!", "How are you?", "I'm good, and you?", "The same!"] def show_messages(messages): for message in messages: print(f"{message}\n") show_messages(message_list)
c5a559474d66a4a49796a3aa35b921528e07527b
dee29293af049cac224f0c94a7eaf439e8766085
/bluezutils.py
8c9f7f962272215923940598f7e84d9b713cd26f
[]
no_license
lubusax/2005_dbus
9721d88c42081138fac1b55814f5fc1bbb9eec09
0647a951448fe8bb297ba2988ef35ec7117e389f
refs/heads/master
2022-12-01T23:33:52.162681
2020-08-10T19:41:02
2020-08-10T19:41:02
263,895,499
0
0
null
null
null
null
UTF-8
Python
false
false
1,649
py
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter1" DEVICE_INTERFACE = SERVICE_NAME + ".Device1" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.items(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or \ path.endswith(pattern): obj = bus.get_object(SERVICE_NAME, path) #print("BLUEZ :", SERVICE_NAME) print("PATH_HCI0 :", path) print("hci0 :", obj) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") def find_device(device_address, adapter_pattern=None): return find_device_in_objects(get_managed_objects(), device_address, adapter_pattern) def find_device_in_objects(objects, device_address, adapter_pattern=None): bus = dbus.SystemBus() path_prefix = "" if adapter_pattern: adapter = find_adapter_in_objects(objects, adapter_pattern) path_prefix = adapter.object_path for path, ifaces in objects.items(): device = ifaces.get(DEVICE_INTERFACE) if device is None: continue if (device["Address"] == device_address and path.startswith(path_prefix)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, DEVICE_INTERFACE) raise Exception("Bluetooth device not found")
3ebb7a68bca91cfa6d41a0fe4b1d036325352a14
09e57dd1374713f06b70d7b37a580130d9bbab0d
/benchmark/startQiskit2215.py
5f520456f8eb7cadea2dc6cd635e3fff07eb5941
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
3,852
py
# qubit number=4 # total number=28 import cirq import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2 import numpy as np import networkx as nx def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() return oracle def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.x(input_qubit[3]) # number=1 prog.rx(-1.9352210746113125,input_qubit[3]) # number=14 prog.cx(input_qubit[1],input_qubit[2]) # number=22 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.y(input_qubit[2]) # number=13 prog.rx(0.13823007675795101,input_qubit[2]) # number=24 prog.h(input_qubit[0]) # number=5 oracle = build_oracle(n-1, f) prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]]) prog.h(input_qubit[1]) # number=6 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=9 prog.rx(-1.9069467407290044,input_qubit[2]) # number=20 prog.h(input_qubit[3]) # number=21 prog.y(input_qubit[2]) # number=10 prog.h(input_qubit[1]) # number=17 prog.cz(input_qubit[3],input_qubit[1]) # number=18 prog.h(input_qubit[1]) # number=19 prog.y(input_qubit[2]) # number=11 prog.h(input_qubit[0]) # number=25 prog.cz(input_qubit[1],input_qubit[0]) # number=26 prog.h(input_qubit[0]) # number=27 prog.cx(input_qubit[1],input_qubit[0]) # number=16 prog.z(input_qubit[3]) # number=23 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog if __name__ == '__main__': a = "111" b = "0" f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b) prog = make_circuit(4,f) backend = BasicAer.get_backend('qasm_simulator') sample_shot =8000 info = execute(prog, backend=backend, shots=sample_shot).result().get_counts() backend = FakeVigo() circuit1 = transpile(prog,backend,optimization_level=2) writefile = open("../data/startQiskit2215.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.__len__(),file=writefile) print(circuit1,file=writefile) writefile.close()
1e225faa5c2c7bc6323a87b9640d07cc541acb30
51fd2216d5182a1b3655e7cb1b197862424054f6
/insta_api/config/urls.py
8258104c833242de67443431202090483e1a9431
[]
no_license
seungjinhan/django_clone_instagram
3217829fabe893190e7d6cc37b64b7d3c881f441
f0ea8649d426c167e2ccd2fa3b15e5d3b7867d7b
refs/heads/master
2022-12-26T05:39:16.320763
2020-10-05T13:40:39
2020-10-05T13:40:39
291,262,260
0
0
null
null
null
null
UTF-8
Python
false
false
998
py
"""config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('api/', include('api.urls')), path('token/', include('djoser.urls.jwt')), path('admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
062718780f0e402218a9160bf8cafdd20d5a1da6
1749147fb24b13803d3437e0ae94250d67d618bd
/keras/keras33_tensorboard.py
a9043cf01d608a05cfe76b9a3fafa8b1681e955d
[]
no_license
MJK0211/bit_seoul
65dcccb9336d9565bf9b3bc210b1e9c1c8bd840e
44d78ce3e03f0a9cf44afafc95879e4e92d27d54
refs/heads/master
2023-02-06T00:45:52.999272
2020-12-26T07:47:30
2020-12-26T07:47:30
311,308,648
1
0
null
null
null
null
UTF-8
Python
false
false
2,076
py
import numpy as np #1. 데이터 dataset = np.array(range(1,11)) size = 5 def split_x(seq, size): aaa = [] for i in range(len(seq) - size + 1): subset = seq[i : (i+size)] aaa.append([item for item in subset]) # print(type(aaa)) return np.array(aaa) datasets = split_x(dataset, size) x = datasets[:, 0:4] #(96,4) y = datasets[:, 4] #(96,) x = np.reshape(x, (x.shape[0], x.shape[1],1)) #(96,4,1) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test, = train_test_split(x, y, train_size=0.9, shuffle=False) #2. 모델구성 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM model = Sequential() model.add(LSTM(200, activation='relu', input_shape=(4,1))) model.add(Dense(180, activation='relu')) model.add(Dense(150, activation='relu')) model.add(Dense(110, activation='relu')) model.add(Dense(60, activation='relu')) model.add(Dense(10, activation='relu')) model.add(Dense(1)) model.summary() #3. 컴파일, 훈련 model.compile(loss='mse', optimizer='adam', metrics=['mae']) from tensorflow.keras.callbacks import EarlyStopping, TensorBoard #TensorBoard 추가 early_stopping = EarlyStopping(monitor='loss', patience=200, mode='min') to_hist = TensorBoard(log_dir='graph', histogram_freq=0, write_graph=True, write_images=True) #graph 폴더에 파일들이 생기는 것을 볼 수 있다 #cmd - d: - cd Study - cd bit_seoul - cd graph (파일 최종 경로) - tensorboard --logdir=. enter #TensorBoard 2.3.0 at http://localhost:6006/ (Press CTRL+C to quit) #위에 표시된 url 접속 #log가 겹칠 수 있다. 새로 볼 경우에는 로그를 지우고 새로 하는게 좋을 수 있다 history = model.fit(x_train, y_train, epochs=1000, batch_size=1, validation_split= 0.2, verbose=1, callbacks=[early_stopping, to_hist]) #to_hist를 콜백에 list형태로 추가 #4. 평가, 예측 loss, mae = model.evaluate(x_test, y_test) print("loss : ", loss) print("mae : ", mae) y_predict = model.predict(x_test) print("y_predict : \n", y_predict)
49582bc92163da9907c82cade99055d72e45a69b
9b422078f4ae22fe16610f2ebc54b8c7d905ccad
/xlsxwriter/test/comparison/test_chart_format08.py
058d4a13f4a4112c40ccca93ab04951eaf939c95
[ "BSD-2-Clause-Views" ]
permissive
projectsmahendra/XlsxWriter
73d8c73ea648a911deea63cb46b9069fb4116b60
9b9d6fb283c89af8b6c89ad20f72b8208c2aeb45
refs/heads/master
2023-07-21T19:40:41.103336
2023-07-08T16:54:37
2023-07-08T16:54:37
353,636,960
0
0
NOASSERTION
2021-04-01T08:57:21
2021-04-01T08:57:20
null
UTF-8
Python
false
false
1,440
py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2021, John McNamara, [email protected] # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('chart_format08.xlsx') def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'line'}) chart.axis_ids = [46164608, 46176128] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$B$1:$B$5', 'trendline': {'type': 'linear'}, }) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$C$1:$C$5', }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
e768c417c324d6053a1501c6620777767efd6bbf
5483ac2ccf7ac0d951b31dab2a86fe564c397408
/appos.py
f801bf21a4cacfc9c718c9eab3adaad81a3221a0
[]
no_license
Ram-Aditya/Music-Recommender
9d4a7ee8379e98756e2082a95bbb1d5e4318e806
1fdeb5ed208be7908f09a1a5576a30218505a979
refs/heads/master
2020-05-07T14:20:13.772004
2019-10-25T16:12:57
2019-10-25T16:12:57
180,589,469
0
2
null
2019-10-27T12:58:23
2019-04-10T13:37:25
Python
UTF-8
Python
false
false
1,308
py
appos = { "ain't":"it is not like", "aren't" : "are not", "can't" : "cannot", "couldn't" : "could not", "didn't" : "did not", "doesn't" : "does not", "don't" : "do not", "hadn't" : "had not", "hasn't" : "has not", "haven't" : "have not", "he'd" : "he would", "he'll" : "he will", "he's" : "he is", "i'd" : "I would", "i'd" : "I had", "i'll" : "I will", "i'm" : "I am", "isn't" : "is not", "it's" : "it is", "it'll":"it will", "i've" : "I have", "let's" : "let us", "mightn't" : "might not", "mustn't" : "must not", "shan't" : "shall not", "she'd" : "she would", "she'll" : "she will", "she's" : "she is", "shouldn't" : "should not", "that's" : "that is", "there's" : "there is", "they'd" : "they would", "they'll" : "they will", "they're" : "they are", "they've" : "they have", "we'd" : "we would", "we're" : "we are", "weren't" : "were not", "we've" : "we have", "what'll" : "what will", "what're" : "what are", "what's" : "what is", "what've" : "what have", "where's" : "where is", "who'd" : "who would", "who'll" : "who will", "who're" : "who are", "who's" : "who is", "who've" : "who have", "won't" : "will not", "wouldn't" : "would not", "you'd" : "you would", "you'll" : "you will", "you're" : "you are", "you've" : "you have", "'re": " are", "wasn't": "was not", "we'll":" will", "didn't": "did not" }
a56d370607d4b4332ef539db433c38161c4a2bcb
8972658ca2c64703e8281db89d7a6ac47cbabbf7
/backend/linkanywhere/apps/base/behaviors.py
d3c96ffeda67dc40478d7c26a088712f96c2161d
[ "MIT" ]
permissive
denisorehovsky/linkanywhere
15721824719cc8a959cdddb4178cfe754eb4862d
e21d6725fbe0e74a7301e40f9d9bdbac17c68e68
refs/heads/master
2022-07-21T16:16:17.412930
2017-08-24T06:32:37
2017-08-24T06:32:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,051
py
from django.db import models from django.utils import timezone from django.utils.translation import ugettext as _ from behaviors.querysets import PublishedQuerySet from .constants import DRAFT, PUBLISHED, PUBLICATION_STATUS_CHOICES class Published(models.Model): publication_status = models.CharField( _('publication status'), max_length=1, choices=PUBLICATION_STATUS_CHOICES, default=DRAFT ) publication_date = models.DateTimeField( _('publication date'), null=True, blank=True ) objects = PublishedQuerySet.as_manager() publications = PublishedQuerySet.as_manager() class Meta: abstract = True def save(self, *args, **kwargs): if self.publication_date is None and self.is_published: self.publication_date = timezone.now() super().save(*args, **kwargs) @property def is_draft(self): return self.publication_status == DRAFT @property def is_published(self): return self.publication_status == PUBLISHED
20bf26f6d4991ace9ec7a0a74530718eaf4fd7c0
be0f3dfbaa2fa3d8bbe59229aef3212d032e7dd1
/Gauss_v45r10p1/Gen/DecFiles/options/20072002.py
a5d0a92707cd731867593ec97455a57a39004f3e
[]
no_license
Sally27/backup_cmtuser_full
34782102ed23c6335c48650a6eaa901137355d00
8924bebb935b96d438ce85b384cfc132d9af90f6
refs/heads/master
2020-05-21T09:27:04.370765
2018-12-12T14:41:07
2018-12-12T14:41:07
185,989,173
0
0
null
null
null
null
UTF-8
Python
false
false
1,268
py
# file /home/hep/ss4314/cmtuser/Gauss_v45r10p1/Gen/DecFiles/options/20072002.py generated: Wed, 25 Jan 2017 15:25:32 # # Event Type: 20072002 # # ASCII decay Descriptor: pp => [<Xc>]cc ... # from Gaudi.Configuration import * importOptions( "$DECFILESROOT/options/DiMuon_for_tau23mu.py" ) from Configurables import Generation Generation().EventType = 20072002 Generation().SampleGenerationTool = "Inclusive" from Configurables import Inclusive Generation().addTool( Inclusive ) Generation().Inclusive.ProductionTool = "PythiaProduction" from Configurables import ToolSvc from Configurables import EvtGenDecay ToolSvc().addTool( EvtGenDecay ) ToolSvc().EvtGenDecay.UserDecayFile = "$DECFILESROOT/dkfiles/incl_c=DiMuon,tau23mu_cuts.dec" Generation().Inclusive.CutTool = "LHCbAcceptance" Generation().FullGenEventCutTool = "DiLeptonInAcceptance" Generation().Inclusive.InclusivePIDList = [ 421, -421, 411, -411, 431, -431, 4122, -4122, 443, 4112, -4112, 4212, -4212, 4222, -4222, 4312, -4312, 4322, -4322, 4332, -4332, 4132, -4132, 4232, -4232, 100443, 441, 10441, 20443, 445, 4214, -4214, 4224, -4224, 4314, -4314, 4324, -4324, 4334, -4334, 4412, -4412, 4414,-4414, 4422, -4422, 4424, -4424, 4432, -4432, 4434, -4434, 4444, -4444, 14122, -14122, 14124, -14124, 100441 ]
80ee0b807b6645849b86857892b8f89176016c50
98b63e3dc79c75048163512c3d1b71d4b6987493
/tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_sparse_mat_mul_grad_test.py
07d1e6a2a061f98ad65a92e1259fed8bc646e0ac
[ "Apache-2.0" ]
permissive
galeone/tensorflow
11a4e4a3f42f4f61a65b432c429ace00401c9cc4
1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206
refs/heads/master
2022-11-13T11:56:56.143276
2020-11-10T14:35:01
2020-11-10T14:35:01
310,642,488
21
12
Apache-2.0
2020-11-06T16:01:03
2020-11-06T16:01:02
null
UTF-8
Python
false
false
5,236
py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """CSR sparse matrix tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import numpy as np from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import math_ops from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_grad # pylint: disable=unused-import from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging def dense_to_csr_sparse_matrix(dense): dense_t = ops.convert_to_tensor(dense) locs = array_ops.stop_gradient(array_ops.where(math_ops.abs(dense_t) > 0)) return sparse_csr_matrix_ops.dense_to_csr_sparse_matrix(dense_t, locs) def _add_test(test, op_name, testcase_name, fn): # pylint: disable=redefined-outer-name if fn is None: return test_name = "_".join(["test", op_name, testcase_name]) if hasattr(test, test_name): raise RuntimeError("Test %s defined more than once" % test_name) setattr(test, test_name, fn) class CSRSparseMatrixGradTest(test.TestCase): @classmethod def setUpClass(cls): super(CSRSparseMatrixGradTest, cls).setUpClass() cls._gpu_available = test_util.is_gpu_available() # TODO(penporn): Make these tests runnable on eager mode. # (tf.gradients and gradient_checker only run in graph mode.) @test_util.run_deprecated_v1 def _testLargeBatchSparseMatrixSparseMatMulGrad(self, datatype, transpose_a, transpose_b, adjoint_a, adjoint_b): if not self._gpu_available: return sparsify = lambda m: m * (m > 0) a_mats_val = sparsify( np.random.randn(3, 5, 11) + 1.j * np.random.randn(3, 5, 11)).astype(datatype) if transpose_a or adjoint_a: a_mats_val = np.transpose(a_mats_val, (0, 2, 1)) if adjoint_a: a_mats_val = np.conj(a_mats_val) b_mats_val = sparsify( np.random.randn(3, 11, 13) + 1.j * np.random.randn(3, 11, 13)).astype(datatype) if transpose_b or adjoint_b: b_mats_val = np.transpose(b_mats_val, (0, 2, 1)) if adjoint_b: b_mats_val = np.conj(b_mats_val) with self.test_session(use_gpu=True): a_mats = ops.convert_to_tensor(a_mats_val, dtype=datatype) b_mats = ops.convert_to_tensor(b_mats_val, dtype=datatype) a_sm = dense_to_csr_sparse_matrix(a_mats) b_sm = dense_to_csr_sparse_matrix(b_mats) c_sm = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul( a_sm, b_sm, transpose_a=transpose_a, transpose_b=transpose_b, adjoint_a=adjoint_a, adjoint_b=adjoint_b, type=datatype) c_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense( c_sm, type=datatype) for ten, val, nn in [[a_mats, a_mats_val, "a"], [b_mats, b_mats_val, "b"]]: tf_logging.info("Testing gradients for %s" % nn) theoretical, numerical = gradient_checker.compute_gradient( ten, ten.get_shape().as_list(), c_dense, c_dense.get_shape().as_list(), x_init_value=val, delta=1e-3) self.assertAllClose(theoretical, numerical, atol=1e-3, rtol=1e-3) # These tests are refactored from sparse_csr_matrix_grad_test to keep its size # "medium". for dtype in (np.float32, np.complex64): for (t_a, t_b, adj_a, adj_b) in itertools.product(*(([False, True],) * 4)): def create_sparse_mat_mul_test_fn(dtype_, t_a_, t_b_, adj_a_, adj_b_): # Skip invalid cases. if (t_a_ and adj_a_) or (t_b_ and adj_b_): return # Skip cases where we conjugate real matrices. if dtype_ == np.float32 and (adj_a_ or adj_b_): return def test_fn(self): self._testLargeBatchSparseMatrixSparseMatMulGrad( dtype_, t_a_, t_b_, adj_a_, adj_b_) return test_fn name = ( "_testLargeBatchSparseMatrixSparseMatMulGrad_dtype_%s_t_a_%s_t_b_%s_" "adj_a_%s_adj_b_%s" % (dtype.__name__, t_a, t_b, adj_a, adj_b)) _add_test(CSRSparseMatrixGradTest, "CSRSparseMatrixSparseGradTest", name, create_sparse_mat_mul_test_fn(dtype, t_a, t_b, adj_a, adj_b)) if __name__ == "__main__": test.main()
acec0e95d1ab761a24af1b9dc5a5772237ac0c6a
28c517d75c71dcdefa3dfaa0dff6d5998f885e53
/testing/regrid/testDiag.py
6722eaa555a1b1ca4ba13982a9b03f7b2e8220ae
[]
no_license
AZed/uvcdat
5863eba99f230c23336cc4e0772e0d406b24a919
58e745bbed25c7b80584fa25a29dd8239d917cd9
refs/heads/master
2021-01-18T10:36:45.792190
2013-01-25T22:29:10
2013-01-25T22:29:10
8,485,065
1
0
null
null
null
null
UTF-8
Python
false
false
6,890
py
""" $Id: testDiag.py 2389 2012-07-26 15:51:43Z dkindig $ Test diagnostics """ import re import numpy import cdms2 import regrid2 import unittest import ESMP from regrid2 import esmf from matplotlib import pylab from mpi4py import MPI import types from math import pi import sys class Test(unittest.TestCase): def setUp(self): self.pe = MPI.COMM_WORLD.Get_rank() self.nprocs = MPI.COMM_WORLD.Get_size() def Xtest1_libcf(self): srcF = cdms2.open(sys.prefix + \ '/sample_data/so_Omon_ACCESS1-0_historical_r1i1p1_185001-185412_2timesteps.nc') so = srcF('so')[0, 0, ...] clt = cdms2.open(sys.prefix + '/sample_data/clt.nc')('clt') diag = {'numValid': None, 'numDstPoints': None} soInterp = so.regrid(clt.getGrid(), regridTool = 'libcf', regridMethod='linear', diag = diag) if self.pe == 0: # diag = {'numDstPoints': 3312, 'numValid': 2933} self.assertEqual(diag['numDstPoints'], 3312) self.assertEqual(diag['numValid'], 2933) if False: pylab.subplot(1, 2, 1) pylab.pcolor(so, vmin = 20, vmax = 40) pylab.colorbar() pylab.title('so') pylab.subplot(1, 2, 2) pylab.pcolor(soInterp, vmin = 20, vmax = 40) pylab.colorbar() pylab.title('soInterp') def test2_varRegrid(self): print print 'test2_varRegrid' srcF = cdms2.open(sys.prefix + \ '/sample_data/so_Omon_ACCESS1-0_historical_r1i1p1_185001-185412_2timesteps.nc') so = srcF('so')[0, 0, ...] clt = cdms2.open(sys.prefix + '/sample_data/clt.nc')('clt') diag = {'srcAreas': None, 'dstAreas': None, 'srcAreaFractions': None, 'dstAreaFractions': None} soInterp = so.regrid(clt.getGrid(), regridTool = 'esmf', regridMethod='conserve', diag = diag) if self.pe == 0: totSrcArea = diag['srcAreas'].sum() totDstArea = diag['dstAreas'].sum() totSrcFrac = diag['srcAreaFractions'].sum() self.assertEqual(numpy.isnan(totSrcFrac).sum(), 0) self.assertLess(abs(totSrcArea - 4*pi)/(4*pi), 0.02) self.assertLess(abs(totDstArea - 4*pi)/(4*pi), 0.01) soMass = (so*diag['srcAreas']).sum() inMass = (soInterp*diag['dstAreas']).sum() print soMass, inMass diff = abs(soMass - inMass)/soMass self.assertLess(diff, 7.e-7) if False: pylab.subplot(1, 2, 1) pylab.pcolor(so, vmin = 20, vmax = 40) pylab.colorbar() pylab.title('so') pylab.subplot(1, 2, 2) pylab.pcolor(soInterp, vmin = 20, vmax = 40) pylab.colorbar() pylab.title('soInterp') def Xtest3_esmf(self): print print 'test3_esmf' srcF = cdms2.open(sys.prefix + \ '/sample_data/so_Omon_ACCESS1-0_historical_r1i1p1_185001-185412_2timesteps.nc') so = srcF('so')[0, 0, ...] clt = cdms2.open(sys.prefix + '/sample_data/clt.nc')('clt')[0, ...] diag = {'srcAreas': None, 'dstAreas': None, 'srcAreaFractions': None, 'dstAreaFractions': None} srcCoords = [so.getGrid().getLatitude()[:], so.getGrid().getLongitude()[:]] srcBounds = cdms2.mvCdmsRegrid.getBoundList(srcCoords) tmp = clt.getGrid().toCurveGrid() dstCoords = [tmp.getLatitude()[:], tmp.getLongitude()[:]] dstBounds = cdms2.mvCdmsRegrid.getBoundList(dstCoords) # Establish the grids srcGrid = esmf.EsmfStructGrid(so.shape, periodicity = 1) dstGrid = esmf.EsmfStructGrid(clt.shape, periodicity = 1) srcGrid.setCoords(srcCoords) dstGrid.setCoords(dstCoords) srcGrid.setCoords(srcBounds, staggerloc = esmf.CORNER) dstGrid.setCoords(dstBounds, staggerloc = esmf.CORNER) # Establish the fields srcFeld = esmf.EsmfStructField(srcGrid, 'srcFeld', so.dtype) dstFeld = esmf.EsmfStructField(dstGrid, 'dstFeld',so.dtype) srcFeldPtr = srcFeld.getPointer() srcFeldPtr[:] = so.data.flat dstFeldPtr = dstFeld.getPointer() dstFeldPtr[:] = so.missing_value # Fractions srcFrac = esmf.EsmfStructField(srcGrid, 'srcFrac', so.dtype) dstFrac = esmf.EsmfStructField(dstGrid, 'dstFrac', so.dtype) srcFracPtr = srcFrac.getPointer() srcFracPtr[:] = 1.0 dstFracPtr = dstFrac.getPointer() dstFracPtr[:] = 1.0 nnan = numpy.isnan(srcFeldPtr).sum() if nnan > 0: print "There are nan's in srcFracPtr" # Areas presrcArea = esmf.EsmfStructField(srcGrid, 'srcArea', so.dtype) predstArea = esmf.EsmfStructField(dstGrid, 'dstArea', so.dtype) presrcAreaPtr = presrcArea.getPointer() presrcAreaPtr[:] = 1.0 predstAreaPtr = predstArea.getPointer() predstAreaPtr[:] = 1.0 ro = esmf.EsmfRegrid(srcFeld, dstFeld, srcFrac = srcFrac, dstFrac = dstFrac, srcMaskValues = None, dstMaskValues = None, regridMethod = esmf.CONSERVE, unMappedAction = esmf.IGNORE) ro() srcAreas = ro.getSrcAreas(None) dstAreas = ro.getDstAreas(None) srcFracPtrPost = ro.getSrcAreaFractions(None) nnanPost = numpy.isnan(srcFracPtrPost).sum() nnan = numpy.isnan(srcFracPtr).sum() if nnan > 0 or nnanPost > 0: print "There are nan's in srcFracPtrPost", nnanPost print "There are nan's in srcFracPtr", nnan self.assertNotEqual(nnan, 0) self.assertNotEqual(nnanPost, 0) dstFracPtrPost = ro.getDstAreaFractions(None) nnanPost = numpy.isnan(dstFracPtrPost).sum() nnan = numpy.isnan(dstFracPtrPost).sum() if nnan > 0 or nnanPost > 0: print "There are nan's in dstFracPtrPost", nnanPost print "There are nan's in dstFracPtr", nnan self.assertNotEqual(nnan, 0) self.assertNotEqual(nnanPost, 0) srcMass = (srcFeldPtr * srcAreas.flatten() * srcFracPtr).sum() dstMass = (dstFeldPtr * dstAreas.flatten()).sum() dstMassPtr = (dstFeldPtr * predstAreaPtr).sum() diff = abs(srcMass - dstMass) self.assertLess(diff/srcMass, 1.e-7) if __name__ == '__main__': print "" ESMP.ESMP_Initialize() suite = unittest.TestLoader().loadTestsFromTestCase(Test) unittest.TextTestRunner(verbosity = 1).run(suite) pylab.show()
b1b4c6f3cdff8fb9c2d1c39ee1f4d1670dd9d919
25bcf095a803470b4be9bba394569cb218b997ed
/book/算法和数据操作-回溯法-矩阵中的路径.py
02aeb344a4c555b22f17c04134e17a8e2968819c
[]
no_license
lcqbit11/algorithms
c8a3da6d3a9d387d54639c0a08d14ca6b9118bb3
ca4dacda39dc12d53ed8d4448b3356a3f2936603
refs/heads/master
2023-06-22T06:36:22.106780
2023-06-11T07:10:40
2023-06-11T07:10:40
245,633,883
0
0
null
2023-06-11T07:10:41
2020-03-07T13:02:24
Python
UTF-8
Python
false
false
1,403
py
#!/usr/bin/env python # -*- coding: utf-8 -*- def matrix_path(matrix, s): """ :param matrix: List[List[int]] :param s: str :return: bool """ def new_matrix(m, row, col): matrix = [[0] * len(m[0]) for k in range(len(m))] for i in range(len(m)): for j in range(len(m[0])): if row == i and col == j: matrix[i][j] = 0 else: matrix[i][j] = m[i][j] return matrix def has_path(matrix, row, col, i, j, s): if len(s) == 0: return True is_path = False if i >= 0 and i < row and j >= 0 and j < col and matrix[i][j] == s[0]: matrix = new_matrix(matrix, i, j) is_path = has_path(matrix, row, col, i+1, j, s[1:]) or has_path(matrix, row, col, i, j+1, s[1:]) or has_path(matrix, row, col, i-1, j, s[1:]) or has_path(matrix, row, col, i, j-1, s[1:]) return is_path row = len(matrix) col = len(matrix[0]) length = len(s) for i in range(row): for j in range(col): if matrix[i][j] == s[0]: if has_path(matrix, row, col, i, j, s): return True return False if __name__ == "__main__": matrix = [['a', 'b', 't', 'g'], ['c', 'f', 'c', 's'], ['j', 'd', 'e', 'h']] s = "bfce" print(matrix_path(matrix, s))
eca5c374b5e021bedadf8e451f0537bea855034d
7f24023d365e013ec0924844c1a872edfb0c75b4
/tests/trac/test-trac-0091.py
22249454c7a9b898e8f2d4b3e96a19e52251d7dc
[ "Python-2.0", "MIT", "Apache-2.0" ]
permissive
pabigot/pyxb
cd42c024607572c6363682d389e9296caf3f2857
5ee5ba54c9f702dc9c9efc2731ee547ecd4dae4a
refs/heads/next
2023-05-11T03:23:19.599756
2023-04-29T20:38:15
2023-04-29T20:45:13
20,547,850
130
63
Apache-2.0
2021-08-19T16:52:18
2014-06-06T01:49:03
Python
UTF-8
Python
false
false
4,794
py
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import pyxb.binding.generate import pyxb.binding.datatypes as xs import pyxb.binding.basis import pyxb.utils.domutils import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="f13p8"> <xs:restriction base="xs:decimal"> <xs:totalDigits value="13"/> <xs:fractionDigits value="8"/> </xs:restriction> </xs:simpleType> <xs:element name="e13p8" type="f13p8"/> <xs:simpleType name="f15p5"> <xs:restriction base="xs:decimal"> <xs:totalDigits value="15"/> <xs:fractionDigits value="5"/> </xs:restriction> </xs:simpleType> <xs:element name="e15p5" type="f15p5"/> </xs:schema>''' code = pyxb.binding.generate.GeneratePython(schema_text=xsd) #open('code.py', 'w').write(code) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest class TestTrac_0091 (unittest.TestCase): def assertAlmostEqual (self, v1, v2, *args, **kw): from decimal import Decimal if (isinstance(v1, Decimal) or isinstance(v2, Decimal)): if not isinstance(v1, Decimal): v1 = Decimal(str(v1)) if not isinstance(v2, Decimal): v2 = Decimal(str(v2)) return super(TestTrac_0091, self).assertAlmostEqual(v1, v2, *args, **kw) def testBasic (self): if sys.version_info[:2] >= (2, 7): # Prior to 2.7 float/Decimal comparisons returned invalid results. self.assertEqual(1.0, e13p8(1.0)) self.assertEqual(1.0, e13p8('1.0')) self.assertEqual(1234567890123.0, e13p8('1234567890123')) self.assertEqual(1234567890123.0, CreateFromDocument('<e13p8>1234567890123</e13p8>')) self.assertRaises(SimpleFacetValueError, e13p8, '12345678901234') self.assertAlmostEqual(1.00000001, e13p8('1.00000001')) self.assertRaises(SimpleFacetValueError, e13p8, '1.000000001') def testBadCase (self): # Prior to fix, this raised a facet violation due to rounding self.assertAlmostEqual(0.00790287, e13p8('0.00790287')) def test15_5 (self): from decimal import Decimal # For compatibility in Python 2.6 PyXB will convert the float # to a string before invoking the underlying decimal.Decimal fv = e15p5(1234.56789) self.assertTrue(fv.validateBinding()) dv = Decimal('1234.56789') self.assertEqual(fv, dv) # In Python 2.7 decimal.Decimal will create from the float, # which will already be in a form that won't validate if sys.version_info[:2] >= (2, 7): self.assertRaises(SimpleFacetValueError, e15p5, Decimal(1234.56789)) sv = e15p5('1234.56789') self.assertEqual(sv, dv) self.assertTrue(sv.validateBinding()) self.assertTrue(e15p5('1000000.0').validateBinding()) def testRanges (self): from decimal import Decimal o14o = [1] + ([0] * 12) + [1] self.assertEqual(14, len(o14o)) o15o = [1] + ([0] * 13) + [1] self.assertEqual(15, len(o15o)) o16o = [1] + ([0] * 14) + [1] self.assertEqual(16, len(o16o)) self.assertTrue(e15p5(Decimal((0, o14o, 0))).validateBinding()) self.assertTrue(e15p5(Decimal((0, o15o, 0))).validateBinding()) # Negative exponents do not reduce total digit count with self.assertRaises(pyxb.SimpleFacetValueError) as cm: e15p5(Decimal((0, o16o, 0))) self.assertEqual(cm.exception.facet, f15p5._CF_totalDigits) with self.assertRaises(pyxb.SimpleFacetValueError) as cm: e15p5(Decimal((0, o16o, -1))) self.assertEqual(cm.exception.facet, f15p5._CF_totalDigits) # Positive exponents add to total digit count self.assertTrue(e15p5(Decimal((0, o14o, 1))).validateBinding()) with self.assertRaises(pyxb.SimpleFacetValueError) as cm: e15p5(Decimal((0, o15o, 1))) self.assertEqual(cm.exception.facet, f15p5._CF_totalDigits) with self.assertRaises(pyxb.SimpleFacetValueError) as cm: e15p5(Decimal((0, o14o, 2))) self.assertEqual(cm.exception.facet, f15p5._CF_totalDigits) # Negative exponents affect fractionDigits only self.assertTrue(e15p5(Decimal((0, o15o, -1))).validateBinding()) self.assertTrue(e15p5(Decimal((0, o15o, -5))).validateBinding()) with self.assertRaises(pyxb.SimpleFacetValueError) as cm: e15p5(Decimal((0, o15o, -6))) self.assertEqual(cm.exception.facet, f15p5._CF_fractionDigits) if __name__ == '__main__': unittest.main()
82a11268ed01c2cbfc7d9a0e833ebc4444f24e80
7ffa7b3be3ef25db511d0f9db673fa4ff2350daf
/src/Sample43.py
744edd556499d9dfe4437b8197b871bc69d6b9db
[]
no_license
jacoloves/start_Python
33c9ee8baa5650a66d496a207269b2228a1640d4
1ced11d131b612d78a69ae261d4e06889313afcf
refs/heads/master
2022-11-24T02:06:40.582895
2020-02-15T13:57:13
2020-02-15T13:57:13
133,673,161
0
0
null
2022-11-22T02:19:43
2018-05-16T13:52:03
Python
UTF-8
Python
false
false
102
py
class A: """docstring for A""" def __init__(self): self.__value = 1 a = A() print(a._A__value)
f95738894ed4e42648865c0d36d329579bf719eb
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/132/usersdata/239/41382/submittedfiles/al14.py
5754055aa4ef2a253321a042cdc75ce2db4c6048
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
214
py
# -*- coding: utf-8 -*- n=int(input("Digite o número de pessoas: ")) i=0 termo=n while termo>0: idade=int(input("Digite a idade das pessoas: ")) i=i+idade termo=termo-1 media=(i/n) print("%.2f"%media)
4ff05fb289e34cc72623f03733a105c7aa80dbf4
38d6a6ac271fca4d5fff422541bc59df10e66ef5
/landlab/_info.py
0a320b3bd55222275db2d17e22a791571245c485
[ "MIT" ]
permissive
AndresQuichimbo/landlab
767d3c42eaa4e6477865594666dd49eb3eb684bb
39fee962ec962a389ae4522a55a17f53a0d37a6e
refs/heads/master
2020-04-01T21:31:11.422998
2020-02-06T23:12:26
2020-02-06T23:12:26
240,261,264
0
0
MIT
2020-02-13T13:00:25
2020-02-13T13:00:24
null
UTF-8
Python
false
false
584
py
name = "landlab" cite_as = [ """@article{hobley2017creative, title={Creative computing with Landlab: an open-source toolkit for building, coupling, and exploring two-dimensional numerical models of Earth-surface dynamics}, author={Hobley, Daniel EJ and Adams, Jordan M and Nudurupati, Sai Siddhartha and Hutton, Eric WH and Gasparini, Nicole M and Istanbulluoglu, Erkan and Tucker, Gregory E}, journal={Earth Surface Dynamics}, volume={5}, number={1}, pages={21}, year={2017}, publisher={Copernicus GmbH} }""" ]
ee0b438af7cec5ea6648945f35afe8bbfd233040
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/415/usersdata/296/86500/submittedfiles/exe11.py
3e55da52506b436ee00c29807dd6008b54ef4d53
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
234
py
# -*- coding: utf-8 -*- n = int(input("Digite um número: ")) soma = 0 while n > 0: if 10000000 <= n <= 90000000: resto = n%10000000 n = (n - resto)/10000000 soma = soma + resto print(soma)
c22bc6d09d1dba9ee889fd0d138c6d55c329be08
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/BuildLinks1.10/test_input/CJ_16_1/16_1_2_Erisky_solve_B.py
414d395289b8df01c731ab2d840c390f59fd2a13
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
826
py
import math # raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. total = int(raw_input()) # read a line with a single integer for i in xrange(1, total + 1): N = int(raw_input()) output = {} for j in range(2*N-1): S = raw_input().split() for x in S: if x in output: output[x] = output[x] + 1 else: output[x] = 1 olist = [] for any in output: if output[any] % 2 == 1: olist.append(int(any)) olist.sort() # print olist os="" for gg in olist: os += str(gg) os += " " print "Case #{}: {}".format(i, "".join(os)) # check out .format's specification for more formatting options
54b141b59dad195d7bb823334914e9748de22edc
18f8abb90efece37949f5b5758c7752b1602fb12
/py/django_tools/django-exceptional/test/example/settings.py
91dbfbd0d5b7de0bc9be14860552db1f2cde198f
[ "Unlicense" ]
permissive
marceltoben/evandrix.github.com
caa7d4c2ef84ba8c5a9a6ace2126e8fd6db1a516
abc3fbfb34f791f84e9a9d4dc522966421778ab2
refs/heads/master
2021-08-02T06:18:12.953567
2011-08-23T16:49:33
2011-08-23T16:49:33
2,267,457
3
5
null
2021-07-28T11:39:25
2011-08-25T11:18:56
C
UTF-8
Python
false
false
2,603
py
# Django settings for example project. import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'src')) DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Zachary Voase', '[email protected]'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = 'dev.sqlite3' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = '' SESSION_ENGINE = "django.contrib.sessions.backends.cache" CACHE_BACKEND = "dummy://" # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Europe/London' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-gb' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = '8@+k3lm3=s+ml6_*(cnpbg1w=6k9xpk5f=irs+&j4_6i=62fy^' EXCEPTIONAL_API_KEY = open("exceptional.key").read().strip() # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'djexceptional.ExceptionalMiddleware', ) ROOT_URLCONF = 'example.urls' TEMPLATE_DIRS = ( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'), ) INSTALLED_APPS = ( 'django.contrib.sessions', 'djexceptional', # So we can run the app tests. )
612bc2e1e4649e4a7d9af7a4aabbdcc5d0eac099
80d50ea48e10674b1b7d3f583a1c4b7d0b01200f
/src/datadog_api_client/v2/model/opsgenie_service_response_attributes.py
5d6473bfa2a5e8c186c521947868485560bb1cad
[ "Apache-2.0", "BSD-3-Clause", "MIT", "MPL-2.0" ]
permissive
DataDog/datadog-api-client-python
3e01fa630278ad0b5c7005f08b7f61d07aa87345
392de360e7de659ee25e4a6753706820ca7c6a92
refs/heads/master
2023-09-01T20:32:37.718187
2023-09-01T14:42:04
2023-09-01T14:42:04
193,793,657
82
36
Apache-2.0
2023-09-14T18:22:39
2019-06-25T22:52:04
Python
UTF-8
Python
false
false
1,920
py
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from __future__ import annotations from typing import Union, TYPE_CHECKING from datadog_api_client.model_utils import ( ModelNormal, cached_property, none_type, unset, UnsetType, ) if TYPE_CHECKING: from datadog_api_client.v2.model.opsgenie_service_region_type import OpsgenieServiceRegionType class OpsgenieServiceResponseAttributes(ModelNormal): @cached_property def openapi_types(_): from datadog_api_client.v2.model.opsgenie_service_region_type import OpsgenieServiceRegionType return { "custom_url": (str, none_type), "name": (str,), "region": (OpsgenieServiceRegionType,), } attribute_map = { "custom_url": "custom_url", "name": "name", "region": "region", } def __init__( self_, custom_url: Union[str, none_type, UnsetType] = unset, name: Union[str, UnsetType] = unset, region: Union[OpsgenieServiceRegionType, UnsetType] = unset, **kwargs, ): """ The attributes from an Opsgenie service response. :param custom_url: The custom URL for a custom region. :type custom_url: str, none_type, optional :param name: The name for the Opsgenie service. :type name: str, optional :param region: The region for the Opsgenie service. :type region: OpsgenieServiceRegionType, optional """ if custom_url is not unset: kwargs["custom_url"] = custom_url if name is not unset: kwargs["name"] = name if region is not unset: kwargs["region"] = region super().__init__(kwargs)
3e40c665d4a08a20bf0af0dfd2e3714d906f4c00
8ab61e98b8b4efa7378ad50ee12ea5ec81b8c310
/thredo/requests.py
6891e62a04fde54970e922350c53ce1b8bc23643
[ "MIT" ]
permissive
RalphWalters/thredo
5a791d0848067e2b028c3040874476d582509543
ea109c693036764dd192527f9b6bba18d3b18042
refs/heads/master
2020-04-05T05:18:56.942365
2018-11-08T23:25:54
2018-11-08T23:25:54
156,589,958
1
0
MIT
2018-11-07T18:21:27
2018-11-07T18:21:27
null
UTF-8
Python
false
false
2,746
py
# requests.py # # Session adapter that allows requests to use thredo socket objects. # This is a bit of plumbing, but it's a clean interface that doesn't # require any monkeypatching or other low-level magic __all__ = ['get_session'] # -- Thredo from . import socket # -- Requests/third party import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3 import PoolManager, HTTPConnectionPool from requests.packages.urllib3 import HTTPSConnectionPool from http.client import HTTPConnection, HTTPSConnection class ThredoAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block): self.poolmanager = ThredoPoolManager(num_pools=connections, maxsize=maxsize, block=block) class ThredoPoolManager(PoolManager): def _new_pool(self, scheme, host, port): # Important! if scheme == 'http': return ThredoHTTPConnectionPool(host, port, **self.connection_pool_kw) if scheme == 'https': return ThredoHTTPSConnectionPool(host, port, **self.connection_pool_kw) return super(PoolManager, self)._new_pool(self, scheme, host, port) class ThredoHTTPConnectionPool(HTTPConnectionPool): def _new_conn(self): self.num_connections += 1 return ThredoHTTPConnection(host=self.host, port=self.port) class ThredoHTTPSConnectionPool(HTTPSConnectionPool): def _new_conn(self): self.num_connections += 1 return ThredoHTTPSConnection(host=self.host, port=self.port) class ThredoHTTPConnection(HTTPConnection): def connect(self): """Connect to the host and port specified in __init__.""" # Uses thredo self.sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) # Important! if self._tunnel_host: self._tunnel() class ThredoHTTPSConnection(HTTPSConnection): def connect(self): """Connect to the host and port specified in __init__.""" # Uses thredo self.sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) # Important! if self._tunnel_host: server_hostname = self._tunnel_host else: server_hostname = self.host self.sock = self._context.wrap_socket(self.sock, server_hostname=server_hostname) def get_session(): s = requests.Session() s.mount('http://', ThredoAdapter()) s.mount('https://', ThredoAdapter()) return s
7cbb1ee16366420627e8f8f83747002cf7163930
f30b91db647dca1f77fffa4b7e26b6c6a68abbc6
/8_kyu/Who is going to pay for the wall/test_who_is_paying.py
3d95d5e8ac506893d12e7e9d460f4df00a45d1e8
[]
no_license
estraviz/codewars
73caf95519eaac6f34962b8ade543bf4417df5b7
5f8685e883cb78381c528a0988f2b5cad6c129c2
refs/heads/master
2023-05-13T07:57:43.165290
2023-05-08T21:50:39
2023-05-08T21:50:39
159,744,593
10
55
null
null
null
null
UTF-8
Python
false
false
354
py
from who_is_paying import who_is_paying def test_who_is_paying(): assert who_is_paying("Mexico") == ["Mexico", "Me"] assert who_is_paying("Melania") == ["Melania", "Me"] assert who_is_paying("Melissa") == ["Melissa", "Me"] assert who_is_paying("Me") == ["Me"] assert who_is_paying("") == [""] assert who_is_paying("I") == ["I"]
94d0d82808b7bba21ce96fec06a1c65195e30c94
6343f30acc402f655dc5c89baeb2e0be69d0d561
/manage.py
85c69964a47c933ab9731577553efc751e8f6c9d
[]
no_license
manchos/rd90-rest
724ab162a1041a9e0c90617be0f900fec2f3e542
a86c49e427d96366fa61fb4e09e6e9bd252d1e3d
refs/heads/master
2021-01-20T21:35:26.130896
2017-08-29T14:46:36
2017-08-29T14:46:36
101,772,749
0
0
null
null
null
null
UTF-8
Python
false
false
806
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rd90rest.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
7e6b93f712239743b62500083227e02253458129
92993cff825da80a8ff601572a0c52b0b7d3cbde
/algorithms/Svm/ADMM/L2/ADMM_L2_m43.py
abb30b1ac1a4beb3a53b43d81d55a8428c66bbb9
[]
no_license
yingzhuoy/MRs-of-linear-models
06e8b1f84b08c6aa77553813824cf35c1806c5a7
c3df8299e039a12613f2022b370b8c3e9c2dd822
refs/heads/master
2023-04-07T23:09:37.736952
2021-04-04T05:33:37
2021-04-04T05:33:37
265,124,549
0
0
null
null
null
null
UTF-8
Python
false
false
4,061
py
import numpy as np from numpy import linalg #import cvxopt #from cvxopt import matrix,solvers from algorithms.clf import Clf """ Preconditioned Conjugate Gradient Method """ def precond(M, r): q = M * r return q def inner_prod(A, B): A = np.matrix(A) B = np.matrix(B) return np.dot(A.reshape(-1,1).T, B.reshape(-1,1)) def cg(A, b, x=None, tol=1.0e-6, max_iter=128): # precondition A = np.matrix(A) b = np.matrix(b) normb = np.linalg.norm(b, 'fro') m = b.shape[0] M = np.eye(m) x = np.zeros((m, m)) Aq = (A*x) r = b - Aq # m x m q = precond(M, r) # m x m tau_old = np.linalg.norm(q, 'fro') rho_old = inner_prod(r, q) theta_old = 0 Ad = np.zeros((m, m)) d = np.zeros((m, m)) res = r.reshape(m, m) tiny = 1e-30 for i in range(max_iter): Aq = A * q sigma = inner_prod(q, Aq) if abs(sigma.item()) < tiny: break else: alpha = rho_old / sigma; alpha = alpha.item() r = r - alpha * Aq r = r.reshape(m, m) u = precond(M, r) theta = np.linalg.norm(u,'fro')/tau_old c = 1 / np.sqrt(1+theta*theta) #----bug---- #tau = tau_old * theta * c tau = tau_old / theta * c gam = c*c*theta_old*theta_old eta = c*c*alpha d = gam * d + eta * q x = x + d # stop Ad = gam*Ad+eta*Aq res = res - Ad if np.linalg.norm(res, 'fro') < tol*normb: break else: rho = inner_prod(r, u) beta = rho / rho_old beta = beta.item() q = u + beta * q rho_old = rho tau_old = tau theta_old = theta return x def admm(X, y, max_iter=5000): # solve by inner point method m, n = X.shape X = np.column_stack((X, np.ones((m, 1)))) y = y.astype(np.float64) data_num = len(y) C = 1.0 kernel = np.dot(X, np.transpose(X)) p = np.matrix(np.multiply(kernel,np.outer(y, y))) + np.diag(np.ones(data_num, np.float64)) * .5/C e = np.matrix(np.ones([data_num, 1], np.float64)) bounds = (0, np.inf) low, up = bounds x = np.ones((m,1)) tau = 1.618 sigma = 1 # initial u = np.ones((m, 1)) t = x A = p + sigma * np.eye(m) I = np.eye(m) invA = cg(A, I) for it in range(max_iter): # update x b = e + u + sigma * t x = invA * b # update y t = x - (1/sigma)*u t[t < low] = low t[t > up] = up # update u u = u - tau*sigma*(x-t) dual = -(0.5*x.T*(p*x) - e.T*x) dual = dual.item() y1 = np.reshape(y, (-1, 1)) lambda1 = np.multiply(x, y1) w = np.dot(X.T, lambda1) w = np.matrix(w).reshape(-1, 1) tmp = np.maximum(1-np.multiply(y1, X*w),0) primal = 0.5*np.linalg.norm(w)**2 + 1 * np.sum(tmp) primal = primal.item() # stop criteria if np.abs(dual-primal)/(1+np.abs(dual)+np.abs(primal)) < 1e-12: break # print(t, np.linalg.norm(gradient)) # print(np.min(x), np.max(x)) # print(np.sum(x < -1e-4), np.sum(x>1+1e-4)) # print(np.abs(dual-primal)/(1+np.abs(dual)+np.abs(primal))) y1 = np.reshape(y, (-1, 1)) alpha1 = x lambda1 = np.multiply(y1,alpha1) w = np.dot(X.T, lambda1) w = np.array(w).reshape(-1) b = w[n] w = w[0:n] return w, b #L2-svm class ADMM_L2_m43(): def fit(self, X, y): y[y == 0] = -1 # add logitR to verify the correctness #from sklearn.svm import LinearSVC #SVM = LinearSVC(loss='squared_hinge', tol=1e-6, max_iter=100000, verbose=1).fit(X, np.array(y).ravel()) #w1 = SVM.coef_; b1 = SVM.intercept_ #w1 = w1.reshape(-1); b1 = b1[0] w, b = admm(X, y) #print('diff', np.linalg.norm(w1-w), b, b1) clf = Clf(w, b) return clf
e7e2dee5d2d5cf21363e6875097b7870703e164a
fa60618b9f68aee452b278c6efb6300e50d90dbc
/py_demo/默尼森数.py
3ef57dd22c062c2bb03ddc9a5ffa9c3545cb59a4
[]
no_license
ALICE5/Python
668feaaf87e88df0d14252c0fcbc8c5b479cb7c8
6b2037bd3e6fa5689f355a128739343779d28fe5
refs/heads/master
2021-01-01T16:26:57.170646
2017-09-18T09:31:30
2017-09-18T09:31:30
97,832,226
0
0
null
null
null
null
UTF-8
Python
false
false
718
py
# Judge a number is a prime or not import math def isPrime(x): if x==1: return False k = int(math.sqrt(x)) for j in range(2, k+1): if x % j == 0: return False return True # Generate the num Prime def prime(num): if num == 1: return 2 k = 1 i = 1 while(k<num): i += 2 if(isPrime(i)==True): k += 1 return i # Generate the no Monisen def Monisen(no): k = 0 i = 1 m = 0 while(k<no): p=prime(i) m = 2**p-1 if(isPrime(m)==True): k+=1 i+=1 return m if __name__ == '__main__': print(Monisen(6)) # print(Monisen(int(input('Please input the number:'))))
044b87731f9adbeed2e6e296cf4226b7b2b50499
51804f7ed108b355e979f9e67018a4f8b2a46df6
/py-scripts/tsqx.py
8124bc4f79892006a8dfff5e56f135e22ecde59e
[ "BSL-1.0" ]
permissive
vEnhance/dotfiles
5b36652c9f6ce0b368d7833f43018ba94f1dc8f1
47045aaf7054bc8efe657d1e9e070e6b27652c64
refs/heads/main
2023-08-31T16:01:14.814010
2023-08-30T21:52:40
2023-08-30T21:52:40
47,777,946
119
174
BSL-1.0
2023-07-20T11:53:06
2015-12-10T17:46:56
Python
UTF-8
Python
false
false
14,069
py
# st######### ## TSQX ## ########## # original TSQX by CJ Quines: https://github.com/cjquines/tsqx # original TSQ by evan chen import re import sys from io import TextIOWrapper from typing import Any, Generator, TextIO, TypedDict def generate_points(kind, n) -> list[str]: if kind == "triangle": return ["dir(110)", "dir(210)", "dir(330)"] elif kind == "regular": return [f"dir({(90 + i*360/n) % 360})" for i in range(n)] raise SyntaxError("Special command not recognized") T_TOKEN = str | list[str] | list["T_TOKEN"] class T_OCR(TypedDict): # op, comment, raw op: "Op" comment: str raw: str GENERIC_PREAMBLE = r""" usepackage("amsmath"); usepackage("amssymb"); settings.tex="pdflatex"; settings.outformat="pdf"; // Replacement for olympiad+cse5 which is not standard import geometry; // recalibrate fill and filldraw for conics void filldraw(picture pic = currentpicture, conic g, pen fillpen=defaultpen, pen drawpen=defaultpen) { filldraw(pic, (path) g, fillpen, drawpen); } void fill(picture pic = currentpicture, conic g, pen p=defaultpen) { filldraw(pic, (path) g, p); } // some geometry pair foot(pair P, pair A, pair B) { return foot(triangle(A,B,P).VC); } pair orthocenter(pair A, pair B, pair C) { return orthocentercenter(A,B,C); } pair centroid(pair A, pair B, pair C) { return (A+B+C)/3; } // cse5 abbreviations path CP(pair P, pair A) { return circle(P, abs(A-P)); } path CR(pair P, real r) { return circle(P, r); } pair IP(path p, path q) { return intersectionpoints(p,q)[0]; } pair OP(path p, path q) { return intersectionpoints(p,q)[1]; } path Line(pair A, pair B, real a=0.6, real b=a) { return (a*(A-B)+A)--(b*(B-A)+B); } size(%s); """.strip() ARITHMETIC_OPERATORS = {"plus": "+", "minus": "-", "mult": "*", "divide": "/"} class Op: exp: T_TOKEN def _join_exp(self, exp: T_TOKEN, join_str: str) -> str: return join_str.join(self._emit_exp(e) for e in exp) def _emit_exp(self, exp: T_TOKEN) -> str: if not isinstance(exp, list): return exp if "," in exp: return f"({self._join_exp(exp, ' ')})" head, *tail = exp if not tail: return self._emit_exp(head) if isinstance(head, list) else head elif tail[0] in ["--", "..", "^^"]: return self._join_exp(exp, ", ") elif (binop := ARITHMETIC_OPERATORS.get(str(head))) is not None: return "(" + self._join_exp(tail, binop) + ")" else: return f"{head}({self._join_exp(tail, ', ')})" def emit_exp(self) -> str: res = self._join_exp(self.exp, "*") for j in ["--", "..", "^^"]: res = res.replace(f", {j}, ", j) return res def emit(self): raise Exception("Operation not recognized") def post_emit(self): return None class Blank(Op): def emit(self): return "" class DirectCommand(Op): def __init__(self, exp: str): self.exp = exp def emit(self): return self.exp def post_emit(self): return None class Point(Op): def __init__( self, name: str, exp: T_TOKEN, dot=True, label="", direction="", ): self.name = name self.exp = exp self.dot = dot self.label = name if label else None if self.label: self.label = self.label.replace("_prime", "'") self.label = self.label.replace("_asterisk", r"^{\ast}") self.direction = direction or f"dir({name})" def emit(self) -> str: return f"pair {self.name} = {self.emit_exp()};" def post_emit(self): args = [self.name] if self.label: args = [f'"${self.label}$"', *args, self.direction] if self.dot: return f"dot({', '.join(args)});" if len(args) > 1: return f"label({', '.join(args)});" return "" class Draw(Op): def __init__( self, exp: T_TOKEN, fill: str | None = None, outline: str | None = None, ): self.exp = exp self.fill = fill self.outline = outline def emit(self): exp = self.emit_exp() if self.fill: outline = self.outline or "defaultpen" return f"filldraw({exp}, {self.fill}, {outline});" elif self.outline: return f"draw({exp}, {self.outline});" else: return f"draw({exp});" class Parser: def __init__(self, soft_label: str | None = None, **_: Any): self.soft_label = soft_label self.alias_map = {"": "dl", ":": "", ".": "d", ";": "l"} if self.soft_label: self.alias_map |= {"": "l", ";": "dl"} self.aliases = self.alias_map.keys() | self.alias_map.values() def tokenize(self, line: str) -> list[T_TOKEN]: line = line.strip() + " " for old, new in [ # ~ and = are separate tokens ("~", " ~ "), ("=", " = "), # for tsqx syntax processing ("(", "( "), (")", " ) "), (",", " , "), # spline joiners ("--", " -- "), ("..", " .. "), ("^^", " ^^ "), # no spaces around asymptote arithmetic (" +", "+"), ("+ ", "+"), ("- ", "-"), (" *", "*"), ("* ", "*"), # but slashes in draw ops should remain tokens (" / ", " / "), (" /", "/"), ("/ ", "/"), # ' not allowed in variable names ("'", "_prime"), ("&", "_asterisk"), ]: line = line.replace(old, new) return list(filter(None, line.split())) def parse_subexp( self, tokens: list[T_TOKEN], idx: int, func_mode=False, ) -> tuple[T_TOKEN, int]: token = tokens[idx] if token[-1] == "(": is_func = len(token) > 1 res: list[T_TOKEN] = [] idx += 1 if is_func: res.append(token[:-1]) while tokens[idx] != ")": exp, idx = self.parse_subexp(tokens, idx, is_func) res.append(exp) return res, idx + 1 if token == "," and func_mode: return "", idx + 1 return token, idx + 1 def parse_exp(self, tokens: list[T_TOKEN]): if tokens[0][-1] != "(" or tokens[-1] != ")": tokens = ["(", *tokens, ")"] res: list[T_TOKEN] = [] idx = 0 while idx != len(tokens): try: exp, idx = self.parse_subexp(tokens, idx) res.append(list(filter(None, exp))) except IndexError: raise SyntaxError(f"Unexpected end of line: {tokens}") return res def parse_special( self, tokens: list[T_TOKEN], comment: str | None, raw_line: str, ) -> Generator[T_OCR, None, None]: if not tokens: raise SyntaxError("Can't parse special command") head, *tail = tokens if comment is not None: yield {"op": Blank(), "comment": comment, "raw": raw_line} if head in ["triangle", "regular"]: for name, exp in zip(tail, generate_points(head, len(tail))): assert isinstance(name, str) yield {"op": Point(name, [exp]), "comment": "", "raw": raw_line} return else: raise SyntaxError("Special command not recognized") def parse_name(self, tokens: list[T_TOKEN]) -> tuple[str, dict[str, Any]]: if not tokens: raise SyntaxError("Can't parse point name") name, *rest = tokens assert isinstance(name, str) if rest and rest[-1] in self.aliases: *rest, opts = rest assert isinstance(opts, str) else: opts = "" opts = self.alias_map.get(opts, opts) options = {"dot": "d" in opts, "label": name if "l" in opts else None} if rest: dirs, *rest = rest assert isinstance(dirs, str) if m := re.fullmatch(r"([\d\.]+)R([\d\.]+)", dirs): options["direction"] = f"{m.groups()[0]}*dir({m.groups()[1]})" elif dir_pairs := re.findall(r"(\d+)([A-Z]+)", dirs): options["direction"] = "+".join(f"{n}*plain.{w}" for n, w in dir_pairs) elif dirs.isdigit(): options["direction"] = f"dir({dirs})" elif re.fullmatch(r"N?S?E?W?", dirs): options["direction"] = f"plain.{dirs}" else: rest.append(dirs) if "direction" not in options: options["direction"] = f"dir({name})" if rest: raise SyntaxError("Can't parse point name") return name, options def parse_draw(self, tokens: list[T_TOKEN]): try: idx = tokens.index("/") except ValueError: fill_: list[T_TOKEN] = [] outline_ = tokens else: fill_ = tokens[:idx] outline_ = tokens[idx + 1 :] assert all(isinstance(_, str) for _ in outline_) outline: list[str] = [ str(_) for _ in outline_ ] # this is idiotic, what did i miss? fill: list[str] = [] for pen in fill_: assert isinstance(pen, str) if re.fullmatch(r"\d*\.?\d*", pen): fill.append(f"opacity({pen})") else: fill.append(pen) return {"fill": "+".join(fill), "outline": "+".join(outline)} def parse(self, line: str) -> Generator[T_OCR, None, None]: # escape sequence raw_line = line if raw_line.startswith("!"): yield { "op": DirectCommand(line[1:].strip()), "comment": "", "raw": raw_line, } return if "#" in line: line, comment = line.split("#", 1) else: comment = "" tokens = self.tokenize(line) if not tokens: yield {"op": Blank(), "comment": comment, "raw": raw_line} return # special if tokens[0] == "~": yield from self.parse_special(tokens[1:], comment, raw_line) return # point try: idx = tokens.index("=") name, options = self.parse_name(tokens[:idx]) exp = self.parse_exp(tokens[idx + 1 :]) yield { "op": Point(name, exp, **options), "comment": comment, "raw": raw_line, } return except ValueError: pass # draw with options try: idx = tokens.index("/") exp = self.parse_exp(tokens[:idx]) options = self.parse_draw(tokens[idx + 1 :]) yield {"op": Draw(exp, **options), "comment": comment, "raw": raw_line} return except ValueError: pass # draw without options exp = self.parse_exp(tokens) yield {"op": Draw(exp), "comment": comment, "raw": raw_line} return class Emitter: def __init__( self, lines: TextIOWrapper | TextIO, print_=print, **args: Any, ): self.lines = lines self.print = print_ self.preamble = args.get("preamble", False) self.size = args.get("size", "8cm") self.parser = Parser(**args) self.terse = args.get("terse", False) def emit(self): if self.preamble: self.print(GENERIC_PREAMBLE % self.size) ocrs = [ocr for line in self.lines for ocr in self.parser.parse(line)] for ocr in ocrs: self.print( ocr["op"].emit() + (f" //{c}" if (c := ocr["comment"].rstrip()) else "") ) self.print() for ocr in ocrs: if out := ocr["op"].post_emit(): self.print(out) if not self.terse: self.print("") self.print( r"/* -----------------------------------------------------------------+" ) self.print( r"| TSQX: by CJ Quines and Evan Chen |" ) self.print( r"| https://github.com/vEnhance/dotfiles/blob/main/py-scripts/tsqx.py |" ) self.print( r"+-------------------------------------------------------------------+" ) for ocr in ocrs: if x := ocr["raw"].strip(): self.print(x) self.print("*/") def main(): from argparse import ArgumentParser argparser = ArgumentParser(description="Generate Asymptote code.") argparser.add_argument( "-p", "--pre", help="Adds a preamble.", action="store_true", dest="preamble", default=False, ) argparser.add_argument( "fname", help="Read from file rather than stdin.", metavar="filename", nargs="?", default="", ) argparser.add_argument( "-s", "--size", help="Set image size in preamble.", action="store", dest="size", default="8cm", ) argparser.add_argument( "-b", "--soft-label", help="Don't draw dots on points by default.", action="store_true", dest="soft_label", default=False, ) argparser.add_argument( "-t", "--terse", help="Hide the advertisement and orig source", action="store_true", dest="terse", default=False, ) args = argparser.parse_args() stream = open(args.fname, "r") if args.fname else sys.stdin emitter = Emitter(stream, print, **vars(args)) emitter.emit() if __name__ == "__main__": main()
2b2a6d1bc2ac3e00c7327b4266870bcecb87ea3b
6d36b40aa5a2fdfd068731b7ee657ec25279bdec
/uncluster/cluster_distributions/gnedin.py
9821ec84c3c8a1c3e62379f581f647ecf90cdfd8
[ "MIT" ]
permissive
adrn/uncluster
5efee493c4319e4e0d07615fb6da6dbdcb172301
0e487f7cc17426bbd03ff1f02000bc3437075ab3
refs/heads/master
2021-04-30T18:30:48.693052
2017-02-21T14:08:54
2017-02-21T14:08:54
63,977,520
0
0
null
null
null
null
UTF-8
Python
false
false
3,605
py
from __future__ import division, print_function __author__ = "adrn <[email protected]>" # Third-party import astropy.units as u import numpy as np from scipy.special import gammainc from scipy.interpolate import InterpolatedUnivariateSpline from scipy.misc import derivative from ..config import M_min, M_max __all__ = ['gc_prob_density', 'sample_masses', 'sample_radii'] def _sersic_frac_mass_enclosed(r, n_s=2.2, R_e=4.): """ This was adapted from Oleg's C code (uncluster/src/gc_evolution.c). For the Milky Way, the parameters (r_s, n_s, etc.) don't evolve and z=0. """ a_n = 2 * n_s b_n = 2. * n_s - 1./3. + 0.0098765/n_s + 0.0018/n_s**2 # approximation from Ciotti ...something # rmax = r_max.to(u.kpc).value # argc = b_n * (rmax/R_e) ** (1./n_s) # gamnorm = gammainc(a_n, argc) gamnorm = 1. # r_max = infinity arg = b_n * (r/R_e)**(1./n_s) return gammainc(a_n, arg) / gamnorm # HACK: I need a function to evaluate the density profile, so I do this numerically... # - this does a calculation on import (BAD) but it's very fast (~10s of ms) n_grid = 4096 # MAGIC NUMBER r_grid = np.logspace(-4, 2.5, n_grid) # kpc m_grid = _sersic_frac_mass_enclosed(r_grid) # if necessary, remove duplicate m's where it saturates _idx, = np.where(m_grid >= 1.) if len(_idx) > 1: r_grid = r_grid[:_idx[0]+1] m_grid = m_grid[:_idx[0]+1] dm_dr = np.zeros(n_grid) for i,r in enumerate(r_grid): d = derivative(_sersic_frac_mass_enclosed, r, dx=1E-3*r) dm_dr[i] = d _idx = np.isfinite(dm_dr) & (dm_dr>0.) _interp_ln_dens = InterpolatedUnivariateSpline(r_grid[_idx], np.log(dm_dr[_idx]) - np.log(4*np.pi*r_grid[_idx]**2), k=1) def gc_prob_density(r): r""" Evaluate the **probability** density of the spatial distribtuon of globular clusters following a Hernquist profile. This is *not* the mass-density or number-density, but: .. math:: \nu (r) = \int {\rm d}v \, f(r,v) .. note:: This function computes the density numerically using linear interpolation. Parameters ---------- r : float Radius in kpc. """ return np.exp(_interp_ln_dens(r)) @u.quantity_input(M_min=u.Msun, M_max=u.Msun) def sample_masses(M_min=M_min, M_max=M_max, size=1): r""" Use inverse transform sampling to generate samples from a power-law initial mass distribution with :math:`\beta = -2`: .. math:: p(M) = A M^{-2} M \in [M_{\rm min}, M_{\rm max}] Parameters ---------- M_min : `~astropy.units.Quantity` [mass] The minimum mass or lower-bound for sampling. M_max : `~astropy.units.Quantity` [mass] The maximum mass or upper-bound for sampling. size : int, tuple (optional) The shape of the output array. Returns ------- masses : `~astropy.units.Quantity` [Msun] Masses sampled from the mass function. """ A = 1 / (1/M_min - 1/M_max) R = np.random.uniform(size=size) return 1 / (1/M_min - R/A) def sample_radii(size=1): """ Use inverse transform sampling to generate samples from a Sersic mass profile (following Gnedin et al. 2014). Parameters ---------- size : int, tuple (optional) The shape of the output array. Returns ------- radii : `~astropy.units.Quantity` [kpc] """ interp_func = InterpolatedUnivariateSpline(m_grid, np.log(r_grid), k=1) return np.exp(interp_func(np.random.uniform(0, 1, size=size))) * u.kpc
ea703a24032f314d7e01b11a64fa900fc1c2c605
b7683c108e68ee2d28573edf55923eb34cc2f5ee
/5_Video_Analysis/3_Background_substraction/3_GMG.py
e72711d3c0643816ef3b230ff18d92f712be427c
[]
no_license
aCuissot/openVC_win_py_tutorial
cc42ab1a1fb6eaefe5a91c7e1bb1926a776b0e01
7186b629747cb16f2bf42a03d2339d3dc3ea77bd
refs/heads/master
2020-05-18T12:17:04.619047
2019-07-10T13:45:00
2019-07-10T13:45:00
184,403,715
0
0
null
null
null
null
UTF-8
Python
false
false
454
py
import numpy as np import cv2 as cv cap = cv.VideoCapture('../../Data/in/vtest.avi') kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3)) fgbg = cv.bgsegm.createBackgroundSubtractorGMG() while True: ret, frame = cap.read() fgmask = fgbg.apply(frame) fgmask = cv.morphologyEx(fgmask, cv.MORPH_OPEN, kernel) cv.imshow('frame', fgmask) k = cv.waitKey(30) & 0xff if k == 27: break cap.release() cv.destroyAllWindows()
c74b74d06dfb216f30a2b9bb4f52d9be55005706
429211c01057abcd51e5120d566c7daa0a8e2f33
/1804/二/day4/class4.py
adce94b9a462cd19775068f56485909388f5f106
[]
no_license
LDZ-RGZN/b1804
2788c922a6d1a6dc11267920a90336d1df93a453
c57f8b7cf14686036cae3c30a30f07514622b5ca
refs/heads/master
2021-07-19T12:54:07.031858
2018-10-12T02:48:39
2018-10-12T02:48:39
133,500,880
0
0
null
null
null
null
UTF-8
Python
false
false
1,017
py
import time class cat: def __init__(self,lun_zi,color): self.lunzi = lun_zi self.color = color def pao(self): print ('一辆%d个轮子的%s色%s汽车正在公里上飞驰'%(self.lunzi,self.color,self.name)) def jiao(self): print ('这辆%s汽车正在冲着前面的那辆%s汽车鸣笛'%(self.name,self.name2)) def zw(self): print ('后面的%s汽车成功的追尾了前面的%s汽车,鼓掌'%(self.name,self.name2)) def __str__(self): s = '车的品牌是:'+self.name+' 车的颜色是:'+self.color return s bm = cat(4,'红') bm.name = '宝马' bm.name2 = '奥迪' bm.pao() bm.jiao() print ('请稍等.即将追尾') time.sleep(1) bm.zw() print (bm) print ('内存位置是%d'%(id(bm))) print ('下一波操作即将进行') time.sleep(1) bm1 = cat(8,'蓝') bm1.name = '奥迪' bm1.name2 = '宝马' bm1.pao() bm1.jiao() print ('请稍等.即将追尾') time.sleep(1) bm1.zw() print (bm1) print ('内存位置是%d'%(id(bm1)))
a06b0f3b510d0fcfa322e082ae0570ff938b9e68
e393cb9a1a67a5c944e7a5cf72a7f230caa4f1a7
/estimation_matlab.py
1f6702e2e95443588c03beaa937fc09db6982a91
[]
no_license
AndreyGorbatov1/Jacobian-Estimation
5f6ec4251235af3bc05ea52aa8c3efd7d3947fb8
caec92965a7a9837ac777c9ca082468433c14cba
refs/heads/master
2023-03-10T18:19:27.478542
2018-08-30T13:02:00
2018-08-30T13:02:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,953
py
from keras.layers import Input, Dense, Dropout, BatchNormalization, PReLU, LeakyReLU from keras.models import Model, Sequential from keras import optimizers from keras import regularizers import numpy from scipy.io import loadmat import tensorflow as tf from sklearn.preprocessing import normalize, scale from sklearn.metrics import r2_score from sklearn.preprocessing import minmax_scale from datetime import datetime import pandas as pd import shutil import keras import json import sys import os from sklearn.metrics import r2_score #a=pd.read_csv('featureTrain.csv' ,dtype='double') #print(a) import tensorflow as tf def huber_loss(y_true, y_pred): return tf.losses.huber_loss(y_true,y_pred) sys.path.append('/home/alexanderliao/data/GitHub/') from kerasresnet import resnet def nn_1(input_length): model = Sequential() model = Sequential() model.add(Dense(32, input_dim=input_length, kernel_initializer='RandomUniform')) ##model.add(BatchNormalization()) model.add(LeakyReLU()) #model.add(Dropout(0.25)) model.add(Dense(64, input_dim=32, kernel_initializer='RandomUniform')) ##model.add(BatchNormalization()) model.add(LeakyReLU()) #model.add(Dropout(0.25)) model.add(Dense(128, input_dim=64, kernel_initializer='RandomUniform')) ##model.add(BatchNormalization()) model.add(LeakyReLU()) #model.add(Dropout(0.25)) model.add(Dense(256, input_dim=128, kernel_initializer='RandomUniform')) #model.add(BatchNormalization()) model.add(LeakyReLU()) #model.add(Dropout(0.25)) model.add(Dense(512, input_dim=256, kernel_initializer='RandomUniform')) model.add(BatchNormalization()) model.add(LeakyReLU()) model.add(Dropout(0.5)) model.add(Dense(1050, input_dim=512, kernel_initializer='RandomUniform')) model.add(BatchNormalization()) model.add(LeakyReLU()) model.add(Dropout(0.5)) model.add(Dense(2150, input_dim=1050, kernel_initializer='RandomUniform')) model.add(BatchNormalization()) model.add(LeakyReLU()) model.add(Dropout(0.5)) model.add(Dense(1050, input_dim=2150, kernel_initializer='RandomUniform')) model.add(BatchNormalization()) model.add(LeakyReLU()) model.add(Dropout(0.5)) model.add(Dense(512, input_dim=1050, kernel_initializer='RandomUniform')) model.add(BatchNormalization()) model.add(LeakyReLU()) model.add(Dropout(0.5)) model.add(Dense(512, input_dim=1024, kernel_initializer='RandomUniform')) model.add(BatchNormalization()) model.add(LeakyReLU()) model.add(Dropout(0.5)) model.add(Dense(512, input_dim=512, kernel_initializer='RandomUniform')) model.add(BatchNormalization()) model.add(LeakyReLU()) model.add(Dropout(0.5)) model.add(Dense(256, input_dim=512, kernel_initializer='RandomUniform')) #model.add(BatchNormalization()) model.add(LeakyReLU()) #model.add(Dropout(0.5)) model.add(Dense(128, input_dim=256, kernel_initializer='RandomUniform')) ##model.add(BatchNormalization()) model.add(LeakyReLU()) #model.add(Dropout(0.5)) model.add(Dense(64, input_dim=128, kernel_initializer='RandomUniform')) ##model.add(BatchNormalization()) model.add(LeakyReLU()) #model.add(Dropout(0.5)) model.add(Dense(32, input_dim=64, kernel_initializer='RandomUniform')) ##model.add(BatchNormalization()) model.add(Dense(25, activation="linear")) #Dense(64, input_dim=24, kernel_initializer="RandomUniform")` opt = optimizers.SGD(lr=0.001, momentum=0.9, decay=0.0001, nesterov=False) model.compile(optimizer="adam", loss="mean_squared_error") #model.compile(optimizer="adam", loss="softmax") return model def routine(Ytest,nn_predictor): acc=r2_score(Ytest,nn_predictor.predict(Xtest)) print(acc) string=str(datetime.now()).replace(".","").replace(" ","")+'-'+str(round(acc,2)) nn_predictor.save(string+'.model') shutil.move(string+'.model','./models/'+string+'.model') #print(r2_score(Ytest,nn_predictor.predict(Xtest))) return string def baseline(Ytest,nn_predictor): acc=r2_score(Ytest,nn_predictor.predict(Xtest)) print(acc) string="jacob_baseline" nn_predictor.save(string+'.model') #shutil.move(string+'.model','./models/'+string+'.model') #print(r2_score(Ytest,nn_predictor.predict(Xtest))) return string if __name__ == "__main__": """ Xtrain=scale(pd.read_csv('featureTrain.csv' ,dtype='double').dropna(axis=1),axis=0) Ytrain=pd.read_csv('labelTrain.csv' ,dtype='double').dropna(axis=1) Xtest=scale(pd.read_csv('featureTest.csv' ,dtype='double').dropna(axis=1),axis=0) Ytest=pd.read_csv('labelTest.csv' ,dtype='double').dropna(axis=1) """ print("Reading training data...") Xtrain=pd.read_csv('data/jacob_feature_train.csv' ,dtype='double') Xtrain=scale(Xtrain.dropna(axis=1).loc[:, ~(Xtrain == 0).any(0)]) #Xtrain=Xtrain[0:k,:] #Xtrain=Xtrain.reshape((-1,1,len(Xtrain[0,:]),1)) #Xtrain=Xtrain.reshape((k,2,-1,1)) print(" ") print("Sanity Check:") print(Xtrain) Ytrain=pd.read_csv('data/jacob_label_train.csv' ,dtype='double').dropna(axis=1) Ytrain=minmax_scale(Ytrain.loc[:, ~(Ytrain == 0).any(0)],feature_range=(-1,1)) print("Done!") #Ytrain=Ytrain.values.reshape((-1,1)) #Ytrain=Ytrain[0:k,:] print("Reading test data...") Xtest=pd.read_csv('data/jacob_feature_test.csv' ,dtype='double') Xtest=scale(Xtest.dropna(axis=1).loc[:, ~(Xtest == 0).any(0)]) #Xtest=Xtest.reshape((-1,1,len(Xtest[0,:]),1)) #Xtest=Xtest.reshape((300,2,-1,1)) Ytest=pd.read_csv('data/jacob_label_test.csv' ,dtype='double').dropna(axis=1) Ytest=minmax_scale(Ytest.loc[:, ~(Ytest == 0).any(0)],feature_range=(-1,1)) print("Done!") #Ytest=Ytest.values.reshape((-1,1)) #Ytest=Ytest[0:k,:] # fix random seed for reproducibility numpy.random.seed(7) #print("Seed: {}".format(numpy.random.seed(7))) #Xtrain=numpy.nonzero(numpy.loadtxt('featureTrain.csv',dtype='float32',delimiter=',')) #Ytrain=numpy.loadtxt('labelTrain.csv',dtype='float32',delimiter=',') #Xtrain=Xtrain[1:30000,:] #Ytrain=Ytrain[1:30000,:] #Ytrain=minmax_scale(Ytrain, feature_range=(0, 1), axis=0, copy=True) #Xtrain=normalize(Xtrain,axis=1) #Xtrain = scale( Xtrain, axis=0, with_mean=True, with_std=True, copy=True ) #Ytrain = scale( Ytrain, axis=0, with_mean=True, with_std=True, copy=True ) #print(type(Xtrain)) #print(Ytrain.shape) #Xtest=numpy.nonzero(numpy.loadtxt('featureTest.csv',dtype='float32',delimiter=',')) #Ytest=numpy.loadtxt('labelTest.csv',dtype='float32',delimiter=',') #Xtest=Xtest[1:30000,:] #Ytest=Ytest[1:30000,:] #Ytest=minmax_scale(Ytest, feature_range=(0, 1), axis=0, copy=True) #Xtest=normalize(Xtest,axis=1) #Xtest = scale( Xtest, axis=0, with_mean=True, with_std=True, copy=True ) #Ytest = scale( Ytest, axis=0, with_mean=True, with_std=True, copy=True ) #print(type(Xtrain)) #print(type(Ytrain)) #nn_predictor=resnet.ResnetBuilder().build_resnet_18([1,1,14],1) #nn_predictor=resnet.ResnetBuilder().build([1,1,14],1,'basic_block',8) #print(nn_predictor.input_shape) #print(nn_predictor.output_shape) opt = optimizers.RMSprop(lr=0.01) #nn_predictor.compile(optimizer="adadelta", loss="binary_crossentropy") nn_predictor = nn_1(len(Xtrain[0,:])) print(len(Xtrain[0,:])) print(nn_predictor.summary()) print("Cleaning directories...") os.system("rm -r graph") os.system("mkdir graph") b_size = 4096 epoch = 750 val_split = 0.2 model_checkpoint = keras.callbacks.ModelCheckpoint("./est_matlab.hdf5", save_best_only=True, verbose=1) reduce_lr = keras.callbacks.ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.00001, verbose=1) tensorboard=keras.callbacks.TensorBoard(log_dir='./graph', histogram_freq=0, write_graph=True, write_images=True) callbacks = [model_checkpoint,tensorboard] with tf.device('/gpu:0'): try: print(Ytrain.shape) print(Xtrain.shape) print("Batch Size: {}".format(b_size) ) print("Epochs: {}".format(epoch) ) print("Validation Split: {}".format(val_split) ) history=nn_predictor.fit(Xtrain,Ytrain, batch_size=b_size, epochs=epoch, validation_split=val_split,verbose=1, callbacks=callbacks, shuffle=True) nn_predictor.save("est_matlab.hdf5") with open('./est_matlab_hist', 'wb') as file_pi: pickle.dump(history.history, file_pi) print(type(history)) #baseline(Ytest,nn_predictor) string=routine(Ytest,nn_predictor) json.dump(history.history, open( string+".json", "w" )) shutil.move(string+'.json','./histories/'+string+'.pickle') except (KeyboardInterrupt, SystemExit): routine(Ytest,nn_predictor) #baseline(Ytest,nn_predictor) #print(nn_predictor.predict([0.15,0.4318,0.4318,0.0203,1.5708,-1.5708,1.5708,-1.5708,0,17.4,4.8,0.82,0.34,0.09,0.3638,0.006,0.2275,-0.0203,-0.0141,0.07,0,0.019,0,0,0,0,0,0,0.032]))
aa37b24dc0979c643a0174561ca08482a852901f
f8d2521a88e465eed01adc3981c7a173d5c2554b
/round/round0326-0350/round0335/c1.py
0851e5dcae97aadd46d36170be48457946510b85
[]
no_license
clarinet758/codeforces
b2a8a349bba40e7761a8ce50dd5ff9a57477b60d
d79870c47bdb109547891a0d076dd173d6d647cf
refs/heads/main
2021-12-15T05:46:51.000160
2021-12-01T12:01:33
2021-12-01T12:01:33
41,968,658
1
0
null
null
null
null
UTF-8
Python
false
false
873
py
#!/usr/bin/env python # -*- coding: UTF-8 -*- import time import sys import io import re import math import itertools import collections import bisect #sys.stdin=file('input.txt') #sys.stdout=file('output.txt','w') #10**9+7 mod=1000000007 #mod=1777777777 pi=3.141592653589 IS=float('inf') xy=[(1,0),(-1,0),(0,1),(0,-1)] bs=[(-1,-1),(-1,1),(1,1),(1,-1)] def niten(a,b): return abs(a-b) if a>=0 and b>=0 else a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b)) def gcd(a,b): return a if b==0 else gcd(b,a%b) def lcm(a,b): return a*b/gcd(a,b) def euclid_dis(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5 def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0 n=int(raw_input()) l=map(int,raw_input().split()) a=[0]*(n+1) for i in l: a[i]=a[i-1]+1 print n-max(a) ans=chk=0 #end = time.clock() #print end - start
28a3bfc7da27cf64ba42e18b5e5435e5e8ca427d
bd9d82f616f8658d8431bedaed524647f0f2d7a5
/commands/delete_empty_dirs_fm.py
d0a52082cf2bf783c1e5d20a8dccb62bdb85588d
[]
no_license
alclass/PyMirrorFileSystemsByHash
d4331523e9948c119f98c248ca3daf3a71eb8f0b
d59d35dfef5107183309fde825ab082fbb4dc465
refs/heads/master
2023-02-20T15:38:24.432268
2023-02-17T20:58:39
2023-02-17T20:58:39
49,807,870
0
0
null
2021-12-12T21:31:28
2016-01-17T07:40:28
Python
UTF-8
Python
false
false
1,232
py
#!/usr/bin/env python3 """ delete_empty_dirs_fm.py Deletes / removes empty directory in the target dirtree. Usage: $delete_empty_dirs_fm.py <prunepath> Example: $delete_empty_dirs_fm.py "/Science/Physics/Einsteinian Relativity" Explanation: The above (hypothetical) example will remove all empty directories inside folder "Einsteinian Relativity". """ import os import sys import default_settings as defaults import fs.dirfilefs.dir_n_file_fs_mod as df def show_help_cli_msg_if_asked(): for arg in sys.argv: if arg in ['-h', '--help']: print(__doc__) sys.exit(0) def prune_dirtree_from_prunepath(prunepath): if not os.path.isdir(prunepath): error_msg = 'Error: prunepath (%s) is not a directory' % prunepath raise OSError(error_msg) n_visited, n_removed, n_failed = df.prune_dirtree_deleting_empty_folders(prunepath) print('Report delete_empty_dirs_fm.py') print('prune path', prunepath) print('n_visited =', n_visited, 'n_removed =', n_removed, 'n_failed =', n_failed) def process(): """ """ show_help_cli_msg_if_asked() prunepath, _ = defaults.get_src_n_trg_mountpath_args_or_default() prune_dirtree_from_prunepath(prunepath) if __name__ == '__main__': process()
5d77d8ac4fa0e33cef967a4ca48b0dde1c4f790f
b3729186993105603a77016d6a911932fec06630
/recruiters/admin.py
eaa3ca4b800202fd737efd8323b6ab526769977c
[]
no_license
MichalDrosio/grades
05425498bbee3873ebe7128f96227491861b1395
a6fa146ef1ac06f23f423eaf2de43c23f0faf754
refs/heads/main
2022-12-30T06:31:04.100722
2020-10-16T13:22:10
2020-10-16T13:22:10
302,673,025
0
0
null
null
null
null
UTF-8
Python
false
false
217
py
from django.contrib import admin from recruiters.models import Recruiter # Register your models here. @admin.register(Recruiter) class RecruiterAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name']
ddeb531997001b9fb93293cd39b1753ce9651b68
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03829/s592787585.py
ebd0d0601946a683251cf998983ed53be8aa1d91
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
691
py
#!/usr/bin/env python3 import sys INF = float("inf") def solve(N: int, A: int, B: int, X: "List[int]"): tot = 0 for i in range(N-1): sub = X[i+1]-X[i] if sub*A < B: tot += sub*A else: tot += B print(tot) return def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int A = int(next(tokens)) # type: int B = int(next(tokens)) # type: int X = [int(next(tokens)) for _ in range(N)] # type: "List[int]" solve(N, A, B, X) if __name__ == '__main__': main()
f374c7cef3de091b5e831f7f98e75da674e18e19
003ffcf8144565404636f3d74590a8d6b10a90a4
/236-lowest-common-ancestor-of-a-binary-tree/236-lowest-common-ancestor-of-a-binary-tree.py
60b7ab8908ab9f3753694aa14207fbaaac761668
[]
no_license
congve1/leetcode
fb31edf93049e21210d73f7b3e7b9b82057e1d7a
ce1e802b5052da2cdb919d6d7e39eed860e0b61b
refs/heads/master
2020-05-13T19:19:58.835432
2019-05-06T00:44:07
2019-05-06T00:44:07
181,652,371
0
0
null
null
null
null
UTF-8
Python
false
false
411
py
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """
54c8b17645a160598c0851c1e30eb074dbff22f8
1398346d986f4b3b79a557854ec9293690a20cc7
/Tools/BuildSlaveSupport/ews-app/ews/urls.py
2010c72b63e80288c93f9af2c823b33a8e6abc3d
[]
no_license
feltnerm/webkit
49607fc29ccb2082654f6a5eb97e4f51c78527d5
f50e47081541dcf3f69bcfc36d55867441aa3325
refs/heads/master
2023-03-18T08:41:03.727396
2020-02-10T21:14:39
2020-02-10T21:14:39
239,619,580
1
0
null
2020-02-10T21:43:21
2020-02-10T21:43:20
null
UTF-8
Python
false
false
2,056
py
# Copyright (C) 2018-2019 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 django.conf.urls import url from ews.views.index import Index from ews.views.results import Results from ews.views.statusbubble import StatusBubble from ews.views.retrypatch import RetryPatch from ews.views.submittoews import SubmitToEWS app_name = 'ews' urlpatterns = [ # ex: / url(r'^$', Index.as_view(), name='index'), # ex: /results/ url(r'^results/$', Results.as_view(), name='results'), # ex: /retry/ url(r'^retry/$', RetryPatch.as_view(), name='retrypatch'), # ex: /status-bubble/5 url(r'^status-bubble/(?P<patch_id>[0-9]+)/$', StatusBubble.as_view(), name='statusbubble'), # ex: /submit-to-ews/ url(r'^submit-to-ews/$', SubmitToEWS.as_view(), name='submittoews'), ]
[ "[email protected]@268f45cc-cd09-0410-ab3c-d52691b4dbfc" ]
[email protected]@268f45cc-cd09-0410-ab3c-d52691b4dbfc
3815b2c20d699b436ba4bc74ed8c267903c0ac7b
ddcf878cca43d49f73fd673279a97e82ced521e8
/examples/phylesystem/ott_status_report.py
0fd8436424d6ce7f141fc38e84a759947ba49e8f
[ "BSD-2-Clause", "Python-2.0" ]
permissive
OpenTreeOfLife/peyotl
ca5fcbc4f1754c3da7a25c93d89cfeaaad17057f
b50f7217966c18195c9b52be42454513ffa3e7f3
refs/heads/master
2023-08-03T14:35:46.793662
2023-07-26T20:30:08
2023-07-26T20:30:08
16,637,087
6
4
BSD-2-Clause
2023-07-24T20:02:30
2014-02-08T05:52:12
Jupyter Notebook
UTF-8
Python
false
false
2,568
py
#!/usr/bin/env python """Trying to make a report that corresponds to https://github.com/OpenTreeOfLife/germinator/wiki/Overview-of-repository-statistics """ import time start_clock = time.time() from peyotl.phylesystem.phylesystem_umbrella import Phylesystem from peyotl.nexson_syntax import get_nexml_el from peyotl import gen_otu_dict, iter_node from peyotl.manip import iter_trees import codecs import json import sys out = codecs.getwriter('utf-8')(sys.stdout) phy = Phylesystem() # Start all of the properties for the report at 0 report_properties = ['reported_study_count', 'study_count', 'OTU_count', 'unmapped_OTU_count', 'unique_OTU_count', 'nominated_study_count', 'nominated_study_OTU_count', 'nominated_study_unique_OTU_count', 'nominated_study_unmapped_OTU_count', 'run_time'] reported_study_count = 0 study_count = 0 OTU_count = 0 unmapped_OTU_count = 0 unique_OTU_count = 0 nominated_study_count = 0 nominated_study_OTU_count = 0 nominated_study_unique_OTU_count = 0 nominated_study_unmapped_OTU_count = 0 run_time = 0 ott_id_set = set() nominated_ott_id_set = set() for study_id, n in phy.iter_study_objs(): reported_study_count += 1 otu_dict = gen_otu_dict(n) if not bool(otu_dict): continue nex_obj = get_nexml_el(n) study_count += 1 not_intended_for_synth = nex_obj.get('^ot:notIntendedForSynthesis') intended_for_synth = (not_intended_for_synth is None) or (not_intended_for_synth is False) if intended_for_synth: nominated_study_count += 1 nominated_study_OTU_count += len(otu_dict) OTU_count += len(otu_dict) for oid, o in otu_dict.items(): ott_id = o.get('^ot:ottId') if ott_id is None: unmapped_OTU_count += 1 if intended_for_synth: nominated_study_unmapped_OTU_count += 1 else: ott_id_set.add(ott_id) if intended_for_synth: nominated_ott_id_set.add(ott_id) unique_OTU_count = len(ott_id_set) nominated_study_unique_OTU_count = len(nominated_ott_id_set) end_clock = time.time() run_time = end_clock - start_clock ################################################# # write variables in local scope in a JSON blob report = {} for prop in report_properties: report[prop] = locals()[prop] json.dump(report, out, sort_keys=True, indent=2, separators=(',', ': ')) out.write('\n')
7849d81916ebfbd27f3cf13b5e2beedef0e36485
2c74bb301f1ed83b79254944183ac5a18a639fdf
/homeassistant/components/uptime/const.py
bbce80214747bdfbdf17642a0a22328308f9e3e1
[ "Apache-2.0" ]
permissive
Adminiuga/home-assistant
5bec93007ddac1a268cc359bf7e48530c5f73b38
dcf68d768e4f628d038f1fdd6e40bad713fbc222
refs/heads/dev
2023-02-22T22:03:31.013931
2022-11-09T00:27:20
2022-11-09T00:27:20
123,929,062
5
4
Apache-2.0
2023-02-22T06:14:31
2018-03-05T14:11:09
Python
UTF-8
Python
false
false
206
py
"""Constants for the Uptime integration.""" from typing import Final from homeassistant.const import Platform DOMAIN: Final = "uptime" PLATFORMS: Final = [Platform.SENSOR] DEFAULT_NAME: Final = "Uptime"
65b07c011b7740295f45d257c0828bc529be2270
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2281/60722/273569.py
6d9e698fb32bc6a21a6cd03a7a25481fe3bf9c89
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
385
py
T=int(input()) for m in range(T): N=int(input()) string=input().split(" ") result=[] for i in range(N): string[i]=int(string[i]) for i in range(N): index=1 for j in range(i+1,N): if string[j]>string[i]: index=0 if index==1: result.append(string[i]) print(" ".join(str(i) for i in result))
2d7e12cad2ba51810b0b9cfc38c0785b64b5c48d
bb33e6be8316f35decbb2b81badf2b6dcf7df515
/source/res/scripts/client/gui/battle_control/battle_session.py
3e27372a59b36128587e02e581e111189cb2d27d
[]
no_license
StranikS-Scan/WorldOfTanks-Decompiled
999c9567de38c32c760ab72c21c00ea7bc20990c
d2fe9c195825ececc728e87a02983908b7ea9199
refs/heads/1.18
2023-08-25T17:39:27.718097
2022-09-22T06:49:44
2022-09-22T06:49:44
148,696,315
103
39
null
2022-09-14T17:50:03
2018-09-13T20:49:11
Python
UTF-8
Python
false
false
15,613
py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/battle_control/battle_session.py import weakref from collections import namedtuple import BigWorld import Event import BattleReplay from PlayerEvents import g_playerEvents from adisp import async from debug_utils import LOG_DEBUG from gui import g_tankActiveCamouflage from gui.battle_control import arena_visitor from gui.battle_control import avatar_getter from gui.battle_control import controllers from gui.battle_control.arena_info import invitations from gui.battle_control.arena_info.arena_dp import ArenaDataProvider from gui.battle_control.arena_info.listeners import ListenersCollection from gui.battle_control.battle_cache import BattleClientCache from gui.battle_control.battle_constants import VEHICLE_VIEW_STATE from gui.battle_control.battle_constants import VIEW_COMPONENT_RULE from gui.battle_control.battle_ctx import BattleContext from gui.battle_control.requests import AvatarRequestsController from gui.battle_control.view_components import createComponentsBridge from items.components.c11n_constants import SeasonType from skeletons.gui.battle_session import IBattleSessionProvider from cgf_components import wt_helpers BattleExitResult = namedtuple('BattleExitResult', 'isDeserter playerInfo') class BattleSessionProvider(IBattleSessionProvider): __slots__ = ('__ctx', '__sharedRepo', '__dynamicRepo', '__requestsCtrl', '__arenaDP', '__arenaListeners', '__viewComponentsBridge', '__weakref__', '__arenaVisitor', '__invitations', '__isReplayPlaying', '__battleCache', 'onUpdateObservedVehicleData') def __init__(self): super(BattleSessionProvider, self).__init__() self.__ctx = BattleContext() self.__sharedRepo = controllers.SharedControllersLocator() self.__dynamicRepo = controllers.DynamicControllersLocator() self.__requestsCtrl = None self.__arenaDP = None self.__arenaVisitor = arena_visitor.createSkeleton() self.__arenaListeners = None self.__viewComponentsBridge = None self.__invitations = None self.__isReplayPlaying = False self.__battleCache = BattleClientCache() self.onBattleSessionStart = Event.Event() self.onBattleSessionStop = Event.Event() self.onUpdateObservedVehicleData = Event.Event() return @property def shared(self): return self.__sharedRepo @property def dynamic(self): return self.__dynamicRepo @property def arenaVisitor(self): return self.__arenaVisitor @property def invitations(self): return self.__invitations @property def battleCache(self): return self.__battleCache @property def isReplayPlaying(self): return self.__isReplayPlaying def getCtx(self): return self.__ctx @async def sendRequest(self, ctx, callback, allowDelay=None): self.__requestsCtrl.request(ctx, callback=callback, allowDelay=allowDelay) def setPlayerVehicle(self, vID, vDesc): ctrl = self.shared.prebattleSetups isSetupsSelectionStarted = ctrl.isSelectionStarted() if ctrl is not None else False ctrl = self.__sharedRepo.ammo if ctrl is not None: if not isSetupsSelectionStarted: ctrl.clearAmmo() ctrl.setGunSettings(vDesc.gun) ctrl = self.__sharedRepo.equipments if ctrl is not None: ctrl.notifyPlayerVehicleSet(vID) ctrl = self.__sharedRepo.vehicleState if ctrl is not None: ctrl.setPlayerVehicle(vID) ctrl = self.shared.prebattleSetups if ctrl is not None: ctrl.setPlayerVehicle(vID, vDesc) ctrl = self.__dynamicRepo.respawn if ctrl is not None: ctrl.spawnVehicle(vID) mapKind = self.__arenaVisitor.type.getVehicleCamouflageKind() g_tankActiveCamouflage[vDesc.type.compactDescr] = SeasonType.fromArenaKind(mapKind) return def switchVehicle(self, vehicleID): repo = self.shared if repo.vehicleState is not None and repo.vehicleState.getControllingVehicleID() != vehicleID: for ctrl in (repo.ammo, repo.equipments, repo.optionalDevices): if ctrl is not None: ctrl.clear(False) repo.vehicleState.switchToOther(vehicleID) return def updateObservedVehicleData(self, vehicle): ammoCtrl = self.__sharedRepo.ammo if ammoCtrl is not None: ammoCtrl.clear(False) ammoCtrl.setGunSettings(vehicle.typeDescriptor.gun) ctrl = self.__sharedRepo.equipments if ctrl is not None: ctrl.clear(False) ctrl.notifyPlayerVehicleSet(vehicle.id) ctrl = self.__sharedRepo.optionalDevices if ctrl is not None: ctrl.clear(False) vehicle.ownVehicle.initialUpdate(force=True) self.updateVehicleEffects(vehicle) self.onUpdateObservedVehicleData(vehicle.id, None) return def updateVehicleEffects(self, vehicle): if vehicle is not None: vehicle.onDebuffEffectApplied(vehicle.debuff > 0) if vehicle.stunInfo > 0.0: vehicle.updateStunInfo() if vehicle.inspired: vehicle.set_inspired() if vehicle.healing: vehicle.set_healing() return def getArenaDP(self): return self.__arenaDP def addArenaCtrl(self, controller): return self.__arenaListeners.addController(controller) if self.__arenaListeners is not None else False def removeArenaCtrl(self, controller): if self.__arenaListeners is not None: self.__arenaListeners.removeController(controller) return def registerViewComponentsCtrl(self, controller): if self.__viewComponentsBridge is not None: self.__viewComponentsBridge.registerController(controller) return True else: return False def registerViewComponents(self, *data): if self.__viewComponentsBridge is not None: self.__viewComponentsBridge.registerViewComponents(*data) return True else: return False def addViewComponent(self, componentID, component, rule=VIEW_COMPONENT_RULE.PROXY): if self.__viewComponentsBridge is not None: self.__viewComponentsBridge.addViewComponent(componentID, component, rule=rule) return def removeViewComponent(self, componentID): if self.__viewComponentsBridge is not None: self.__viewComponentsBridge.removeViewComponent(componentID) return def getExitResult(self): if not self.__isReplayPlaying and not self.__arenaVisitor.gui.isTrainingBattle() and not self.__arenaVisitor.gui.isBattleRoyale() and not self.__arenaVisitor.gui.isMapsTraining(): vInfo = self.__arenaDP.getVehicleInfo() vStats = self.__arenaDP.getVehicleStats() if self.__arenaVisitor.hasRespawns(): isDeserter = not vStats.stopRespawn elif self.__arenaVisitor.hasVSERespawns(): isDeserter = wt_helpers.getPlayerLives() > 0 or wt_helpers.isBoss() and avatar_getter.isVehicleAlive() else: isDeserter = avatar_getter.isVehicleAlive() and not avatar_getter.isVehicleOverturned() return BattleExitResult(isDeserter, vInfo.player) else: return BattleExitResult(False, None) return None def exit(self): if self.__arenaVisitor.gui.isMapsTraining(): self.__onMapsTrainingExit() avatar_getter.leaveArena() def start(self, setup): self.__isReplayPlaying = setup.isReplayPlaying self.__arenaVisitor = arena_visitor.createByAvatar(avatar=setup.avatar) setup.sessionProvider = weakref.proxy(self) self.__arenaDP = ArenaDataProvider(setup) self.__ctx.start(self.__arenaDP) self.__battleCache.load() self.__arenaListeners = ListenersCollection() self.__arenaListeners.start(setup) self.__viewComponentsBridge = createComponentsBridge() setup.sessionProvider = weakref.proxy(self) self.__sharedRepo = controllers.createShared(setup) self.__dynamicRepo = controllers.createDynamic(setup) self.__requestsCtrl = AvatarRequestsController() self.__invitations = invitations.createInvitationsHandler(setup) setup.clear() g_playerEvents.onBattleResultsReceived += self.__pe_onBattleResultsReceived self.onBattleSessionStart() def stop(self): self.onBattleSessionStop() g_playerEvents.onBattleResultsReceived -= self.__pe_onBattleResultsReceived if self.__viewComponentsBridge is not None: self.__viewComponentsBridge.clear() self.__viewComponentsBridge = None if self.__invitations is not None: self.__invitations.clear() self.__invitations = None if self.__requestsCtrl is not None: self.__requestsCtrl.fini() self.__requestsCtrl = None if self.__arenaListeners is not None: self.__arenaListeners.stop() self.__arenaListeners = None if self.__arenaDP is not None: self.__arenaDP.clear() self.__arenaDP = None self.__sharedRepo.destroy() self.__dynamicRepo.destroy() self.__arenaVisitor.clear() self.__arenaVisitor = arena_visitor.createSkeleton() self.__battleCache.clear() self.__ctx.stop() self.__isReplayPlaying = False return def switchToPostmortem(self, noRespawnPossible=True, respawnAvailable=False): ctrl = self.__sharedRepo.ammo if ctrl is not None: ctrl.clear(False) ctrl = self.__sharedRepo.equipments if ctrl is not None: ctrl.clear(False) ctrl = self.__sharedRepo.optionalDevices if ctrl is not None: ctrl.clear(False) ctrl = self.__sharedRepo.vehicleState if ctrl is not None: ctrl.switchToPostmortem(noRespawnPossible, respawnAvailable) return def updateVehicleQuickShellChanger(self, isActive): ammoCtrl = self.__sharedRepo.ammo if ammoCtrl is not None: ammoCtrl.updateVehicleQuickShellChanger(isActive) return def movingToRespawnBase(self, vehicle): ctrl = self.__sharedRepo.ammo if ctrl is not None: ctrl.clear(False) if vehicle: ctrl.setGunSettings(vehicle.typeDescriptor.gun) ctrl = self.__sharedRepo.equipments if ctrl is not None: ctrl.clear(False) if vehicle: ctrl.notifyPlayerVehicleSet(vehicle.id) ctrl = self.__sharedRepo.optionalDevices if ctrl is not None: ctrl.clear(False) ctrl = self.__sharedRepo.vehicleState if ctrl is not None: ctrl.movingToRespawn() ctrl = self.__dynamicRepo.respawn if ctrl is not None: ctrl.movingToRespawn() return def invalidateVehicleState(self, state, value, vehicleID=0): ctrl = self.__sharedRepo.vehicleState if ctrl is not None: ctrl.invalidate(state, value, vehicleID) if state == VEHICLE_VIEW_STATE.DESTROYED: ctrl = self.__sharedRepo.ammo if ctrl is not None: ctrl.clear(leave=False) ctrl = self.__sharedRepo.equipments if ctrl is not None: ctrl.clear(leave=False) ctrl = self.__sharedRepo.optionalDevices if ctrl is not None: ctrl.clear(leave=False) return def setVehicleHealth(self, isPlayerVehicle, vehicleID, newHealth, attackerID, attackReasonID): if not isPlayerVehicle: ctrl = self.__sharedRepo.feedback if ctrl is not None: ctrl.setVehicleNewHealth(vehicleID, newHealth, attackerID, attackReasonID) ctrl = self.__dynamicRepo.battleField if ctrl is not None: ctrl.setVehicleHealth(vehicleID, newHealth) return def repairPointAction(self, repairPointIndex, action, nextActionTime): ctrl = self.__dynamicRepo.repair if ctrl is not None: ctrl.action(repairPointIndex, action, nextActionTime) return def updateAvatarPrivateStats(self, stats): ctrl = self.__sharedRepo.privateStats if ctrl is not None: ctrl.update(stats) return def addHitDirection(self, hitDirYaw, attackerID, damage, isBlocked, critFlags, isHighExplosive, damagedID, attackReasonID): hitDirectionCtrl = self.__sharedRepo.hitDirection if hitDirectionCtrl is not None: hitDirectionCtrl.addHit(hitDirYaw, attackerID, damage, isBlocked, critFlags, isHighExplosive, damagedID, attackReasonID) return def startVehicleVisual(self, vProxy, isImmediate=False): vehicleID = vProxy.id ctrl = self.__sharedRepo.optionalDevices if ctrl is not None: ctrl.startVehicleVisual(vProxy, isImmediate) ctrl = self.__sharedRepo.feedback if ctrl is not None: ctrl.startVehicleVisual(vProxy, isImmediate) ctrl = self.__dynamicRepo.battleField if ctrl is not None: ctrl.setVehicleVisible(vehicleID, vProxy.health) ctrl = self.__sharedRepo.vehicleState if ctrl is not None and BigWorld.player().observedVehicleID == vehicleID: ctrl.refreshObserverVehicleVisual() return def stopVehicleVisual(self, vehicleID, isPlayerVehicle): ctrl = self.__sharedRepo.feedback if ctrl is not None: ctrl.stopVehicleVisual(vehicleID, isPlayerVehicle) ctrl = self.__dynamicRepo.battleField if ctrl is not None: ctrl.stopVehicleVisual(vehicleID) return def handleShortcutChatCommand(self, key): ctrl = self.__sharedRepo.chatCommands if ctrl is None: return else: if self.__arenaVisitor.gui.isInEpicRange(): mapCtrl = self.dynamic.maps if not mapCtrl or mapCtrl.overviewMapScreenVisible: return ctrl.handleShortcutChatCommand(key) return def handleContexChatCommand(self, key): ctrl = self.__sharedRepo.chatCommands if ctrl is None: return else: ctrl.handleContexChatCommand(key) return def __pe_onBattleResultsReceived(self, isActiveVehicle, _): if isActiveVehicle and not BattleReplay.g_replayCtrl.isPlaying: arenaUniqueID = self.__arenaVisitor.getArenaUniqueID() arenaBonusType = self.__arenaVisitor.getArenaBonusType() LOG_DEBUG('Try to exit from arena', arenaUniqueID, arenaBonusType) if arenaUniqueID: self.__ctx.lastArenaUniqueID = arenaUniqueID if arenaBonusType: self.__ctx.lastArenaBonusType = arenaBonusType self.exit() def __onMapsTrainingExit(self): if not BattleReplay.isPlaying() and self.__ctx.lastArenaUniqueID is None: self.__ctx.lastArenaUniqueID = self.__arenaVisitor.getArenaUniqueID() self.__ctx.lastArenaBonusType = self.__arenaVisitor.getArenaBonusType() return
86f0dcff18cacb525ba4a9744c6204c57e8a82bf
caf192dbc1ca90fee18bb4ce170d37eb14870ec5
/Chapter-5/8. Caesar cipher improved.py
e8e8417f0af034fccd1069c3f4c9c7d4851dc931
[]
no_license
Dfredude/PythonZelle
858b00f5eacce841173c64b3cecd978dedbeb145
1923fe84df604968eebc5269f23b7c0f167d55f0
refs/heads/main
2023-08-30T21:45:57.070344
2021-10-17T01:32:57
2021-10-17T01:32:57
359,041,963
0
0
null
null
null
null
UTF-8
Python
false
false
626
py
def main(): #Get plaintext(p_text) and key(x) from the user p_text = str(input("Enter the message you'd like encrypted:\n")) key = int(input("What's the key?: ")) p_text = p_text.upper() #Create string of letters table = "abcdefghijklmnopqrstuvwxyz" full_table = table * 6 #Check if there are spaces #Convert plaintext to ciphertext(c_text) using cipher loop result = "" for ch in p_text: if ch == ' ': result += ' ' else: new_n = ord(ch) + 13 result += full_table[new_n+key] print("Your encoded message is {0}.".format(result)) main()
32fc774be7ccea0bc9dd9d2bc3b6d739fdf9d0e1
2ff83d7af0bcbc5822593d826b0c3276346d1276
/transformers_local_rep/src/transformers/models/xlm/configuration_xlm.py
3ef91c99803ead154f7a5b1ca700f4ae9e22099b
[]
no_license
mauricerupp/PolitBERT
43af66f5562bb5c5cf965aa99bb065d1c22f4fae
a8c4eb517eb38cb51101fc87780ed1de182560c8
refs/heads/master
2023-06-17T03:13:43.070682
2021-07-15T15:15:30
2021-07-15T15:15:30
386,334,080
1
0
null
null
null
null
UTF-8
Python
false
false
11,933
py
# coding=utf-8 # Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ XLM configuration """ from ...configuration_utils import PretrainedConfig from ...utils import logging logger = logging.get_logger(__name__) XLM_PRETRAINED_CONFIG_ARCHIVE_MAP = { "xlm-mlm-en-2048": "https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json", "xlm-mlm-ende-1024": "https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json", "xlm-mlm-enfr-1024": "https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json", "xlm-mlm-enro-1024": "https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json", "xlm-mlm-tlm-xnli15-1024": "https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json", "xlm-mlm-xnli15-1024": "https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json", "xlm-clm-enfr-1024": "https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json", "xlm-clm-ende-1024": "https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json", "xlm-mlm-17-1280": "https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json", "xlm-mlm-100-1280": "https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json", } class XLMConfig(PretrainedConfig): """ This is the configuration class to store the configuration of a :class:`~transformers_local.XLMModel` or a :class:`~transformers_local.TFXLMModel`. It is used to instantiate a XLM model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the `xlm-mlm-en-2048 <https://huggingface.co/xlm-mlm-en-2048>`__ architecture. Configuration objects inherit from :class:`~transformers_local.PretrainedConfig` and can be used to control the model outputs. Read the documentation from :class:`~transformers_local.PretrainedConfig` for more information. Args: vocab_size (:obj:`int`, `optional`, defaults to 30145): Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the :obj:`inputs_ids` passed when calling :class:`~transformers_local.XLMModel` or :class:`~transformers_local.TFXLMModel`. emb_dim (:obj:`int`, `optional`, defaults to 2048): Dimensionality of the encoder layers and the pooler layer. n_layer (:obj:`int`, `optional`, defaults to 12): Number of hidden layers in the Transformer encoder. n_head (:obj:`int`, `optional`, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. dropout (:obj:`float`, `optional`, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_dropout (:obj:`float`, `optional`, defaults to 0.1): The dropout probability for the attention mechanism gelu_activation (:obj:`bool`, `optional`, defaults to :obj:`True`): Whether or not to use `gelu` for the activations instead of `relu`. sinusoidal_embeddings (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not to use sinusoidal positional embeddings instead of absolute positional embeddings. causal (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the model should behave in a causal manner. Causal models use a triangular attention mask in order to only attend to the left-side context instead if a bidirectional context. asm (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not to use an adaptive log softmax projection layer instead of a linear layer for the prediction layer. n_langs (:obj:`int`, `optional`, defaults to 1): The number of languages the model handles. Set to 1 for monolingual models. use_lang_emb (:obj:`bool`, `optional`, defaults to :obj:`True`) Whether to use language embeddings. Some models use additional language embeddings, see `the multilingual models page <http://huggingface.co/transformers/multilingual.html#xlm-language-embeddings>`__ for information on how to use them. max_position_embeddings (:obj:`int`, `optional`, defaults to 512): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). embed_init_std (:obj:`float`, `optional`, defaults to 2048^-0.5): The standard deviation of the truncated_normal_initializer for initializing the embedding matrices. init_std (:obj:`int`, `optional`, defaults to 50257): The standard deviation of the truncated_normal_initializer for initializing all weight matrices except the embedding matrices. layer_norm_eps (:obj:`float`, `optional`, defaults to 1e-12): The epsilon used by the layer normalization layers. bos_index (:obj:`int`, `optional`, defaults to 0): The index of the beginning of sentence token in the vocabulary. eos_index (:obj:`int`, `optional`, defaults to 1): The index of the end of sentence token in the vocabulary. pad_index (:obj:`int`, `optional`, defaults to 2): The index of the padding token in the vocabulary. unk_index (:obj:`int`, `optional`, defaults to 3): The index of the unknown token in the vocabulary. mask_index (:obj:`int`, `optional`, defaults to 5): The index of the masking token in the vocabulary. is_encoder(:obj:`bool`, `optional`, defaults to :obj:`True`): Whether or not the initialized model should be a transformer encoder or decoder as seen in Vaswani et al. summary_type (:obj:`string`, `optional`, defaults to "first"): Argument used when doing sequence summary. Used in the sequence classification and multiple choice models. Has to be one of the following options: - :obj:`"last"`: Take the last token hidden state (like XLNet). - :obj:`"first"`: Take the first token hidden state (like BERT). - :obj:`"mean"`: Take the mean of all tokens hidden states. - :obj:`"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2). - :obj:`"attn"`: Not implemented now, use multi-head attention. summary_use_proj (:obj:`bool`, `optional`, defaults to :obj:`True`): Argument used when doing sequence summary. Used in the sequence classification and multiple choice models. Whether or not to add a projection after the vector extraction. summary_activation (:obj:`str`, `optional`): Argument used when doing sequence summary. Used in the sequence classification and multiple choice models. Pass :obj:`"tanh"` for a tanh activation to the output, any other value will result in no activation. summary_proj_to_labels (:obj:`bool`, `optional`, defaults to :obj:`True`): Used in the sequence classification and multiple choice models. Whether the projection outputs should have :obj:`config.num_labels` or :obj:`config.hidden_size` classes. summary_first_dropout (:obj:`float`, `optional`, defaults to 0.1): Used in the sequence classification and multiple choice models. The dropout ratio to be used after the projection and activation. start_n_top (:obj:`int`, `optional`, defaults to 5): Used in the SQuAD evaluation script. end_n_top (:obj:`int`, `optional`, defaults to 5): Used in the SQuAD evaluation script. mask_token_id (:obj:`int`, `optional`, defaults to 0): Model agnostic parameter to identify masked tokens when generating text in an MLM context. lang_id (:obj:`int`, `optional`, defaults to 1): The ID of the language used by the model. This parameter is used when generating text in a given language. Examples:: >>> from transformers_local import XLMConfig, XLMModel >>> # Initializing a XLM configuration >>> configuration = XLMConfig() >>> # Initializing a model from the configuration >>> model = XLMModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config """ model_type = "xlm" def __init__( self, vocab_size=30145, emb_dim=2048, n_layers=12, n_heads=16, dropout=0.1, attention_dropout=0.1, gelu_activation=True, sinusoidal_embeddings=False, causal=False, asm=False, n_langs=1, use_lang_emb=True, max_position_embeddings=512, embed_init_std=2048 ** -0.5, layer_norm_eps=1e-12, init_std=0.02, bos_index=0, eos_index=1, pad_index=2, unk_index=3, mask_index=5, is_encoder=True, summary_type="first", summary_use_proj=True, summary_activation=None, summary_proj_to_labels=True, summary_first_dropout=0.1, start_n_top=5, end_n_top=5, mask_token_id=0, lang_id=0, pad_token_id=2, bos_token_id=0, **kwargs ): """Constructs XLMConfig.""" super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, **kwargs) self.vocab_size = vocab_size self.emb_dim = emb_dim self.n_layers = n_layers self.n_heads = n_heads self.dropout = dropout self.attention_dropout = attention_dropout self.gelu_activation = gelu_activation self.sinusoidal_embeddings = sinusoidal_embeddings self.causal = causal self.asm = asm self.n_langs = n_langs self.use_lang_emb = use_lang_emb self.layer_norm_eps = layer_norm_eps self.bos_index = bos_index self.eos_index = eos_index self.pad_index = pad_index self.unk_index = unk_index self.mask_index = mask_index self.is_encoder = is_encoder self.max_position_embeddings = max_position_embeddings self.embed_init_std = embed_init_std self.init_std = init_std self.summary_type = summary_type self.summary_use_proj = summary_use_proj self.summary_activation = summary_activation self.summary_proj_to_labels = summary_proj_to_labels self.summary_first_dropout = summary_first_dropout self.start_n_top = start_n_top self.end_n_top = end_n_top self.mask_token_id = mask_token_id self.lang_id = lang_id if "n_words" in kwargs: self.n_words = kwargs["n_words"] @property def n_words(self): # For backward compatibility return self.vocab_size @n_words.setter def n_words(self, value): # For backward compatibility self.vocab_size = value @property def hidden_size(self): return self.emb_dim @property def num_attention_heads(self): return self.n_heads @property def num_hidden_layers(self): return self.n_layers
84db13e8ee0d75e7c968eabc624c915b95174b9a
ba054fa1ec409011444e9c6b963309745e150d6f
/ave_SR/prueba_carga/loadStateData.py
ea4caae0a5653c6b78ca817bb8466e5022a68528
[]
no_license
berndhahnebach/XCmodels
a6500fdde253dea10ef2bb64b7ebc3dbfc2577c2
4acdd7747abd7cd71f5ef580f65e93359560e5a9
refs/heads/master
2020-04-02T23:36:36.385054
2018-10-20T16:49:21
2018-10-20T16:49:21
154,873,006
0
0
null
2018-10-26T17:52:36
2018-10-26T17:52:35
null
UTF-8
Python
false
false
7,436
py
# -*- coding: utf-8 -*- '''In this script we define default data of load cases to be used (or changed) while displaying loads or results associated to single load cases ''' from postprocess.reports import graphical_reports ''' Definition of record objects with these attributes: loadCaseName: name of the load case to be depicted loadCaseDescr: description text of the load case loadCaseExpr: mathematical expression to define the load case (ex: '1.0*GselfWeight+1.0*DeadLoad') setsToDispLoads: ordered list of sets of elements to display loads setsToDispBeamLoads: ordered list of sets of beam elements to display loads (defaults to []) compElLoad: component of load on beam elements to be represented available components: 'axialComponent', 'transComponent', 'transYComponent','transZComponent' unitsScaleLoads: factor to apply to loads if we want to change the units (defaults to 1). unitsLoads: text to especify the units in which loads are represented (defaults to 'units:[m,kN]') vectorScaleLoads: factor to apply to the vectors length in the representation of loads (defaults to 1 -> auto-scale). vectorScalePointLoads: factor to apply to the vectors length in the representation of nodal loads (defaults to 1). multByElemAreaLoads: boolean value that must be True if we want to represent the total load on each element (=load multiplied by element area) and False if we are going to depict the value of the uniform load per unit area (defaults to False) listDspRot: ordered list of displacement or rotations to be displayed available components: 'uX', 'uY', 'uZ', 'rotX', rotY', 'rotZ' (defaults to ['uX', 'uY', 'uZ']) setsToDispDspRot: ordered list of sets of elements to display displacements or rotations unitsScaleDispl: factor to apply to displacements if we want to change the units (defaults to 1). unitsDispl: text to especify the units in which displacements are represented (defaults to '[m]' listIntForc: ordered list of internal forces to be displayed as scalar field over «shell» elements available components: 'N1', 'N2', 'M1', 'M2', 'Q1', 'Q2' (defaults to ['N1', 'N2', 'M1', 'M2', 'Q1', 'Q2']) setsToDispIntForc: ordered list of sets of elements (of type «shell»)to display internal forces listBeamIntForc: ordered list of internal forces to be displayed as diagrams on lines for «beam» elements available components: 'N', 'My', 'Mz', 'Qy', 'Qz','T' (defaults to ['N', 'My', 'Mz', 'Qy', 'Qz','T']) setsToDispBeamIntForc: ordered list of sets of elements (of type «beam»)to display internal forces (defaults to []) scaleDispBeamIntForc: tuple (escN,escQ,escM) correponding to the scales to apply to displays of, respectively, N Q and M beam internal forces (defaults to (1.0,1.0,1.0)) unitsScaleForc: factor to apply to internal forces if we want to change the units (defaults to 1). unitsForc: text to especify the units in which forces are represented (defaults to '[kN/m]') unitsScaleMom: factor to apply to internal moments if we want to change the units (defaults to 1). unitsMom: text to especify the units in which bending moments are represented (defaults to '[kN.m/m]') viewName: name of the view that contains the renderer (available standard views: "XYZPos", "XYZNeg", "XPos", "XNeg","YPos", "YNeg", "ZPos", "ZNeg", "+X+Y+Z", "+X+Y-Z", "+X-Y+Z", "+X-Y-Z", "-X+Y+Z", "-X+Y-Z", "-X-Y+Z", "-X-Y-Z") (defaults to "XYZPos") hCamFct: factor that applies to the height of the camera position in order to change perspective of isometric views (defaults to 1, usual values 0.1 to 10) viewNameBeams: name of the view for beam elements displays (defaults to "XYZPos") hCamFctBeams: factor that applies to the height of the camera position for beam displays (defaults to 1) ''' Q1=graphical_reports.RecordLoadCaseDisp(loadCaseName='Q1',loadCaseDescr='Q1: Prueba de carga estática',loadCaseExpr='1.0*Q1',setsToDispLoads=[overallSet],setsToDispDspRot=[dintel],setsToDispIntForc=[dintel]) Q1.unitsScaleLoads=1e-3 Q1.unitsScaleDispl=1e3 Q1.unitsDispl='[mm]' Q1.unitsScaleMom=1e-3 Q1.unitsMom='[m.kN]' Q1.unitsScaleForc=1e-3 Q1.unitsForc='[kN]' Q1.viewName="XYZPos" Q1.hCamFct=1 Q1.listDspRot=[] Q1.listIntForc=['M2'] Q2=graphical_reports.RecordLoadCaseDisp(loadCaseName='Q2',loadCaseDescr='Q2: tren de cargas ferroviario (2 vías)',loadCaseExpr='1.00*Q2',setsToDispLoads=[overallSet],setsToDispDspRot=[dintel],setsToDispIntForc=[dintel]) Q2.unitsScaleLoads=1e-3 Q2.unitsScaleDispl=1e3 Q2.unitsDispl='[mm]' Q2.unitsScaleMom=1e-3 Q2.unitsMom='[m.kN]' Q2.unitsScaleForc=1e-3 Q2.unitsForc='[kN]' Q2.viewName="XYZPos" Q2.hCamFct=1 Q2.listDspRot=[] Q2.listIntForc=['M2'] Q3=graphical_reports.RecordLoadCaseDisp(loadCaseName='Q3',loadCaseDescr='Q3: tren de cargas ferroviario (1 vía)',loadCaseExpr='1.00*Q3',setsToDispLoads=[dintel],setsToDispDspRot=[dintel],setsToDispIntForc=[dintel]) Q3.unitsScaleLoads=1e-3 Q3.unitsScaleDispl=1e3 Q3.unitsDispl='[mm]' Q3.unitsScaleMom=1e-3 Q3.unitsMom='[m.kN]' Q3.unitsScaleForc=1e-3 Q3.unitsForc='[kN]' Q3.viewName="XYZPos" Q3.hCamFct=1 Q3.listDspRot=[] Q3.listIntForc=['M2'] PrueCarga=graphical_reports.RecordLoadCaseDisp(loadCaseName='PC',loadCaseDescr='PrueCarga: Prueba de carga estática',loadCaseExpr='1.0*G1+1.00*G3+1.0*Q1',setsToDispLoads=[dintel],setsToDispDspRot=[dintel],setsToDispIntForc=[dintel]) PrueCarga.unitsScaleLoads=1e-3 PrueCarga.unitsScaleDispl=1e3 PrueCarga.unitsDispl='[mm]' PrueCarga.unitsScaleMom=1e-3 PrueCarga.unitsMom='[m.kN]' PrueCarga.unitsScaleForc=1e-3 PrueCarga.unitsForc='[kN]' PrueCarga.viewName="XYZPos" PrueCarga.hCamFct=1 PrueCarga.listDspRot=[] PrueCarga.listIntForc=['M2'] Qtren2vias=graphical_reports.RecordLoadCaseDisp(loadCaseName='TF2',loadCaseDescr='Qtren: tren de cargas ferroviario',loadCaseExpr='1.00*G1 + 1.00*G2 + 1.00*G3 + 1.00*Q2',setsToDispLoads=[dintel],setsToDispDspRot=[dintel],setsToDispIntForc=[dintel]) Qtren2vias.unitsScaleLoads=1e-3 Qtren2vias.unitsScaleDispl=1e3 Qtren2vias.unitsDispl='[mm]' Qtren2vias.unitsScaleMom=1e-3 Qtren2vias.unitsMom='[m.kN]' Qtren2vias.unitsScaleForc=1e-3 Qtren2vias.unitsForc='[kN]' Qtren2vias.viewName="XYZPos" Qtren2vias.hCamFct=1 Qtren2vias.listDspRot=[] Qtren2vias.listIntForc=['M2'] Qtren1via=graphical_reports.RecordLoadCaseDisp(loadCaseName='TF1',loadCaseDescr='Qtren: tren de cargas ferroviario',loadCaseExpr='1.00*G1 + 1.00*G2 + 1.00*G3 + 1.00*Q3',setsToDispLoads=[dintel],setsToDispDspRot=[dintel],setsToDispIntForc=[dintel]) Qtren1via.unitsScaleLoads=1e-3 Qtren1via.unitsScaleDispl=1e3 Qtren1via.unitsDispl='[mm]' Qtren1via.unitsScaleMom=1e-3 Qtren1via.unitsMom='[m.kN]' Qtren1via.unitsScaleForc=1e-3 Qtren1via.unitsForc='[kN]' Qtren1via.viewName="XYZPos" Qtren1via.hCamFct=1 Qtren1via.listDspRot=[] Qtren1via.listIntForc=['M2']
bedc758c9a51a568cc9c7b658fc0ecc6f2e0d95f
9a257043e72660ba8ba64bafbd626c7cd2638fad
/demos/demo3.py
0445986140b7e45ee5705195ce62abfbcb846da7
[ "MIT" ]
permissive
desecho/django-tqdm
1b38a4955b8205ca18a215eea9ea4ba969c0baaa
053d2a259a503a574fa29960d66568feba85d25e
refs/heads/master
2023-08-07T18:40:52.643836
2022-11-01T05:08:47
2022-11-03T04:12:35
88,812,309
15
0
MIT
2023-09-01T04:02:46
2017-04-20T02:33:56
Python
UTF-8
Python
false
false
294
py
"""Demo 3 - Vanilla tqdm with default settings for comparison.""" import sys from time import sleep from tqdm import tqdm t = tqdm(total=50) for x in range(50): sleep(0.02) t.update(1) if x == 25: t.write("info") if x == 40: t.write("error", file=sys.stderr)
975f5ad103c66ee683287f7f8c490cd1822a58f7
cb1fb3bf87b3f7006b564a0f2acd2d68e5d5ffaa
/pyram/gsf/run.py
aa7a2ce83652d1e311fa6636ac4285f33e5b39e0
[ "GPL-3.0-only", "MIT" ]
permissive
Hoseung/pyRamAn
2778f8b12ca966e7586ebf077a964aecd1654223
f9386fa5a9f045f98590039988d3cd50bc488dc2
refs/heads/master
2021-06-22T18:35:06.478492
2021-06-05T03:26:31
2021-06-05T03:26:31
227,741,934
1
1
MIT
2020-03-04T12:39:06
2019-12-13T02:49:30
Jupyter Notebook
UTF-8
Python
false
false
1,146
py
import sys, os, numexpr import gsf print('This script calls gsf given a valid simulation output file, snaphot_file (required input)') print('gsf.py is a collection of functions that cover the computation of the gravitational potential,') print('a wrapper for the Gaussian Mixture Models of scikit-learn and various plotting options.') print('To have an idea of the various arguments that can be set use verbose=True.') print('If no optional argument is given, the code will look for 2 clusters in the kinematic stellar space of') print('(jz/jc,jp/jc,binding_energy) of the most massive halo in snaphot_file.') print('The runtime for the computation of the potential scales as ~N^2') print('If you want to run this part of gsf in parallel, set the system variable OMP_NUM_THREADS first.') snaphot_file = '/scratch/database/nihao/gasoline2.1/g8.26e11/g8.26e11.01024' out_dir='./' print('Running gsf for the sim in %s'%snaphot_file) gsf.wgsf(snaphot_file, out_dir=out_dir, number_of_clusters=2, covariance_type='full', whiten_data=None, halo_id=1, radius_align=0.1, align_with='baryon', n_init=1, plot=True, verbose=True)
9670b3eacf994b8b048b41b1e35eb381b467e6fe
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_200/194.py
52851c11321931979d7349e69ceeae6308d70d7a
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
692
py
file_in = open('B-large.in', 'r') file_out = open('b.out', 'w') T = int(file_in.readline()) for t in range(1, T+1): n = list(file_in.readline().strip()) n = [int(i) for i in n] i = 1 k = None while(i < len(n)): if(n[i] < n[i-1]): k = i n[i-1] -= 1 break i += 1 while(i < len(n)): n[i] = 9 i += 1 if k is not None: while(k > 1): k -= 1 if(n[k] < n[k-1]): n[k] = 9 n[k-1] -= 1 else: break while n[0] is 0: n.pop(0) n = [str(i) for i in n] ans = ''.join(n) file_out.write("Case #{}: ".format(t)) file_out.write(ans) file_out.write('\n')
af84c590c0b37d96166d6afa222258397d069324
d9232bb31eb01eb97014bb5c769e0dd210512769
/python2/classes/person.py
49b723a7627db3a17556b313fcce5f1e07d523cc
[ "MIT" ]
permissive
hygull/pyrandocs
c5d0defff6a9465678f713deed384a097bbe0e02
31cd2a4fc23b91c692e104f533ce3c4d21698ff5
refs/heads/master
2020-04-20T10:44:59.921958
2019-02-10T10:34:13
2019-02-10T10:34:13
168,797,735
0
0
null
null
null
null
UTF-8
Python
false
false
2,163
py
from datetime import date class Person(object): """ Person ====== - A class to represent a person class """ def __init__(self, fullname, username, dob, email, profession, address): super(Person, self).__init__() self.fullname = fullname self.username = username self.dob = self.__get_dob(dob) self.age = self.__get_age() self.email = email self.profession = profession self.address = address def __get_dob(self, dob): """ >>> arr = [1, 3, 4] >>> x, y, z = a >>> x 1 >>> y 3 >>> z 4 >>> >>> def func(a, b, c): ... print(a, b, c) ... >>> func(*[55, 67, 88]) (55, 67, 88) >>> >>> func(*[55, 67, 88][::-1]) (88, 67, 55) >>> """ dob = date(*[int(data) for data in dob.split('-')][::-1]) return dob def __get_age(self): today = date.today() delta = today - self.dob years = delta.days / 365.25 days = delta.days % 365.25 message = '' if years or days: message = '{0:d} years {1:d} days (approx.)'.format(int(years), int(days)) else: message = 'Unborn baby' return message def details(self): for atrribute_name, atrribute_value in self.__dict__.items(): print('{0:15s} - {1}'.format(atrribute_name, atrribute_value)) if __name__ == "__main__": person = Person( 'Rishikesh Agrawani', 'hygull', '14-05-1992', '[email protected]', 'Python/Node developer', 'Banaglore, India' ) person.details() """ username - hygull dob - 1992-05-14 age - 26 years 263 days (approx.) profession - Python/Node developer address - Banaglore, India fullname - Rishikesh Agrawani email - [email protected] """
a80ac9bcd6682244b0f36d5f03d259cfe6d63e1c
3e06c2e64c14c3e3486cd3604268f12510fdeb56
/chatbot/actions/actions.py
a89ec89ba87288f0c31ed895a8ea90df9b8a36f2
[ "Apache-2.0" ]
permissive
exactpro/nostradamus
42296e9d4762ac6d7364a665dd5cd74117caacc8
80df847a012374ad2b702cc9f9c9cb46c1153ee7
refs/heads/master
2022-09-29T08:49:14.505795
2021-12-21T12:43:01
2021-12-21T12:43:01
162,601,150
32
8
Apache-2.0
2022-09-13T23:04:20
2018-12-20T15:58:05
TypeScript
UTF-8
Python
false
false
5,976
py
from typing import Dict, Text, Any, List, Union, Optional from json import loads, JSONDecodeError from rasa_sdk.events import EventType, SlotSet from rasa_sdk.forms import FormAction, REQUESTED_SLOT, Form from rasa_sdk.executor import CollectingDispatcher from rasa_sdk.events import AllSlotsReset from .responses import RESPONSES, WORKFLOW from rasa_sdk import Tracker, Action from .api.report_generator import ( generate_report, request_values, generate_report_payload, check_issues, ) def get_action_with_help_intent(latest_intent: str) -> list: """ Get action name for intent name. Parameters ---------- latest_intent: Bot intent. Returns ---------- Actions name list. """ actions = [] for action, intents in WORKFLOW.items(): for intent in intents: if intent == latest_intent: actions.append(action) return actions class ReportForm(FormAction): """Collects data for report.""" def name(self) -> Text: return "report_form" def validate_period( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Dict[Text, Any]: """Validate period value.""" try: if isinstance(loads(value), list): return {"period": value} else: dispatcher.utter_message("Incorrect date. Please try again") return {"period": None} except (JSONDecodeError, TypeError): dispatcher.utter_message("Incorrect date. Please try again") return {"period": None} @staticmethod def required_slots(tracker): required_slots = ["project", "period"] if tracker.get_slot("project") == "Pick a project": required_slots.insert(1, "project_selection") return required_slots def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]: return { "project": self.from_entity(entity="project"), "project_selection": self.from_text(), "period": self.from_text(), } def request_next_slot( self, dispatcher: "CollectingDispatcher", tracker: "Tracker", domain: Dict[Text, Any], ) -> Optional[List[EventType]]: for slot in self.required_slots(tracker): if self._should_request_slot(tracker, slot): if not check_issues(): dispatcher.utter_message( text="Oops! Bugs haven't been uploaded yet. Please try again later" ) return [Form(None), AllSlotsReset()] if slot == "project_selection": response = request_values("Project") response["operation"] = "filtration" dispatcher.utter_message( json_message=response, timeout=100, ) elif slot == "period": response = { "operation": "calendar", "title": "Please choose a date", } dispatcher.utter_message(json_message=response) else: dispatcher.utter_message( template=f"utter_ask_{slot}", **tracker.slots ) return [SlotSet(REQUESTED_SLOT, slot)] # no more required slots to fill return def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: payload = generate_report_payload(tracker) message = generate_report(payload) if not message.get("filename"): message = "Oops! There is no data you’re looking for 😔" dispatcher.utter_message(text=message, timeout=100) else: message["operation"] = "report" message["filters"] = payload dispatcher.utter_message(json_message=message, timeout=100) return [AllSlotsReset()] class ActionFAQSelector(Action): """Basic FAQ response selector.""" def name(self) -> Text: return "action_faq_selector" def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: intent = tracker.latest_message["intent"].get("name") messages = RESPONSES.get("faq").get(intent) for message in messages: dispatcher.utter_message(text=message) return [] class ActionCustomFallback(Action): """Action custom fallback.""" def name(self) -> Text: return "action_custom_fallback" def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict]: latest_intent = tracker.latest_message["intent"].get("name") actions = get_action_with_help_intent(latest_intent) if actions: for action in actions: if action != tracker.latest_action_name: if action == "action_faq_selector": ActionFAQSelector().run( dispatcher=dispatcher, tracker=tracker, domain=domain, ) else: dispatcher.utter_message(template=action) elif ( latest_intent == "affirm" and tracker.events[-4].get("text") == "Do you want to learn more?" ): dispatcher.utter_message( template="utter_more_details_analysis_and_training" ) else: dispatcher.utter_message(template="utter_cannot_help") return [Form(None), AllSlotsReset()]
cca0f267aec18ee02e6b05d3dabf877f009d2934
a5dee3e5dd839bf24c04e34f1774ff9d7b1fff43
/venvs/tensorflow/lib/python3.6/fnmatch.py
1bfc742e482849966c5f34e74b2dfcbac5ffc174
[ "MIT" ]
permissive
hsnodgrass/Chatbot
17876e7e176355a1d4793b7817e0a5e527233531
7b8336a3365c50c3e156cb51d762578633d4dac2
refs/heads/master
2022-10-19T03:57:10.273171
2017-07-16T17:37:14
2017-07-16T17:37:14
95,172,310
0
1
MIT
2022-10-09T04:59:02
2017-06-23T01:45:05
Python
UTF-8
Python
false
false
31
py
/usr/lib64/python3.6/fnmatch.py
761a7acc9b2a233cc75164049125415fb69cae73
4c5608f20fa2580774d734d94198dd10648e4339
/test/vpp_ipip_tun_interface.py
6e5ade6eb3df3d311f1a783d8d2216bccaf237fb
[ "Apache-2.0" ]
permissive
mojtaba-eshghie/VPP-In-Situ-IOAM
3d1c3d01752a7934d2f060326674280e0bd93413
efebd91195eb1b0d98a4a1f5efd962ae79c77be6
refs/heads/master
2022-12-10T13:37:04.644952
2020-05-29T11:42:36
2020-05-29T11:42:36
194,249,816
2
0
Apache-2.0
2022-12-08T05:17:31
2019-06-28T09:50:05
C
UTF-8
Python
false
false
1,159
py
from vpp_tunnel_interface import VppTunnelInterface from ipaddress import ip_address class VppIpIpTunInterface(VppTunnelInterface): """ VPP IP-IP Tunnel interface """ def __init__(self, test, parent_if, src, dst): super(VppIpIpTunInterface, self).__init__(test, parent_if) self.src = src self.dst = dst def add_vpp_config(self): r = self.test.vapi.ipip_add_tunnel( tunnel={ 'src': self.src, 'dst': self.dst, 'table_id': 0, 'instance': 0xffffffff, }) self.set_sw_if_index(r.sw_if_index) self.test.registry.register(self, self.test.logger) def remove_vpp_config(self): self.test.vapi.ipip_del_tunnel(sw_if_index=self._sw_if_index) def query_vpp_config(self): ts = self.test.vapi.ipip_tunnel_dump(sw_if_index=0xffffffff) for t in ts: if t.tunnel.sw_if_index == self._sw_if_index: return True return False def __str__(self): return self.object_id() def object_id(self): return "ipip-%d" % self._sw_if_index
44346aeefb47e47c8a5bb430be1212dd468b75c0
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/WLKF79mxKnhjtrFRB_15.py
ec801d798caa324b8d8c58381efa49d628ae96e0
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
192
py
def is_good_match(lst): if len(lst) % 2 == 1: return "bad match" else: arr = [] i = 0 while i < len(lst): arr.append(lst[i] + lst[i+1]) i += 2 return arr
4f3cbcad439bda75a73b98cde610a99c85c288c2
833b43575815ce6c5fa8cbac2628cb774331eda7
/chap11_p208_code3.py
058f6b30f32ce9b2502ec1382e81358e712a6821
[]
no_license
ai-times/infinitybook_python
d9529dfe7d486bf5c713d52b530915a23cbf1812
1c011c31994d07fe959bba9b519c4365f5f40e7f
refs/heads/main
2023-03-01T12:18:20.695888
2021-02-14T04:22:40
2021-02-14T04:22:40
338,578,047
0
0
null
null
null
null
UTF-8
Python
false
false
97
py
n = 100 while n<= 150 : print("Count ", n) n += 5 print("종료합니다.")
b7df96df10ecc11c9aba8c67da97b71ad4c027a4
bb150497a05203a718fb3630941231be9e3b6a32
/models/PaddleHub/hub_all_func/all_module/all_spinalnet_res50_gemstone.py
067d964d381f6ca7b6630d4f597a3c9537170d28
[]
no_license
PaddlePaddle/PaddleTest
4fb3dec677f0f13f7f1003fd30df748bf0b5940d
bd3790ce72a2a26611b5eda3901651b5a809348f
refs/heads/develop
2023-09-06T04:23:39.181903
2023-09-04T11:17:50
2023-09-04T11:17:50
383,138,186
42
312
null
2023-09-13T11:13:35
2021-07-05T12:44:59
Python
UTF-8
Python
false
false
559
py
"""spinalnet_res50_gemstone""" import os import paddle import paddlehub as hub import cv2 if paddle.is_compiled_with_cuda(): paddle.set_device("gpu") use_gpu = True else: paddle.set_device("cpu") use_gpu = False def test_spinalnet_res50_gemstone_predict(): """spinalnet_res50_gemstone predict""" os.system("hub install spinalnet_res50_gemstone") classifier = hub.Module(name="spinalnet_res50_gemstone") result = classifier.predict(["doc_img.jpeg"]) print(result) os.system("hub uninstall spinalnet_res50_gemstone")
6971b11f655b673532cf1a066881ac27f4e2a1b9
6fcfb638fa725b6d21083ec54e3609fc1b287d9e
/python/eliben_deep-learning-samples/deep-learning-samples-master/ud730/assign5_cbow.py
d84f68e0e772e796b8949a82b3fde5dd5521b697
[]
no_license
LiuFang816/SALSTM_py_data
6db258e51858aeff14af38898fef715b46980ac1
d494b3041069d377d6a7a9c296a14334f2fa5acc
refs/heads/master
2022-12-25T06:39:52.222097
2019-12-12T08:49:07
2019-12-12T08:49:07
227,546,525
10
7
null
2022-12-19T02:53:01
2019-12-12T07:29:39
Python
UTF-8
Python
false
false
7,497
py
from __future__ import print_function import itertools import math import numpy as np import os import random import tensorflow as tf from six.moves import cPickle as pickle from timer import Timer from word_utils import read_data, build_dataset, report_words_distance def generate_batch_cbow(data, batch_size, context_size): """ Args: data: List of IDs - the input sequence. batch_size: Number of samples to generate. context_size: How many words to consider around the target word, left and right. With context_size=2, in the sentence above for "consider" as the target word, the context will be [words, to, around, the]. Yields: Pairs of (context, label) where context is an array with shape (batch_size, context_size * 2) and label is an array with shape (batch_size,). For each context vector, a single label is matched (target ID). """ data_index = 0 window_size = 2 * context_size + 1 while True: context = np.zeros((batch_size, context_size * 2), dtype=np.int32) label = np.zeros((batch_size, 1), dtype=np.int32) for b in range(batch_size): window_end = (data_index + window_size) % len(data) window = data[data_index:window_end] context[b, 0:context_size] = window[:context_size] context[b, context_size:] = window[context_size + 1:] label[b, 0] = window[context_size] data_index = (data_index + 1) % len(data) yield (context, label) pickle_filename = 'textdata.pickle' # Only the vocabulary_size most common words are retained in the dictionary. # All others are mapped to UNK. vocabulary_size = 50000 try: with Timer('Loading pickle...'): with open(pickle_filename, 'rb') as pickle_file: save = pickle.load(pickle_file) data = save['data'] count = save['count'] dictionary = save['dictionary'] reverse_dictionary = save['reverse_dictionary'] except: print('No pickle... recomputing data.') filename = 'text8.zip' with Timer('read_data'): words = read_data(filename) with Timer('build_dataset'): data, count, dictionary, reverse_dictionary = build_dataset(words) save = { 'data': data, 'count': count, 'dictionary': dictionary, 'reverse_dictionary': reverse_dictionary, } with open(pickle_filename, 'wb') as pickle_file: pickle.dump(save, pickle_file, pickle.HIGHEST_PROTOCOL) print('First words in data:') print(data[:50]) gen = generate_batch_cbow(data, 10, 2) for i in range(5): print(gen.next()) batch_size = 128 embedding_size = 128 # Dimension of the embedding vector. context_size = 2 # How many words to take for context, left and right # Number of input words to the network context_full_size = context_size * 2 # We pick a random validation set to sample nearest neighbors. here we limit the # validation samples to the words that have a low numeric ID, which by # construction are also the most frequent. valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # Only pick dev samples in the head of the distribution. valid_examples = np.array(random.sample(range(valid_window), valid_size)) num_sampled = 64 # Number of negative examples to sample. graph = tf.Graph() with graph.as_default(), tf.device('/cpu:0'): # Input data. train_dataset = tf.placeholder(tf.int32, shape=[batch_size, context_full_size]) train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1]) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # Variables. # The embeddings is a VxN matrix, where V is the vocabulary size and N # is the embedding dimensionality. embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size ], -1.0, 1.0)) softmax_weights = tf.Variable(tf.truncated_normal( [vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) softmax_biases = tf.Variable(tf.zeros([vocabulary_size])) # Model. # Look up embeddings for inputs, for each input... # The shape should be (batch_size, context_full_size, embedding_size). # We want to average all the context vectors within each batch, so we # reduce-mean along dimension 1. embed = tf.nn.embedding_lookup(embeddings, train_dataset) embed_mean = tf.reduce_mean(embed, reduction_indices=[1]) # Compute the softmax loss, using a sample of the negative labels each time. loss = tf.reduce_mean( tf.nn.sampled_softmax_loss(softmax_weights, softmax_biases, embed_mean, train_labels, num_sampled, vocabulary_size)) # Optimizer. # Note: The optimizer will optimize the softmax_weights AND the embeddings. # This is because the embeddings are defined as a variable quantity and the # optimizer's `minimize` method will by default modify all variable # quantities that contribute to the tensor it is passed. See docs on # `tf.train.Optimizer.minimize()` for more details. optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss) # Compute the similarity between minibatch examples and all embeddings. # We use the cosine distance: norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True)) normalized_embeddings = embeddings / norm valid_embeddings = tf.nn.embedding_lookup(normalized_embeddings, valid_dataset) similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings)) num_steps = 23001 with tf.Session(graph=graph) as session: tf.initialize_all_variables().run() print('Initialized') print('embed shape:', embed.get_shape()) print('embed_mean shape:', embed_mean.get_shape()) initial_embeddings = embeddings.eval() #do_report_distances(initial_embeddings) average_loss = 0 batch_gen = generate_batch_cbow(data, batch_size, context_size) for step, batch in itertools.izip(range(num_steps), batch_gen): batch_data, batch_labels = batch feed_dict = {train_dataset: batch_data, train_labels: batch_labels} _, l = session.run([optimizer, loss], feed_dict=feed_dict) average_loss += l if step % 2000 == 0: if step > 0: average_loss = average_loss / 2000 # The average loss is an estimate of the loss over the last 2000 # batches. print('Average loss at step %d: %f' % (step, average_loss)) average_loss = 0 # note that this is expensive (~20% slowdown if computed every 500 # steps) if step % 10000 == 0: sim = similarity.eval() for i in range(valid_size): valid_word = reverse_dictionary[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k + 1] log = 'Nearest to %s:' % valid_word for k in range(top_k): close_word = reverse_dictionary[nearest[k]] log = '%s %s,' % (log, close_word) print(log) final_embeddings = normalized_embeddings.eval() print('final_embeddings shape:', final_embeddings.shape)
357382c47b4901fd489af666983de3e30ee3f162
f00e077c1acbed3a99d73fcc0880f9eb40b396fb
/examples/menus.py
d83b87b31b75032ef36cf99a4d07d28fd9cf35d3
[]
no_license
rasql/cocos2d-tutorial
089f6ddc1d2c26f2786fb78a97e1690c4ead57ff
92bad88d51c37b30a74b32d35dac07b24a8073d6
refs/heads/master
2020-04-28T13:10:27.444561
2019-04-17T07:11:36
2019-04-17T07:11:36
175,299,934
1
4
null
null
null
null
UTF-8
Python
false
false
2,215
py
""" Raphael Holzer 16. 02. 2019 Displaying a main menu and an options menu. """ import cocos import sys from cocos.layer import * from cocos.menu import * from cocos.scene import * import pyglet pyglet.resource.path = ['../animals'] pyglet.resource.reindex() class OptionsMenu(Menu): def __init__(self): super(OptionsMenu, self).__init__('Menus') items = [] self.values = ['Mute','10','20','30','40','50','60','70','80','90','100'] self.colors = [(255, 255, 255), (255, 0, 50), (0, 255, 50), (0, 50, 255)] items.append(MenuItem('Menu', self.cb0)) items.append(MultipleMenuItem('Multiple:', self.cb, self.values, 5)) items.append(ToggleMenuItem('Toggle:', self.cb)) items.append(EntryMenuItem('Entry:', self.cb, 'abc', 10)) items.append(ColorMenuItem('Color:', self.cb, self.colors)) items.append(ImageMenuItem('bird-icon.png', self.cb0)) self.create_menu( items, zoom_in(), zoom_out() ) def cb0(self): """Callback function without callback value.""" print('cb') def cb(self, val): """Callback function with callback value.""" print('cb value =', val) class MainMenu(Menu): def __init__(self): super(MainMenu, self).__init__('Main') items = [] items.append(MenuItem('New', self.on_new_game)) items.append(MenuItem('Options', self.on_options)) items.append(MenuItem('Scores', self.on_scores)) items.append(MenuItem('Quit', self.on_quit)) self.create_menu(items, shake(), shake_back()) def on_new_game(self): print('new game') def on_options(self): self.parent.switch_to(1) def on_scores(self): print('scores') def on_quit(self): print('quit') cocos.director.pyglet.app.exit() sys.exit() def main(): director.init(resizable=True) bg = cocos.layer.ColorLayer(0, 127, 127, 255) scene = Scene() scene.add(MultiplexLayer(MainMenu(), OptionsMenu()), z=1) scene.add(bg, z=0 ) director.run(scene) if __name__ == "__main__": main()
3134ee871bcf3dc40961cafeb278a697a4097357
9da79ead6d0dda0b4959c3e7f59c603c085b1f8d
/tests/conftest.py
8e5d0ee28807793d1d9ea9ad37dc0a42e256095f
[ "MIT" ]
permissive
fariddarabi/fastapi-chameleon
34e99385e0b66b72e30af5c2ba16d4d65e0fb3f4
8012037480b402d5881760c4c9f01b6c7969c086
refs/heads/main
2023-08-26T08:56:00.294057
2021-11-14T06:27:25
2021-11-14T06:27:25
427,679,374
0
0
MIT
2021-11-14T06:43:05
2021-11-13T13:56:17
null
UTF-8
Python
false
false
380
py
import pytest from pathlib import Path import fastapi_chameleon as fc @pytest.fixture def test_templates_path(pytestconfig): return Path(pytestconfig.rootdir, "tests", "templates") @pytest.fixture def setup_global_template(test_templates_path): fc.global_init(str(test_templates_path)) yield # Clear paths so as to no affect future tests fc.engine.clear()
2080b5395f84f98f67296c859811a86d994f1c2c
dac7095e7b5ad4dae993871c1ae45cbb7a5ce5f7
/Character/23.Mayuri/Mayuri_SSS_Re.py
2c73df441ab8236d477c19d7b2c0c843f3fb5a24
[]
no_license
Lastation/RenewalAniChaos
d12a8423f4b83cb019495c59ed059451e67e0483
c3edb29af58925de55c11110ccaf927d2b5d1b39
refs/heads/master
2023-08-24T11:28:35.614844
2023-08-22T21:23:14
2023-08-22T21:23:14
246,617,812
1
0
null
null
null
null
UTF-8
Python
false
false
6,999
py
import Function as f; const s = StringBuffer(); function main(cp) { if (f.delay[cp] == 0) { if (f.count[cp] == 0) { if (f.loop[cp] == 0) { f.SquareShape(cp, 1, "Target", 50, 50); f.SquareShape(cp, 1, " Creep. Dunkelheit", 50, 50); MoveLocation(f.location[cp], f.heroID[cp], cp, "Anywhere"); MoveUnit(All, " Creep. Dunkelheit", cp, "[Skill]Unit_Wait_ALL", f.location[cp]); Order(" Creep. Dunkelheit", cp, "Anywhere", Attack, f.location[cp]); KillUnitAt(All, "Target", "Anywhere", cp); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 1) { RemoveUnitAt(All, " Creep. Dunkelheit", "Anywhere", cp); f.SquareShape(cp, 1, "Target", 50, 50); f.SquareShape(cp, 1, " Creep. Dunkelheit", 50, 50); MoveLocation(f.location[cp], f.heroID[cp], cp, "Anywhere"); MoveUnit(All, " Creep. Dunkelheit", cp, "[Skill]Unit_Wait_ALL", f.location[cp]); Order(" Creep. Dunkelheit", cp, "Anywhere", Attack, f.location[cp]); KillUnitAt(All, "Target", "Anywhere", cp); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 2) { RemoveUnitAt(All, " Creep. Dunkelheit", "Anywhere", cp); f.SquareShape(cp, 1, "Target", 50, 0); f.SquareShape(cp, 1, "Target", 100, 0); KillUnitAt(All, "Target", "Anywhere", cp); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 3) { f.EdgeShape(cp, 1, "Protoss Dark Templar", 45, 5, 100); KillUnitAt(All, "Protoss Dark Templar", "Anywhere", cp); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 4) { f.EdgeShape(cp, 1, "40 + 1n Mutalisk", 0, 5, 100); KillUnitAt(All, "40 + 1n Mutalisk", "Anywhere", cp); f.EdgeShape(cp, 1, "40 + 1n Ghost", 0, 3, 100); MoveLocation(f.location[cp], f.heroID[cp], cp, "Anywhere"); MoveUnit(All, "40 + 1n Ghost", cp, "[Skill]Unit_Wait_ALL", f.location[cp]); Order("40 + 1n Ghost", cp, "Anywhere", Attack, f.location[cp]); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 5) { f.EdgeShape(cp, 1, "60 + 1n Danimoth", 0, 7, 150); KillUnitAt(All, "60 + 1n Danimoth", "Anywhere", cp); f.EdgeShape(cp, 1, "60 + 1n Archon", 0, 7, 150); KillUnitAt(All, "60 + 1n Archon", "Anywhere", cp); f.EdgeShape(cp, 1, "Kakaru (Twilight)", 0, 5, 100); KillUnitAt(All, "Kakaru (Twilight)", "Anywhere", cp); f.SkillWait(cp, 80); f.count[cp] += 1; f.loop[cp] = 0; } } else if (f.count[cp] == 1) { if (f.loop[cp] < 4) { f.DotShape(cp, 1, "Protoss Dark Templar", 100 - 25 * f.loop[cp], 25 * f.loop[cp]); f.DotShape(cp, 1, "Protoss Dark Templar", -100 + 25 * f.loop[cp], -25 * f.loop[cp]); f.DotShape(cp, 1, "40 + 1n Zealot", -25 * f.loop[cp], 100 - 25 * f.loop[cp]); f.DotShape(cp, 1, "40 + 1n Zealot", 25 * f.loop[cp], -100 + 25 * f.loop[cp]); KillUnitAt(All, "40 + 1n Zealot", "Anywhere", cp); KillUnitAt(All, "Protoss Dark Templar", "Anywhere", cp); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 4) { KillUnitAt(All, "40 + 1n Ghost", "Anywhere", cp); f.SkillWait(cp, 320); f.count[cp] += 1; f.loop[cp] = 0; } } else if (f.count[cp] == 2) { if (f.loop[cp] == 0) { f.Voice_Routine(cp, 2); f.SquareShape(cp, 1, "50 + 1n Battlecruiser", 75, 150); f.SquareShape(cp, 1, "60 + 1n Archon", 50, 100); f.SquareShape(cp, 1, "50 + 1n Battlecruiser", 150, 75); f.SquareShape(cp, 1, "60 + 1n Archon", 100, 50); KillUnitAt(All, "50 + 1n Battlecruiser", "Anywhere", cp); KillUnitAt(All, "60 + 1n Archon", "Anywhere", cp); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 1) { f.SquareShape(cp, 1, "Kakaru (Twilight)", 75, 150); f.SquareShape(cp, 1, "40 + 1n Mojo", 50, 100); f.SquareShape(cp, 1, "Kakaru (Twilight)", 150, 75); f.SquareShape(cp, 1, "40 + 1n Mojo", 100, 50); KillUnitAt(All, "Kakaru (Twilight)", "Anywhere", cp); KillUnitAt(All, "40 + 1n Mojo", "Anywhere", cp); f.SquareShape(cp, 1, "40 + 1n Ghost", 50, 100); f.SquareShape(cp, 1, "40 + 1n Ghost", 100, 50); MoveLocation(f.location[cp], f.heroID[cp], cp, "Anywhere"); MoveUnit(All, "40 + 1n Ghost", cp, "[Skill]Unit_Wait_ALL", f.location[cp]); Order("40 + 1n Ghost", cp, "Anywhere", Attack, f.location[cp]); f.SkillWait(cp, 160); f.loop[cp] += 1; } else if (f.loop[cp] == 2) { f.SquareShape(cp, 1, "40 + 1n Mutalisk", 50, 0); f.SquareShape(cp, 1, "40 + 1n Mutalisk", 100, 0); KillUnitAt(All, "40 + 1n Mutalisk", "Anywhere", cp); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 3) { f.SquareShape(cp, 1, "40 + 1n Guardian", 50, 100); f.SquareShape(cp, 1, "40 + 1n Guardian", 100, 50); KillUnitAt(All, "40 + 1n Guardian", "Anywhere", cp); f.SkillWait(cp, 80); f.loop[cp] += 1; } else if (f.loop[cp] == 4) { KillUnitAt(All, "40 + 1n Ghost", "Anywhere", cp); f.SquareShape(cp, 1, "50 + 1n Battlecruiser", 75, 150); f.SquareShape(cp, 1, "40 + 1n Ghost", 75, 150); f.SquareShape(cp, 1, "50 + 1n Battlecruiser", 150, 75); f.SquareShape(cp, 1, "40 + 1n Ghost", 150, 75); KillUnitAt(All, "50 + 1n Battlecruiser", "Anywhere", cp); MoveLocation(f.location[cp], f.heroID[cp], cp, "Anywhere"); MoveUnit(All, "40 + 1n Ghost", cp, "[Skill]Unit_Wait_ALL", f.location[cp]); Order("40 + 1n Ghost", cp, "Anywhere", Attack, f.location[cp]); f.SkillWait(cp, 320); f.count[cp] += 1; f.loop[cp] = 0; } } else if (f.count[cp] == 3) { KillUnitAt(All, "40 + 1n Ghost", "Anywhere", cp); f.SkillEnd(cp); } } }
0885548cdf5bbe0cf59c4dd0eec8952cdf0b8ec4
0ec8af8988245d864c63d923e5524403090cd7e0
/mitm/gifshow/addons.py
16b3430b8b46d322369d126b417009aed7b866dc
[]
no_license
radtek/Spider
d26b685cb5e41c67c6a7ce0d632072f3cac5f061
5a419e8ec77915804d3e659631f09b19aa90a088
refs/heads/master
2022-10-30T13:13:29.736256
2020-06-11T03:34:58
2020-06-11T03:34:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
561
py
import json import mitmproxy.http from mitmproxy import ctx class Download: def response(self, flow: mitmproxy.http.HTTPFlow): if flow.request.host != 'api.gifshow.com' or flow.request.method != 'POST': return url = flow.request.url data = flow.response.content.decode() if 'hot' in url and 'feeds' in json.loads(data): ctx.log.info('get a url:{}'.format(url)) with open('GifShow.json', 'a', encoding='utf8')as f: f.write(json.dumps(data) + '\n') addons = [Download()]
88419024324527e193a5c6b09a90736869273d4a
db8f0b2db2fe8c9b5d2cc2e33f669028da7830a8
/multidimensional_lists/snake_moves.py
dea7167f02c1d7548342216f18fc2746f3691145
[]
no_license
yordan-marinov/advanced_python
9694184eed31a9769fa1b552b087fb7b7736af84
63ad860f356978c13f208f18502a39a8f23cd18b
refs/heads/master
2023-03-29T18:04:08.252558
2021-03-26T13:39:39
2021-03-26T13:39:39
309,930,564
0
0
null
null
null
null
UTF-8
Python
false
false
447
py
def snake_moves() -> str: matrix = [] rows, cols = [int(i) for i in input().split()] string = list(input()) for row_index in range(rows): row = "" for col_index in range(cols): letter = string.pop(0) row += letter string.append(letter) if row_index % 2 != 0: row = row[::-1] matrix.append(row) return "\n".join(matrix) print(snake_moves())
9bf8cc9f91390481c2e2641bfc85865a946ef9be
bd4535b2ff5fc80234eed709f46da53b9ab260cf
/Packs/CheckPointSandBlast/Integrations/CheckPointSandBlast/CheckPointSandBlast.py
e7f58fa7c428c9ae9e08839e114ec6ed0070aa67
[ "MIT" ]
permissive
vibhuabharadwaj/content
0641284c862668b577e82e32e2daecdb9fabb39a
518da763814fefce538379560282ff8c2ce661b9
refs/heads/master
2023-03-07T21:36:31.768989
2022-09-28T15:50:46
2022-09-28T15:50:46
202,795,410
1
0
MIT
2023-03-06T17:25:01
2019-08-16T20:30:23
Python
UTF-8
Python
false
false
34,925
py
""" Check Point Threat Emulation (SandBlast) API Integration for Cortex XSOAR (aka Demisto). """ from typing import Dict, Any, List import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' GLOBAL/PARAMS ''' DEFAULT_INTERVAL = 60 DEFAULT_TIMEOUT = 600 MD5_SIZE = 32 SHA1_SIZE = 40 SHA256_SIZE = 64 DIGEST_BY_LENGTH = { MD5_SIZE: 'md5', SHA1_SIZE: 'sha1', SHA256_SIZE: 'sha256', } EXTRACTED_PARTS_CODE_BY_DESCRIPTION = { 'Linked Objects': 1025, 'Macros and Code': 1026, 'Sensitive Hyperlinks': 1034, 'PDF GoToR Actions': 1137, 'PDF Launch Actions': 1139, 'PDF URI Actions': 1141, 'PDF Sound Actions': 1142, 'PDF Movie Actions': 1143, 'PDF JavaScript Actions': 1150, 'PDF Submit Form Actions': 1151, 'Database Queries': 1018, 'Embedded Objects': 1019, 'Fast Save Data': 1021, 'Custom Properties': 1017, 'Statistic Properties': 1036, 'Summary Properties': 1037, } FEATURE_BY_NAME = { 'Threat Emulation': 'te', 'Anti-Virus': 'av', 'Threat Extraction': 'extraction', 'All': 'all' } QUOTA_HEADERS = [ 'RemainQuotaHour', 'RemainQuotaMonth', 'AssignedQuotaHour', 'AssignedQuotaMonth', 'HourlyQuotaNextReset', 'MonthlyQuotaNextReset', 'QuotaId', 'CloudMonthlyQuotaPeriodStart', 'CloudMonthlyQuotaUsageForThisGw', 'CloudHourlyQuotaUsageForThisGw', 'CloudMonthlyQuotaUsageForQuotaId', 'CloudHourlyQuotaUsageForQuotaId', 'MonthlyExceededQuota', 'HourlyExceededQuota', 'CloudQuotaMaxAllowToExceedPercentage', 'PodTimeGmt', 'QuotaExpiration', 'Action', ] ''' CLIENT CLASS ''' class Client(BaseClient): """ API Client to communicate with Check Point Threat Prevention API. """ VERSION = 'v1' def __init__(self, host: str, api_key: str, verify: bool = False, proxy: bool = False): """ Client constructor, set headers and call super class BaseClient. Args: host (str): Check Point Threat Emulation (SandBlast) API URL. api_key (str): API key to connect to the server. verify (bool): SSL verification handled by BaseClient. Defaults to False. proxy (bool): System proxy is handled by BaseClient. Defaults to False. """ super().__init__( base_url=f'{host}/tecloud/api/{Client.VERSION}/file', verify=verify, proxy=proxy, headers={ 'Authorization': api_key } ) def query_request( self, features: List[str], reports: List[str], method: str, file_name: str = None, extracted_parts_codes: List[int] = None, **kwargs ) -> Dict[str, Any]: """ Return an analysis report or status of a file that was uploaded according to a file hash. Args: features (List[str]): Features to include in the query, options: te, av, extraction. reports (List[str]): Report format for the query, options: pdf, xml, tar, summary. method (str): Threat extraction method, options: clean, pdf. file_name (str): Name of the file to query. Defaults to None. extracted_parts_codes (List[int]): Cleans file according to inserted codes. Defaults to None. **kwargs: can hold - md5 (str): md5 digest of the file to query. Defaults to None. sha1 (str): sha1 digest of the file to query. Defaults to None. sha256 (str): sha256 digest of the file to query. Defaults to None. Returns: Dict[str, Any]: Analysis report or status of the queried file. """ json_data = remove_empty_elements({ 'request': { 'features': features, 'md5': kwargs.get('md5'), 'sha1': kwargs.get('sha1'), 'sha256': kwargs.get('sha256'), 'file_name': file_name, 'te': { 'reports': reports, }, 'extraction': { 'extracted_parts_codes': extracted_parts_codes, 'method': method } } }) return self._http_request( method='POST', url_suffix='/query', json_data=json_data ) def upload_request( self, file_path: str, file_name: str, file_type: str, features: List[str], image_ids: List[str], image_revisions: List[Optional[int]], reports: List[str], method: str, extracted_parts_codes: List[int] = None, ) -> Dict[str, Any]: """ Once the file has been uploaded return an analysis report or status of a file that was uploaded. Args: file_path (str): Path to the file to upload. file_name (str): Name of the file to upload. file_type (str): Type (extension) of the file to upload. features (List[str]): Features to include when uploading, options: te, av, extraction. image_ids (List[str]): ID of available OS images. An image is an operating system configuration. image_revisions (List[int]): Revision of available OS images. An image is an operating system configuration. reports (List[str]): Report format to upload, options: pdf, xml, tar, summary. method (str): Threat extraction method, options: clean, pdf. extracted_parts_codes (List[int]): Cleans file according to inserted codes. Defaults to None. Returns: Dict[str, Any]: Analysis report or status of the uploaded file. """ request = json.dumps(remove_empty_elements({ 'request': { 'file_name': file_name, 'file_type': file_type, 'features': features, 'te': { 'reports': reports, 'images': [ {'id': image_id, 'image_revision': revision} for image_id, revision in zip(image_ids, image_revisions) ] }, 'extraction': { 'extracted_parts_codes': extracted_parts_codes, 'method': method } } })) with open(file_path, 'rb') as file_handler: file = (file_name, file_handler.read()) return self._http_request( method='POST', url_suffix='/upload', files={ 'request': request, 'file': file } ) def download_request(self, file_id: str) -> requests.Response: """ Return the file saved in the server. Args: file_id (str): ID of the file in the database. Returns: bytes: File in database. """ return self._http_request( method='GET', url_suffix='/download', params={ 'id': file_id }, resp_type='response' ) def quota_request(self) -> Dict[str, Any]: """ Return the quota information about current API key. Returns: Dict[str, Any]: Quota information. """ return self._http_request( method='POST', url_suffix='/quota', ) ''' COMMAND FUNCTIONS ''' def test_module(client: Client) -> str: """ Tests API connectivity and authentication Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. Args: client (Client): Connection to the client class from which we can run the desired request. Returns: str: 'ok' if test passed, anything else will fail the test. """ try: client.query_request( file_name='test.pdf', features=['te', 'av', 'extraction'], reports=['xml', 'summary'], method='pdf', **{'md5': '80f284ccdf2afae0f5347f4532584a61'} # type:ignore ) except DemistoException as e: e_string = str(e) if '403' in e_string: return 'Authorization Error: make sure API Key is correctly set' if '404' in e_string: return 'URL Error: make sure URL is correctly set' return e_string return 'ok' def file_command(client: Client, args: Dict[str, Any]) -> List[CommandResults]: """ Get file_hash list from user input and check if they are in the correct format. Client will make a Query request with every file_hash, if the file_hash exists in the server a dbot_score will be calculated. Args: client (Client): Connection to the client class from which we can run the desired request. args (Dict[str, Any]): Arguments passed down by the CLI to provide in the HTTP request. Raises: ValueError: In case the file_hash isn't Returns: List[CommandResults]: Indicator for every file_hash """ files = argToList(args['file']) command_results: List[CommandResults] = [] for file_hash in files: try: hash_type = get_hash_type(file_hash) if hash_type not in ('md5', 'sha1', 'sha256'): raise ValueError(f'Hash "{file_hash}" is not of type SHA-256, SHA-1 or MD5') raw_response = client.query_request( features=['te', 'av', 'extraction'], reports=['xml', 'summary'], method='pdf', **{hash_type: file_hash} ) label = dict_safe_get(raw_response, ['response', 'status', 'label']) if label not in ('FOUND', 'PARTIALLY_FOUND'): message = dict_safe_get(raw_response, ['response', 'status', 'message']) command_results.append(CommandResults(readable_output=f'File not found: "{file_hash}"\n{message}')) continue outputs = remove_empty_elements({ 'MD5': dict_safe_get(raw_response, ['response', 'md5']), 'SHA1': dict_safe_get(raw_response, ['response', 'sha1']), 'SHA256': dict_safe_get(raw_response, ['response', 'sha256']), 'Malicious': { 'Vendor': 'CheckPointSandBlast', 'Description': dict_safe_get(raw_response, ['response', 'av', 'malware_info']), } }) readable_output = tableToMarkdown( f'Results of file hash: "{file_hash}"', outputs, headers=[ 'MD5', 'SHA1', 'SHA256', 'Malicious', ] ) file_indicator = get_file_indicator(file_hash, hash_type, raw_response) command_results.append(CommandResults( readable_output=readable_output, outputs_prefix=outputPaths.get('file'), indicator=file_indicator, outputs=outputs, raw_response=raw_response, )) except Exception as e: command_results.append(CommandResults(readable_output=f'Could not process file: "{file_hash}"\n{str(e)}')) return command_results def query_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Query information of a file. The command will be a bridge between the client request and the presented value to the user. Get arguments inputted by the user and send them to the client. Once a response has been received, process and return it so it can be sent to the user. Args: client (Client): Connection to the client class from which we can run the desired request. args (Dict[str, Any]): Arguments passed down by the CLI to provide in the HTTP request. Raises: ValueError: reports input was invalid. ValueError: file_hash input was invalid. Returns: CommandResults: Information about the queried file. """ file_name = args.get('file_name', '') file_hash = args['file_hash'] features = argToList(args.get('features', '')) reports = argToList(args.get('reports')) method = args.get('method', '') extracted_parts = argToList(args.get('extracted_parts')) features = [FEATURE_BY_NAME[feature] for feature in features] if 'all' in features: features = ['te', 'av', 'extraction'] if 'te' in features and {'pdf', 'summary'}.issubset(reports): raise ValueError( 'Requesting for PDF and summary reports simultaneously is not supported!' ) if method != 'clean': extracted_parts_codes = None else: extracted_parts_codes = [ EXTRACTED_PARTS_CODE_BY_DESCRIPTION[extracted_part] for extracted_part in extracted_parts ] file_hash_size = len(file_hash) digest = DIGEST_BY_LENGTH.get(file_hash_size) if digest is None: raise ValueError('file_hash is not recognized!') raw_output = client.query_request( file_name=file_name, features=features, reports=reports, method=method, extracted_parts_codes=extracted_parts_codes, **{digest: file_hash} ) output = raw_output.get('response', {'': ''}) readable_output = get_analysis_readable_output(features, output, 'Query') output = get_analysis_context_output(output) return CommandResults( readable_output=readable_output, outputs_prefix='SandBlast.Query', outputs_key_field=['MD5', 'SHA1', 'SHA256'], outputs=output, raw_response=raw_output, ) def upload_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Upload a file to the server. The command will be a bridge between the client request and the presented value to the user. Get arguments inputted by the user and send them to the client. Once a response has been received, process and return it so it can be sent to the user. Args: client (Client): Connection to the client class from which we can run the desired request. args (Dict[str, Any]): Arguments passed down by the CLI to provide in the HTTP request. Raises: ValueError: The new file's name extension is different from the original. ValueError: The length of image_id and image_revision isn't equal. ValueError: Reports input was invalid. Returns: CommandResults: Information about the uploaded file. """ file_id = args['file_id'] file_name = args.get('file_name') features = argToList(args.get('features')) image_ids = argToList(args.get('image_ids')) image_revisions = [arg_to_number(image_revision) for image_revision in argToList(args.get('image_revisions'))] reports = argToList(args.get('reports')) method = args.get('method', '') extracted_parts = argToList(args.get('extracted_parts')) file_entry = demisto.getFilePath(file_id) if not file_name: file_name = file_entry['name'] file_type = os.path.splitext(file_name)[1] if file_type != os.path.splitext(file_entry['name'])[1]: raise ValueError('New file name must have the same extension as the original file!') features = [FEATURE_BY_NAME[feature] for feature in features] if 'all' in features: features = ['te', 'av', 'extraction'] if len(image_ids) != len(image_revisions): raise ValueError('Image IDs and image revisions must be of same length!') if 'te' in features and {'pdf', 'summary'}.issubset(reports): raise ValueError( 'Requesting for PDF and summary reports simultaneously is not supported!' ) if method != 'clean': extracted_parts_codes = None else: extracted_parts_codes = [ EXTRACTED_PARTS_CODE_BY_DESCRIPTION[extracted_part] for extracted_part in extracted_parts ] raw_output = client.upload_request( file_path=file_entry['path'], file_name=file_name, file_type=file_type, features=features, image_ids=image_ids, image_revisions=image_revisions, reports=reports, method=method, extracted_parts_codes=extracted_parts_codes, ) output = raw_output.get('response', {'': ''}) readable_output = get_analysis_readable_output(features, output, 'Upload') output = get_analysis_context_output(output) return CommandResults( readable_output=readable_output, outputs_prefix='SandBlast.Upload', outputs_key_field=['MD5', 'SHA1', 'SHA256'], outputs=output, raw_response=raw_output, ) def download_command(client: Client, args: Dict[str, Any]) -> Any: """ Download a file from the server. The command will be a bridge between the client request and the presented value to the user. Get arguments inputted by the user and send them to the client. Once a response has been received, process and return it so it can be sent to the user. Args: client (Client): Connection to the client class from which we can run the desired request. args (Dict[str, Any]): Arguments passed down by the CLI to provide in the HTTP request. Returns: Any: File from the server. """ file_id = args['file_id'] output = client.download_request(file_id) content_disposition = output.headers.get("Content-Disposition") split_content_disposition = content_disposition.split('"') if content_disposition is not None else [] if len(split_content_disposition) < 2: file_name = 'file.pdf' else: file_name = split_content_disposition[1] return fileResult(filename=file_name, data=output.content) def quota_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Get quota information about an API key. The command will be a bridge between the client request and the presented value to the user. Once a response has been received, process and return it so it can be sent to the user. Args: client (Client): Connection to the client class from which we can run the desired request. args (Dict[str, Any]): Arguments passed down by the CLI to provide in the HTTP request. Returns: CommandResults: Quota information about the API key. """ raw_outputs = client.quota_request() outputs = raw_outputs.get('response')[0] # type:ignore output = get_quota_context_output(outputs) readable_output = tableToMarkdown( 'Quota Information', output, headers=QUOTA_HEADERS, headerTransform=string_to_table_header, removeNull=True, ) return CommandResults( readable_output=readable_output, outputs_prefix='SandBlast.Quota', outputs_key_field='QuotaId', outputs=output, raw_response=raw_outputs, ) ''' POLLING COMMANDS ''' def setup_upload_polling_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Initiate polling command for upload command. Args: client (Client): Connection to the client class from which we can run the desired request. args (Dict[str, Any]): Arguments passed down by the CLI to provide in the HTTP request. Returns: CommandResults: A result to return to the user which will be presented in a markdown value. The result itself will depend on the stage of polling. """ return upload_polling_command(args, client=client) @polling_function( name='sandblast-upload', interval=arg_to_number(demisto.args().get('interval_in_seconds', DEFAULT_INTERVAL)), timeout=arg_to_number(demisto.args().get('timeout_in_seconds', DEFAULT_TIMEOUT)), requires_polling_arg=False, ) def upload_polling_command(args: Dict[str, Any], **kwargs) -> PollResult: """ Polling command to display the progress of the upload command. After the first run, progress will be shown through the query command. Once a new file is uploaded to the server, upload command will provide the status 'UPLOAD_SUCCESS' and pass arguments to the with query command. Query command will run till its status is 'FOUND' or 'PARTIALLY_FOUND', which is the ending term for the polling command. Args: args (Dict[str, Any]): Arguments passed down by the CLI to provide in the HTTP request and a Client. Returns: PollResult: A result to return to the user which will be set as a CommandResults. The result itself will depend on the stage of polling. """ if 'file_hash' not in args: command_results = upload_command(kwargs['client'], args) else: command_results = query_command(kwargs['client'], args) raw_response = command_results.raw_response file_name = dict_safe_get(raw_response, ['response', 'file_name']) file_hash = dict_safe_get(raw_response, ['response', 'md5']) label = dict_safe_get(raw_response, ['response', 'status', 'label']) if label in ('FOUND', 'PARTIALLY_FOUND'): return PollResult( response=command_results, continue_to_poll=False, ) polling_args = { 'file_name': file_name, 'file_hash': file_hash, **args } return PollResult( response=command_results, continue_to_poll=True, args_for_next_run=polling_args, partial_result=command_results ) ''' HELPER FUNCTIONS ''' def get_analysis_context_output(output: Dict[str, Any]) -> Dict[str, Any]: av = dict_safe_get(output, ['av']) malware_info = dict_safe_get(av, ['malware_info']) extraction = dict_safe_get(output, ['extraction']) extraction_data = dict_safe_get(extraction, ['extraction_data']) te = dict_safe_get(output, ['te']) return remove_empty_elements({ 'Status': dict_safe_get(output, ['status']), 'MD5': dict_safe_get(output, ['md5']), 'SHA1': dict_safe_get(output, ['sha1']), 'SHA256': dict_safe_get(output, ['sha256']), 'FileType': dict_safe_get(output, ['file_type']), 'FileName': dict_safe_get(output, ['file_name']), 'Features': dict_safe_get(output, ['features']), 'AntiVirus': { 'SignatureName': dict_safe_get(malware_info, ['signature_name']), 'MalwareFamily': dict_safe_get(malware_info, ['malware_family']), 'MalwareType': dict_safe_get(malware_info, ['malware_type']), 'Severity': dict_safe_get(malware_info, ['severity']), 'Confidence': dict_safe_get(malware_info, ['confidence']), 'Status': dict_safe_get(av, ['status']), }, 'ThreatExtraction': { 'Method': dict_safe_get(extraction, ['method']), 'ExtractResult': dict_safe_get(extraction, ['extract_result']), 'ExtractedFileDownloadId': dict_safe_get(extraction, ['extracted_file_download_id']), 'OutputFileName': dict_safe_get(extraction, ['output_file_name']), 'Time': dict_safe_get(extraction, ['time']), 'ExtractContent': dict_safe_get(extraction, ['extract_content']), 'TexProduct': dict_safe_get(extraction, ['tex_product']), 'Status': dict_safe_get(extraction, ['status']), 'ExtractionData': { 'InputExtension': dict_safe_get(extraction_data, ['input_extension']), 'InputRealExtension': dict_safe_get(extraction_data, ['input_real_extension']), 'Message': dict_safe_get(extraction_data, ['message']), 'ProtectionName': dict_safe_get(extraction_data, ['protection_name']), 'ProtectionType': dict_safe_get(extraction_data, ['protection_type']), 'ProtocolVersion': dict_safe_get(extraction_data, ['protocol_version']), 'RealExtension': dict_safe_get(extraction_data, ['real_extension']), 'Risk': dict_safe_get(extraction_data, ['risk']), 'ScrubActivity': dict_safe_get(extraction_data, ['scrub_activity']), 'ScrubMethod': dict_safe_get(extraction_data, ['scrub_method']), 'ScrubResult': dict_safe_get(extraction_data, ['scrub_result']), 'ScrubTime': dict_safe_get(extraction_data, ['scrub_time']), 'ScrubbedContent': dict_safe_get(extraction_data, ['scrubbed_content']), }, }, 'ThreatEmulation': { 'Trust': dict_safe_get(te, ['trust']), 'Score': dict_safe_get(te, ['score']), 'CombinedVerdict': dict_safe_get(te, ['combined_verdict']), 'Images': dict_safe_get(te, ['images']), 'Status': dict_safe_get(te, ['status']), } }) def get_analysis_readable_output( features: List[str], output: Dict[str, Any], command: str ) -> Any: """ Get a response outputs and set them to be readable outputs with tableToMarkdown. Args: features (Dict[str, Any]): Features in the HTTP response. output (Dict[str, Any]): HTTP response outputs which will be processed. command (str): Name of the calling command. Returns: Any: Readable outputs which have been set to Markdown """ readable_output = f'{command} Results\n' status_label = dict_safe_get(output, ['status', 'label']) output_file_info = { 'FileName': dict_safe_get(output, ['file_name']), 'FileType': dict_safe_get(output, ['file_type']), 'Label': status_label, 'Message': dict_safe_get(output, ['status', 'message']), 'MD5': dict_safe_get(output, ['md5']), 'SHA1': dict_safe_get(output, ['sha1']), 'SHA256': dict_safe_get(output, ['sha256']), } headers_file_info = [ 'FileName', 'FileType', 'Label', 'Message', 'MD5', 'SHA1', 'SHA256', ] readable_output += tableToMarkdown( 'File Info', output_file_info, headers=headers_file_info, headerTransform=string_to_table_header, removeNull=True, ) if status_label not in ('FOUND', 'PARTIALLY_FOUND'): return readable_output if 'te' in features: output_te = { 'CombinedVerdict': dict_safe_get(output, ['te', 'combined_verdict']), 'Severity': dict_safe_get(output, ['te', 'severity']), 'Confidence': dict_safe_get(output, ['te', 'confidence']), 'Verdict': dict_safe_get(output, ['te', 'verdict']), } headers_te = [ 'CombinedVerdict', 'Severity', 'Confidence', 'Verdict', ] readable_output += tableToMarkdown( 'Threat Emulation', output_te, headers=headers_te, headerTransform=string_to_table_header, removeNull=True, ) if 'av' in features: output_av = { 'SignatureName': dict_safe_get(output, ['av', 'malware_info', 'signature_name']), 'MalwareFamily': dict_safe_get(output, ['av', 'malware_info', 'malware_family']), 'MalwareType': dict_safe_get(output, ['av', 'malware_info', 'malware_type']), 'Confidence': dict_safe_get(output, ['av', 'malware_info', 'confidence']), 'Severity': dict_safe_get(output, ['av', 'malware_info', 'severity']), } headers_av = [ 'SignatureName', 'MalwareFamily', 'MalwareType', 'Confidence', 'Severity', ] readable_output += tableToMarkdown( 'Anti-Virus', output_av, headers=headers_av, headerTransform=string_to_table_header, removeNull=True, ) if 'extraction' in features: output_extraction = { 'ExtractResult': dict_safe_get(output, ['extraction', 'extract_result']), 'ExtractedFileDownloadId': dict_safe_get(output, ['extraction', 'extracted_file_download_id']), 'Risk': dict_safe_get(output, ['extraction', 'extraction_data', 'risk']), } headers_extraction = [ 'ExtractResult', 'ExtractedFileDownloadId', 'Risk', ] readable_output += tableToMarkdown( 'Threat Extraction', output_extraction, headers=headers_extraction, headerTransform=string_to_table_header, removeNull=True, ) return readable_output def get_dbotscore(response: Dict[str, Any]) -> int: """ Response received from the API request which holds fields that will help indicate the DBotScore. Args: response (Dict[str, Any]): Response received from the API request. Returns: int: A score to represent the reputation of an indicator. """ av_confidence = dict_safe_get(response, ['response', 'av', 'malware_info', 'confidence']) av_severity = dict_safe_get(response, ['response', 'av', 'malware_info', 'severity']) te_confidence = dict_safe_get(response, ['response', 'te', 'confidence']) te_severity = dict_safe_get(response, ['response', 'te', 'severity']) te_combined_verdict = dict_safe_get(response, ['response', 'te', 'combined_verdict']) if av_confidence == 0 and av_severity == 0 and \ te_combined_verdict == 'benign' and te_severity is None and (te_confidence == 1 or te_confidence is None): score = Common.DBotScore.GOOD elif te_severity == 1: score = Common.DBotScore.SUSPICIOUS else: score = Common.DBotScore.BAD return score def get_file_indicator(file_hash: str, hash_type: str, response: Dict[str, Any]) -> Common.File: """ Returns a file indicator that could potentially be malicious and will be checked for reputation. Args: file_hash (str): File hash value hash_type (str): File hash type. response (Dict[str, Any]): Response received from the API request. Returns: Common.File: File indicator. """ dbot_score = Common.DBotScore( indicator=file_hash, indicator_type=DBotScoreType.FILE, integration_name='CheckPointSandBlast', reliability=DBotScoreReliability.C, score=get_dbotscore(response), ) file_name = dict_safe_get(response, ['response', 'file_name']) if not file_name: file_type = None else: file_type = os.path.splitext(file_name)[1] file_indicator = Common.File( dbot_score=dbot_score, name=file_name, file_type=file_type, **{hash_type: file_hash} ) return file_indicator def get_date_string(timestamp_string: str = '0') -> str: """ Cast timestamp to int and convert it to a datetime string. Args: timestamp_string (str, optional): Holds a timestamp to be converted. Defaults to '0'. Returns: str: A string with the timestamp in datetime format. """ timestamp = int(timestamp_string) * 1000 return timestamp_to_datestring(timestamp) def get_quota_context_output(outputs: Dict[str, Any]) -> Dict[str, Any]: """ Convert outputs keys to PascalCase and convert any timestamp to date format. Args: outputs (Dict[str, Any]): API key quota information. Returns: Dict[str, Any]: outputs in a more readable form. """ response_by_context = { 'RemainQuotaHour': 'remain_quota_hour', 'RemainQuotaMonth': 'remain_quota_month', 'AssignedQuotaHour': 'assigned_quota_hour', 'AssignedQuotaMonth': 'assigned_quota_month', 'HourlyQuotaNextReset': 'hourly_quota_next_reset', 'MonthlyQuotaNextReset': 'monthly_quota_next_reset', 'QuotaId': 'quota_id', 'CloudMonthlyQuotaPeriodStart': 'cloud_monthly_quota_period_start', 'CloudMonthlyQuotaUsageForThisGw': 'cloud_monthly_quota_usage_for_this_gw', 'CloudHourlyQuotaUsageForThisGw': 'cloud_hourly_quota_usage_for_this_gw', 'CloudMonthlyQuotaUsageForQuotaId': 'cloud_monthly_quota_usage_for_quota_id', 'CloudHourlyQuotaUsageForQuotaId': 'cloud_hourly_quota_usage_for_quota_id', 'MonthlyExceededQuota': 'monthly_exceeded_quota', 'HourlyExceededQuota': 'hourly_exceeded_quota', 'CloudQuotaMaxAllowToExceedPercentage': 'cloud_quota_max_allow_to_exceed_percentage', 'PodTimeGmt': 'pod_time_gmt', 'QuotaExpiration': 'quota_expiration', 'Action': 'action', } context_outputs_with_date = [ 'HourlyQuotaNextReset', 'MonthlyQuotaNextReset', 'CloudMonthlyQuotaPeriodStart', 'PodTimeGmt', 'QuotaExpiration', ] output: Dict[str, Any] = {} for context_output, response in response_by_context.items(): output[context_output] = outputs.get(response) for key in context_outputs_with_date: output[key] = get_date_string(output[key]) return output ''' MAIN FUNCTION ''' def main() -> None: """ Getting data from instance setting and setting up the class Client with an API key. Checking user input command with if statements and a dictionary. """ params: Dict[str, Any] = demisto.params() args: Dict[str, Any] = demisto.args() command = demisto.command() api_key = params['credentials']['password'] host = params['url'] verify_certificate = not params.get('insecure', False) proxy = params.get('proxy', False) commands = { 'sandblast-query': query_command, 'sandblast-upload': setup_upload_polling_command, 'sandblast-download': download_command, 'sandblast-quota': quota_command, } demisto.debug(f'Command being called is {command}') try: client = Client( host=host, api_key=api_key, verify=verify_certificate, proxy=proxy, ) if command == 'test-module': return_results(test_module(client)) elif command in commands: return_results(commands[command](client, args)) else: raise NotImplementedError(f'Command doesn\'t exist - {command}') except Exception as e: demisto.error(traceback.format_exc()) return_error(f'Failed to execute {command} command.\nError:\n{str(e)}') if __name__ in ('__main__', '__builtin__', 'builtins'): main()
c01708c178cb7f4fb3e079d15cf5fe767d065105
a4653fb6c5a7a9e6db0457480e9e860c5304b2b8
/list/add_data.py
cd7bcc9d527b542225e807d86bed20426b453b10
[]
no_license
pratik-iiitkalyani/Python
c315ca1f3a2446ccb871b74026edae97daec3773
082ae6d833f151054567d737de543898ebfe1d87
refs/heads/master
2020-08-07T05:59:21.930089
2020-01-04T17:05:27
2020-01-04T17:05:27
213,324,642
0
0
null
null
null
null
UTF-8
Python
false
false
378
py
# insert method(pos, element) - add data at any position in the list fruits = ["mango","grapes"] fruits.insert(1,"orange") print(fruits) # join two list fruits1 =[1,3] c = fruits1+fruits # fruits1 element come first print(c) #extend method fruits.extend(fruits1) # data of fruits1 added in fruits print(fruits) fruits.append(fruits1) # list inside list print(fruits)
49f9e83cf5c3c542e747db4cd758556b228b23d9
4f9952b7c587c7facb0903d52f6ea4b98786e16d
/Proyecto.py
3e3a92c082cf6f9c0f6d928080961e76734a2c99
[]
no_license
sugar-activities/4786-activity
39a8bed48a81c727d7e3e58cec6fed12ee5d5936
602ca2794da4575df63b124a56534c26dd01d7c7
refs/heads/master
2021-01-19T23:15:30.980502
2017-04-21T05:11:53
2017-04-21T05:11:53
88,939,797
0
0
null
null
null
null
UTF-8
Python
false
false
80,580
py
#!/usr/bin/python import pygame import sys, gtk import pygame.locals from pygame.constants import * from pygame.mixer import music from Cursor import CURSOR #pygame.init() x=1200 y=900 ocultar = 1 class interfaz(): def __init__(self): self.Portada = pygame.image.load("img/Portada.png") self.menu = pygame.image.load("img/Menu.jpg") self.bienvenida = pygame.image.load("img/Bienvenida.png") self.ayuda = pygame.image.load("img/interfaz_Ayuda.png") self.ayuda_actividad = pygame.image.load("img/AYUDA_1.png") self.cir = pygame.image.load("img/Circulo.png") self.circ = pygame.image.load("img/circulo_centro.png") self.cirr = pygame.image.load("img/circulo_radio.png") self.triang = pygame.image.load("img/Triangulo.png") self.triangv = pygame.image.load("img/triangulo_vertice.png") self.triangl = pygame.image.load("img/triangulo_lado.png") self.trianga = pygame.image.load("img/triangulo_altura.png") self.triangb = pygame.image.load("img/triangulo_base.png") self.triangcla = pygame.image.load("img/triangulo_clasificacion.png") self.bienvecir = pygame.image.load("img/portada_actividad_cir.png") self.preg1_cir = pygame.image.load("img/actividad1_circulo/Actividad_Circulo.png") self.preg1_cirbien = pygame.image.load("img/actividad1_circulo/Actividad_Circulo_bien.png") self.preg1_cirmalo1 = pygame.image.load("img/actividad1_circulo/Actividad_Circulo_malo_1.png") self.preg1_cirmalo2 = pygame.image.load("img/actividad1_circulo/Actividad_Circulo_malo_2.png") self.preg2_cir = pygame.image.load("img/actividad2_circulo/Actividad_Circulo_2.png") self.preg2_cirbien = pygame.image.load("img/actividad2_circulo/Actividad_Circulo_2_bien.png") self.preg2_cirmalo1 = pygame.image.load("img/actividad2_circulo/Actividad_Circulo_2_malo_1.png") self.preg2_cirmalo2 = pygame.image.load("img/actividad2_circulo/Actividad_Circulo_2_malo_2.png") self.preg3_cir = pygame.image.load("img/actividad3_circulo/ACTV_3.png") self.preg3_cirbien = pygame.image.load("img/actividad3_circulo/ACTV_3_bien.png") self.preg3_cirmalo1 = pygame.image.load("img/actividad3_circulo/ACTV_3_malo_1.png") self.preg3_cirmalo2 = pygame.image.load("img/actividad3_circulo/ACTV_3_malo_2.png") self.preg4_cir = pygame.image.load("img/actividad4_circulo/ACTV_3_circunferencia.png") self.preg4_cirbien = pygame.image.load("img/actividad4_circulo/ACTV_3_circunferencia_bien.png") self.preg4_cirmalo1 = pygame.image.load("img/actividad4_circulo/ACTV_3_circunferencia_malo_1.png") self.preg4_cirmalo2 = pygame.image.load("img/actividad4_circulo/ACTV_3_circunferencia_malo_2.png") self.preg5_cir = pygame.image.load("img/actividad5_circulo/ACTV_3_radio.png") self.preg5_cirbien = pygame.image.load("img/actividad5_circulo/ACTV_3_radio_Bien.png") self.preg5_cirmalo1 = pygame.image.load("img/actividad5_circulo/ACTV_3_radio_malo_1.png") self.preg5_cirmalo2 = pygame.image.load("img/actividad5_circulo/ACTV_3_radio_malo_2.png") self.preg6_cir = pygame.image.load("img/actividad6_circulo/Actividad_circulo_4.png") self.preg6_cirbien = pygame.image.load("img/actividad6_circulo/Actividad_circulo_4_bien.png") self.preg6_cirmalo1 = pygame.image.load("img/actividad6_circulo/Actividad_circulo_4_malo.png") self.preg6_cirmalo2 = pygame.image.load("img/actividad6_circulo/Actividad_circulo_4_malo_2.png") self.pregfin_cir = pygame.image.load("img/final_actividades_cir.png") self.triangequi =pygame.image.load("img/triangulo_Equilatero.png") self.triangiso =pygame.image.load("img/triangulo_Isosceles.png") self.triangesca =pygame.image.load("img/triangulo_escaleno.png") self.triangbien = pygame.image.load("img/portada_actividad_triangulo.png") self.preg1_triang = pygame.image.load("img/actividad1_triangulo/actividad_1_Triangulo.png") self.preg1_triangbien = pygame.image.load("img/actividad1_triangulo/actividad_1_Triangulo_bien.png") self.preg1_triangmalo1 = pygame.image.load("img/actividad1_triangulo/actividad_1_Triangulo_malo_1.png") self.preg1_triangmalo2 = pygame.image.load("img/actividad1_triangulo/actividad_1_Triangulo_malo_2.png") self.preg2_triang = pygame.image.load("img/actividad2_triangulo/actividad_1_Triangulo.png") self.preg2_triangbien = pygame.image.load("img/actividad2_triangulo/actividad_1_Triangulo_bien.png") self.preg2_triangmalo1 = pygame.image.load("img/actividad2_triangulo/actividad_1_Triangulo_malo_1.png") self.preg2_triangmalo2 = pygame.image.load("img/actividad2_triangulo/actividad_1_Triangulo_malo_2.png") self.preg3_triang = pygame.image.load("img/actividad3_triangulo/actividad_1_Triangulo.png") self.preg3_triangbien = pygame.image.load("img/actividad3_triangulo/actividad_1_Triangulo_bien.png") self.preg3_triangmalo1 = pygame.image.load("img/actividad3_triangulo/actividad_1_Triangulo_malo_1.png") self.preg3_triangmalo2 = pygame.image.load("img/actividad3_triangulo/actividad_1_Triangulo_malo_2.png") self.preg4_triang = pygame.image.load("img/actividad4_triangulo/actividad_1_Triangulo.png") self.preg4_triangbien = pygame.image.load("img/actividad4_triangulo/actividad_1_Triangulo_bien.png") self.preg4_triangmalo1 = pygame.image.load("img/actividad4_triangulo/actividad_1_Triangulo_malo_1.png") self.preg4_triangmalo2 = pygame.image.load("img/actividad4_triangulo/actividad_1_Triangulo_malo_2.png") self.preg5_triang = pygame.image.load("img/actividad5_triangulo/actividad_1_Triangulo.png") self.preg5_triangbien = pygame.image.load("img/actividad5_triangulo/actividad_1_Triangulo_bien.png") self.preg5_triangmalo1 = pygame.image.load("img/actividad5_triangulo/actividad_1_Triangulo_mal.png") self.preg5_triangmalo2 = pygame.image.load("img/actividad5_triangulo/actividad_1_Triangulo_ma_2l.png") self.preg6_triang = pygame.image.load("img/actividad6_triangulo/actividad_1_Triangulo.png") self.preg6_triangbien = pygame.image.load("img/actividad6_triangulo/actividad_1_Triangulo_bien.png") self.preg6_triangmalo1 = pygame.image.load("img/actividad6_triangulo/actividad_1_Triangulo_malo_1.png") self.preg6_triangmalo2 = pygame.image.load("img/actividad6_triangulo/actividad_1_Triangulo_malo_2.png") self.preg7_triang = pygame.image.load("img/actividad7_triangulo/actividad_1_Triangulo.png") self.preg7_triangbien = pygame.image.load("img/actividad7_triangulo/actividad_1_Triangulo.png_bien.png") self.preg7_triangmalo1 = pygame.image.load("img/actividad7_triangulo/actividad_1_Triangulo.png_malo_1.png") self.preg7_triangmalo2 = pygame.image.load("img/actividad7_triangulo/actividad_1_Triangulo.png_malo_2.png") self.pregfin_triang = pygame.image.load("img/portada_actividad_triangulo_final.png") self.cuadra =pygame.image.load("img/Cuadrado.png") self.cuadral =pygame.image.load("img/cuadrado_lado.png") self.cuadrav =pygame.image.load("img/cuadrado_vertice.png") self.rect =pygame.image.load("img/rectangulo.png") self.rectv =pygame.image.load("img/Regtangulo_vertice.png") self.rombo =pygame.image.load("img/Rombo_lado.png") self.rombov =pygame.image.load("img/Rombo_vertice.png") self.trapecio =pygame.image.load("img/Trapecio_lado.png") self.trapeciov =pygame.image.load("img/Trapecio_vertice.png") self.preg1_rect = pygame.image.load("img/actividad1_rectangulo/actividad_cuadrado_1.png") self.preg1_rectgbien = pygame.image.load("img/actividad1_rectangulo/actividad_cuadrado_Bien.png") self.preg1_rectmalo1 = pygame.image.load("img/actividad1_rectangulo/actividad_cuadrado_malo_1.png") self.preg1_rectmalo2 = pygame.image.load("img/actividad1_rectangulo/actividad_cuadrado_malo_2.png") self.preg2_rect = pygame.image.load("img/actividad2_rectangulo/actividad_cuadrado_1.png") self.preg2_rectgbien = pygame.image.load("img/actividad2_rectangulo/actividad_cuadrado_bien.png") self.preg2_rectmalo1 = pygame.image.load("img/actividad2_rectangulo/actividad_cuadrado_mal.png") self.preg2_rectmalo2 = pygame.image.load("img/actividad2_rectangulo/actividad_cuadrado_mal_2.png") self.preg3_rect = pygame.image.load("img/actividad3_rectangulo/actividad_cuadrado_3.png") self.preg3_rectgbien = pygame.image.load("img/actividad3_rectangulo/actividad_cuadrado_Bien.png") self.preg3_rectmalo1 = pygame.image.load("img/actividad3_rectangulo/actividad_cuadrado_mal.png") self.preg3_rectmalo2 = pygame.image.load("img/actividad3_rectangulo/actividad_cuadrado_mal_2.png") self.preg4_rect = pygame.image.load("img/actividad4_rectangulo/actividad_cuadrado_4.png") self.preg4_rectgbien = pygame.image.load("img/actividad4_rectangulo/actividad_cuadrado_bien.png") self.preg4_rectmalo1 = pygame.image.load("img/actividad4_rectangulo/actividad_cuadrado_malo.png") self.preg5_rect = pygame.image.load("img/actividad5_rectangulo/actividad_cuadrado_5.png") self.preg5_rectgbien = pygame.image.load("img/actividad5_rectangulo/actividad_cuadrado_bien.png") self.preg5_rectmalo1 = pygame.image.load("img/actividad5_rectangulo/actividad_cuadrado_malo_1.png") self.preg5_rectmalo2 = pygame.image.load("img/actividad5_rectangulo/actividad_cuadrado_malo_2.png") self.preg6_rect = pygame.image.load("img/actividad6_rectangulo/actividad_cuadrado_6.png") self.preg6_rectgbien = pygame.image.load("img/actividad6_rectangulo/actividad_cuadrado_bien.png") self.preg6_rectmalo1 = pygame.image.load("img/actividad6_rectangulo/actividad_cuadrado_malo_1.png") self.preg6_rectmalo2 = pygame.image.load("img/actividad6_rectangulo/actividad_cuadrado_malo_2.png") self.ladrar = pygame.mixer.Sound("sonido/ladrar.ogg") def inter_principal(self, superficie): superficie.blit(self.Portada, (0,0)) def poscision_elementos_1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if (x_mouse > 459 and x_mouse <= 712) and (y_mouse > 580 and y_mouse < 634) : ocultar= 39 elif (x_mouse > 459 and x_mouse <= 712) and (y_mouse > 681 and y_mouse < 738): ocultar =13 elif (x_mouse > 462 and x_mouse <= 712) and (y_mouse > 711 and y_mouse < 799): sys.exit(0) def interfaz_ayuda(self, superficie): superficie.blit(self.ayuda, (0,0)) def poscision_elementos_ayuda(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =1 def interfaz_menu(self, superficie): superficie.blit(self.menu, (0,0)) def poscision_elementos_menu(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if (x_mouse > 94 and x_mouse <= 320) and (y_mouse > 809 and y_mouse < 860): ocultar = 1 elif (x_mouse > 125 and x_mouse <= 298) and (y_mouse > 232 and y_mouse < 420): ocultar=3 elif (x_mouse > 421 and x_mouse <= 865) and (y_mouse > 529 and y_mouse < 720): ocultar=6 elif (x_mouse > 616 and x_mouse <=1149) and (y_mouse > 322 and y_mouse < 400): ocultar=73 def interfaz_circulo(self, superficie): superficie.blit(self.cir, (0,0)) def poscision_elementos_circulo(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =2 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =4 def interfaz_circuloc(self, superficie): superficie.blit(self.circ, (0,0)) def poscision_elementos_circuloc(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =3 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =5 def interfaz_circulor(self, superficie): superficie.blit(self.cirr, (0,0)) def poscision_elementos_circulor(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =4 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =12 def interfaz_triangulo(self, superficie): superficie.blit(self.triang, (0,0)) def poscision_elementos_triangulo(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =2 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =7 def interfaz_triangulol(self, superficie): superficie.blit(self.triangl, (0,0)) def poscision_elementos_triangulol(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =6 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =8 def interfaz_triangulov(self, superficie): superficie.blit(self.triangv, (0,0)) def poscision_elementos_triangulov(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =7 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =9 def interfaz_trianguloa(self, superficie): superficie.blit(self.trianga, (0,0)) def poscision_elementos_trianguloa(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =8 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =10 def interfaz_triangulob(self, superficie): superficie.blit(self.triangb, (0,0)) def poscision_elementos_triangulob(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =9 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =11 def interfaz_triangulocla(self, superficie): superficie.blit(self.triangcla, (0,0)) def poscision_elementos_triangulocla(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =10 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =40 def interfaz_circulobienvenida(self, superficie): superficie.blit(self.bienvecir, (0,0)) def poscision_elementos_circulobienvenida(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =5 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =14 def interfaz_preg1_cir(self, superficie): superficie.blit(self.preg1_cir, (0,0)) def poscision_elementos_preg1_cir(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 603) and (y_mouse >316 and y_mouse < 383): ocultar =15 self.ladrar.play() elif(x_mouse > 410 and x_mouse<= 871) and (y_mouse >431 and y_mouse < 501): ocultar =16 elif(x_mouse > 646 and x_mouse<= 1113) and (y_mouse >319 and y_mouse < 384): ocultar =17 def interfaz_preg1_cir_bien(self, superficie): superficie.blit(self.preg1_cirbien, (0,0)) def poscision_elementos_preg1_cir_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =18 def interfaz_preg1_cir_malo1(self, superficie): superficie.blit(self.preg1_cirmalo1, (0,0)) def poscision_elementos_preg1_cir_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =14 def interfaz_preg1_cir_malo2(self, superficie): superficie.blit(self.preg1_cirmalo2, (0,0)) def poscision_elementos_preg1_cir_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =14 def interfaz_preg2_cir(self, superficie): superficie.blit(self.preg2_cir, (0,0)) def poscision_elementos_preg2_cir(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 603) and (y_mouse >316 and y_mouse < 383): ocultar =21 elif(x_mouse > 410 and x_mouse<= 871) and (y_mouse >431 and y_mouse < 501): ocultar =20 elif(x_mouse > 646 and x_mouse<= 1113) and (y_mouse >319 and y_mouse < 384): ocultar =19 self.ladrar.play() def interfaz_preg2_cir_bien(self, superficie): superficie.blit(self.preg2_cirbien, (0,0)) def poscision_elementos_preg2_cir_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =22 def interfaz_preg2_cir_malo1(self, superficie): superficie.blit(self.preg2_cirmalo1, (0,0)) def poscision_elementos_preg2_cir_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =18 def interfaz_preg2_cir_malo2(self, superficie): superficie.blit(self.preg2_cirmalo2, (0,0)) def poscision_elementos_preg2_cir_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =18 def interfaz_preg3_cir(self, superficie): superficie.blit(self.preg3_cir, (0,0)) def poscision_elementos_preg3_cir(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 495 and x_mouse<= 744) and (y_mouse >218 and y_mouse < 251): ocultar = 23 self.ladrar.play() elif(x_mouse > 107 and x_mouse<= 390) and (y_mouse >390 and y_mouse < 434): ocultar =24 elif(x_mouse > 793 and x_mouse<= 1100) and (y_mouse >591 and y_mouse < 635): ocultar =25 def interfaz_preg3_cir_bien(self, superficie): superficie.blit(self.preg3_cirbien, (0,0)) def poscision_elementos_preg3_cir_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =26 def interfaz_preg3_cir_malo1(self, superficie): superficie.blit(self.preg3_cirmalo1, (0,0)) def poscision_elementos_preg3_cir_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =22 def interfaz_preg3_cir_malo2(self, superficie): superficie.blit(self.preg3_cirmalo2, (0,0)) def poscision_elementos_preg3_cir_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =22 def interfaz_preg4_cir(self, superficie): superficie.blit(self.preg4_cir, (0,0)) def poscision_elementos_preg4_cir(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 107 and x_mouse<= 390) and (y_mouse >390 and y_mouse < 434): ocultar = 27 self.ladrar.play() elif(x_mouse > 495 and x_mouse<= 744) and (y_mouse >218 and y_mouse < 251): ocultar =28 elif(x_mouse > 793 and x_mouse<= 1100) and (y_mouse >591 and y_mouse < 635): ocultar =29 def interfaz_preg4_cir_bien(self, superficie): superficie.blit(self.preg4_cirbien, (0,0)) def poscision_elementos_preg4_cir_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =30 def interfaz_preg4_cir_malo1(self, superficie): superficie.blit(self.preg4_cirmalo1, (0,0)) def poscision_elementos_preg4_cir_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =26 def interfaz_preg4_cir_malo2(self, superficie): superficie.blit(self.preg4_cirmalo2, (0,0)) def poscision_elementos_preg4_cir_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =26 def interfaz_preg5_cir(self, superficie): superficie.blit(self.preg5_cir, (0,0)) def poscision_elementos_preg5_cir(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 793 and x_mouse<= 1100) and (y_mouse >591 and y_mouse < 635): ocultar = 31 self.ladrar.play() elif(x_mouse > 107 and x_mouse<= 390) and (y_mouse >390 and y_mouse < 434): ocultar =32 elif(x_mouse > 495 and x_mouse<= 744) and (y_mouse >218 and y_mouse < 251): ocultar =33 def interfaz_preg5_cir_bien(self, superficie): superficie.blit(self.preg5_cirbien, (0,0)) def poscision_elementos_preg5_cir_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =34 def interfaz_preg5_cir_malo1(self, superficie): superficie.blit(self.preg5_cirmalo1, (0,0)) def poscision_elementos_preg5_cir_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =30 def interfaz_preg5_cir_malo2(self, superficie): superficie.blit(self.preg5_cirmalo2, (0,0)) def poscision_elementos_preg5_cir_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =30 def interfaz_preg6_cir(self, superficie): superficie.blit(self.preg6_cir, (0,0)) def poscision_elementos_preg6_cir(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 200 and x_mouse<= 375) and (y_mouse >305 and y_mouse < 490): ocultar = 35 self.ladrar.play() elif(x_mouse > 530 and x_mouse<= 680) and (y_mouse >296 and y_mouse < 497): ocultar =36 elif(x_mouse > 767 and x_mouse<= 1100) and (y_mouse >323 and y_mouse < 455): ocultar =37 def interfaz_preg6_cir_bien(self, superficie): superficie.blit(self.preg6_cirbien, (0,0)) def poscision_elementos_preg6_cir_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =38 def interfaz_preg6_cir_malo1(self, superficie): superficie.blit(self.preg6_cirmalo1, (0,0)) def poscision_elementos_preg6_cir_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =34 def interfaz_preg6_cir_malo2(self, superficie): superficie.blit(self.preg6_cirmalo2, (0,0)) def poscision_elementos_preg6_cir_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =34 def interfaz_pregfin_cir(self, superficie): superficie.blit(self.pregfin_cir, (0,0)) def poscision_elementos_pregfin_cir(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 222 and x_mouse<= 525) and (y_mouse >837and y_mouse < 893): ocultar =2 def interfaz_Bienvenida(self, superficie): superficie.blit(self.bienvenida, (0,0)) def poscision_elementos_Bienvenida(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse >36 and x_mouse<= 335) and (y_mouse >816and y_mouse < 880): ocultar =2 def interfaz_trianguloequi(self, superficie): superficie.blit(self.triangequi, (0,0)) def poscision_elementos_trianguloequi(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =11 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =41 def interfaz_trianguloiso(self, superficie): superficie.blit(self.triangiso, (0,0)) def poscision_elementos_trianguloiso(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =40 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =42 def interfaz_trianguloesca(self, superficie): superficie.blit(self.triangesca, (0,0)) def poscision_elementos_trianguloesca(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =41 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =43 def interfaz_triangulobienve(self, superficie): superficie.blit(self.triangbien, (0,0)) def poscision_elementos_triangulobienve(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =42 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =44 def interfaz_preg1_triang(self, superficie): superficie.blit(self.preg1_triang, (0,0)) def poscision_elementos_preg1_triang(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 600) and (y_mouse >314 and y_mouse < 383): ocultar =45 self.ladrar.play() elif(x_mouse > 647 and x_mouse<= 1115) and (y_mouse >315 and y_mouse < 378): ocultar =46 elif(x_mouse > 385 and x_mouse<= 825) and (y_mouse >420 and y_mouse < 483): ocultar =47 def interfaz_preg1_triang_bien(self, superficie): superficie.blit(self.preg1_triangbien, (0,0)) def poscision_elementos_preg1_triang_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =48 def interfaz_preg1_triang_malo1(self, superficie): superficie.blit(self.preg1_triangmalo1, (0,0)) def poscision_elementos_preg1_triang_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =44 def interfaz_preg1_triang_malo2(self, superficie): superficie.blit(self.preg1_triangmalo2, (0,0)) def poscision_elementos_preg1_triang_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =44 def interfaz_preg2_triang(self, superficie): superficie.blit(self.preg2_triang, (0,0)) def poscision_elementos_preg2_triang(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 600) and (y_mouse >314 and y_mouse < 383): ocultar =49 self.ladrar.play() elif(x_mouse > 647 and x_mouse<= 1115) and (y_mouse >315 and y_mouse < 378): ocultar =50 elif(x_mouse > 385 and x_mouse<= 825) and (y_mouse >420 and y_mouse < 483): ocultar =51 def interfaz_preg2_triang_bien(self, superficie): superficie.blit(self.preg2_triangbien, (0,0)) def poscision_elementos_preg2_triang_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =52 def interfaz_preg2_triang_malo1(self, superficie): superficie.blit(self.preg2_triangmalo1, (0,0)) def poscision_elementos_preg2_triang_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =48 def interfaz_preg2_triang_malo2(self, superficie): superficie.blit(self.preg2_triangmalo2, (0,0)) def poscision_elementos_preg2_triang_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =48 def interfaz_preg3_triang(self, superficie): superficie.blit(self.preg3_triang, (0,0)) def poscision_elementos_preg3_triang(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 600) and (y_mouse >314 and y_mouse < 383): ocultar =54 elif(x_mouse > 647 and x_mouse<= 1115) and (y_mouse >315 and y_mouse < 378): ocultar =55 elif(x_mouse > 385 and x_mouse<= 825) and (y_mouse >420 and y_mouse < 483): ocultar =53 self.ladrar.play() def interfaz_preg3_triang_bien(self, superficie): superficie.blit(self.preg3_triangbien, (0,0)) def poscision_elementos_preg3_triang_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =56 def interfaz_preg3_triang_malo1(self, superficie): superficie.blit(self.preg3_triangmalo1, (0,0)) def poscision_elementos_preg3_triang_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =52 def interfaz_preg3_triang_malo2(self, superficie): superficie.blit(self.preg3_triangmalo2, (0,0)) def poscision_elementos_preg3_triang_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =52 def interfaz_preg4_triang(self, superficie): superficie.blit(self.preg4_triang, (0,0)) def poscision_elementos_preg4_triang(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 600) and (y_mouse >314 and y_mouse < 383): ocultar =58 elif(x_mouse > 647 and x_mouse<= 1115) and (y_mouse >315 and y_mouse < 378): ocultar =57 self.ladrar.play() elif(x_mouse > 385 and x_mouse<= 825) and (y_mouse >420 and y_mouse < 483): ocultar =59 def interfaz_preg4_triang_bien(self, superficie): superficie.blit(self.preg4_triangbien, (0,0)) def poscision_elementos_preg4_triang_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =60 def interfaz_preg4_triang_malo1(self, superficie): superficie.blit(self.preg4_triangmalo1, (0,0)) def poscision_elementos_preg4_triang_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =56 def interfaz_preg4_triang_malo2(self, superficie): superficie.blit(self.preg4_triangmalo2, (0,0)) def poscision_elementos_preg4_triang_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =56 def interfaz_preg5_triang(self, superficie): superficie.blit(self.preg5_triang, (0,0)) def poscision_elementos_preg5_triang(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 183 and x_mouse<= 455) and (y_mouse >318 and y_mouse < 503): ocultar =61 self.ladrar.play() elif(x_mouse > 614 and x_mouse<= 723) and (y_mouse >254 and y_mouse < 514): ocultar =62 elif(x_mouse > 855 and x_mouse<= 1095) and (y_mouse >262 and y_mouse < 503): ocultar =63 def interfaz_preg5_triang_bien(self, superficie): superficie.blit(self.preg5_triangbien, (0,0)) def poscision_elementos_preg5_triang_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =64 def interfaz_preg5_triang_malo1(self, superficie): superficie.blit(self.preg5_triangmalo1, (0,0)) def poscision_elementos_preg5_triang_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =60 def interfaz_preg5_triang_malo2(self, superficie): superficie.blit(self.preg5_triangmalo2, (0,0)) def poscision_elementos_preg5_triang_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =60 def interfaz_preg6_triang(self, superficie): superficie.blit(self.preg6_triang, (0,0)) def poscision_elementos_preg6_triang(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 183 and x_mouse<= 455) and (y_mouse >318 and y_mouse < 503): ocultar =66 elif(x_mouse > 548 and x_mouse<= 790) and (y_mouse >257 and y_mouse < 497): ocultar =65 elif(x_mouse > 960 and x_mouse<= 1058) and (y_mouse >265 and y_mouse < 505): ocultar =67 def interfaz_preg6_triang_bien(self, superficie): superficie.blit(self.preg6_triangbien, (0,0)) def poscision_elementos_preg6_triang_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =68 def interfaz_preg6_triang_malo1(self, superficie): superficie.blit(self.preg6_triangmalo1, (0,0)) def poscision_elementos_preg6_triang_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =64 def interfaz_preg6_triang_malo2(self, superficie): superficie.blit(self.preg6_triangmalo2, (0,0)) def poscision_elementos_preg6_triang_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =64 def interfaz_preg7_triang(self, superficie): superficie.blit(self.preg7_triang, (0,0)) def poscision_elementos_preg7_triang(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 270 and x_mouse<= 364) and (y_mouse >258 and y_mouse < 503): ocultar =69 elif(x_mouse > 474 and x_mouse<= 777) and (y_mouse >290 and y_mouse < 497): ocultar =70 elif(x_mouse > 850 and x_mouse<= 1080) and (y_mouse >258 and y_mouse < 500): ocultar =71 def interfaz_preg7_triang_bien(self, superficie): superficie.blit(self.preg7_triangbien, (0,0)) def poscision_elementos_preg7_triang_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =72 def interfaz_preg7_triang_malo1(self, superficie): superficie.blit(self.preg7_triangmalo1, (0,0)) def poscision_elementos_preg7_triang_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =68 def interfaz_preg7_triang_malo2(self, superficie): superficie.blit(self.preg7_triangmalo2, (0,0)) def poscision_elementos_preg7_triang_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =68 def interfaz_pregfin_triang(self, superficie): superficie.blit(self.pregfin_triang, (0,0)) def poscision_elementos_pregfin_triang(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 32 and x_mouse<= 330) and (y_mouse > 822 and y_mouse < 878): ocultar =2 def interfaz_cuadra(self, superficie): superficie.blit(self.cuadra, (0,0)) def poscision_elementos_cuadra(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =2 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =74 def interfaz_cuadral(self, superficie): superficie.blit(self.cuadral, (0,0)) def poscision_elementos_cuadral(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =73 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =75 def interfaz_cuadrav(self, superficie): superficie.blit(self.cuadrav, (0,0)) def poscision_elementos_cuadrav(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =74 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =76 def interfaz_rect(self, superficie): superficie.blit(self.rect, (0,0)) def poscision_elementos_rect(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =75 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =77 def interfaz_rectv(self, superficie): superficie.blit(self.rectv, (0,0)) def poscision_elementos_rectv(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =76 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =78 def interfaz_rombo(self, superficie): superficie.blit(self.rombo, (0,0)) def poscision_elementos_rombo(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =77 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =79 def interfaz_rombov(self, superficie): superficie.blit(self.rombov, (0,0)) def poscision_elementos_rombov(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =78 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =80 def interfaz_trapecio(self, superficie): superficie.blit(self.trapecio, (0,0)) def poscision_elementos_trapecio(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =79 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =81 def interfaz_trapeciov(self, superficie): superficie.blit(self.trapeciov, (0,0)) def poscision_elementos_trapeciov(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =80 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =82 def interfaz_reclobienve(self, superficie): superficie.blit(self.triangbien, (0,0)) def poscision_elementos_recbienve(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 49 and x_mouse<= 341) and (y_mouse >26 and y_mouse < 79): ocultar =81 elif(x_mouse > 79 and x_mouse<= 379) and (y_mouse >815 and y_mouse < 870): ocultar =83 def interfaz_preg1_rect(self, superficie): superficie.blit(self.preg1_rect, (0,0)) def poscision_elementos_preg1_rect(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 603) and (y_mouse >316 and y_mouse < 383): ocultar =85 elif(x_mouse > 410 and x_mouse<= 871) and (y_mouse >431 and y_mouse < 501): ocultar =84 self.ladrar.play() elif(x_mouse > 646 and x_mouse<= 1113) and (y_mouse >319 and y_mouse < 384): ocultar =86 def interfaz_preg1_rect_bien(self, superficie): superficie.blit(self.preg1_rectgbien, (0,0)) def poscision_elementos_preg1_rect_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =87 def interfaz_preg1_rect_malo1(self, superficie): superficie.blit(self.preg1_rectmalo1, (0,0)) def poscision_elementos_preg1_rect_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =83 def interfaz_preg1_rect_malo2(self, superficie): superficie.blit(self.preg1_rectmalo2, (0,0)) def poscision_elementos_preg1_rect_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =83 def interfaz_preg2_rect(self, superficie): superficie.blit(self.preg2_rect, (0,0)) def poscision_elementos_preg2_rect(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 603) and (y_mouse >316 and y_mouse < 383): ocultar =88 self.ladrar.play() elif(x_mouse > 410 and x_mouse<= 871) and (y_mouse >431 and y_mouse < 501): ocultar =89 elif(x_mouse > 646 and x_mouse<= 1113) and (y_mouse >319 and y_mouse < 384): ocultar =90 def interfaz_preg2_rect_bien(self, superficie): superficie.blit(self.preg2_rectgbien, (0,0)) def poscision_elementos_preg2_rect_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =91 def interfaz_preg2_rect_malo1(self, superficie): superficie.blit(self.preg2_rectmalo1, (0,0)) def poscision_elementos_preg2_rect_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =87 def interfaz_preg2_rect_malo2(self, superficie): superficie.blit(self.preg2_rectmalo2, (0,0)) def poscision_elementos_preg2_rect_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =87 def interfaz_preg3_rect(self, superficie): superficie.blit(self.preg3_rect, (0,0)) def poscision_elementos_preg3_rect(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 603) and (y_mouse >316 and y_mouse < 383): ocultar =92 self.ladrar.play() elif(x_mouse > 410 and x_mouse<= 871) and (y_mouse >431 and y_mouse < 501): ocultar =93 elif(x_mouse > 646 and x_mouse<= 1113) and (y_mouse >319 and y_mouse < 384): ocultar =94 def interfaz_preg3_rect_bien(self, superficie): superficie.blit(self.preg3_rectgbien, (0,0)) def poscision_elementos_preg3_rect_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =95 def interfaz_preg3_rect_malo1(self, superficie): superficie.blit(self.preg3_rectmalo1, (0,0)) def poscision_elementos_preg3_rect_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =91 def interfaz_preg3_rect_malo2(self, superficie): superficie.blit(self.preg3_rectmalo2, (0,0)) def poscision_elementos_preg3_rect_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =91 def interfaz_preg4_rect(self, superficie): superficie.blit(self.preg4_rect, (0,0)) def poscision_elementos_preg4_rect(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 129 and x_mouse<= 603) and (y_mouse >300 and y_mouse < 490): ocultar =96 self.ladrar.play() elif(x_mouse > 647 and x_mouse<= 1128) and (y_mouse >303 and y_mouse < 488): ocultar =97 def interfaz_preg4_rect_bien(self, superficie): superficie.blit(self.preg4_rectgbien, (0,0)) def poscision_elementos_preg4_rect_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =98 def interfaz_preg4_rect_malo1(self, superficie): superficie.blit(self.preg4_rectmalo1, (0,0)) def poscision_elementos_preg4_rect_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =95 def interfaz_preg5_rect(self, superficie): superficie.blit(self.preg5_rect, (0,0)) def poscision_elementos_preg5_rect(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 603) and (y_mouse >316 and y_mouse < 383): ocultar =99 self.ladrar.play() elif(x_mouse > 410 and x_mouse<= 871) and (y_mouse >431 and y_mouse < 501): ocultar =100 elif(x_mouse > 646 and x_mouse<= 1113) and (y_mouse >319 and y_mouse < 384): ocultar =101 def interfaz_preg5_rect_bien(self, superficie): superficie.blit(self.preg5_rectgbien, (0,0)) def poscision_elementos_preg5_rect_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =102 def interfaz_preg5_rect_malo1(self, superficie): superficie.blit(self.preg5_rectmalo2, (0,0)) def poscision_elementos_preg5_rect_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =98 def interfaz_preg5_rect_malo2(self, superficie): superficie.blit(self.preg5_rectmalo1, (0,0)) def poscision_elementos_preg5_rect_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =98 def interfaz_preg6_rect(self, superficie): superficie.blit(self.preg6_rect, (0,0)) def poscision_elementos_preg6_rect(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 136 and x_mouse<= 603) and (y_mouse >316 and y_mouse < 383): ocultar = 104 elif(x_mouse > 410 and x_mouse<= 871) and (y_mouse >431 and y_mouse < 501): ocultar =103 self.ladrar.play() elif(x_mouse > 646 and x_mouse<= 1113) and (y_mouse >319 and y_mouse < 384): ocultar =105 def interfaz_preg6_rect_bien(self, superficie): superficie.blit(self.preg6_rectgbien, (0,0)) def poscision_elementos_preg6_rect_bien(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 467 and x_mouse<= 762) and (y_mouse >800 and y_mouse < 859): ocultar =72 def interfaz_preg6_rect_malo1(self, superficie): superficie.blit(self.preg6_rectmalo1, (0,0)) def poscision_elementos_preg6_rect_malo1(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =102 def interfaz_preg6_rect_malo2(self, superficie): superficie.blit(self.preg6_rectmalo2, (0,0)) def poscision_elementos_preg6_rect_malo2(self, superficie): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() if(x_mouse > 551 and x_mouse<= 650) and (y_mouse >800 and y_mouse < 888): ocultar =102 def main(): global ocultar x_mouse, y_mouse = pygame.mouse.get_pos() ventana = pygame.display.set_mode((x,y)) cursor = pygame.cursors.compile(CURSOR) pygame.mouse.set_cursor((32,32), (1,1), *cursor) pygame.mixer.music.load("sonido/intro.ogg") pygame.mixer.music.play(10) prin=interfaz() while True: while gtk.events_pending(): gtk.main_iteration() x_mouse, y_mouse = pygame.mouse.get_pos() for eventos in pygame.event.get(): if eventos.type == QUIT: sys.exit(0) elif eventos.type == MOUSEBUTTONDOWN: if(ocultar==1): prin.poscision_elementos_1(ventana) if (x_mouse > 1043 and x_mouse<= 1099) and (y_mouse >17 and y_mouse < 76): pygame.mixer.music.unpause() elif (x_mouse > 1136 and x_mouse<= 1178) and (y_mouse >19 and y_mouse < 73): pygame.mixer.music.pause() elif(ocultar==2): prin.poscision_elementos_menu(ventana) elif(ocultar==3): prin.poscision_elementos_circulo(ventana) elif(ocultar==4): prin.poscision_elementos_circuloc(ventana) elif(ocultar==5): prin.poscision_elementos_circulor(ventana) elif(ocultar==6): prin.poscision_elementos_triangulo(ventana) elif(ocultar==7): prin.poscision_elementos_triangulol(ventana) elif(ocultar==8): prin.poscision_elementos_triangulov(ventana) elif(ocultar==9): prin.poscision_elementos_trianguloa(ventana) elif(ocultar==10): prin.poscision_elementos_triangulob(ventana) elif(ocultar==11): prin.poscision_elementos_triangulocla(ventana) elif(ocultar==12): prin.poscision_elementos_circulobienvenida(ventana) elif(ocultar==13): prin.poscision_elementos_ayuda(ventana) elif(ocultar==14): prin.poscision_elementos_preg1_cir(ventana) elif(ocultar==15): prin.poscision_elementos_preg1_cir_bien(ventana) elif(ocultar==16): prin.poscision_elementos_preg1_cir_malo1(ventana) elif(ocultar==17): prin.poscision_elementos_preg1_cir_malo2(ventana) elif(ocultar==18): prin.poscision_elementos_preg2_cir(ventana) elif(ocultar==19): prin.poscision_elementos_preg2_cir_bien(ventana) elif(ocultar==20): prin.poscision_elementos_preg2_cir_malo1(ventana) elif(ocultar==21): prin.poscision_elementos_preg2_cir_malo2(ventana) elif(ocultar==22): prin.poscision_elementos_preg3_cir(ventana) elif(ocultar==23): prin.poscision_elementos_preg3_cir_bien(ventana) elif(ocultar==24): prin.poscision_elementos_preg3_cir_malo1(ventana) elif(ocultar==25): prin.poscision_elementos_preg3_cir_malo2(ventana) elif(ocultar==26): prin.poscision_elementos_preg4_cir(ventana) elif(ocultar==27): prin.poscision_elementos_preg4_cir_bien(ventana) elif(ocultar==28): prin.poscision_elementos_preg4_cir_malo1(ventana) elif(ocultar==29): prin.poscision_elementos_preg4_cir_malo2(ventana) elif(ocultar==30): prin.poscision_elementos_preg5_cir(ventana) elif(ocultar==31): prin.poscision_elementos_preg5_cir_bien(ventana) elif(ocultar==32): prin.poscision_elementos_preg5_cir_malo1(ventana) elif(ocultar==33): prin.poscision_elementos_preg5_cir_malo2(ventana) elif(ocultar==34): prin.poscision_elementos_preg6_cir(ventana) elif(ocultar==35): prin.poscision_elementos_preg6_cir_bien(ventana) elif(ocultar==36): prin.poscision_elementos_preg6_cir_malo1(ventana) elif(ocultar==37): prin.poscision_elementos_preg6_cir_malo2(ventana) elif(ocultar==38): prin.poscision_elementos_pregfin_cir(ventana) elif(ocultar==39): prin.poscision_elementos_Bienvenida(ventana) elif(ocultar==40): prin.poscision_elementos_trianguloequi(ventana) elif(ocultar==41): prin.poscision_elementos_trianguloiso(ventana) elif(ocultar==42): prin.poscision_elementos_trianguloesca(ventana) elif(ocultar==43): prin.poscision_elementos_triangulobienve(ventana) elif(ocultar==44): prin.poscision_elementos_preg1_triang(ventana) elif(ocultar==45): prin.poscision_elementos_preg1_triang_bien(ventana) elif(ocultar==46): prin.poscision_elementos_preg1_triang_malo1(ventana) elif(ocultar==47): prin.poscision_elementos_preg1_triang_malo2(ventana) elif(ocultar==48): prin.poscision_elementos_preg2_triang(ventana) elif(ocultar==49): prin.poscision_elementos_preg2_triang_bien(ventana) elif(ocultar==50): prin.poscision_elementos_preg2_triang_malo1(ventana) elif(ocultar==51): prin.poscision_elementos_preg2_triang_malo2(ventana) elif(ocultar==52): prin.poscision_elementos_preg3_triang(ventana) elif(ocultar==53): prin.poscision_elementos_preg3_triang_bien(ventana) elif(ocultar==54): prin.poscision_elementos_preg3_triang_malo1(ventana) elif(ocultar==55): prin.poscision_elementos_preg3_triang_malo2(ventana) elif(ocultar==56): prin.poscision_elementos_preg4_triang(ventana) elif(ocultar==57): prin.poscision_elementos_preg4_triang_bien(ventana) elif(ocultar==58): prin.poscision_elementos_preg4_triang_malo1(ventana) elif(ocultar==59): prin.poscision_elementos_preg4_triang_malo2(ventana) elif(ocultar==60): prin.poscision_elementos_preg5_triang(ventana) elif(ocultar==61): prin.poscision_elementos_preg5_triang_bien(ventana) elif(ocultar==62): prin.poscision_elementos_preg5_triang_malo1(ventana) elif(ocultar==63): prin.poscision_elementos_preg5_triang_malo2(ventana) elif(ocultar==64): prin.poscision_elementos_preg6_triang(ventana) elif(ocultar==65): prin.poscision_elementos_preg6_triang_bien(ventana) elif(ocultar==66): prin.poscision_elementos_preg6_triang_malo1(ventana) elif(ocultar==67): prin.poscision_elementos_preg6_triang_malo2(ventana) elif(ocultar==68): prin.poscision_elementos_preg7_triang(ventana) elif(ocultar==69): prin.poscision_elementos_preg7_triang_bien(ventana) elif(ocultar==70): prin.poscision_elementos_preg7_triang_malo1(ventana) elif(ocultar==71): prin.poscision_elementos_preg7_triang_malo2(ventana) elif(ocultar==72): prin.poscision_elementos_pregfin_triang(ventana) elif(ocultar==73): prin.poscision_elementos_cuadra(ventana) elif(ocultar==74): prin.poscision_elementos_cuadral(ventana) elif(ocultar==75): prin.poscision_elementos_cuadrav(ventana) elif(ocultar==76): prin.poscision_elementos_rect(ventana) elif(ocultar==77): prin.poscision_elementos_rectv(ventana) elif(ocultar==78): prin.poscision_elementos_rombo(ventana) elif(ocultar==79): prin.poscision_elementos_rombov(ventana) elif(ocultar==80): prin.poscision_elementos_trapecio(ventana) elif(ocultar==81): prin.poscision_elementos_trapeciov(ventana) elif(ocultar==82): prin.poscision_elementos_recbienve(ventana) elif(ocultar==83): prin.poscision_elementos_preg1_rect(ventana) elif(ocultar==84): prin.poscision_elementos_preg1_rect_bien(ventana) elif(ocultar==85): prin.poscision_elementos_preg1_rect_malo1(ventana) elif(ocultar==86): prin.poscision_elementos_preg1_rect_malo2(ventana) elif(ocultar==87): prin.poscision_elementos_preg2_rect(ventana) elif(ocultar==88): prin.poscision_elementos_preg2_rect_bien(ventana) elif(ocultar==89): prin.poscision_elementos_preg2_rect_malo1(ventana) elif(ocultar==90): prin.poscision_elementos_preg2_rect_malo2(ventana) elif(ocultar==91): prin.poscision_elementos_preg3_rect(ventana) elif(ocultar==92): prin.poscision_elementos_preg3_rect_bien(ventana) elif(ocultar==93): prin.poscision_elementos_preg3_rect_malo1(ventana) elif(ocultar==94): prin.poscision_elementos_preg3_rect_malo2(ventana) elif(ocultar==95): prin.poscision_elementos_preg4_rect(ventana) elif(ocultar==96): prin.poscision_elementos_preg4_rect_bien(ventana) elif(ocultar==97): prin.poscision_elementos_preg4_rect_malo1(ventana) elif(ocultar==98): prin.poscision_elementos_preg5_rect(ventana) elif(ocultar==99): prin.poscision_elementos_preg5_rect_bien(ventana) elif(ocultar==100): prin.poscision_elementos_preg5_rect_malo1(ventana) elif(ocultar==101): prin.poscision_elementos_preg5_rect_malo2(ventana) elif(ocultar==102): prin.poscision_elementos_preg6_rect(ventana) elif(ocultar==103): prin.poscision_elementos_preg6_rect_bien(ventana) elif(ocultar==104): prin.poscision_elementos_preg6_rect_malo1(ventana) elif(ocultar==105): prin.poscision_elementos_preg6_rect_malo2(ventana) elif eventos.type == KEYDOWN: if eventos.key == K_ESCAPE: sys.exit(0) if(ocultar==1): prin.inter_principal(ventana) elif (ocultar==2): prin.interfaz_menu(ventana) elif (ocultar==3): prin.interfaz_circulo(ventana) elif (ocultar==4): prin.interfaz_circuloc(ventana) elif (ocultar==5): prin.interfaz_circulor(ventana) elif (ocultar==6): prin.interfaz_triangulo(ventana) elif (ocultar==7): prin.interfaz_triangulol(ventana) elif (ocultar==8): prin.interfaz_triangulov(ventana) elif (ocultar==9): prin.interfaz_trianguloa(ventana) elif (ocultar==10): prin.interfaz_triangulob(ventana) elif (ocultar==11): prin.interfaz_triangulocla(ventana) elif (ocultar==12): prin.interfaz_circulobienvenida(ventana) elif (ocultar==13): prin.interfaz_ayuda(ventana) elif (ocultar==14): prin.interfaz_preg1_cir(ventana) elif (ocultar==15): prin.interfaz_preg1_cir_bien(ventana) elif (ocultar==16): prin.interfaz_preg1_cir_malo1(ventana) elif (ocultar==17): prin.interfaz_preg1_cir_malo2(ventana) elif (ocultar==18): prin.interfaz_preg2_cir(ventana) elif (ocultar==19): prin.interfaz_preg2_cir_bien(ventana) elif (ocultar==20): prin.interfaz_preg2_cir_malo1(ventana) elif (ocultar==21): prin.interfaz_preg2_cir_malo2(ventana) elif (ocultar==22): prin.interfaz_preg3_cir(ventana) elif (ocultar==23): prin.interfaz_preg3_cir_bien(ventana) elif (ocultar==24): prin.interfaz_preg3_cir_malo1(ventana) elif (ocultar==25): prin.interfaz_preg3_cir_malo2(ventana) elif (ocultar==26): prin.interfaz_preg4_cir(ventana) elif (ocultar==27): prin.interfaz_preg4_cir_bien(ventana) elif (ocultar==28): prin.interfaz_preg4_cir_malo1(ventana) elif (ocultar==29): prin.interfaz_preg4_cir_malo2(ventana) elif (ocultar==30): prin.interfaz_preg5_cir(ventana) elif (ocultar==31): prin.interfaz_preg5_cir_bien(ventana) elif (ocultar==32): prin.interfaz_preg5_cir_malo1(ventana) elif (ocultar==33): prin.interfaz_preg5_cir_malo2(ventana) elif (ocultar==34): prin.interfaz_preg6_cir(ventana) elif (ocultar==35): prin.interfaz_preg6_cir_bien(ventana) elif (ocultar==36): prin.interfaz_preg6_cir_malo1(ventana) elif (ocultar==37): prin.interfaz_preg6_cir_malo2(ventana) elif (ocultar==38): prin.interfaz_pregfin_cir(ventana) elif (ocultar==39): prin.interfaz_Bienvenida(ventana) elif (ocultar==40): prin.interfaz_trianguloequi(ventana) elif (ocultar==41): prin.interfaz_trianguloiso(ventana) elif (ocultar==42): prin.interfaz_trianguloesca(ventana) elif (ocultar==43): prin.interfaz_triangulobienve(ventana) elif (ocultar==44): prin.interfaz_preg1_triang(ventana) elif (ocultar==45): prin.interfaz_preg1_triang_bien(ventana) elif (ocultar==46): prin.interfaz_preg1_triang_malo1(ventana) elif (ocultar==47): prin.interfaz_preg1_triang_malo2(ventana) elif (ocultar==48): prin.interfaz_preg2_triang(ventana) elif (ocultar==49): prin.interfaz_preg2_triang_bien(ventana) elif (ocultar==50): prin.interfaz_preg2_triang_malo1(ventana) elif (ocultar==51): prin.interfaz_preg2_triang_malo2(ventana) elif (ocultar==52): prin.interfaz_preg3_triang(ventana) elif (ocultar==53): prin.interfaz_preg3_triang_bien(ventana) elif (ocultar==54): prin.interfaz_preg3_triang_malo1(ventana) elif (ocultar==55): prin.interfaz_preg3_triang_malo2(ventana) elif (ocultar==56): prin.interfaz_preg4_triang(ventana) elif (ocultar==57): prin.interfaz_preg4_triang_bien(ventana) elif (ocultar==58): prin.interfaz_preg4_triang_malo1(ventana) elif (ocultar==59): prin.interfaz_preg4_triang_malo2(ventana) elif (ocultar==60): prin.interfaz_preg5_triang(ventana) elif (ocultar==61): prin.interfaz_preg5_triang_bien(ventana) elif (ocultar==62): prin.interfaz_preg5_triang_malo1(ventana) elif (ocultar==63): prin.interfaz_preg5_triang_malo2(ventana) elif (ocultar==64): prin.interfaz_preg6_triang(ventana) elif (ocultar==65): prin.interfaz_preg6_triang_bien(ventana) elif (ocultar==66): prin.interfaz_preg6_triang_malo1(ventana) elif (ocultar==67): prin.interfaz_preg6_triang_malo2(ventana) elif (ocultar==68): prin.interfaz_preg7_triang(ventana) elif (ocultar==69): prin.interfaz_preg7_triang_bien(ventana) elif (ocultar==70): prin.interfaz_preg7_triang_malo1(ventana) elif (ocultar==71): prin.interfaz_preg7_triang_malo2(ventana) elif (ocultar==72): prin.interfaz_pregfin_triang(ventana) elif (ocultar==73): prin.interfaz_cuadra(ventana) elif (ocultar==74): prin.interfaz_cuadral(ventana) elif (ocultar==75): prin.interfaz_cuadrav(ventana) elif (ocultar==76): prin.interfaz_rect(ventana) elif (ocultar==77): prin.interfaz_rectv(ventana) elif (ocultar==78): prin.interfaz_rombo(ventana) elif (ocultar==79): prin.interfaz_rombov(ventana) elif (ocultar==80): prin.interfaz_trapecio(ventana) elif (ocultar==81): prin.interfaz_trapeciov(ventana) elif (ocultar==82): prin.interfaz_reclobienve(ventana) elif (ocultar==83): prin.interfaz_preg1_rect(ventana) elif (ocultar==84): prin.interfaz_preg1_rect_bien(ventana) elif (ocultar==85): prin.interfaz_preg1_rect_malo1(ventana) elif (ocultar==86): prin.interfaz_preg1_rect_malo2(ventana) elif (ocultar==87): prin.interfaz_preg2_rect(ventana) elif (ocultar==88): prin.interfaz_preg2_rect_bien(ventana) elif (ocultar==89): prin.interfaz_preg2_rect_malo1(ventana) elif (ocultar==90): prin.interfaz_preg2_rect_malo2(ventana) elif (ocultar==91): prin.interfaz_preg3_rect(ventana) elif (ocultar==92): prin.interfaz_preg3_rect_bien(ventana) elif (ocultar==93): prin.interfaz_preg3_rect_malo1(ventana) elif (ocultar==94): prin.interfaz_preg3_rect_malo2(ventana) elif (ocultar==95): prin.interfaz_preg4_rect(ventana) elif (ocultar==96): prin.interfaz_preg4_rect_bien(ventana) elif (ocultar==97): prin.interfaz_preg4_rect_malo1(ventana) elif (ocultar==98): prin.interfaz_preg5_rect(ventana) elif (ocultar==99): prin.interfaz_preg5_rect_bien(ventana) elif (ocultar==100): prin.interfaz_preg5_rect_malo1(ventana) elif (ocultar==101): prin.interfaz_preg5_rect_malo2(ventana) elif (ocultar==102): prin.interfaz_preg6_rect(ventana) elif (ocultar==103): prin.interfaz_preg6_rect_bien(ventana) elif (ocultar==104): prin.interfaz_preg6_rect_malo1(ventana) elif (ocultar==105): prin.interfaz_preg6_rect_malo2(ventana) print (x_mouse, y_mouse) pygame.display.update() if __name__ == '__main__': main()
3047f01521ecf352af10c869568fa355aa6ab390
693d93174f43a81d8a65041553282a8872e3a6ff
/contrib/devtools/test-security-check.py
269ffb5b075cedd5e4fa6e25ff81602fa3c44195
[ "MIT" ]
permissive
eleccoin/eleccoin
c075719d5ee676fc2bb9a21f3711d75d673655bd
963f6d4a069e40ab2e46217e5d49bc94adda2c5c
refs/heads/master
2022-11-13T02:38:36.662655
2022-10-30T08:56:57
2022-10-30T08:56:57
238,475,897
3
7
MIT
2022-01-10T07:29:19
2020-02-05T14:56:34
C++
UTF-8
Python
false
false
10,020
py
#!/usr/bin/env python3 # Copyright (c) 2020-2022 The Eleccoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Test script for security-check.py ''' import lief #type:ignore import os import subprocess from typing import List import unittest from utils import determine_wellknown_cmd def write_testcode(filename): with open(filename, 'w', encoding="utf8") as f: f.write(''' #include <stdio.h> int main() { printf("the quick brown fox jumps over the lazy god\\n"); return 0; } ''') def clean_files(source, executable): os.remove(source) os.remove(executable) def call_security_check(cc, source, executable, options): # This should behave the same as AC_TRY_LINK, so arrange well-known flags # in the same order as autoconf would. # # See the definitions for ac_link in autoconf's lib/autoconf/c.m4 file for # reference. env_flags: List[str] = [] for var in ['CFLAGS', 'CPPFLAGS', 'LDFLAGS']: env_flags += filter(None, os.environ.get(var, '').split(' ')) subprocess.run([*cc,source,'-o',executable] + env_flags + options, check=True) p = subprocess.run(['./contrib/devtools/security-check.py',executable], stdout=subprocess.PIPE, universal_newlines=True) return (p.returncode, p.stdout.rstrip()) def get_arch(cc, source, executable): subprocess.run([*cc, source, '-o', executable], check=True) binary = lief.parse(executable) arch = binary.abstract.header.architecture os.remove(executable) return arch class TestSecurityChecks(unittest.TestCase): def test_ELF(self): source = 'test1.c' executable = 'test1' cc = determine_wellknown_cmd('CC', 'gcc') write_testcode(source) arch = get_arch(cc, source, executable) if arch == lief.ARCHITECTURES.X86: self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-zexecstack','-fno-stack-protector','-Wl,-znorelro','-no-pie','-fno-PIE', '-Wl,-z,separate-code']), (1, executable+': failed PIE NX RELRO Canary CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fno-stack-protector','-Wl,-znorelro','-no-pie','-fno-PIE', '-Wl,-z,separate-code']), (1, executable+': failed PIE RELRO Canary CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-znorelro','-no-pie','-fno-PIE', '-Wl,-z,separate-code']), (1, executable+': failed PIE RELRO CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-znorelro','-pie','-fPIE', '-Wl,-z,separate-code']), (1, executable+': failed RELRO CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-zrelro','-Wl,-z,now','-pie','-fPIE', '-Wl,-z,noseparate-code']), (1, executable+': failed separate_code CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-zrelro','-Wl,-z,now','-pie','-fPIE', '-Wl,-z,separate-code']), (1, executable+': failed CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-zrelro','-Wl,-z,now','-pie','-fPIE', '-Wl,-z,separate-code', '-fcf-protection=full']), (0, '')) else: self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-zexecstack','-fno-stack-protector','-Wl,-znorelro','-no-pie','-fno-PIE', '-Wl,-z,separate-code']), (1, executable+': failed PIE NX RELRO Canary')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fno-stack-protector','-Wl,-znorelro','-no-pie','-fno-PIE', '-Wl,-z,separate-code']), (1, executable+': failed PIE RELRO Canary')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-znorelro','-no-pie','-fno-PIE', '-Wl,-z,separate-code']), (1, executable+': failed PIE RELRO')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-znorelro','-pie','-fPIE', '-Wl,-z,separate-code']), (1, executable+': failed RELRO')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-zrelro','-Wl,-z,now','-pie','-fPIE', '-Wl,-z,noseparate-code']), (1, executable+': failed separate_code')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-zrelro','-Wl,-z,now','-pie','-fPIE', '-Wl,-z,separate-code']), (0, '')) clean_files(source, executable) def test_PE(self): source = 'test1.c' executable = 'test1.exe' cc = determine_wellknown_cmd('CC', 'x86_64-w64-mingw32-gcc') write_testcode(source) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--disable-nxcompat','-Wl,--disable-reloc-section','-Wl,--disable-dynamicbase','-Wl,--disable-high-entropy-va','-no-pie','-fno-PIE']), (1, executable+': failed PIE DYNAMIC_BASE HIGH_ENTROPY_VA NX RELOC_SECTION CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--disable-reloc-section','-Wl,--disable-dynamicbase','-Wl,--disable-high-entropy-va','-no-pie','-fno-PIE']), (1, executable+': failed PIE DYNAMIC_BASE HIGH_ENTROPY_VA RELOC_SECTION CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--enable-reloc-section','-Wl,--disable-dynamicbase','-Wl,--disable-high-entropy-va','-no-pie','-fno-PIE']), (1, executable+': failed PIE DYNAMIC_BASE HIGH_ENTROPY_VA CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--enable-reloc-section','-Wl,--disable-dynamicbase','-Wl,--disable-high-entropy-va','-pie','-fPIE']), (1, executable+': failed PIE DYNAMIC_BASE HIGH_ENTROPY_VA CONTROL_FLOW')) # -pie -fPIE does nothing unless --dynamicbase is also supplied self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--enable-reloc-section','-Wl,--dynamicbase','-Wl,--disable-high-entropy-va','-pie','-fPIE']), (1, executable+': failed HIGH_ENTROPY_VA CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--enable-reloc-section','-Wl,--dynamicbase','-Wl,--high-entropy-va','-pie','-fPIE']), (1, executable+': failed CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,--nxcompat','-Wl,--enable-reloc-section','-Wl,--dynamicbase','-Wl,--high-entropy-va','-pie','-fPIE', '-fcf-protection=full']), (0, '')) clean_files(source, executable) def test_MACHO(self): source = 'test1.c' executable = 'test1' cc = determine_wellknown_cmd('CC', 'clang') write_testcode(source) arch = get_arch(cc, source, executable) if arch == lief.ARCHITECTURES.X86: self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-no_pie','-Wl,-flat_namespace','-Wl,-allow_stack_execute','-fno-stack-protector']), (1, executable+': failed NOUNDEFS LAZY_BINDINGS Canary PIE NX CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-no_pie','-Wl,-flat_namespace','-Wl,-allow_stack_execute','-fstack-protector-all']), (1, executable+': failed NOUNDEFS LAZY_BINDINGS PIE NX CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-no_pie','-Wl,-flat_namespace','-fstack-protector-all']), (1, executable+': failed NOUNDEFS LAZY_BINDINGS PIE CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-no_pie','-fstack-protector-all']), (1, executable+': failed LAZY_BINDINGS PIE CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-no_pie','-Wl,-bind_at_load','-fstack-protector-all']), (1, executable+': failed PIE CONTROL_FLOW')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-no_pie','-Wl,-bind_at_load','-fstack-protector-all', '-fcf-protection=full']), (1, executable+': failed PIE')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-pie','-Wl,-bind_at_load','-fstack-protector-all', '-fcf-protection=full']), (0, '')) else: # arm64 darwin doesn't support non-PIE binaries, control flow or executable stacks self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-flat_namespace','-fno-stack-protector']), (1, executable+': failed NOUNDEFS LAZY_BINDINGS Canary')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-flat_namespace','-fstack-protector-all']), (1, executable+': failed NOUNDEFS LAZY_BINDINGS')) self.assertEqual(call_security_check(cc, source, executable, ['-fstack-protector-all']), (1, executable+': failed LAZY_BINDINGS')) self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-bind_at_load','-fstack-protector-all']), (0, '')) clean_files(source, executable) if __name__ == '__main__': unittest.main()
76b439eb64e7052b75da1d1be31c934fb3855f54
71d608a5e6cc30bef2004a4008d62143de07f50c
/plots/Techinical_indicators_for_Goldman_Sachs_last_400_days.py
dd9cb186948e5a5eedbad60bf8c3673ba5bb96d3
[]
no_license
webclinic017/quant-3
f4fc462b3964717e2435e09dd0be35548066a967
98b31d92b89da10a409947b4bea653ceb4319af6
refs/heads/master
2022-01-27T21:06:39.345394
2019-07-21T10:35:12
2019-07-21T10:35:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,705
py
import matplotlib.pyplot as plt from Data import Data, get_technical_indicators def plot_technical_indicators(dataset, last_days): ticker = dataset.columns.values[1] plt.figure(figsize=(16, 10), dpi=100) shape_0 = dataset.shape[0] xmacd_ = shape_0 - last_days dataset = dataset.iloc[-last_days:, :] x_ = range(3, dataset.shape[0]) x_ = list(dataset.index) # Plot first subplot plt.subplot(2, 1, 1) plt.plot(dataset['ma7'], label='MA 7', color='g', linestyle='--') plt.plot(dataset[ticker], label='Closing Price', color='b') plt.plot(dataset['ma21'], label='MA 21', color='r', linestyle='--') plt.plot(dataset['upper_band'], label='Upper Band', color='c') plt.plot(dataset['lower_band'], label='Lower Band', color='c') plt.fill_between(x_, dataset['lower_band'], dataset['upper_band'], alpha=0.35) plt.title('Technical indicators for Goldman Sachs - last {} days.'.format( last_days)) plt.ylabel('USD') plt.legend() # Plot second subplot plt.subplot(2, 1, 2) plt.title('MACD') plt.plot(dataset['MACD'], label='MACD', linestyle='-.') plt.hlines(15, xmacd_, shape_0, colors='g', linestyles='--') plt.hlines(-15, xmacd_, shape_0, colors='g', linestyles='--') plt.plot(dataset['log_momentum'], label='Momentum', color='b', linestyle='-') plt.savefig( '../assets/Techinical_indicators_for_Goldman_Sachs_last_400_days.png') plt.legend() plt.show() if __name__ == "__main__": data = Data('GS') df = data.get_close_data() df_ti = get_technical_indicators(df) plot_technical_indicators(df_ti, 400)
6ee1904358d0968c67a404a23c8686c263e0b35c
4007632edd395d243bca022418848a2ff54409c8
/学习/atest6.py
54471b4561bb9f98d4319de5c82e87a0702bb3bf
[]
no_license
549982170/python_learning
d80a9403cbe2eb8304aba50ff373b2b67df095e2
2c3f73718e0a6d9d4923a2e0f22ff2d4230357e9
refs/heads/master
2021-06-22T04:32:06.286691
2020-12-10T03:29:56
2020-12-10T03:29:56
101,596,379
0
0
null
null
null
null
UTF-8
Python
false
false
430
py
# coding:utf-8 # !/user/bin/python import requests import json headers = {'Authorization': "Token 03f7409574a55e98cd33b7cc44bcbe968fd0988f"} host = "http://127.0.0.1:8000/" url = "v5/discovery/search/service/" # url = "v1/generator/test/mytest/" url = host + url data = {"keyword": "ss"} re = requests.post(url) re = requests.post(url, data=data, headers=headers) print re.text # # a = "ssddda" # print a[-1:]
d5526e5e11970b9cf7389f8167209a965ef78e49
7bc54bae28eec4b735c05ac7bc40b1a8711bb381
/src/misc/show_checkpoint_vars.py
d869d35e1eb9f214c813932df22cedf891373257
[]
no_license
clover3/Chair
755efd4abbd5f3f2fb59e9b1bc6e7bc070b8d05e
a2102ebf826a58efbc479181f1ebb5de21d1e49f
refs/heads/master
2023-07-20T17:29:42.414170
2023-07-18T21:12:46
2023-07-18T21:12:46
157,024,916
0
0
null
2023-02-16T05:20:37
2018-11-10T21:55:29
Python
UTF-8
Python
false
false
642
py
from collections import OrderedDict import tensorflow as tf def load_checkpoint_vars(checkpoint_path): ckpt_reader = tf.train.load_checkpoint(checkpoint_path) d = OrderedDict() for x in tf.train.list_variables(checkpoint_path): (name, var) = (x[0], x[1]) d[name] = ckpt_reader.get_tensor(name) return d def load_checkpoint_vars_v2(checkpoint_path): ckpt_reader = tf.compat.v1.train.load_checkpoint(checkpoint_path) d = OrderedDict() for x in tf.compat.v1.train.list_variables(checkpoint_path): (name, var) = (x[0], x[1]) d[name] = ckpt_reader.get_tensor(name) return d
e9a860e399fac3764ecab8ebb8b31901390468c7
491c7a6b2eeaccf9e8421c0b1ec5a2d9d77407e2
/ceres/consensus/all_coins_default_constants/chaingreen_default_constants.py
7fde41f6c0352db6f6c46ba63b01b94d2a6a068e
[ "Apache-2.0" ]
permissive
zhenglcc/ceres-combineharvester
25609627a4a16b3e3067c2e4296de82a65f3b2bd
47b685a63fb5f38ac9e2eceb9724a562feb06ee9
refs/heads/main
2023-08-25T04:49:31.531840
2021-10-30T09:06:08
2021-10-30T09:06:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,781
py
from ceres.util.ints import uint64 from ceres.consensus.constants import ConsensusConstants testnet_kwargs = { "SLOT_BLOCKS_TARGET": 32, "MIN_BLOCKS_PER_CHALLENGE_BLOCK": 16, # Must be less than half of SLOT_BLOCKS_TARGET "MAX_SUB_SLOT_BLOCKS": 128, # Must be less than half of SUB_EPOCH_BLOCKS "NUM_SPS_SUB_SLOT": 64, # Must be a power of 2 "SUB_SLOT_ITERS_STARTING": 2 ** 16, # DIFFICULTY_STARTING is the starting difficulty for the first epoch, which is then further # multiplied by another factor of DIFFICULTY_CONSTANT_FACTOR, to be used in the VDF iter calculation formula. "DIFFICULTY_CONSTANT_FACTOR": 2 ** 20, "DIFFICULTY_STARTING": 1, "DIFFICULTY_CHANGE_MAX_FACTOR": 81, # The next difficulty is truncated to range [prev / FACTOR, prev * FACTOR] # "DIFFICULTY_CHANGE_MAX_FACTOR_v1_2_0": 81, # This difficulty change to be applied with v1.2.0 # "v1_2_0_ACTIVATION_BLOCK": 170496, # activation of v1.2.0 rules height # These 3 constants must be changed at the same time "SUB_EPOCH_BLOCKS": 384, # The number of blocks per sub-epoch, mainnet 384 "EPOCH_BLOCKS": 4608, # The number of blocks per epoch, mainnet 4608. Must be multiple of SUB_EPOCH_BLOCKS "SIGNIFICANT_BITS": 8, # The number of bits to look at in difficulty and min iters. The rest are zeroed "DISCRIMINANT_SIZE_BITS": 1024, # Max is 1024 (based on ClassGroupElement int size) "NUMBER_ZERO_BITS_PLOT_FILTER": 9, # H(plot signature of the challenge) must start with these many zeroes "MIN_PLOT_SIZE": 32, # 32 for mainnet "MAX_PLOT_SIZE": 50, "SUB_SLOT_TIME_TARGET": 600, # The target number of seconds per slot, mainnet 600 "NUM_SP_INTERVALS_EXTRA": 3, # The number of sp intervals to add to the signage point "MAX_FUTURE_TIME": 5 * 60, # The next block can have a timestamp of at most these many seconds in the future "NUMBER_OF_TIMESTAMPS": 11, # Than the average of the last NUMBER_OF_TIMESTAMPS blocks # Used as the initial cc rc challenges, as well as first block back pointers, and first SES back pointer # We override this value based on the chain being run (testnet0, testnet1, mainnet, etc) # Default used for tests is std_hash(b'') "GENESIS_CHALLENGE": bytes.fromhex("2cef93a2ebf7c0546609311684e484f08555d3c0e4336a30a044e1ba7f26f691"), # Forks of chia should change this value to provide replay attack protection. This is set to mainnet genesis chall "AGG_SIG_ME_ADDITIONAL_DATA": bytes.fromhex("0235e47be80dbba72e8e105f87776fe16690838dde7f71e8a77086c0374bcaf3"), "GENESIS_PRE_FARM_POOL_PUZZLE_HASH": bytes.fromhex( "42e52e6fac97b0f409c372865989bc9443755887ab24cab3b00bcd1fdacad7f5" ), "GENESIS_PRE_FARM_FARMER_PUZZLE_HASH": bytes.fromhex( "427930199ca2f1d7669de76057fc215abed4cf28e33ffdf662873f6d6622e3e6" ), "MAX_VDF_WITNESS_SIZE": 64, # Size of mempool = 50x the size of block "MEMPOOL_BLOCK_BUFFER": 50, # Max coin amount, fits into 64 bits "MAX_COIN_AMOUNT": uint64((1 << 64) - 1), # Max block cost in clvm cost units "MAX_BLOCK_COST_CLVM": 11000000000, # The cost per byte of generator program "COST_PER_BYTE": 12000, "WEIGHT_PROOF_THRESHOLD": 2, "BLOCKS_CACHE_SIZE": 4608 + (128 * 4), "WEIGHT_PROOF_RECENT_BLOCKS": 1000, "MAX_BLOCK_COUNT_PER_REQUESTS": 32, # Allow up to 32 blocks per request # "INITIAL_FREEZE_END_TIMESTAMP": 1621630800, # 2021-05-21T21:00:00Z "NETWORK_TYPE": 0, "MAX_GENERATOR_SIZE": 1000000, "MAX_GENERATOR_REF_LIST_SIZE": 512, # Number of references allowed in the block generator ref list "POOL_SUB_SLOT_ITERS": 37600000000, # iters limit * NUM_SPS } DEFAULT_CONSTANTS = ConsensusConstants(**testnet_kwargs) # type: ignore
ec35ca8c45e83ee2346b6490fe0798b8a2c19343
177464b6a6199b72d5f9342423fd507630e7ef8c
/setup.py
857b0b44d0307a6e4622d21dbb085cd8f1d2f053
[ "BSD-2-Clause" ]
permissive
yyr93520/sne
19f58f40840d18665fbdaff552396c0ce9ccd180
caaa2cce9b623f5ffc411ece4c9176872a672793
refs/heads/master
2021-08-23T14:48:42.730451
2017-12-05T08:52:05
2017-12-05T08:52:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,358
py
from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md')) as f: long_description = f.read() setup( name='learning sparse network embedding for identity user retrieval', version='1.0.0.dev', url='https://github.com/Allen517/sne', description='', long_description=long_description, keywords='', author='', maintainer='King Wang', maintainer_email='[email protected]', license='BSD', packages=find_packages(exclude=('tests', 'tests.*')), package_data={ }, entry_points={ }, classifiers=[ 'Framework :: SNE', 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: Chinese (Simplified)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Softwamax_shinglere Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=[ 'tensorflow==1.3.0', 'numpy', ], )
1418f12136d730e578a93b5499f6ad816057a019
5ce1c0ab1b6147428fc30bcd1698e4d0e53b688e
/829.py
4fe73b828e6983e64730ae6da4385af8d2cf971f
[]
no_license
junyang10734/leetcode-python
035b12df3f7d9fc33553140d1eb0692750b44f0a
eff322f04d22ffbc4f9b10e77f97c28aac5c7004
refs/heads/master
2023-07-22T11:16:38.740863
2023-07-14T00:22:00
2023-07-14T00:22:00
189,197,380
0
0
null
null
null
null
UTF-8
Python
false
false
392
py
# 829. Consecutive Numbers Sum # Math # https://leetcode.com/problems/consecutive-numbers-sum/solution/ # runtime: O(N**0.5) class Solution: def consecutiveNumbersSum(self, N: int) -> int: count = 0 upper = ceil((2 * N + 0.25) ** 0.5 - 0.5) + 1 for k in range(1, upper): if (N - (k+1)*k // 2) % k == 0: count += 1 return count
1ddcfa2db57a2e28a25671ce5333c37ca126c22a
e6c65e2e354336a4bea5b6a4ccbccd3682915fe2
/out-bin/py/google/fhir/models/model_test.runfiles/pypi__tensorflow_1_12_0/tensorflow-1.12.0.data/purelib/tensorflow/contrib/sparsemax/python/ops/__init__.py
393d43d4cfa0fb8d855ebba91c4effe94a98abaa
[ "Apache-2.0" ]
permissive
rasalt/fhir-datalab
c30ab773d84983dd04a37e9d0ddec8bf2824b8a4
3e329fc8b4226d3e3a4a7c23c306a86e7a9ea0de
refs/heads/master
2021-10-09T05:51:04.593416
2018-12-21T18:11:03
2018-12-22T05:38:32
162,744,237
0
0
null
null
null
null
UTF-8
Python
false
false
192
py
/home/rkharwar/.cache/bazel/_bazel_rkharwar/0ddaa3627472ad9d1367a008236ce2f5/external/pypi__tensorflow_1_12_0/tensorflow-1.12.0.data/purelib/tensorflow/contrib/sparsemax/python/ops/__init__.py
c14a556a8fc7a81e031a648406e986ae7db52409
9e5bf5e7d0bdfa4ff2aca65ac306ed801d146608
/python-06-stdlib-review/chapter-03-Algorithms/3.2-itertools/py_01_itertools.py
ed3063a35bb616b55116f551571022cacd42e8f5
[]
no_license
AuroraBoreas/python_advanced_tricks
90b07967789960beec381de676459c1e84b95860
ba0940e25eda52345a27cf9ddffed9d18fa2a031
refs/heads/master
2022-11-27T19:09:45.666017
2020-08-11T17:33:11
2020-08-11T17:33:11
275,083,831
0
0
null
null
null
null
UTF-8
Python
false
false
357
py
""" P163-P176, itertools: iterator functions ! What? ! Why? ! How? itertools |-- merging and splitting iterators "分合" |-- converting inputs "转" |-- producing new valeus "生" |-- filtering "滤" |-- grouping data "群" |-- combining inputs "主" """
4c50d3114769805bd5144afdece91f515c6f551f
b83ac23819fd7ba998563f2ad870405bdd07cc2b
/gym_idsgame/__init__.py
31ebf59e36a8fcf1596d6ed9c09c6d07bb97e533
[ "MIT" ]
permissive
Limmen/gym-idsgame
699abd2894bce15108f1606f5fb71f612dd7ba03
d10830fef55308d383c98b41b34688a7fceae357
refs/heads/master
2023-09-01T17:32:16.768138
2023-08-22T12:00:53
2023-08-22T12:00:53
247,794,752
49
12
MIT
2021-04-21T07:50:06
2020-03-16T19:00:27
Python
UTF-8
Python
false
false
66,874
py
""" Register OpenAI Envs """ from gymnasium.envs.registration import register # -------- Version 0 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Sparse # [Version] 0 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v0', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV0Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Sparse # [Version] 0 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v0', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV0Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Sparse # [Version] 0 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v0', entry_point='gym_idsgame.envs:IdsGameRandomAttackV0Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Sparse # [Version] 0 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v0', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV0Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Sparse # [Version] 0 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v0', entry_point='gym_idsgame.envs:IdsGameV0Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 1 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 1 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v1', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV1Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 1 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v1', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV1Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 1 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v1', entry_point='gym_idsgame.envs:IdsGameRandomAttackV1Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 1 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v1', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV1Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 1 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v1', entry_point='gym_idsgame.envs:IdsGameV1Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 2 ------------ # [AttackerEnv] 1 layer, 2 servers per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 2 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v2', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV2Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 2 servers per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 2 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v2', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV2Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 2 servers per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 2 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v2', entry_point='gym_idsgame.envs:IdsGameRandomAttackV2Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 2 servers per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 2 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v2', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV2Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 2 servers per layer, 10 attack-defense-values # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 2 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v2', entry_point='gym_idsgame.envs:IdsGameV2Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 3 ------------ # [AttackerEnv] 2 layers, 3 servers per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 3 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v3', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV3Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 2 layer, 3 servers per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 3 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v3', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV3Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 2 layers, 3 servers per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 3 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v3', entry_point='gym_idsgame.envs:IdsGameRandomAttackV3Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 2 layers, 3 servers per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 3 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v3', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV3Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 2 layers, 3 servers per layer, 10 attack-defense-values # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 3 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v3', entry_point='gym_idsgame.envs:IdsGameV3Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 4 ------------ # [AttackerEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 4 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v4', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV4Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 4 layer, 5 servers per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 4 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v4', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV4Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 4 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v4', entry_point='gym_idsgame.envs:IdsGameRandomAttackV4Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 4 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v4', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV4Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 4 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v4', entry_point='gym_idsgame.envs:IdsGameV4Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 5 ------------ # [AttackerEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, random defender, connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 5 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v5', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV5Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, # defender following the "defend minimal strategy", connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 5 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v5', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV5Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, random attacker, connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 5 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v5', entry_point='gym_idsgame.envs:IdsGameRandomAttackV5Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, # attacker following the "attack maximal strategy", connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 5 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v5', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV5Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Sparse # [Version] 5 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v5', entry_point='gym_idsgame.envs:IdsGameV5Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 6 ------------ # [AttackerEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, random defender, connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 6 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v6', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV6Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 4 layer, 5 servers per layer, 10 attack-defense-values, # defender following the "defend minimal strategy", connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 6 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v6', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV6Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, random attacker, connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 6 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v6', entry_point='gym_idsgame.envs:IdsGameRandomAttackV6Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, # attacker following the "attack maximal strategy", connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 6 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v6', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV6Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 4 layers, 5 servers per layer, 10 attack-defense-values, connected layers # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 5 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v6', entry_point='gym_idsgame.envs:IdsGameV6Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 7 ------------ # [AttackerEnv] 2 layers, 3 servers per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 7 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v7', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV7Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 2 layer, 3 servers per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 7 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v7', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV7Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 2 layers, 3 servers per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 7 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v7', entry_point='gym_idsgame.envs:IdsGameRandomAttackV7Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 2 layers, 3 servers per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 7 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v7', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV7Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 2 layers, 3 servers per layer, 10 attack-defense-values # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 7 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v7', entry_point='gym_idsgame.envs:IdsGameV7Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 8 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 8 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v8', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV8Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 8 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v8', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV8Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 8 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v8', entry_point='gym_idsgame.envs:IdsGameRandomAttackV8Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 8 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v8', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV8Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 8 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v8', entry_point='gym_idsgame.envs:IdsGameV8Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 9 ------------ # [AttackerEnv] 1 layer, 2 servers per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 9 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v9', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV9Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 2 servers per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 9 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v9', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV9Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 2 servers per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 9 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v9', entry_point='gym_idsgame.envs:IdsGameRandomAttackV9Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 2 servers per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 9 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v9', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV9Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 2 servers per layer, 10 attack-defense-values # [Initial State] Defense: 4, Attack:0, Num vulnerabilities: 4, Det: 3, Vulnerability value: 0 # [Rewards] Dense # [Version] 9 # [Observations] partially observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v9', entry_point='gym_idsgame.envs:IdsGameV9Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 10 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random defender # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 10 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v10', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV10Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 10 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 10 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v10', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV10Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values, random attacker # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 10 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v10', entry_point='gym_idsgame.envs:IdsGameRandomAttackV10Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 10 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v10', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV10Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 10 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 2, Vulnerability value: 0 # [Rewards] Dense # [Version] 10 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v10', entry_point='gym_idsgame.envs:IdsGameV10Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 11 ------------ # [AttackerEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 11 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v11', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV11Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 11 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v11', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV11Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 11 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v11', entry_point='gym_idsgame.envs:IdsGameRandomAttackV11Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 11 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v11', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV11Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 11 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v11', entry_point='gym_idsgame.envs:IdsGameV11Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 12 ------------ # [AttackerEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: (0-1) (random), Attack: (0-1) (random), Num vulnerabilities: 0, Det: (0-1) (random), # Vulnerability value: 0 # [Rewards] Dense # [Version] 12 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v12', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV12Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: (0-1) (random), Attack: (0-1) (random), Num vulnerabilities: 0, Det: (0-1) (random), # Vulnerability value: 0 # [Rewards] Dense # [Version] 12 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v12', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV12Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: (0-1) (random), Attack: (0-1) (random), Num vulnerabilities: 0, Det: (0-1) (random), # Vulnerability value: 0 # [Rewards] Dense # [Version] 12 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v12', entry_point='gym_idsgame.envs:IdsGameRandomAttackV12Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: (0-1) (random), Attack: (0-1) (random), Num vulnerabilities: 0, Det: (0-1) (random), # Vulnerability value: 0 # [Rewards] Dense # [Version] 12 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v12', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV12Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: (0-1) (random), Attack: (0-1) (random), Num vulnerabilities: 0, Det: (0-1) (random), # Vulnerability value: 0 # [Rewards] Dense # [Version] 12 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v12', entry_point='gym_idsgame.envs:IdsGameV12Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 13 ------------ # [AttackerEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 10, Vulnerability value: 0 # [Rewards] Dense # [Version] 13 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v13', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV13Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 10, Vulnerability value: 0 # [Rewards] Dense # [Version] 13 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v13', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV13Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 10, Vulnerability value: 0 # [Rewards] Dense # [Version] 13 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v13', entry_point='gym_idsgame.envs:IdsGameRandomAttackV13Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 10, Vulnerability value: 0 # [Rewards] Dense # [Version] 13 # [Observations] fully observed # [Environment] Deterministic # [Attacker Starting Position] Start node # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v13', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV13Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 0 layers, 1 server per layer, 2 attack-defense-values # [Initial State] Defense: 0, Attack:0, Num vulnerabilities: 0, Det: 10, Vulnerability value: 0 # [Rewards] Dense # [Version] 13 # [Observations] fully observed # [Attacker Starting Position] Start node # [Environment] Deterministic # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v13', entry_point='gym_idsgame.envs:IdsGameV13Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 14 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 4 attack-defense-values, random defender # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 14 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v14', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV14Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 4 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 14 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v14', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV14Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values, random attacker # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 14 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v14', entry_point='gym_idsgame.envs:IdsGameRandomAttackV14Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 14 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v14', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV14Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 14 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v14', entry_point='gym_idsgame.envs:IdsGameV14Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 15 ------------ # [AttackEnv] 1 layer, 1 server per layer, 4 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 15 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v15', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV15Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackEnv] 1 layer, 1 server per layer, 4 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 15 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v15', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV15Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 15 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v15', entry_point='gym_idsgame.envs:IdsGameRandomAttackV15Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 15 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v15', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV15Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 15 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Start node # [Local View] Yes # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v15', entry_point='gym_idsgame.envs:IdsGameV15Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 16 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 4 attack-defense-values, random defender # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 16 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v16', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV16Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 4 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 16 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v16', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV16Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values, random attacker # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 16 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v16', entry_point='gym_idsgame.envs:IdsGameRandomAttackV16Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 16 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v16', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV16Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 16 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v16', entry_point='gym_idsgame.envs:IdsGameV16Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 17 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 4 attack-defense-values, random defender # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 17 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_defense-v17', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV17Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 4 attack-defense-values, defender following the "defend minimal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 17 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-minimal_defense-v17', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV17Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values, random attacker # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 17 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-random_attack-v17', entry_point='gym_idsgame.envs:IdsGameRandomAttackV17Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values, attacker following the "attack maximal strategy" # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 17 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-maximal_attack-v17', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV17Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 4 attack-defense-values # [Initial State] Defense: 2, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 0 # [Rewards] Dense # [Version] 17 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] No # [Reconnaissance activities] disabled # [Reconnaissance bool features] No register( id='idsgame-v17', entry_point='gym_idsgame.envs:IdsGameV17Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 18 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, random defender # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 18 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-random_defense-v18', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV18Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, defender following the "defend minimal strategy" # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 18 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-minimal_defense-v18', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV18Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, random attacker # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 18 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-random_attack-v18', entry_point='gym_idsgame.envs:IdsGameRandomAttackV18Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, attacker following the "attack maximal strategy" # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 18 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-maximal_attack-v18', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV18Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 18 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-v18', entry_point='gym_idsgame.envs:IdsGameV18Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 19 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, random defender # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 19 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-random_defense-v19', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV19Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, defender following the "defend minimal strategy" # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 19 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-minimal_defense-v19', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV19Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, random attacker # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 19 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-random_attack-v19', entry_point='gym_idsgame.envs:IdsGameRandomAttackV19Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, attacker following the "attack maximal strategy" # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 19 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-maximal_attack-v19', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV19Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 19 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-v19', entry_point='gym_idsgame.envs:IdsGameV19Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 20 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, random defender # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 20 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-random_defense-v20', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV20Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, defender following the "defend minimal strategy" # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 20 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-minimal_defense-v20', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV20Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, random attacker # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 20 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-random_attack-v20', entry_point='gym_idsgame.envs:IdsGameRandomAttackV20Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, attacker following the "attack maximal strategy" # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 20 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-maximal_attack-v20', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV20Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 20 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-v20', entry_point='gym_idsgame.envs:IdsGameV20Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # -------- Version 21 ------------ # [AttackerEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, random defender # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 21 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-random_defense-v21', entry_point='gym_idsgame.envs:IdsGameRandomDefenseV21Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackerEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, defender following the "defend minimal strategy" # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 21 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-minimal_defense-v21', entry_point='gym_idsgame.envs:IdsGameMinimalDefenseV21Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, random attacker # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 21 # [Observations] fully observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-random_attack-v21', entry_point='gym_idsgame.envs:IdsGameRandomAttackV21Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [DefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender, attacker following the "attack maximal strategy" # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 21 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-maximal_attack-v21', entry_point='gym_idsgame.envs:IdsGameMaximalAttackV21Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} ) # [AttackDefenseEnv] 1 layer, 1 server per layer, 7 attack-defense-values, random defender # [Initial State] Defense: 7, Attack:0, Num vulnerabilities: 1, Det: 1, Vulnerability value: 1 # [Rewards] Dense # [Version] 21 # [Observations] partially observed # [Environment] Random # [Attacker Starting Position] Random # [Local View] Yes # [Reconnaissance activities] enabled # [Reconnaissance bool features] Yes register( id='idsgame-v21', entry_point='gym_idsgame.envs:IdsGameV21Env', kwargs={'idsgame_config': None, 'save_dir': None, 'initial_state_path': None} )
402f8b11f4f79126a7238680b4d8b3c9291b6525
2d930aadf19b2ad6ea49725099d2f37475cd57f8
/test/functional/signrawtransactions.py
01b71fc8133e8036171530c690526d90558605d1
[ "MIT" ]
permissive
stratton-oakcoin/oakcoin
ea83774c9f6ea64adb8832770e6219ffb31edef6
fe53193a50bd3674211448f1dcc39c6f9f042bb2
refs/heads/master
2021-01-20T13:22:05.877005
2017-05-07T10:09:57
2017-05-07T10:09:57
90,477,972
1
2
null
2017-05-07T10:09:57
2017-05-06T16:58:05
C++
UTF-8
Python
false
false
5,919
py
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Oakcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test transaction signing using the signrawtransaction RPC.""" from test_framework.test_framework import OakcoinTestFramework from test_framework.util import * class SignRawTransactionsTest(OakcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 1 def successful_signing_test(self): """Create and sign a valid raw transaction with one input. Expected results: 1) The transaction has a complete set of signatures 2) No script verification error occurred""" privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N', 'cVKpPfVKSJxKqVpE9awvXNWuLHCa5j5tiE7K6zbUSptFpTEtiFrA'] inputs = [ # Valid pay-to-pubkey scripts {'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0, 'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'}, {'txid': '83a4f6a6b73660e13ee6cb3c6063fa3759c50c9b7521d0536022961898f4fb02', 'vout': 0, 'scriptPubKey': '76a914669b857c03a5ed269d5d85a1ffac9ed5d663072788ac'}, ] outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) rawTxSigned = self.nodes[0].signrawtransaction(rawTx, inputs, privKeys) # 1) The transaction has a complete set of signatures assert 'complete' in rawTxSigned assert_equal(rawTxSigned['complete'], True) # 2) No script verification error occurred assert 'errors' not in rawTxSigned # Check that signrawtransaction doesn't blow up on garbage merge attempts dummyTxInconsistent = self.nodes[0].createrawtransaction([inputs[0]], outputs) rawTxUnsigned = self.nodes[0].signrawtransaction(rawTx + dummyTxInconsistent, inputs) assert 'complete' in rawTxUnsigned assert_equal(rawTxUnsigned['complete'], False) # Check that signrawtransaction properly merges unsigned and signed txn, even with garbage in the middle rawTxSigned2 = self.nodes[0].signrawtransaction(rawTxUnsigned["hex"] + dummyTxInconsistent + rawTxSigned["hex"], inputs) assert 'complete' in rawTxSigned2 assert_equal(rawTxSigned2['complete'], True) assert 'errors' not in rawTxSigned2 def script_verification_error_test(self): """Create and sign a raw transaction with valid (vin 0), invalid (vin 1) and one missing (vin 2) input script. Expected results: 3) The transaction has no complete set of signatures 4) Two script verification errors occurred 5) Script verification errors have certain properties ("txid", "vout", "scriptSig", "sequence", "error") 6) The verification errors refer to the invalid (vin 1) and missing input (vin 2)""" privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N'] inputs = [ # Valid pay-to-pubkey script {'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0}, # Invalid script {'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7}, # Missing scriptPubKey {'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 1}, ] scripts = [ # Valid pay-to-pubkey script {'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0, 'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'}, # Invalid script {'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7, 'scriptPubKey': 'badbadbadbad'} ] outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) # Make sure decoderawtransaction is at least marginally sane decodedRawTx = self.nodes[0].decoderawtransaction(rawTx) for i, inp in enumerate(inputs): assert_equal(decodedRawTx["vin"][i]["txid"], inp["txid"]) assert_equal(decodedRawTx["vin"][i]["vout"], inp["vout"]) # Make sure decoderawtransaction throws if there is extra data assert_raises(JSONRPCException, self.nodes[0].decoderawtransaction, rawTx + "00") rawTxSigned = self.nodes[0].signrawtransaction(rawTx, scripts, privKeys) # 3) The transaction has no complete set of signatures assert 'complete' in rawTxSigned assert_equal(rawTxSigned['complete'], False) # 4) Two script verification errors occurred assert 'errors' in rawTxSigned assert_equal(len(rawTxSigned['errors']), 2) # 5) Script verification errors have certain properties assert 'txid' in rawTxSigned['errors'][0] assert 'vout' in rawTxSigned['errors'][0] assert 'scriptSig' in rawTxSigned['errors'][0] assert 'sequence' in rawTxSigned['errors'][0] assert 'error' in rawTxSigned['errors'][0] # 6) The verification errors refer to the invalid (vin 1) and missing input (vin 2) assert_equal(rawTxSigned['errors'][0]['txid'], inputs[1]['txid']) assert_equal(rawTxSigned['errors'][0]['vout'], inputs[1]['vout']) assert_equal(rawTxSigned['errors'][1]['txid'], inputs[2]['txid']) assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout']) def run_test(self): self.successful_signing_test() self.script_verification_error_test() if __name__ == '__main__': SignRawTransactionsTest().main()
678efd8416616f304423b9610caa21b3b0aa6bb3
b70f99aee135ea27a03951e75524ede3be18d316
/test/tob_pyner/fill_fields/bin/fill/customer_bin.py
f3be56157b686a98e42d5ab2d0c2ff980456bc57
[]
no_license
zlbl/AutoTestPytestN
968e11b205d824eca0fcb73a166f21208ce405d5
a86f71a4ad50796f5031cdb40c4d5a808f421383
refs/heads/master
2020-11-28T19:27:21.056844
2019-12-24T08:25:45
2019-12-24T08:25:45
229,902,483
0
0
null
null
null
null
UTF-8
Python
false
false
3,096
py
from datetime import datetime from test.tob_pyner.fill_fields.bin.fill.update_cust_info_sql import * from test.tob_pyner.fill_fields.util.MySqlHelper import select_insert, update def generate_customer(): """生成客户id""" # ALTER TABLE pyner_customer AUTO_INCREMENT = 1000000001; select_insert(generateSQL) """生成平台客户ID""" update(updatePlatformCredInfoUSCCSQL) update(updatePlatformCredInfoBLCSQL) select_insert(generatePlatformSQL) print('generate_customer Finish', datetime.now()) def update_user_customer_id(): """更新用户表客户Id""" update(updateUserCustomerIdSQL) print('update_user_customer_id Finish', datetime.now()) def update_person_customer_id(): update(updatePersonCustomerIdSQL) print('update_person_customer_id Finish', datetime.now()) def update_enterprise_customer_id(): update(updateEnterpriseCustomerIdSQL) print('update_enterprise_customer_id Finish', datetime.now()) def update_platform_customer_id(): update(updatePlatformCustomerIdSQL) print('update_platform_customer_id Finish', datetime.now()) def update_account_customer_id(): # 更新用户账户表 update(updateAccountCustomerIdSQL1) # 更新平台账户表 update(updateAccountCustomerIdSQL2) print('update_account_customer_id Finish', datetime.now()) def update_bid_customer_id(): update(updateBidCustomerIdSQL) print('update_bid_customer_id Finish', datetime.now()) def update_obligatory_customer_id(): update(updateObligatoryCustomerIdSQL) print('update_obligatory_customer_id Finish', datetime.now()) def update_trade_pay_customer_id(): update(updateTradePayCustomerIdSQL) print('update_trade_pay_customer_id Finish', datetime.now()) def update_trade_receive_customer_id(): update(updateTradeReceiveCustomerIdSQL) print('update_trade_receive_customer_id Finish', datetime.now()) if __name__ == '__main__': print('开始时间:', datetime.now()) # generate_customer() update_user_customer_id() update_person_customer_id() update_enterprise_customer_id() update_platform_customer_id() update_account_customer_id() update_bid_customer_id() update_obligatory_customer_id() update_trade_pay_customer_id() update_trade_receive_customer_id() print('结束时间:', datetime.now()) def generate_customer_id(): # 生成customerId generate_customer() # 更新customerId到User表 update_user_customer_id() # 更新customerId到Person表 update_person_customer_id() # 更新customerId到Enterprise表 update_enterprise_customer_id() # 更新customerId到Platform表 update_platform_customer_id() # 更新customerId到Account表 update_account_customer_id() # 更新customerId到Bid表 update_bid_customer_id() # 更新customerId到Obligatory表 update_obligatory_customer_id() # 更新付款方customerId到Trade表 update_trade_pay_customer_id() # 更新收款方customerId到Trade表 update_trade_receive_customer_id()
78f5536e736c9e86de6b0ca888abfd4a50ce2276
22a243d9535602e2f56b4e8d78f743b6240afc94
/image_captioning/coco_caption/pycocoevalcap/bleu/bleu.py
1c3a2c5a4780bbba09e046123fced9affa79d062
[ "MIT", "BSD-2-Clause-Views" ]
permissive
RitaRamo/memory-augmented-nn
05bc969fa28225e95b38d6f1d5f0fa09a94b30db
0553df245a6976ad1c15075a65df93591e2c2632
refs/heads/main
2023-03-08T13:59:52.530224
2021-02-22T19:03:25
2021-02-22T19:03:25
309,144,074
0
1
null
null
null
null
UTF-8
Python
false
false
1,311
py
#!/usr/bin/env python # # File Name : bleu.py # # Description : Wrapper for BLEU scorer. # # Creation Date : 06-01-2015 # Last Modified : Thu 19 Mar 2015 09:13:28 PM PDT # Authors : Hao Fang <[email protected]> and Tsung-Yi Lin <[email protected]> from bleu_scorer import BleuScorer class Bleu: def __init__(self, n=4): # default compute Blue score up to 4 self._n = n self._hypo_for_image = {} self.ref_for_image = {} def compute_score(self, gts, res): assert(gts.keys() == res.keys()) imgIds = gts.keys() bleu_scorer = BleuScorer(n=self._n) for id in imgIds: hypo = res[id] ref = gts[id] print("image id", id) print("hypo", hypo) # Sanity check. assert(type(hypo) is list) assert(len(hypo) == 1) assert(type(ref) is list) assert(len(ref) >= 1) bleu_scorer += (hypo[0], ref) #score, scores = bleu_scorer.compute_score(option='shortest') score, scores = bleu_scorer.compute_score(option='closest', verbose=1) #score, scores = bleu_scorer.compute_score(option='average', verbose=1) # return (bleu, bleu_info) return score, scores def method(self): return "Bleu"
67b81c79caf9d6e7e0ca40ffe64b68a22a98c497
529694a395c88a1c0c097f80456a0eb01144131f
/tensorpac/spectral.py
994abb93382c017eed859bd9f28e43ec0298d8f4
[ "BSD-3-Clause" ]
permissive
cjayb/tensorpac
0d83c4dcec2b40c75c119f243070faacb3b220bf
e4ee18ca3faa8ad9f3cdd4f5233be224f12523af
refs/heads/master
2023-01-27T12:49:32.841580
2020-12-08T14:44:35
2020-12-08T14:44:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,860
py
"""Extract spectral informations from data.""" import numpy as np from joblib import Parallel, delayed from scipy.signal import hilbert, filtfilt from scipy import fftpack from tensorpac.config import CONFIG def hilbertm(x): """Faster Hilbert fix. x must have a shape of (..., n_pts) """ n_pts = x.shape[-1] fc = fftpack.helper.next_fast_len(n_pts) return hilbert(x, fc, axis=-1)[..., 0:n_pts] def spectral(x, sf, f, stype, dcomplex, cycle, width, n_jobs): """Extract spectral informations from data. Parameters ---------- x : array_like Array of data sf : float Sampling frequency f : array_like Frequency vector of shape (N, 2) stype : string Spectral informations to extract (use either 'pha' or 'amp') dcomplex : string Complex decomposition type. Use either 'hilbert' or 'wavelet' cycle : int Number of cycles to use for fir1 filtering. width : int Width of the wavelet. n_jobs : int Number of jobs to use. If jobs is -1, all of them are going to be used. """ n_freqs = f.shape[0] # Filtering + complex decomposition : if dcomplex is 'hilbert': # get filtering coefficients b = [] a = np.zeros((n_freqs,), dtype=float) forder = np.zeros((n_freqs,), dtype=int) for k in range(n_freqs): forder[k] = fir_order(sf, x.shape[-1], f[k, 0], cycle=cycle) _b, a[k] = fir1(forder[k], f[k, :] / (sf / 2.)) b += [_b] # Filt each time series : xf = Parallel(n_jobs=n_jobs, **CONFIG['JOBLIB_CFG'])(delayed(filtfilt)( b[k], a[k], x, padlen=forder[k], axis=-1) for k in range(n_freqs)) # Use hilbert for the complex decomposition : xd = np.asarray(xf) if stype is not None: xd = hilbertm(xd) elif dcomplex is 'wavelet': f = f.mean(1) # centered frequencies xd = Parallel(n_jobs=n_jobs, **CONFIG['JOBLIB_CFG'])(delayed(morlet)( x, sf, k, width) for k in f) # Extract phase / amplitude : if stype is 'pha': return np.angle(xd).astype(np.float64) elif stype is 'amp': return np.abs(xd).astype(np.float64) elif stype is None: return xd.astype(np.float64) ############################################################################### ############################################################################### # FILTERING ############################################################################### ############################################################################### def fir_order(fs, sizevec, flow, cycle=3): filtorder = cycle * (fs // flow) if (sizevec < 3 * filtorder): filtorder = (sizevec - 1) // 3 return int(filtorder) def n_odd_fcn(f, o, w, l): """Odd case.""" # Variables : b0 = 0 m = np.array(range(int(l + 1))) k = m[1:len(m)] b = np.zeros(k.shape) # Run Loop : for s in range(0, len(f), 2): m = (o[s + 1] - o[s]) / (f[s + 1] - f[s]) b1 = o[s] - m * f[s] b0 = b0 + (b1 * (f[s + 1] - f[s]) + m / 2 * ( f[s + 1] * f[s + 1] - f[s] * f[s])) * abs( np.square(w[round((s + 1) / 2)])) b = b + (m / (4 * np.pi * np.pi) * ( np.cos(2 * np.pi * k * f[s + 1]) - np.cos(2 * np.pi * k * f[s]) ) / (k * k)) * abs(np.square(w[round((s + 1) / 2)])) b = b + (f[s + 1] * (m * f[s + 1] + b1) * np.sinc(2 * k * f[ s + 1]) - f[s] * (m * f[s] + b1) * np.sinc(2 * k * f[s])) * abs( np.square(w[round((s + 1) / 2)])) b = np.insert(b, 0, b0) a = (np.square(w[0])) * 4 * b a[0] = a[0] / 2 aud = np.flipud(a[1:len(a)]) / 2 a2 = np.insert(aud, len(aud), a[0]) h = np.concatenate((a2, a[1:] / 2)) return h def n_even_fcn(f, o, w, l): """Even case.""" # Variables : k = np.array(range(0, int(l) + 1, 1)) + 0.5 b = np.zeros(k.shape) # # Run Loop : for s in range(0, len(f), 2): m = (o[s + 1] - o[s]) / (f[s + 1] - f[s]) b1 = o[s] - m * f[s] b = b + (m / (4 * np.pi * np.pi) * (np.cos(2 * np.pi * k * f[ s + 1]) - np.cos(2 * np.pi * k * f[s])) / ( k * k)) * abs(np.square(w[round((s + 1) / 2)])) b = b + (f[s + 1] * (m * f[s + 1] + b1) * np.sinc(2 * k * f[ s + 1]) - f[s] * (m * f[s] + b1) * np.sinc(2 * k * f[s])) * abs( np.square(w[round((s + 1) / 2)])) a = (np.square(w[0])) * 4 * b h = 0.5 * np.concatenate((np.flipud(a), a)) return h def firls(n, f, o): # Variables definition : w = np.ones(round(len(f) / 2)) n += 1 f /= 2 lo = (n - 1) / 2 nodd = bool(n % 2) if nodd: # Odd case h = n_odd_fcn(f, o, w, lo) else: # Even case h = n_even_fcn(f, o, w, lo) return h def fir1(n, wn): # Variables definition : nbands = len(wn) + 1 ff = np.array((0, wn[0], wn[0], wn[1], wn[1], 1)) f0 = np.mean(ff[2:4]) lo = n + 1 mags = np.array(range(nbands)).reshape(1, -1) % 2 aa = np.ravel(np.tile(mags, (2, 1)), order='F') # Get filter coefficients : h = firls(lo - 1, ff, aa) # Apply a window to coefficients : wind = np.hamming(lo) b = h * wind c = np.exp(-1j * 2 * np.pi * (f0 / 2) * np.array(range(lo))) b /= abs(c @ b) return b, 1 ############################################################################### ############################################################################### # FILTERING ############################################################################### ############################################################################### def morlet(x, sf, f, width=7.): """Complex decomposition of a signal x using the morlet wavelet. Parameters ---------- x : array_like, shape (N,) The signal to use for the complex decomposition. Must be a vector of length N. sf : float Sampling frequency f : array_like, shape (2,) Frequency vector width : float | 7. Width of the wavelet Returns ------- xout: array_like, shape (N,) The complex decomposition of the signal x. """ dt = 1 / sf sf = f / width st = 1 / (2 * np.pi * sf) # Build morlet's wavelet : t = np.arange(-width * st / 2, width * st / 2, dt) a = 1 / np.sqrt((st * np.sqrt(np.pi))) m = a * np.exp(-np.square(t) / (2 * np.square(st))) * np.exp( 1j * 2 * np.pi * f * t) def ndmorlet(xt): # Compute morlet : y = np.convolve(xt, m) return y[int(np.ceil(len(m) / 2)) - 1:int(len(y) - np.floor( len(m) / 2))] return np.apply_along_axis(ndmorlet, -1, x)
f79f65f0b11e74e90409fdb59e7626a53d9164e7
a0643c775515499dd9492464384b05e82da608a8
/test_interface/CEM/marketingManagement/marketingManagement/nodeDefineRecord_test.py
64d559fe436d1d8ca8fff826bd8e7489a6ea7554
[]
no_license
EmmySmith/autoInterfaceTest
e4935e5fbe85324502f1c8b9ba33ede51cfee81b
56d31476994bfc276cc53ab32c9b27b8d2447e0b
refs/heads/master
2023-05-28T05:27:22.615719
2020-05-09T03:40:04
2020-05-09T03:40:04
262,480,416
0
0
null
2023-05-22T22:44:16
2020-05-09T03:26:26
HTML
UTF-8
Python
false
false
1,120
py
#!/usr/bin/python # coding=utf-8 import requests import unittest import json,time,random from common.public import * from mysqlHandle.common_mysql import * class ICEM_Interface(unittest.TestCase): @classmethod def setUpClass(self): self.headers = headers self.host = host self.path = "/api/icem-activity/workflow/nodeDefineRecord" self.random = random.randint(1000,99999) self.sql = "SELECT id FROM t_activity ORDER BY id DESC LIMIT 1;" self.dbname = "geek_icem_activity" print("----------开始测试----------") #节点列表接口 def test_nodeDefineRecord(self): '''节点列表接口''' self.url = self.host + self.path self.activityId = DB_ICEM_proc(self.dbname).get_vslues(self.sql) data = {"activityId":self.activityId} print(self.url) response = requests.post(url=self.url,data= json.dumps(data), headers=self.headers) print (response.text) assert response.json()['error'] == 0 def tearDown(self): pass if __name__ == "__main__": sms = ICEM_Interface()
d93b2b2d13b8c15e3517aaffa07d6e531fbcc33b
39689ee725bc7183d5d59fb34f7d2ffe5fd6ad36
/ABC_B/ABC152B.py
35c5db735fa5cc883c21d5980d6836368cc1fc04
[]
no_license
yu5shi8/AtCoder
b6eb920a9046bdfa98012dd3fc65f75f16214ffe
f9ca69001ece8379e3a70c993c44b540f8be2217
refs/heads/master
2021-06-15T17:58:07.027699
2021-03-20T14:04:03
2021-03-20T14:04:03
177,757,053
0
0
null
null
null
null
UTF-8
Python
false
false
221
py
# -*- coding: utf-8 -*- # B - Comparing Strings # https://atcoder.jp/contests/abc152/tasks/abc152_b a, b = map(int, input().split()) if a <= b: print(str(a) * b) else: print(str(b) * a) # 23:32 - 23:36(AC)
b654a1eafce5e94c9b993cdbd1877fa3a05eafcb
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03805/s743667282.py
877dfca86e7d05d94725d8483f03ad1b21f93854
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
614
py
from collections import deque def dfs(G, visited, s, n, ans): # すべての頂点を訪れた場合の処理 if all(visited) : ans += 1 return ans # 次の頂点の探索 for i in G[s] : if visited[i] == False : visited[i] = True ans = dfs(G, visited, i, n, ans) visited[i] = False return ans # グラフGの入力 n,m = map(int,input().split()) G = [[] for j in range(n)] for i in range(m) : a,b = map(int,input().split()) G[a-1].append(b-1) G[b-1].append(a-1) visited = [False for i in range(n)] visited[0] = True ans = 0 print(dfs(G, visited, 0, n, ans))
66c9edb88fbf7c5955f202577b420c7e013304bd
8d3adc6867d80a75ac12984f52c78938221404a4
/Bio/_utils.py
77144e9015a72b4147ce67e6833712d851ccd8c7
[ "LicenseRef-scancode-biopython" ]
permissive
chapmanb/biopython
407b17f44f599d71818c5e16bd86a44cf323e062
cade0aec7ecff7d052c42040f5cae8036e297941
refs/heads/master
2020-12-29T03:07:42.778627
2013-07-09T09:36:26
2013-07-09T09:36:26
412,030
1
0
null
null
null
null
UTF-8
Python
false
false
3,568
py
# Copyright 2010 by Eric Talevich. All rights reserved. # Copyright 2012 by Wibowo Arindrarto. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Common utility functions for various Bio submodules.""" import os def iterlen(items): """Count the number of items in an iterable. If the argument supports len(items), and some iterators do, then this returns len(items). Otherwise it will scan over the entries in order to count them. Exhausts a generator, but doesn't require creating a full list. >>> iterlen("abcde") 5 >>> iterlen(iter("abcde")) 5 >>> iterlen(xrange(5)) 5 """ try: #e.g. Under Python 2, the xrange iterator defines __len__ return len(items) except TypeError: for i, x in enumerate(items): count = i return count + 1 def read_forward(handle): """Reads through whitespaces, returns the first non-whitespace line.""" while True: line = handle.readline() # if line has characters and stripping does not remove them, # return the line if line and line.strip(): return line # if line ends, return None elif not line: return line def trim_str(string, max_len, concat_char): """Truncates the given string for display.""" if len(string) > max_len: return string[:max_len - len(concat_char)] + concat_char return string def getattr_str(obj, attr, fmt=None, fallback='?'): """Returns a string of the given object's attribute, defaulting to the fallback value if attribute is not present.""" if hasattr(obj, attr): if fmt is not None: return fmt % getattr(obj, attr) return str(getattr(obj, attr)) return fallback def find_test_dir(start_dir=None): """Finds the absolute path of Biopython's Tests directory. Arguments: start_dir -- Initial directory to begin lookup (default to current dir) If the directory is not found up the filesystem's root directory, an exception will be raised. """ if not start_dir: # no callbacks in function signatures! # defaults to the current directory # (using __file__ would give the installed Biopython) start_dir = "." target = os.path.abspath(start_dir) while True: if os.path.isdir(os.path.join(target, "Bio")) \ and os.path.isdir(os.path.join(target, "Tests")): #Good, we're in the Biopython root now return os.path.abspath(os.path.join(target, "Tests")) #Recurse up the tree #TODO - Test this on Windows new, tmp = os.path.split(target) if target == new: #Reached root break target = new raise ValueError("Not within Biopython source tree: %r" % os.path.abspath(start_dir)) def run_doctest(target_dir=None, *args, **kwargs): """Runs doctest for the importing module.""" import doctest # default doctest options default_kwargs = { 'optionflags': doctest.ELLIPSIS, } kwargs.update(default_kwargs) cur_dir = os.path.abspath(os.curdir) print "Runing doctests..." try: os.chdir(find_test_dir(target_dir)) doctest.testmod(*args, **kwargs) finally: # and revert back to initial directory os.chdir(cur_dir) print "Done" if __name__ == "__main__": run_doctest()
ccd23976c670e92724953d4e4f62a84424828fb2
0bce7412d58675d6cc410fa7a81c294ede72154e
/Python3/0287. Find the Duplicate Number.py
6fdd5f3ec43b8bdf3b456532302c0ad8a9ed6823
[]
no_license
yang4978/LeetCode
9ddf010b0f1dda32cddc7e94c3f987509dea3214
6387d05b619d403414bad273fc3a7a2c58668db7
refs/heads/master
2022-01-15T04:21:54.739812
2021-12-28T12:28:28
2021-12-28T12:28:28
182,653,666
0
0
null
null
null
null
UTF-8
Python
false
false
386
py
class Solution: def findDuplicate(self, nums: List[int]) -> int: left = 1 right = len(nums)-1 while left<right: mid = left + (right-left)//2 temp = 0 for i in nums: temp += (i<=mid) if temp<=mid: left = mid + 1 else: right = mid return left
b3621c42eac9b9c4eb104fc6c10c7e9dd8bc2186
bf99b1b14e9ca1ad40645a7423f23ef32f4a62e6
/AtCoder/abc/142d_2.py
aaf992c2ab19b95ac0e17785ef21ba969269e9b6
[]
no_license
y-oksaku/Competitive-Programming
3f9c1953956d1d1dfbf46d5a87b56550ff3ab3db
a3ff52f538329bed034d3008e051f30442aaadae
refs/heads/master
2021-06-11T16:14:12.635947
2021-05-04T08:18:35
2021-05-04T08:18:35
188,639,647
0
0
null
null
null
null
UTF-8
Python
false
false
564
py
A, B = map(int, input().split()) def primeCount(N): R = int(N**(0.5)) + 1 # 素数の範囲 primes = {} # 素数のリスト n = N for num in range(2, R): primes[num] = 0 while n % num == 0: n //= num primes[num] += 1 if n > 1 : primes[n] = 1 return { key : val for key, val in primes.items() if val > 0} # フィルターをかける primeA = primeCount(A) ans = 1 prd = 1 for p in sorted(primeA.keys()): if B % p == 0 and prd % p != 0: prd *= p ans += 1 print(ans)
d1702a2e70f5ca443f6715b7cd628f3999e8f553
db4cbb94ac337e670bc6d66c93244d37a6ca3aae
/configuration/mm45_rc28_wpz_M_mm41_cityscapes_aug_cluster_yang.py
5c5f57d4fc672882c565ac33875d4f1757c4fe21
[]
no_license
gy20073/CIL_modular
1d14dbde21690c42162a6686926cb23a0148a929
da35bfec7d40708e4f76d08f54e04587bef1dd8b
refs/heads/master
2021-06-12T05:26:35.212861
2019-10-12T05:34:50
2019-10-12T05:34:50
137,950,075
2
4
null
null
null
null
UTF-8
Python
false
false
9,149
py
import glob import os from imgaug import augmenters as iaa # # This is a config file, with three parts: Input, Training, Output, which are then joined in Main # class configMain: def __init__(self): # this is used for data balancing. Labels are balanced first, and then for each label group # the [-1,1] interval is split into so many equal intervals # when we need to sample a mini-batch, we sample bins and then sample inside the bins self.steering_bins_perc = [0.05, 0.05, 0.1, 0.3, 0.3, 0.1, 0.05, 0.05] self.number_steering_bins = len(self.steering_bins_perc) self.batch_size = self.number_steering_bins * 15 self.batch_size_val = self.number_steering_bins * 15 self.number_images_val = self.batch_size_val # Number of images used in a validation Section - Default: 20* # self.input_size = (227,227,3) # self.manager_name = 'control_speed' # y , x self.image_size = (88, 200, 3) self.network_input_size = (88, 200, 3) self.variable_names = ['Steer', 'Gas', 'Brake', 'Hand_B', 'Reverse', 'Steer_N', 'Gas_N', 'Brake_N', 'Pos_X', 'Pos_Y', 'Speed', \ 'C_Gen', 'C_Ped', 'C_Car', 'Road_I', 'Side_I', 'Acc_x', 'Acc_y', 'Acc_z', 'Plat_Ts', 'Game_Ts', 'Ori_X', 'Ori_Y', \ 'Ori_Z', 'Control', 'Camera', 'Angle', 'wp1_x', 'wp1_y', 'wp2_x', 'wp2_y', 'wp1_angle', 'wp1_mag', 'wp2_angle', 'wp2_mag'] # _N is noise, Yaw_S is angular speed self.sensor_names = ['rgb'] self.sensors_size = [(88, 200, 3)] self.sensors_normalize = [True] # CHANGE THIS FOR A DICTIONARY FOR GOD SAKE self.targets_names = ['wp1_angle', 'wp2_angle', 'Steer', 'Gas', 'Brake', 'Speed'] self.targets_sizes = [1, 1, 1, 1, 1, 1] self.inputs_names = ['Control', 'Speed'] self.inputs_sizes = [4, 1] # if there is branching, this is used to build the network. Names should be same as targets # currently the ["Steer"]x4 should not be changed self.branch_config = [['wp1_angle', 'wp2_angle', "Steer", "Gas", "Brake"], ['wp1_angle', 'wp2_angle', "Steer", "Gas", "Brake"], \ ['wp1_angle', 'wp2_angle', "Steer", "Gas", "Brake"], ['wp1_angle', 'wp2_angle', "Steer", "Gas", "Brake"], ["Speed"]] # a list of keep_prob corresponding to the list of layers: # 8 conv layers, 2 img FC layer, 2 speed FC layers, 1 joint FC layer, 5 branches X 2 FC layers each # This is error prone..... GOES TO THE NETWORK FILE DIRECTLY self.dropout = [0.8] * 8 + [0.5] * 2 + [0.5] * 2 + [0.5] * 1 + [0.5, 1.] * len(self.branch_config) self.restore = True # This is if you want to restore a saved model self.models_path = os.path.join('models', os.path.basename(__file__).split('.')[0]) self.train_path_write = os.path.join(self.models_path, 'train') self.val_path_write = os.path.join(self.models_path, 'val') self.test_path_write = os.path.join(self.models_path, 'test') self.number_iterations = 501000 # 500k # Not used anywhere self.pre_train_experiment = None # Control the execution of simulation testing during training self.perform_simulation_test = False self.output_is_on = True # self.extra_augment_factor = 6.0 # Yang: reproduce the segmentation model self.segmentation_model = '/data/yang/code/aws/scratch/CIL_modular_data/matthias_data/erfnet_small_cityscapes_aug' self.segmentation_model_name = "ErfNet_Small" class configInput(configMain): def __init__(self, path='/'): configMain.__init__(self) st = lambda aug: iaa.Sometimes(0.2, aug) oc = lambda aug: iaa.Sometimes(0.1, aug) rl = lambda aug: iaa.Sometimes(0.05, aug) # Yang: actually there is only one sensor modalities, thus, the second augmenter is not used. self.augment = [iaa.Sequential([ rl(iaa.GaussianBlur((0, 1.3))), # blur images with a sigma between 0 and 1.5 rl(iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05), per_channel=0.5)), # add gaussian noise to images rl(iaa.Dropout((0.0, 0.10), per_channel=0.5)), # randomly remove up to X% of the pixels oc(iaa.Add((-20, 20), per_channel=0.5)), # change brightness of images (by -X to Y of original value) st(iaa.Multiply((0.25, 2.5), per_channel=0.2)), # change brightness of images (X-Y% of original value) rl(iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5)), # improve or worsen the contrast rl(iaa.Grayscale((0.0, 1))), # put grayscale ], random_order=True # do all of the above in random order ), iaa.Sequential([ # AUGMENTATION Labels rl(iaa.Dropout((0.0, 0.03))), # randomly remove up to X% of the pixels rl(iaa.CoarseDropout((0.0, 0.03), size_percent=(0.2, 0.3))), # randomly remove up to X% of the pixels ], random_order=True # do all of the above in random order ) ] # self.augment = [None] # there are files with data, 200 images each, and here we select which ones to use self.dataset_name = 'Carla' train_path = "/data/yang/code/aws/scratch/CIL_modular_data/matthias_data/RC025Val/fake_train" val_path = "/data/yang/code/aws/scratch/CIL_modular_data/matthias_data/RC025Val/fake_val" print(train_path) self.train_db_path = [os.path.join(train_path, f) for f in glob.glob1(train_path, "data_*.h5")] self.val_db_path = [os.path.join(val_path, f) for f in glob.glob1(val_path, "data_*.h5")] # Speed Divide Factor # TODO: FOr now is hardcooded, but eventually we should be able to calculate this from data at the loading time. self.speed_factor = 40.0 # In KM/H FOR GTA it should be maximun 30.0 # The division is made by three diferent data kinds # in every mini-batch there will be equal number of samples with labels from each group # e.g. for [[0,1],[2]] there will be 50% samples with labels 0 and 1, and 50% samples with label 2 self.labels_per_division = [[0, 2, 5], [3], [4]] self.dataset_names = ['targets'] self.queue_capacity = 20 * self.batch_size # TODO NOT IMPLEMENTED Felipe: True/False switches to turn data balancing on or off class configTrain(configMain): def __init__(self): configMain.__init__(self) self.loss_function = 'mse_branched' # Chose between: mse_branched, mse_branched_ladd self.control_mode = 'single_branch_wp' # TODO: study the loss_function and control_mode self.learning_rate = 0.0002 # First # use the default segmentation network self.seg_network_erfnet_one_hot = True self.train_segmentation = True # TODO: why train segmentation == True? will it be not transferrable? # self.finetune_segmentation = True self.number_of_labels = 2 self.restore_seg_test = False self.training_schedule = [[50000, 0.5], [100000, 0.5 * 0.5], [150000, 0.5 * 0.5 * 0.5], [200000, 0.5 * 0.5 * 0.5 * 0.5], [250000, 0.5 * 0.5 * 0.5 * 0.5 * 0.5]] # Number of iterations, multiplying factor self.lambda_l2 = 1e-3 # Not used self.branch_loss_weight = [0.95, 0.95, 0.95, 0.95, 0.05] self.variable_weight = {'wp1_angle': 0.3, 'wp2_angle': 0.3, 'Steer': 0.1, 'Gas': 0.2, 'Brake': 0.1, 'Speed': 1.0} self.network_name = 'chauffeurNet_deeper' self.lambda_tolerance = 5 self.is_training = True self.selected_gpu = "0" self.state_output_size = (0) class configOutput(configMain): def __init__(self): configMain.__init__(self) self.print_interval = 100 self.summary_writing_period = 100 self.validation_period = 1000 # I consider validation as an output thing since it does not directly affects the training in general self.feature_save_interval = 100 self.use_curses = False # If we want to use curses library for a cutter print self.targets_to_print = ['wp1_angle', 'wp2_angle', 'Steer', 'Gas', 'Brake'] # Also prints the error. Maybe Energy self.selected_branch = 0 # for the branches that have steering we also select the branch self.inputs_to_print = ['Speed'] """ Feature Visualization Part """ # TODO : self.histograms_list=[] self.features_to_draw= self.weights_to_draw= class configTest(configMain): def __init__(self): configMain.__init__(self) self.interface_name = 'Carla' self.driver_config = "9cam_agent_carla_test_rc" # "3cam_carla_drive_config" # This is the carla configuration related stuff
731ff8381159eac4f3c4c5622d279515b577b095
74565d83bccccfae0d57d0e947f12db2bcae2999
/phi/tests/test_nodsl.py
a9258eb9895c9db82cb8352393e4fd3274fe940a
[ "MIT" ]
permissive
iCodeIN/phi
2fe9eaaf21615381e1b1815853adeb76a79fb696
87fd7100a76f823232f4fd8360498b4b80675265
refs/heads/master
2023-03-21T07:50:28.218564
2018-08-13T14:14:07
2018-08-13T14:14:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
480
py
from phi.dsl import Expression P = Expression() class TestNoDSL(object): def test_seq(self): f = P.Seq( P + 2, P * 2 ) assert 10 == f(3) def test_branch(self): f = P.List( P + 2, P * 2 ) assert [5, 6] == f(3) f = P.List( P + 2, P.Seq( P + 1, P * 2 ) ) assert [5, 8] == f(3)
df097ee6147b01ee82e411a12f00ca1fdff8c780
773e6eefd35d3fe8f86faed6f8de0470e9da722f
/tests/wire/test_msg_mempool.py
d8d4a0ef565bc4c7b0fc63cfe915eb85e3ed4c35
[]
no_license
imnisen/pybtcd
5a9e13b0461e41958e3d1c948100e20c92459d43
b89ec2063348805755d9f2c474a1494f0fb6ef46
refs/heads/master
2020-03-28T03:11:01.877408
2019-11-05T07:07:26
2019-11-05T07:07:26
147,625,874
2
2
null
2019-11-05T07:07:27
2018-09-06T06:09:40
Python
UTF-8
Python
false
false
2,180
py
import unittest import io from wire.msg_mempool import * class TestMsgMemPool(unittest.TestCase): def setUp(self): pver = ProtocolVersion oldPver = BIP0035Version - 1 msgMemPool = MsgMemPool() msgMemPoolEncoded = bytes([]) self.tests = [ # Latest protocol version. { "in": msgMemPool, "out": msgMemPool, "buf": msgMemPoolEncoded, "pver": pver, "enc": BaseEncoding, "err": None }, # Protocol version BIP0035Version -1 . { "in": msgMemPool, "out": msgMemPool, "buf": msgMemPoolEncoded, "pver": oldPver, "enc": BaseEncoding, "err": MemPoolVerionBelowBIP35MsgErr }, ] def test_command(self): msg = MsgMemPool() self.assertEqual(str(msg.command()), "mempool") def test_max_payload_length(self): msg = MsgMemPool() want_payload = 0 self.assertEqual(msg.max_payload_length(ProtocolVersion), want_payload) def test_btc_encode(self): for c in self.tests: if c["err"]: try: s = io.BytesIO() c['in'].btc_encode(s, c['pver'], c['enc']) except Exception as e: self.assertEqual(type(e), c['err']) else: s = io.BytesIO() c['in'].btc_encode(s, c['pver'], c['enc']) self.assertEqual(s.getvalue(), c['buf']) def test_btc_decode(self): for c in self.tests: if c['err']: try: s = io.BytesIO(c['buf']) msg = MsgMemPool() msg.btc_decode(s, c['pver'], c['enc']) except Exception as e: self.assertEqual(type(e), c['err']) else: s = io.BytesIO(c['buf']) msg = MsgMemPool() msg.btc_decode(s, c['pver'], c['enc']) self.assertEqual(msg, c['out'])
71ce5358015438612bd7c9b6178dddfd3a3af130
5dfb9ca5e0c8cb4cb7a7a92d6f6a34b34a841869
/LeetCodeSolutions/python/211_Add_and_Search_Word_Data_structure_design.py
6fdd8ce15c0c90bf5632e2ebbd8b40ec1c9fee03
[ "MIT" ]
permissive
ChuanleiGuo/AlgorithmsPlayground
2f71d29e697a656562e3d2a2de783d964dc6a325
90b6287b742c8bfd3797540c408d679be2821a40
refs/heads/master
2021-01-11T18:30:43.218959
2018-11-19T02:20:31
2018-11-19T02:20:31
79,550,052
1
0
null
null
null
null
UTF-8
Python
false
false
1,004
py
class WordDictionary(object): def __init__(self): """ initialize your data structure here. """ self.root = {} def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ node = self.root for c in word: if c not in node: node[c] = {} node = node[c] node['#'] = '#' def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ def find(word, node): if not word: return '#' in node c, word = word[0], word[1:] if c != '.': return c in node and find(word, node[c]) return any(find(word, d) for d in node.values() if d != '#') return find(word, self.root)
0de233d96169369c052b67111582e5676b2b3aed
8adec48dfaee1cdfd6c7f4d2fb3038aa1c17bda6
/WProf/src/tools/valgrind/.svn/text-base/chrome_tests.py.svn-base
21a6793f8cee1ff440b310d5a38a4c56461367de
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kusoof/wprof
ef507cfa92b3fd0f664d0eefef7fc7d6cd69481e
8511e9d4339d3d6fad5e14ad7fff73dfbd96beb8
refs/heads/master
2021-01-11T00:52:51.152225
2016-12-10T23:51:14
2016-12-10T23:51:14
70,486,057
0
1
null
null
null
null
UTF-8
Python
false
false
23,261
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. ''' Runs various chrome tests through valgrind_test.py.''' import glob import logging import optparse import os import stat import sys import logging_utils import path_utils import common import valgrind_test class TestNotFound(Exception): pass class MultipleGTestFiltersSpecified(Exception): pass class BuildDirNotFound(Exception): pass class BuildDirAmbiguous(Exception): pass class ChromeTests: SLOW_TOOLS = ["memcheck", "tsan", "tsan_rv", "drmemory"] LAYOUT_TESTS_DEFAULT_CHUNK_SIZE = 1500 def __init__(self, options, args, test): if ':' in test: (self._test, self._gtest_filter) = test.split(':', 1) else: self._test = test self._gtest_filter = options.gtest_filter if self._test not in self._test_list: raise TestNotFound("Unknown test: %s" % test) if options.gtest_filter and options.gtest_filter != self._gtest_filter: raise MultipleGTestFiltersSpecified("Can not specify both --gtest_filter " "and --test %s" % test) self._options = options self._args = args script_dir = path_utils.ScriptDir() # Compute the top of the tree (the "source dir") from the script dir (where # this script lives). We assume that the script dir is in tools/valgrind/ # relative to the top of the tree. self._source_dir = os.path.dirname(os.path.dirname(script_dir)) # since this path is used for string matching, make sure it's always # an absolute Unix-style path self._source_dir = os.path.abspath(self._source_dir).replace('\\', '/') valgrind_test_script = os.path.join(script_dir, "valgrind_test.py") self._command_preamble = ["--source_dir=%s" % (self._source_dir)] if not self._options.build_dir: dirs = [ os.path.join(self._source_dir, "xcodebuild", "Debug"), os.path.join(self._source_dir, "out", "Debug"), os.path.join(self._source_dir, "build", "Debug"), ] build_dir = [d for d in dirs if os.path.isdir(d)] if len(build_dir) > 1: raise BuildDirAmbiguous("Found more than one suitable build dir:\n" "%s\nPlease specify just one " "using --build_dir" % ", ".join(build_dir)) elif build_dir: self._options.build_dir = build_dir[0] else: self._options.build_dir = None if self._options.build_dir: build_dir = os.path.abspath(self._options.build_dir) self._command_preamble += ["--build_dir=%s" % (self._options.build_dir)] def _EnsureBuildDirFound(self): if not self._options.build_dir: raise BuildDirNotFound("Oops, couldn't find a build dir, please " "specify it manually using --build_dir") def _DefaultCommand(self, tool, exe=None, valgrind_test_args=None): '''Generates the default command array that most tests will use.''' if exe and common.IsWindows(): exe += '.exe' cmd = list(self._command_preamble) # Find all suppressions matching the following pattern: # tools/valgrind/TOOL/suppressions[_PLATFORM].txt # and list them with --suppressions= prefix. script_dir = path_utils.ScriptDir() tool_name = tool.ToolName(); suppression_file = os.path.join(script_dir, tool_name, "suppressions.txt") if os.path.exists(suppression_file): cmd.append("--suppressions=%s" % suppression_file) # Platform-specific suppression for platform in common.PlatformNames(): platform_suppression_file = \ os.path.join(script_dir, tool_name, 'suppressions_%s.txt' % platform) if os.path.exists(platform_suppression_file): cmd.append("--suppressions=%s" % platform_suppression_file) if self._options.valgrind_tool_flags: cmd += self._options.valgrind_tool_flags.split(" ") if self._options.keep_logs: cmd += ["--keep_logs"] if valgrind_test_args != None: for arg in valgrind_test_args: cmd.append(arg) if exe: self._EnsureBuildDirFound() cmd.append(os.path.join(self._options.build_dir, exe)) # Valgrind runs tests slowly, so slow tests hurt more; show elapased time # so we can find the slowpokes. cmd.append("--gtest_print_time") if self._options.gtest_repeat: cmd.append("--gtest_repeat=%s" % self._options.gtest_repeat) return cmd def Run(self): ''' Runs the test specified by command-line argument --test ''' logging.info("running test %s" % (self._test)) return self._test_list[self._test](self) def _AppendGtestFilter(self, tool, name, cmd): '''Append an appropriate --gtest_filter flag to the googletest binary invocation. If the user passed his own filter mentioning only one test, just use it. Othewise, filter out tests listed in the appropriate gtest_exclude files. ''' if (self._gtest_filter and ":" not in self._gtest_filter and "?" not in self._gtest_filter and "*" not in self._gtest_filter): cmd.append("--gtest_filter=%s" % self._gtest_filter) return filters = [] gtest_files_dir = os.path.join(path_utils.ScriptDir(), "gtest_exclude") gtest_filter_files = [ os.path.join(gtest_files_dir, name + ".gtest-%s.txt" % tool.ToolName())] # Use ".gtest.txt" files only for slow tools, as they now contain # Valgrind- and Dr.Memory-specific filters. # TODO(glider): rename the files to ".gtest_slow.txt" if tool.ToolName() in ChromeTests.SLOW_TOOLS: gtest_filter_files += [os.path.join(gtest_files_dir, name + ".gtest.txt")] for platform_suffix in common.PlatformNames(): gtest_filter_files += [ os.path.join(gtest_files_dir, name + ".gtest_%s.txt" % platform_suffix), os.path.join(gtest_files_dir, name + ".gtest-%s_%s.txt" % \ (tool.ToolName(), platform_suffix))] logging.info("Reading gtest exclude filter files:") for filename in gtest_filter_files: # strip the leading absolute path (may be very long on the bot) # and the following / or \. readable_filename = filename.replace("\\", "/") # '\' on Windows readable_filename = readable_filename.replace(self._source_dir, "")[1:] if not os.path.exists(filename): logging.info(" \"%s\" - not found" % readable_filename) continue logging.info(" \"%s\" - OK" % readable_filename) f = open(filename, 'r') for line in f.readlines(): if line.startswith("#") or line.startswith("//") or line.isspace(): continue line = line.rstrip() test_prefixes = ["FLAKY", "FAILS"] for p in test_prefixes: # Strip prefixes from the test names. line = line.replace(".%s_" % p, ".") # Exclude the original test name. filters.append(line) if line[-2:] != ".*": # List all possible prefixes if line doesn't end with ".*". for p in test_prefixes: filters.append(line.replace(".", ".%s_" % p)) # Get rid of duplicates. filters = set(filters) gtest_filter = self._gtest_filter if len(filters): if gtest_filter: gtest_filter += ":" if gtest_filter.find("-") < 0: gtest_filter += "-" else: gtest_filter = "-" gtest_filter += ":".join(filters) if gtest_filter: cmd.append("--gtest_filter=%s" % gtest_filter) def SetupLdPath(self, requires_build_dir): if requires_build_dir: self._EnsureBuildDirFound() elif not self._options.build_dir: return # Append build_dir to LD_LIBRARY_PATH so external libraries can be loaded. if (os.getenv("LD_LIBRARY_PATH")): os.putenv("LD_LIBRARY_PATH", "%s:%s" % (os.getenv("LD_LIBRARY_PATH"), self._options.build_dir)) else: os.putenv("LD_LIBRARY_PATH", self._options.build_dir) def SimpleTest(self, module, name, valgrind_test_args=None, cmd_args=None): tool = valgrind_test.CreateTool(self._options.valgrind_tool) cmd = self._DefaultCommand(tool, name, valgrind_test_args) self._AppendGtestFilter(tool, name, cmd) cmd.extend(['--test-tiny-timeout=1000']) if cmd_args: cmd.extend(cmd_args) self.SetupLdPath(True) return tool.Run(cmd, module) def RunCmdLine(self): tool = valgrind_test.CreateTool(self._options.valgrind_tool) cmd = self._DefaultCommand(tool, None, self._args) self.SetupLdPath(False) return tool.Run(cmd, None) def TestAsh(self): return self.SimpleTest("ash", "aura_shell_unittests") def TestAura(self): return self.SimpleTest("aura", "aura_unittests") def TestBase(self): return self.SimpleTest("base", "base_unittests") def TestContent(self): return self.SimpleTest("content", "content_unittests") def TestCourgette(self): return self.SimpleTest("courgette", "courgette_unittests") def TestCrypto(self): return self.SimpleTest("crypto", "crypto_unittests") def TestFFmpeg(self): return self.SimpleTest("chrome", "ffmpeg_unittests") def TestFFmpegRegressions(self): return self.SimpleTest("chrome", "ffmpeg_regression_tests") def TestGfx(self): return self.SimpleTest("chrome", "gfx_unittests") def TestGPU(self): return self.SimpleTest("gpu", "gpu_unittests") def TestGURL(self): return self.SimpleTest("chrome", "googleurl_unittests") def TestIpc(self): return self.SimpleTest("ipc", "ipc_tests", valgrind_test_args=["--trace_children"]) def TestJingle(self): return self.SimpleTest("chrome", "jingle_unittests") def TestMedia(self): return self.SimpleTest("chrome", "media_unittests") def TestNet(self): return self.SimpleTest("net", "net_unittests") def TestPPAPI(self): return self.SimpleTest("chrome", "ppapi_unittests") def TestPrinting(self): return self.SimpleTest("chrome", "printing_unittests") def TestRemoting(self): return self.SimpleTest("chrome", "remoting_unittests", cmd_args=[ "--ui-test-action-timeout=60000", "--ui-test-action-max-timeout=150000"]) def TestSql(self): return self.SimpleTest("chrome", "sql_unittests") def TestSync(self): return self.SimpleTest("chrome", "sync_unit_tests") def TestTestShell(self): return self.SimpleTest("webkit", "test_shell_tests") def TestUnit(self): # http://crbug.com/51716 # Disabling all unit tests # Problems reappeared after r119922 if common.IsMac() and (self._options.valgrind_tool == "memcheck"): logging.warning("unit_tests are disabled for memcheck on MacOS.") return 0; return self.SimpleTest("chrome", "unit_tests") def TestUIUnit(self): return self.SimpleTest("chrome", "ui_unittests") def TestViews(self): return self.SimpleTest("views", "views_unittests") # Valgrind timeouts are in seconds. UI_VALGRIND_ARGS = ["--timeout=14400", "--trace_children", "--indirect"] # UI test timeouts are in milliseconds. UI_TEST_ARGS = ["--ui-test-action-timeout=60000", "--ui-test-action-max-timeout=150000"] # TODO(thestig) fine-tune these values. # Valgrind timeouts are in seconds. BROWSER_VALGRIND_ARGS = ["--timeout=50000", "--trace_children", "--indirect"] # Browser test timeouts are in milliseconds. BROWSER_TEST_ARGS = ["--ui-test-action-timeout=200000", "--ui-test-action-max-timeout=400000"] def TestAutomatedUI(self): return self.SimpleTest("chrome", "automated_ui_tests", valgrind_test_args=self.UI_VALGRIND_ARGS, cmd_args=self.UI_TEST_ARGS) def TestBrowser(self): return self.SimpleTest("chrome", "browser_tests", valgrind_test_args=self.BROWSER_VALGRIND_ARGS, cmd_args=self.BROWSER_TEST_ARGS) def TestInteractiveUI(self): return self.SimpleTest("chrome", "interactive_ui_tests", valgrind_test_args=self.UI_VALGRIND_ARGS, cmd_args=self.UI_TEST_ARGS) def TestReliability(self): script_dir = path_utils.ScriptDir() url_list_file = os.path.join(script_dir, "reliability", "url_list.txt") return self.SimpleTest("chrome", "reliability_tests", valgrind_test_args=self.UI_VALGRIND_ARGS, cmd_args=(self.UI_TEST_ARGS + ["--list=%s" % url_list_file])) def TestSafeBrowsing(self): return self.SimpleTest("chrome", "safe_browsing_tests", valgrind_test_args=self.UI_VALGRIND_ARGS, cmd_args=(["--ui-test-action-max-timeout=450000"])) def TestSyncIntegration(self): return self.SimpleTest("chrome", "sync_integration_tests", valgrind_test_args=self.UI_VALGRIND_ARGS, cmd_args=(["--ui-test-action-max-timeout=450000"])) def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run_webkit_tests.py ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. tool = valgrind_test.CreateTool(self._options.valgrind_tool) cmd = self._DefaultCommand(tool) cmd.append("--trace_children") cmd.append("--indirect_webkit_layout") cmd.append("--ignore_exit_code") # Now build script_cmd, the run_webkits_tests.py commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "webkit", "tools", "layout_tests", "run_webkit_tests.py") script_cmd = ["python", script, "-v", "--run-singly", # run a separate DumpRenderTree for each test "--fully-parallel", "--time-out-ms=200000", "--noshow-results", "--no-retry-failures", # retrying takes too much time "--nocheck-sys-deps"] # Pass build mode to run_webkit_tests.py. We aren't passed it directly, # so parse it out of build_dir. run_webkit_tests.py can only handle # the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._AppendGtestFilter(tool, "layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) # Layout tests often times fail quickly, but the buildbot remains green. # Detect this situation when running with the default chunk size. if chunk_size == self.LAYOUT_TESTS_DEFAULT_CHUNK_SIZE: min_runtime_in_seconds=120 else: min_runtime_in_seconds=0 ret = tool.Run(cmd, "layout", min_runtime_in_seconds=min_runtime_in_seconds) return ret def TestLayout(self): # A "chunk file" is maintained in the local directory so that each test # runs a slice of the layout tests of size chunk_size that increments with # each run. Since tests can be added and removed from the layout tests at # any time, this is not going to give exact coverage, but it will allow us # to continuously run small slices of the layout tests under valgrind rather # than having to run all of them in one shot. chunk_size = self._options.num_tests if (chunk_size == 0): return self.TestLayoutChunk(0, 0) chunk_num = 0 chunk_file = os.path.join("valgrind_layout_chunk.txt") logging.info("Reading state from " + chunk_file) try: f = open(chunk_file) if f: str = f.read() if len(str): chunk_num = int(str) # This should be enough so that we have a couple of complete runs # of test data stored in the archive (although note that when we loop # that we almost guaranteed won't be at the end of the test list) if chunk_num > 10000: chunk_num = 0 f.close() except IOError, (errno, strerror): logging.error("error reading from file %s (%d, %s)" % (chunk_file, errno, strerror)) ret = self.TestLayoutChunk(chunk_num, chunk_size) # Wait until after the test runs to completion to write out the new chunk # number. This way, if the bot is killed, we'll start running again from # the current chunk rather than skipping it. logging.info("Saving state to " + chunk_file) try: f = open(chunk_file, "w") chunk_num += 1 f.write("%d" % chunk_num) f.close() except IOError, (errno, strerror): logging.error("error writing to file %s (%d, %s)" % (chunk_file, errno, strerror)) # Since we're running small chunks of the layout tests, it's important to # mark the ones that have errors in them. These won't be visible in the # summary list for long, but will be useful for someone reviewing this bot. return ret # The known list of tests. # Recognise the original abbreviations as well as full executable names. _test_list = { "cmdline" : RunCmdLine, "ash": TestAsh, "aura_shell_unittests": TestAsh, "aura": TestAura, "aura_unittests": TestAura, "automated_ui" : TestAutomatedUI, "base": TestBase, "base_unittests": TestBase, "browser": TestBrowser, "browser_tests": TestBrowser, "crypto": TestCrypto, "crypto_unittests": TestCrypto, "ffmpeg": TestFFmpeg, "ffmpeg_unittests": TestFFmpeg, "ffmpeg_regression_tests": TestFFmpegRegressions, "googleurl": TestGURL, "googleurl_unittests": TestGURL, "content": TestContent, "content_unittests": TestContent, "courgette": TestCourgette, "courgette_unittests": TestCourgette, "ipc": TestIpc, "ipc_tests": TestIpc, "interactive_ui": TestInteractiveUI, "layout": TestLayout, "layout_tests": TestLayout, "webkit": TestLayout, "media": TestMedia, "media_unittests": TestMedia, "net": TestNet, "net_unittests": TestNet, "jingle": TestJingle, "jingle_unittests": TestJingle, "ppapi": TestPPAPI, "ppapi_unittests": TestPPAPI, "printing": TestPrinting, "printing_unittests": TestPrinting, "reliability": TestReliability, "reliability_tests": TestReliability, "remoting": TestRemoting, "remoting_unittests": TestRemoting, "safe_browsing": TestSafeBrowsing, "safe_browsing_tests": TestSafeBrowsing, "sync": TestSync, "sync_unit_tests": TestSync, "sync_integration_tests": TestSyncIntegration, "sync_integration": TestSyncIntegration, "test_shell": TestTestShell, "test_shell_tests": TestTestShell, "unit": TestUnit, "unit_tests": TestUnit, "sql": TestSql, "sql_unittests": TestSql, "ui_unit": TestUIUnit, "ui_unittests": TestUIUnit, "gfx": TestGfx, "gfx_unittests": TestGfx, "gpu": TestGPU, "gpu_unittests": TestGPU, "views": TestViews, "views_unittests": TestViews, } def _main(): parser = optparse.OptionParser("usage: %prog -b <dir> -t <test> " "[-t <test> ...]") parser.disable_interspersed_args() parser.add_option("-b", "--build_dir", help="the location of the compiler output") parser.add_option("-t", "--test", action="append", default=[], help="which test to run, supports test:gtest_filter format " "as well.") parser.add_option("", "--baseline", action="store_true", default=False, help="generate baseline data instead of validating") parser.add_option("", "--gtest_filter", help="additional arguments to --gtest_filter") parser.add_option("", "--gtest_repeat", help="argument for --gtest_repeat") parser.add_option("-v", "--verbose", action="store_true", default=False, help="verbose output - enable debug log messages") parser.add_option("", "--tool", dest="valgrind_tool", default="memcheck", help="specify a valgrind tool to run the tests under") parser.add_option("", "--tool_flags", dest="valgrind_tool_flags", default="", help="specify custom flags for the selected valgrind tool") parser.add_option("", "--keep_logs", action="store_true", default=False, help="store memory tool logs in the <tool>.logs directory " "instead of /tmp.\nThis can be useful for tool " "developers/maintainers.\nPlease note that the <tool>" ".logs directory will be clobbered on tool startup.") parser.add_option("-n", "--num_tests", type="int", default=ChromeTests.LAYOUT_TESTS_DEFAULT_CHUNK_SIZE, help="for layout tests: # of subtests per run. 0 for all.") # TODO(thestig) Remove this if we can. parser.add_option("", "--gtest_color", dest="gtest_color", default="no", help="dummy compatibility flag for sharding_supervisor.") options, args = parser.parse_args() if options.verbose: logging_utils.config_root(logging.DEBUG) else: logging_utils.config_root() if not options.test: parser.error("--test not specified") if len(options.test) != 1 and options.gtest_filter: parser.error("--gtest_filter and multiple tests don't make sense together") for t in options.test: tests = ChromeTests(options, args, t) ret = tests.Run() if ret: return ret return 0 if __name__ == "__main__": sys.exit(_main())
[ "kusoof@kookaburra.(none)" ]
kusoof@kookaburra.(none)
a714dbeb5f32820c71f3d0aa1e6daf2db3de0648
8ceade7e485606cd2d2ea09a996f1e71c1b76f76
/ejerciciosMejorados/p5.py
92e2b94263a31a9ef3c24c00365f32c3cff6ed6a
[]
no_license
jesustr20/test
bdc9a0ffd313e5aad9e63b5df5e87abc2a7d9419
7439f1466995356a709066208fa1a9de21b2266b
refs/heads/master
2023-01-05T17:58:48.601151
2020-11-01T19:24:35
2020-11-01T19:24:35
306,782,231
0
0
null
null
null
null
UTF-8
Python
false
false
1,548
py
#Pregunta 5: # Escribir una funcion sum() y una función multip() que sumen y multipliquen respectivamente # todos los números de una lista. # Por ejemplo: sum([1,2,3,4]) debería devolver 10 y multip([1,2,3,4]) debería devolver 24. #Funcion que genera una lista de un rango def listas(rango): #Genera la lista a partir del parametro "rango" ls = [i for i in range(1,rango+1)] #retorna el rango generado en una lista "ls" return ls #Funcion suma, suma la lista generada y las suma def suma(rango): #Lista generada a partir de la funcion "listas" donde lleva por paramerto rango para realizar la suma ran = listas(rango) #suma toda la lista sumas = sum(ran) #muestra la suma return sumas #Funcion de multiplicacion def multiplicacion(rango): #acumula y multiplica los numeros de la lista n=1 #Lista generada a partir de la funcion "listas" donde lleva por paramerto rango para realizar la suma ran = listas(rango) #Bucle recorre la variable ran que contiene la lista generada a partir del parametro "rango" for i in list(ran): #Acumulador multiplicara el bucle para obtener el resultado final n=n*i t=n #retorna la lista t return t #ingresar un numero que es el rango la cual sera la lista presentada numero = int(input('Calcular la suma de numeros consecutivos de 1 hasta: ')) #Mostrara la lista print(f'lista: {listas(numero)}') #suma la lista print(f'Suma: {suma(numero)}') #multiplica la lista print(f'Producto: {multiplicacion(numero)}')
82ac29168e8c9346fdf4b324d9848eba099f32d1
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_306/ch1_2020_03_04_11_09_36_448958.py
f4249a12eb77b3373a476a9acfe0e6261e82074b
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
72
py
def calcula_valor_devido(vI, nT, j): vF = vI*(1+j)**nT return vF
9b29f05b1777653afa4489a9428e2fa3ad119fb4
8447b5f83be675c5de085d8824783ec0739690b0
/mmdet/ops/roi_align/roi_align.py
875e63d5b6432b257a7ea81289220762413d2c1b
[]
no_license
jie311/mmdetection_lite
bca7070ad88a04e4f6650292642f98f24f7ebeba
1c151a7c44759d022fea1d85fb036a5b39409449
refs/heads/master
2022-04-19T06:18:42.282754
2020-04-13T07:41:10
2020-04-13T07:41:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,068
py
from torch import nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn.modules.utils import _pair from . import roi_align_cuda class RoIAlignFunction(Function): @staticmethod def forward(ctx, features, rois, out_size, spatial_scale, sample_num=0, aligned=True): out_h, out_w = _pair(out_size) assert isinstance(out_h, int) and isinstance(out_w, int) ctx.spatial_scale = spatial_scale ctx.sample_num = sample_num ctx.save_for_backward(rois) ctx.feature_size = features.size() ctx.aligned = aligned if features.is_cuda: if not aligned: (batch_size, num_channels, data_height, data_width) = features.size() num_rois = rois.size(0) output = features.new_zeros(num_rois, num_channels, out_h, out_w) roi_align_cuda.forward_v1(features, rois, out_h, out_w, spatial_scale, sample_num, output) else: output = roi_align_cuda.forward_v2(features, rois, spatial_scale, out_h, out_w, sample_num, aligned) else: raise NotImplementedError return output @staticmethod @once_differentiable def backward(ctx, grad_output): feature_size = ctx.feature_size spatial_scale = ctx.spatial_scale sample_num = ctx.sample_num rois = ctx.saved_tensors[0] aligned = ctx.aligned assert (feature_size is not None and grad_output.is_cuda) batch_size, num_channels, data_height, data_width = feature_size out_w = grad_output.size(3) out_h = grad_output.size(2) grad_input = grad_rois = None if not aligned: if ctx.needs_input_grad[0]: grad_input = rois.new_zeros(batch_size, num_channels, data_height, data_width) roi_align_cuda.backward_v1(grad_output.contiguous(), rois, out_h, out_w, spatial_scale, sample_num, grad_input) else: grad_input = roi_align_cuda.backward_v2( grad_output, rois, spatial_scale, out_h, out_w, batch_size, num_channels, data_height, data_width, sample_num, aligned) return grad_input, grad_rois, None, None, None, None roi_align = RoIAlignFunction.apply class RoIAlign(nn.Module): def __init__(self, out_size, spatial_scale, sample_num=0, use_torchvision=False, aligned=False): """ Args: out_size (tuple): h, w spatial_scale (float): scale the input boxes by this number sample_num (int): number of inputs samples to take for each output sample. 2 to take samples densely for current models. use_torchvision (bool): whether to use roi_align from torchvision aligned (bool): if False, use the legacy implementation in MMDetection. If True, align the results more perfectly. Note: The implementation of RoIAlign when aligned=True is modified from https://github.com/facebookresearch/detectron2/ The meaning of aligned=True: Given a continuous coordinate c, its two neighboring pixel indices (in our pixel model) are computed by floor(c - 0.5) and ceil(c - 0.5). For example, c=1.3 has pixel neighbors with discrete indices [0] and [1] (which are sampled from the underlying signal at continuous coordinates 0.5 and 1.5). But the original roi_align (aligned=False) does not subtract the 0.5 when computing neighboring pixel indices and therefore it uses pixels with a slightly incorrect alignment (relative to our pixel model) when performing bilinear interpolation. With `aligned=True`, we first appropriately scale the ROI and then shift it by -0.5 prior to calling roi_align. This produces the correct neighbors; The difference does not make a difference to the model's performance if ROIAlign is used together with conv layers. """ super(RoIAlign, self).__init__() self.out_size = _pair(out_size) self.spatial_scale = float(spatial_scale) self.aligned = aligned self.sample_num = int(sample_num) self.use_torchvision = use_torchvision assert not (use_torchvision and aligned), 'Torchvision does not support aligned RoIAlgin' def forward(self, features, rois): """ Args: features: NCHW images rois: Bx5 boxes. First column is the index into N. The other 4 columns are xyxy. """ assert rois.dim() == 2 and rois.size(1) == 5 # print(features.shape) if self.use_torchvision: from torchvision.ops import roi_align as tv_roi_align return tv_roi_align(features, rois, self.out_size, self.spatial_scale, self.sample_num) else: return roi_align(features, rois, self.out_size, self.spatial_scale, self.sample_num, self.aligned) def __repr__(self): format_str = self.__class__.__name__ format_str += '(out_size={}, spatial_scale={}, sample_num={}'.format( self.out_size, self.spatial_scale, self.sample_num) format_str += ', use_torchvision={}, aligned={})'.format( self.use_torchvision, self.aligned) return format_str
e6d28bb201f92f5cbd6c7cc8c1a7695415e2e239
8c162bcf0576316d1ce070e4a70f257a01c7ce4c
/piwheels/logger/__init__.py
4f9f281a79e3aaa815449c41cebba5d020ffb514
[ "BSD-3-Clause" ]
permissive
Lauszus/piwheels
8e4a73b0a76715b45ab3586998c78fa3beb26b9f
e51b979f11c1d7a199c9f461312f959f23b5b979
refs/heads/master
2020-03-23T16:14:27.888940
2018-05-13T17:08:45
2018-05-13T17:08:45
141,799,946
0
0
null
2018-07-21T09:44:31
2018-07-21T09:44:31
null
UTF-8
Python
false
false
7,857
py
#!/usr/bin/env python # The piwheels project # Copyright (c) 2017 Ben Nuttall <https://github.com/bennuttall> # Copyright (c) 2017 Dave Jones <[email protected]> # # 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. """ Contains the functions that implement the :program:`piw-log` script. .. autofunction:: main """ import io import sys import gzip import json import logging import datetime as dt import ipaddress from pathlib import PosixPath import zmq from lars.apache import ApacheSource, COMMON, COMMON_VHOST, COMBINED from .. import __version__, terminal, const # Workaround: lars bug; User-Agent instead of User-agent COMBINED = '%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"' def main(args=None): """ This is the main function for the :program:`piw-logger` script. It is designed to be run as a `piped log script`_ under Apache, piping access logs to the :class:`~.lumberjack.Lumberjack` task which stores them in the database. However it can also be used to load pre-existing logs in to. .. _piped log script: https://httpd.apache.org/docs/2.4/logs.html#piped """ logging.getLogger().name = 'logger' parser = terminal.configure_parser("""\ The piw-logger script is intended for use as an Apache "piped log script" but can also be used to feed pre-existing Apache logs to the master by feeding logs to the script's stdin. This script must be run on the same node as the piw-master script. """) parser.add_argument( '--format', default='combined', help="The Apache log format that log lines will be expected to be in " "(default: %(default)s); the short-cuts common, combined and " "common_vhost can be used in addition to Apache LogFormat strings") parser.add_argument( 'files', nargs='*', default=['-'], help="The log file(s) to load into the master; if omitted or - then " "stdin will be read which is the default for piped log usage") parser.add_argument( '--logger-queue', metavar='ADDR', default=const.LOGGER_QUEUE, help="The address of the queue used by piw-logger (default: " "(%(default)s); this should always be an ipc address") parser.add_argument( '--drop', action='store_true', help="Drop log records if unable to send them to the master after a " "short timeout; this should generally be specified when piw-logger " "is used as a piped log script") try: config = parser.parse_args(args) terminal.configure_logging(config.log_level, config.log_file) logging.info("PiWheels Logger version %s", __version__) config.format = { 'common': COMMON, 'common_vhost': COMMON_VHOST, 'combined': COMBINED, }.get(config.format, config.format) ctx = zmq.Context.instance() queue = ctx.socket(zmq.PUSH) queue.connect(config.logger_queue) try: for filename in config.files: log_file = log_open(filename) try: with ApacheSource(log_file, config.format) as src: for row in src: if log_filter(row): if not config.drop or queue.poll(1000, zmq.POLLOUT): queue.send_pyobj(['LOG'] + log_transform(row)) else: logging.warning('dropping log entry') finally: log_file.close() finally: queue.close() ctx.destroy(linger=1000) ctx.term() except RuntimeError as err: logging.error(err) return 1 except: # pylint: disable=bare-except return terminal.error_handler(*sys.exc_info()) else: return 0 def log_open(filename): """ Open the log-file specified by *filename*. If this is ``"-"`` then stdin will be returned. If the filename ends with ``".gz"`` the file will be extracted automatically. Otherwise, the file is opened regularly. :param str filename: The filename to open as a read-only file. :returns: The file-like object to read. """ if filename == '-': logging.info('Processing log entries from stdin') return sys.stdin elif filename.endswith('.gz'): logging.info('Processing gzipped log %s', filename) return io.TextIOWrapper(gzip.open(filename, 'rb'), encoding='ascii') else: logging.info('Processing log %s', filename) return io.open(filename, 'r', encoding='ascii') def log_filter(row): """ Filters which log entries to include. Current criteria are: successful downloads (status 200) only, user-agent must begin with ``"pip/"`` and the accessed path must have an extension of ``".whl"``. :param row: A tuple containing the fields of the log entry, as returned by :class:`lars.apache.ApacheSource`. """ return ( row.status == 200 and row.req_User_Agent is not None and row.req_User_Agent.startswith('pip/') and row.request.url.path_str.endswith('.whl') ) def log_transform(row, decoder=json.JSONDecoder()): """ Extracts the relevant information from the specified *row*. :param row: A tuple containing the fields of the log entry, as returned by :class:`lars.apache.ApacheSource`. """ path = PosixPath(row.request.url.path_str) try: json_start = row.req_User_Agent.index('{') except ValueError: user_data = {} else: try: user_data = decoder.decode(row.req_User_Agent[json_start:]) except ValueError: user_data = {} return [ # Convert lars types into standard types (avoids some issues with # some database backends) path.name, str(row.remote_host), row.time.replace(), user_data.get('cpu'), user_data.get('distro', {}).get('name'), user_data.get('distro', {}).get('version'), user_data.get('system', {}).get('name'), user_data.get('system', {}).get('version'), user_data.get('implementation', {'name': 'CPython'}).get('name'), user_data.get('implementation', {'version': user_data.get('python')}).get('version'), ]
d15144bfccfa3fec3d6c39d294d7d9f9379b012b
3481023b43028c5ee9520a8be0978e914bdcb548
/manga_py/base_classes/params.py
5d90a0761f6bf49a2ebe1be019ec60ff77f0738c
[ "MIT" ]
permissive
manga-py/manga-py
18f6818d8efc96c3e69efee7dff3f3d6c773e32a
0db97123acab1f2fb99e808b0ba54db08977e5c8
refs/heads/stable_1.x
2023-08-20T03:04:06.373108
2023-04-16T08:28:15
2023-04-16T08:28:15
98,638,892
444
56
MIT
2023-07-27T13:21:40
2017-07-28T10:27:43
Python
UTF-8
Python
false
false
1,394
py
from logging import error from urllib.parse import urlparse class ProviderParams: @property def content(self): content = self._storage.get('main_content', None) if content is None: content = self.get_content() return content @property def manga_name(self) -> str: name = self._storage.get('manga_name', None) if name is None: name = self.get_manga_name() return name @property def name(self) -> str: name = self._params.get('name', '') if not len(name): name = self.manga_name return name @property def domain(self) -> str: _url = self._params['url'] try: if not self._storage.get('domain_uri', None): parsed = urlparse(_url, 'https') self._storage['domain_uri'] = '{}://{}'.format( parsed.scheme, parsed.netloc ) return self._storage.get('domain_uri', '') except Exception: error('url "%s" is broken!' % _url) exit() @property def chapter(self): return self.chapters[self.chapter_id] @property def chapters(self): return self._storage['chapters'] @chapters.setter def chapters(self, chapters: list): self._storage['chapters'] = chapters
c0729505d6bf9a498b456982548aa120de9d51a6
4cef47ddd432f2ab814a03fd89112b1dc8b5ab27
/flow/message.py
4c6579ea3c4a1e94e634e4ac2e1ed647ac980500
[ "MIT" ]
permissive
h00shi/flow
279d621cda72a8d2392c2dbe7735ce2ab6b39380
ef45bdd4181d385b1b01042e9ce0b48e4cdc2318
refs/heads/master
2020-09-24T06:50:01.605337
2017-07-05T17:53:50
2017-07-05T17:53:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
433
py
# -*- coding: utf-8 -*- # ''' Allows using DOLFIN's indented block messages with 'with', i.e., with Message('hello world'): # do something ''' from dolfin import begin, end class Message(object): def __init__(self, string): self.string = string return def __enter__(self): begin(self.string) return def __exit__(self, tpe, value, traceback): end() return
d127705f9dd239922fbb76363c5cc3ca519736c3
85c82274a3888fa61795bb0600ab96eaf7665b6a
/meet1/F_max3Angka.py
fa0a3546b66bbd03e24bf5cd643fb372eb6d9263
[]
no_license
refeed/StrukturDataA
8e5a214569f41b19c05842d003ede5941800482a
4d3b77bbd28158f1f1e64a49b8e90da731859407
refs/heads/master
2023-06-03T08:22:12.442536
2021-07-01T03:24:29
2021-07-01T03:24:29
360,478,966
0
0
null
null
null
null
UTF-8
Python
false
false
549
py
''' Max 3 angka Batas Run-time: 1 detik / test-case Batas Memori: 32 MB DESKRIPSI SOAL Buatlah program yang menerima 3 buah input nilai, outputkan nilai paling besar diantara ketiga input tersebut. PETUNJUK MASUKAN Input terdiri atas 3 angka dalam 1 baris PETUNJUK KELUARAN Outputkan angka terbesar dari 3 angka yang dimasukkan CONTOH MASUKAN 10 9 11 CONTOH KELUARAN 11 ''' input_int_list = list(map(int, input().split())) biggest = input_int_list[0] for num in input_int_list: if num > biggest: biggest = num print(biggest)
1611a857f00cc4e23f65789639b9f6eef36aefe9
304f6ea579c2bda6f2a0a0d93c0ffcf332082450
/since_JungleWeek06/정확한 순위.py
0d5fb00f7b7be52e32e728b87a77981421fde412
[]
no_license
Jeongseo21/algorithm
941ae18bb17f6d9a0f3190d40f5f0ae212ffe0f6
0fbda0e320ca6616dfe21680601521549ed019e4
refs/heads/master
2023-04-17T21:37:25.607255
2021-04-25T13:51:02
2021-04-25T13:51:02
276,335,142
1
1
null
null
null
null
UTF-8
Python
false
false
907
py
import sys # import numpy # sys.stdin = open("input.txt", "r") input = sys.stdin.readline INF = int(1e9) N, M = map(int, input().split()) graph = [[INF for _ in range(N+1)] for _ in range(N+1)] #graph = numpy.array(graph) for i in range(1, N+1): for j in range(1, N+1): if i == j: graph[i][j] = 0 for i in range(M): A, B = map(int, input().split()) graph[A][B] = 1 for k in range(1, N+1): for i in range(1, N+1): for j in range(1, N+1): graph[i][j] = min(graph[i][k]+graph[k][j], graph[i][j]) for i in range(N+1): for j in range(N+1): if graph[i][j] == INF: graph[i][j] = 0 result = [0 for _ in range(N+1)] for i in range(1, N+1): for j in range(1, N+1): if graph[i][j] != 0: result[i] += 1 result[j] += 1 answer = 0 for i in result: if i == N-1: answer += 1 print(answer)