content stringlengths 7 1.05M |
|---|
# 24. Swap Nodes in Pairs
'''
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Input: 1->2->3->4,
Output: 2->1->4->3.
'''
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
current = head
while current:
if current.next == None:
return head
if current.next:
current.val, current.next.val = current.next.val, current.val
current = current.next.next
return head |
def encrypt_letter(msg, key):
enc_id = (ord(msg) + ord(key)) % 1114112
return chr(enc_id)
def decrypt_letter(msg, key):
dec_id = (1114112 + ord(msg) - ord(key)) % 1114112
return chr(dec_id)
def process_message(message, key, encrypt):
returned_message = ""
for i, letter in enumerate(message):
if encrypt:
returned_message += encrypt_letter(letter, key[i%len(key)])
else:
returned_message += decrypt_letter(letter, key[i%len(key)])
return returned_message
|
#MaBe
sexo = input("Digite seu sexo: [M/F] ").strip().upper()
while sexo not in "FM":
sexo = input("Dado inválido! Por favor, informe seu sexo: ").strip().upper()
print("Sexo {} registrado com sucesso!".format(sexo))
|
class Ticket():
def __init__(self,weekend=False,child=False):
self.price=100
#假如是周末,加收20%,非周末不加收
if weekend:
self.extra=1.2
else:
self.extra=1
#假如是小孩,打五折,成人不打折
if child:
self.discount=0.5
else:
self.discount=1
def calPrice(self,num):
return self.price*self.extra*self.discount*num
adult=Ticket()
children=Ticket(child=True)
adult.price=adult.calPrice(2)
children.price=children.calPrice(1)
print('在平常的时间里,两张成人票加一张儿童票的价格为:%2.f'%(children.price+adult.price)) |
def pre_save_operation(instance):
# If this is a new record, then someone has started it in the Admin using EITHER a legacy COVE ID
# OR a PBSMM UUID. Depending on which, the retrieval endpoint is slightly different, so this sets
# the appropriate URL to access.
if instance.pk is None:
if instance.object_id and instance.object_id.strip():
url = __get_api_url('pbsmm', instance.object_id)
else:
if instance.legacy_tp_media_id:
url = __get_api_url('cove', str(instance.legacy_tp_media_id))
else:
return # do nothing - can't get an ID to look up!
# Otherwise, it's an existing record and the UUID should be used
else: # Editing an existing record - do nothing if ingest_on_save is NOT checked!
if not instance.ingest_on_save:
return
url = __get_api_url('pbsmm', instance.object_id)
# OK - get the record from the API
(status, json) = get_PBSMM_record(url)
instance.last_api_status = status
# Update this record's time stamp (the API has its own)
instance.date_last_api_update = datetime.datetime.now()
if status != 200:
return
# Process the record (code is in ingest.py)
instance = process_asset_record(json, instance)
# continue saving, but turn off the ingest_on_save flag
instance.ingest_on_save = False # otherwise we could end up in an infinite loop!
# We're done here - continue with the save() operation
return
|
t = int(input().strip())
result = 0
current_time, current_value = 1, 3
def get_next_interval_cycle(time, value):
next_time = time + value
next_value = value * 2
return next_time, next_value
while True:
new_time, new_value = get_next_interval_cycle(
current_time,
current_value
)
if new_time > t:
result = current_value - (t - current_time)
break
elif new_time == t:
result = new_value
current_time, current_value = new_time, new_value
print(result)
|
def acmTeam(topic):
maxtopic, maxteam = 0, 1
for i in range(n):
for j in range(i+1, n):
know = 0
for x in range(m):
if topic[i][x] == '1' or topic[j][x] == '1':
know += 1
if know > maxtopic:
maxtopic = know
maxteam = 1
elif know > 0 and know == maxtopic:
maxteam += 1
return maxtopic, maxteam |
# flake8: noqa
# tor ref src\app\config\auth_dirs.inc
AUTHORITY_DIRS = """
"moria1 orport=9101 "
"v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
"128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
"tor26 orport=443 "
"v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
"ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "
"86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
"dizum orport=443 "
"v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
"45.66.33.45:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
"Serge orport=9001 bridge "
"66.111.2.131:9030 BA44 A889 E64B 93FA A2B1 14E0 2C2A 279A 8555 C533",
"gabelmoo orport=443 "
"v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
"ipv6=[2001:638:a000:4140::ffff:189]:443 "
"131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
"dannenberg orport=443 "
"v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
"ipv6=[2001:678:558:1000::244]:443 "
"193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
"maatuska orport=80 "
"v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
"ipv6=[2001:67c:289c::9]:80 "
"171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
"Faravahar orport=443 "
"v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
"154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
"longclaw orport=443 "
"v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
"199.58.81.140:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
"bastet orport=443 "
"v3ident=27102BC123E7AF1D4741AE047E160C91ADC76B21 "
"ipv6=[2620:13:4000:6000::1000:118]:443 "
"204.13.164.118:80 24E2 F139 121D 4394 C54B 5BCC 368B 3B41 1857 C413",
"""
FALLBACK_DIRS = """
/* type=fallback */
/* version=3.0.0 */
/* timestamp=20200723133610 */
/* source=offer-list */
/* ===== */
/* Offer list excluded 1807 of 1978 candidates. */
/* Checked IPv4 DirPorts served a consensus within 15.0s. */
/*
Final Count: 144 (Eligible 171, Target 447 (2239 * 0.20), Max 200)
Excluded: 27 (Same Operator 15, Failed/Skipped Download 6, Excess 6)
Bandwidth Range: 0.6 - 96.1 MByte/s
*/
/*
Onionoo Source: details Date: 2020-07-23 13:00:00 Version: 8.0
URL: https:onionoo.torproject.orgdetails?fieldsfingerprint%2Cnickname%2Ccontact%2Clast_changed_address_or_port%2Cconsensus_weight%2Cadvertised_bandwidth%2Cor_addresses%2Cdir_address%2Crecommended_version%2Cflags%2Ceffective_family%2Cplatform&typerelay&first_seen_days90-&last_seen_days-0&flagV2Dir&order-consensus_weight%2Cfirst_seen
*/
/*
Onionoo Source: uptime Date: 2020-07-23 13:00:00 Version: 8.0
URL: https:onionoo.torproject.orguptime?typerelay&first_seen_days90-&last_seen_days-0&flagV2Dir&order-consensus_weight%2Cfirst_seen
*/
/* ===== */
"185.225.17.3:80 orport=443 id=0338F9F55111FE8E3570E7DE117EF3AF999CC1D7"
" ipv6=[2a0a:c800:1:5::3]:443"
/* nickname=Nebuchadnezzar */
/* extrainfo=0 */
/* ===== */
,
"81.7.10.193:9002 orport=993 id=03C3069E814E296EB18776EB61B1ECB754ED89FE"
/* nickname=Ichotolot61 */
/* extrainfo=1 */
/* ===== */
,
"163.172.149.155:80 orport=443 id=0B85617241252517E8ECF2CFC7F4C1A32DCD153F"
/* nickname=niij02 */
/* extrainfo=0 */
/* ===== */
,
"5.200.21.144:80 orport=443 id=0C039F35C2E40DCB71CD8A07E97C7FD7787D42D6"
/* nickname=libel */
/* extrainfo=0 */
/* ===== */
,
"81.7.18.7:9030 orport=9001 id=0C475BA4D3AA3C289B716F95954CAD616E50C4E5"
/* nickname=Freebird32 */
/* extrainfo=1 */
/* ===== */
,
"193.234.15.60:80 orport=443 id=0F6E5CA4BF5565D9AA9FDDCA165AFC6A5305763D"
" ipv6=[2a00:1c20:4089:1234:67bc:79f3:61c0:6e49]:443"
/* nickname=jaures3 */
/* extrainfo=0 */
/* ===== */
,
"93.177.67.71:9030 orport=8080 id=113143469021882C3A4B82F084F8125B08EE471E"
" ipv6=[2a03:4000:38:559::2]:8080"
/* nickname=parasol */
/* extrainfo=0 */
/* ===== */
,
"37.120.174.249:80 orport=443 id=11DF0017A43AF1F08825CD5D973297F81AB00FF3"
" ipv6=[2a03:4000:6:724c:df98:15f9:b34d:443]:443"
/* nickname=gGDHjdcC6zAlM8k08lX */
/* extrainfo=0 */
/* ===== */
,
"193.11.114.43:9030 orport=9001 id=12AD30E5D25AA67F519780E2111E611A455FDC89"
" ipv6=[2001:6b0:30:1000::99]:9050"
/* nickname=mdfnet1 */
/* extrainfo=0 */
/* ===== */
,
"37.157.195.87:8030 orport=443 id=12FD624EE73CEF37137C90D38B2406A66F68FAA2"
/* nickname=thanatosCZ */
/* extrainfo=0 */
/* ===== */
,
"193.234.15.61:80 orport=443 id=158581827034DEF1BAB1FC248D180165452E53D3"
" ipv6=[2a00:1c20:4089:1234:2712:a3d0:666b:88a6]:443"
/* nickname=bakunin3 */
/* extrainfo=0 */
/* ===== */
,
"51.15.78.0:9030 orport=9001 id=15BE17C99FACE24470D40AF782D6A9C692AB36D6"
" ipv6=[2001:bc8:1824:c4b::1]:9001"
/* nickname=rofltor07 */
/* extrainfo=0 */
/* ===== */
,
"204.11.50.131:9030 orport=9001 id=185F2A57B0C4620582602761097D17DB81654F70"
/* nickname=BoingBoing */
/* extrainfo=0 */
/* ===== */
,
"50.7.74.171:9030 orport=9001 id=1CD17CB202063C51C7DAD3BACEF87ECE81C2350F"
" ipv6=[2001:49f0:d002:2::51]:443"
/* nickname=theia1 */
/* extrainfo=0 */
/* ===== */
,
"199.184.246.250:80 orport=443 id=1F6ABD086F40B890A33C93CC4606EE68B31C9556"
" ipv6=[2620:124:1009:1::171]:443"
/* nickname=dao */
/* extrainfo=0 */
/* ===== */
,
"212.47.229.2:9030 orport=9001 id=20462CBA5DA4C2D963567D17D0B7249718114A68"
" ipv6=[2001:bc8:47ac:23a::1]:9001"
/* nickname=scaletor */
/* extrainfo=0 */
/* ===== */
,
"77.247.181.164:80 orport=443 id=204DFD2A2C6A0DC1FA0EACB495218E0B661704FD"
/* nickname=HaveHeart */
/* extrainfo=0 */
/* ===== */
,
"163.172.176.167:80 orport=443 id=230A8B2A8BA861210D9B4BA97745AEC217A94207"
/* nickname=niij01 */
/* extrainfo=0 */
/* ===== */
,
"193.234.15.57:80 orport=443 id=24D0491A2ADAAB52C17625FBC926D84477AEA322"
" ipv6=[2a00:1c20:4089:1234:7825:2c5d:1ecd:c66f]:443"
/* nickname=bakunin */
/* extrainfo=0 */
/* ===== */
,
"185.220.101.137:20137 orport=10137 id=28F4F392F8F19E3FBDE09616D9DB8143A1E2DDD3"
" ipv6=[2a0b:f4c2:1::137]:10137"
/* nickname=niftycottonmouse */
/* extrainfo=0 */
/* ===== */
,
"138.201.250.33:9012 orport=9011 id=2BA2C8E96B2590E1072AECE2BDB5C48921BF8510"
/* nickname=storm */
/* extrainfo=0 */
/* ===== */
,
"5.181.50.99:80 orport=443 id=2BB85DC5BD3C6F0D81A4F2B5882176C6BF7ECF5A"
" ipv6=[2a03:4000:3f:16c:3851:6bff:fe07:bd2]:443"
/* nickname=AlanTuring */
/* extrainfo=0 */
/* ===== */
,
"97.74.237.196:9030 orport=9001 id=2F0F32AB1E5B943CA7D062C03F18960C86E70D94"
/* nickname=Minotaur */
/* extrainfo=0 */
/* ===== */
,
"94.230.208.147:8080 orport=8443 id=311A4533F7A2415F42346A6C8FA77E6FD279594C"
" ipv6=[2a02:418:6017::147]:8443"
/* nickname=DigiGesTor3e2 */
/* extrainfo=0 */
/* ===== */
,
"109.105.109.162:52860 orport=60784 id=32EE911D968BE3E016ECA572BB1ED0A9EE43FC2F"
" ipv6=[2001:948:7:2::163]:5001"
/* nickname=ndnr1 */
/* extrainfo=0 */
/* ===== */
,
"185.100.84.212:80 orport=443 id=330CD3DB6AD266DC70CDB512B036957D03D9BC59"
" ipv6=[2a06:1700:0:7::1]:443"
/* nickname=TeamTardis */
/* extrainfo=0 */
/* ===== */
,
"64.79.152.132:80 orport=443 id=375DCBB2DBD94E5263BC0C015F0C9E756669617E"
/* nickname=ebola */
/* extrainfo=0 */
/* ===== */
,
"198.50.191.95:80 orport=443 id=39F096961ED2576975C866D450373A9913AFDC92"
/* nickname=shhovh */
/* extrainfo=0 */
/* ===== */
,
"50.7.74.174:9030 orport=9001 id=3AFDAAD91A15B4C6A7686A53AA8627CA871FF491"
" ipv6=[2001:49f0:d002:2::57]:443"
/* nickname=theia7 */
/* extrainfo=0 */
/* ===== */
,
"212.83.154.33:8888 orport=443 id=3C79699D4FBC37DE1A212D5033B56DAE079AC0EF"
" ipv6=[2001:bc8:31d3:1dd::1]:443"
/* nickname=bauruine203 */
/* extrainfo=0 */
/* ===== */
,
"51.38.65.160:9030 orport=9001 id=3CB4193EF4E239FCEDC4DC43468E0B0D6B67ACC3"
" ipv6=[2001:41d0:801:2000::f6e]:9001"
/* nickname=rofltor10 */
/* extrainfo=0 */
/* ===== */
,
"95.216.211.81:80 orport=443 id=3CCF9573F59137E52787D9C322AC19D2BD090B70"
" ipv6=[2a01:4f9:c010:4dfa::1]:443"
/* nickname=BurningMan */
/* extrainfo=0 */
/* ===== */
,
"217.79.179.177:9030 orport=9001 id=3E53D3979DB07EFD736661C934A1DED14127B684"
" ipv6=[2001:4ba0:fff9:131:6c4f::90d3]:9001"
/* nickname=Unnamed */
/* extrainfo=0 */
/* ===== */
,
"66.111.2.16:9030 orport=9001 id=3F092986E9B87D3FDA09B71FA3A602378285C77A"
" ipv6=[2610:1c0:0:5::16]:9001"
/* nickname=NYCBUG1 */
/* extrainfo=0 */
/* ===== */
,
"185.100.85.101:9030 orport=9001 id=4061C553CA88021B8302F0814365070AAE617270"
/* nickname=TorExitRomania */
/* extrainfo=0 */
/* ===== */
,
"163.172.157.213:8080 orport=443 id=4623A9EC53BFD83155929E56D6F7B55B5E718C24"
/* nickname=Cotopaxi */
/* extrainfo=0 */
/* ===== */
,
"193.70.43.76:9030 orport=9001 id=484A10BA2B8D48A5F0216674C8DD50EF27BC32F3"
/* nickname=Aerodynamik03 */
/* extrainfo=0 */
/* ===== */
,
"109.70.100.4:80 orport=443 id=4BFC9C631A93FF4BA3AA84BC6931B4310C38A263"
" ipv6=[2a03:e600:100::4]:443"
/* nickname=karotte */
/* extrainfo=0 */
/* ===== */
,
"81.7.13.84:80 orport=443 id=4EB55679FA91363B97372554F8DC7C63F4E5B101"
" ipv6=[2a02:180:1:1::5b8f:538c]:443"
/* nickname=torpidsDEisppro */
/* extrainfo=0 */
/* ===== */
,
"108.53.208.157:80 orport=443 id=4F0DB7E687FC7C0AE55C8F243DA8B0EB27FBF1F2"
/* nickname=Binnacle */
/* extrainfo=1 */
/* ===== */
,
"5.9.158.75:9030 orport=9001 id=509EAB4C5D10C9A9A24B4EA0CE402C047A2D64E6"
" ipv6=[2a01:4f8:190:514a::2]:9001"
/* nickname=zwiebeltoralf2 */
/* extrainfo=1 */
/* ===== */
,
"69.30.215.42:80 orport=443 id=510176C07005D47B23E6796F02C93241A29AA0E9"
" ipv6=[2604:4300:a:2e:21b:21ff:fe11:392]:443"
/* nickname=torpidsUSwholesale */
/* extrainfo=0 */
/* ===== */
,
"176.223.141.106:80 orport=443 id=5262556D44A7F2434990FDE1AE7973C67DF49E58"
/* nickname=Theoden */
/* extrainfo=0 */
/* ===== */
,
"85.25.159.65:995 orport=80 id=52BFADA8BEAA01BA46C8F767F83C18E2FE50C1B9"
/* nickname=BeastieJoy63 */
/* extrainfo=0 */
/* ===== */
,
"193.234.15.59:80 orport=443 id=562434D987CF49D45649B76ADCA993BEA8F78471"
" ipv6=[2a00:1c20:4089:1234:bff6:e1bb:1ce3:8dc6]:443"
/* nickname=bakunin2 */
/* extrainfo=0 */
/* ===== */
,
"89.234.157.254:80 orport=443 id=578E007E5E4535FBFEF7758D8587B07B4C8C5D06"
" ipv6=[2001:67c:2608::1]:443"
/* nickname=marylou1 */
/* extrainfo=0 */
/* ===== */
,
"172.98.193.43:80 orport=443 id=5E56738E7F97AA81DEEF59AF28494293DFBFCCDF"
/* nickname=Backplane */
/* extrainfo=0 */
/* ===== */
,
"163.172.139.104:8080 orport=443 id=68F175CCABE727AA2D2309BCD8789499CEE36ED7"
/* nickname=Pichincha */
/* extrainfo=0 */
/* ===== */
,
"95.217.16.212:80 orport=443 id=6A7551EEE18F78A9813096E82BF84F740D32B911"
" ipv6=[2a01:4f9:c010:609a::1]:443"
/* nickname=TorMachine */
/* extrainfo=0 */
/* ===== */
,
"78.156.110.135:9093 orport=9092 id=7262B9D2EDE0B6A266C4B43D6202209BF6BBA888"
/* nickname=SkynetRenegade */
/* extrainfo=0 */
/* ===== */
,
"85.235.250.88:80 orport=443 id=72B2B12A3F60408BDBC98C6DF53988D3A0B3F0EE"
" ipv6=[2a01:3a0:1:1900:85:235:250:88]:443"
/* nickname=TykRelay01 */
/* extrainfo=0 */
/* ===== */
,
"178.17.170.23:9030 orport=9001 id=742C45F2D9004AADE0077E528A4418A6A81BC2BA"
" ipv6=[2a00:1dc0:caff:7d::8254]:9001"
/* nickname=TorExitMoldova2 */
/* extrainfo=0 */
/* ===== */
,
"81.7.14.31:9001 orport=443 id=7600680249A22080ECC6173FBBF64D6FCF330A61"
/* nickname=Ichotolot62 */
/* extrainfo=1 */
/* ===== */
,
"62.171.144.155:80 orport=443 id=7614EF326635DA810638E2F5D449D10AE2BB7158"
" ipv6=[2a02:c207:3004:8874::1]:443"
/* nickname=Nicenstein */
/* extrainfo=0 */
/* ===== */
,
"77.247.181.166:80 orport=443 id=77131D7E2EC1CA9B8D737502256DA9103599CE51"
/* nickname=CriticalMass */
/* extrainfo=0 */
/* ===== */
,
"5.196.23.64:9030 orport=9001 id=775B0FAFDE71AADC23FFC8782B7BEB1D5A92733E"
/* nickname=Aerodynamik01 */
/* extrainfo=0 */
/* ===== */
,
"185.244.193.141:9030 orport=9001 id=79509683AB4C8DDAF90A120C69A4179C6CD5A387"
" ipv6=[2a03:4000:27:192:24:12:1984:4]:9001"
/* nickname=DerDickeReloaded */
/* extrainfo=0 */
/* ===== */
,
"82.223.21.74:9030 orport=9001 id=7A32C9519D80CA458FC8B034A28F5F6815649A98"
" ipv6=[2001:ba0:1800:6c::1]:9001"
/* nickname=silentrocket */
/* extrainfo=0 */
/* ===== */
,
"51.254.136.195:80 orport=443 id=7BB70F8585DFC27E75D692970C0EEB0F22983A63"
/* nickname=torproxy02 */
/* extrainfo=0 */
/* ===== */
,
"77.247.181.162:80 orport=443 id=7BFB908A3AA5B491DA4CA72CCBEE0E1F2A939B55"
/* nickname=sofia */
/* extrainfo=0 */
/* ===== */
,
"193.11.114.45:9031 orport=9002 id=80AAF8D5956A43C197104CEF2550CD42D165C6FB"
/* nickname=mdfnet2 */
/* extrainfo=0 */
/* ===== */
,
"51.254.96.208:9030 orport=9001 id=8101421BEFCCF4C271D5483C5AABCAAD245BBB9D"
" ipv6=[2001:41d0:401:3100::30dc]:9001"
/* nickname=rofltor01 */
/* extrainfo=0 */
/* ===== */
,
"152.89.106.147:9030 orport=9001 id=8111FEB45EF2950EB8F84BFD8FF070AB07AEE9DD"
" ipv6=[2a03:4000:39:605:c4f2:c9ff:fe64:c215]:9001"
/* nickname=TugaOnionMR3 */
/* extrainfo=0 */
/* ===== */
,
"192.42.116.16:80 orport=443 id=81B75D534F91BFB7C57AB67DA10BCEF622582AE8"
/* nickname=hviv104 */
/* extrainfo=0 */
/* ===== */
,
"192.87.28.82:9030 orport=9001 id=844AE9CAD04325E955E2BE1521563B79FE7094B7"
" ipv6=[2001:678:230:3028:192:87:28:82]:9001"
/* nickname=Smeerboel */
/* extrainfo=0 */
/* ===== */
,
"85.228.136.92:9030 orport=443 id=855BC2DABE24C861CD887DB9B2E950424B49FC34"
/* nickname=Logforme */
/* extrainfo=0 */
/* ===== */
,
"178.254.7.88:8080 orport=8443 id=85A885433E50B1874F11CEC9BE98451E24660976"
/* nickname=wr3ck3d0ni0n01 */
/* extrainfo=0 */
/* ===== */
,
"163.172.194.53:9030 orport=9001 id=8C00FA7369A7A308F6A137600F0FA07990D9D451"
" ipv6=[2001:bc8:225f:142:6c69:7461:7669:73]:9001"
/* nickname=GrmmlLitavis */
/* extrainfo=0 */
/* ===== */
,
"188.138.102.98:465 orport=443 id=8CAA470B905758742203E3EB45941719FCA9FEEC"
/* nickname=BeastieJoy64 */
/* extrainfo=0 */
/* ===== */
,
"109.70.100.6:80 orport=443 id=8CF987FF43FB7F3D9AA4C4F3D96FFDF247A9A6C2"
" ipv6=[2a03:e600:100::6]:443"
/* nickname=zucchini */
/* extrainfo=0 */
/* ===== */
,
"5.189.169.190:8030 orport=8080 id=8D79F73DCD91FC4F5017422FAC70074D6DB8DD81"
/* nickname=thanatosDE */
/* extrainfo=0 */
/* ===== */
,
"80.67.172.162:80 orport=443 id=8E6EDA78D8E3ABA88D877C3E37D6D4F0938C7B9F"
" ipv6=[2001:910:1410:600::1]:443"
/* nickname=AlGrothendieck */
/* extrainfo=0 */
/* ===== */
,
"54.37.139.118:9030 orport=9001 id=90A5D1355C4B5840E950EB61E673863A6AE3ACA1"
" ipv6=[2001:41d0:601:1100::1b8]:9001"
/* nickname=rofltor09 */
/* extrainfo=0 */
/* ===== */
,
"96.253.78.108:80 orport=443 id=924B24AFA7F075D059E8EEB284CC400B33D3D036"
/* nickname=NSDFreedom */
/* extrainfo=0 */
/* ===== */
,
"109.70.100.5:80 orport=443 id=9661AC95717798884F3E3727D360DD98D66727CC"
" ipv6=[2a03:e600:100::5]:443"
/* nickname=erdapfel */
/* extrainfo=0 */
/* ===== */
,
"173.212.254.192:31336 orport=31337 id=99E246DB480B313A3012BC3363093CC26CD209C7"
" ipv6=[2a02:c207:3002:3972::1]:31337"
/* nickname=ViDiSrv */
/* extrainfo=0 */
/* ===== */
,
"188.127.69.60:80 orport=443 id=9B2BC7EFD661072AFADC533BE8DCF1C19D8C2DCC"
" ipv6=[2a02:29d0:8008:c0de:bad:beef::]:443"
/* nickname=MIGHTYWANG */
/* extrainfo=0 */
/* ===== */
,
"185.100.86.128:9030 orport=9001 id=9B31F1F1C1554F9FFB3455911F82E818EF7C7883"
" ipv6=[2a06:1700:1::11]:9001"
/* nickname=TorExitFinland */
/* extrainfo=0 */
/* ===== */
,
"95.142.161.63:80 orport=443 id=9BA84E8C90083676F86C7427C8D105925F13716C"
" ipv6=[2001:4b98:dc0:47:216:3eff:fe3d:888c]:443"
/* nickname=ekumen */
/* extrainfo=0 */
/* ===== */
,
"86.105.212.130:9030 orport=443 id=9C900A7F6F5DD034CFFD192DAEC9CCAA813DB022"
/* nickname=firstor2 */
/* extrainfo=0 */
/* ===== */
,
"46.28.110.244:80 orport=443 id=9F7D6E6420183C2B76D3CE99624EBC98A21A967E"
/* nickname=Nivrim */
/* extrainfo=0 */
/* ===== */
,
"46.165.230.5:80 orport=443 id=A0F06C2FADF88D3A39AA3072B406F09D7095AC9E"
/* nickname=Dhalgren */
/* extrainfo=1 */
/* ===== */
,
"193.234.15.55:80 orport=443 id=A1B28D636A56AAFFE92ADCCA937AA4BD5333BB4C"
" ipv6=[2a00:1c20:4089:1234:7b2c:11c5:5221:903e]:443"
/* nickname=bakunin4 */
/* extrainfo=0 */
/* ===== */
,
"128.31.0.13:80 orport=443 id=A53C46F5B157DD83366D45A8E99A244934A14C46"
/* nickname=csailmitexit */
/* extrainfo=0 */
/* ===== */
,
"212.47.233.86:9130 orport=9101 id=A68097FE97D3065B1A6F4CE7187D753F8B8513F5"
/* nickname=olabobamanmu */
/* extrainfo=0 */
/* ===== */
,
"163.172.149.122:80 orport=443 id=A9406A006D6E7B5DA30F2C6D4E42A338B5E340B2"
/* nickname=niij03 */
/* extrainfo=0 */
/* ===== */
,
"176.10.107.180:9030 orport=9001 id=AC2BEDD0BAC72838EA7E6F113F856C4E8018ACDB"
/* nickname=schokomilch */
/* extrainfo=0 */
/* ===== */
,
"195.154.164.243:80 orport=443 id=AC66FFA4AB35A59EBBF5BF4C70008BF24D8A7A5C"
" ipv6=[2001:bc8:399f:f000::1]:993"
/* nickname=torpidsFRonline3 */
/* extrainfo=0 */
/* ===== */
,
"185.129.62.62:9030 orport=9001 id=ACDD9E85A05B127BA010466C13C8C47212E8A38F"
" ipv6=[2a06:d380:0:3700::62]:9001"
/* nickname=kramse */
/* extrainfo=0 */
/* ===== */
,
"188.40.128.246:9030 orport=9001 id=AD19490C7DBB26D3A68EFC824F67E69B0A96E601"
" ipv6=[2a01:4f8:221:1ac1:dead:beef:7005:9001]:9001"
/* nickname=sputnik */
/* extrainfo=0 */
/* ===== */
,
"176.10.104.240:8080 orport=8443 id=AD86CD1A49573D52A7B6F4A35750F161AAD89C88"
/* nickname=DigiGesTor1e2 */
/* extrainfo=0 */
/* ===== */
,
"178.17.174.14:9030 orport=9001 id=B06F093A3D4DFAD3E923F4F28A74901BD4F74EB1"
" ipv6=[2a00:1dc0:caff:8b::5b9a]:9001"
/* nickname=TorExitMoldova */
/* extrainfo=0 */
/* ===== */
,
"212.129.62.232:80 orport=443 id=B143D439B72D239A419F8DCE07B8A8EB1B486FA7"
/* nickname=wardsback */
/* extrainfo=0 */
/* ===== */
,
"109.70.100.2:80 orport=443 id=B27CF1DCEECD50F7992B07D720D7F6BF0EDF9D40"
" ipv6=[2a03:e600:100::2]:443"
/* nickname=radieschen */
/* extrainfo=0 */
/* ===== */
,
"136.243.214.137:80 orport=443 id=B291D30517D23299AD7CEE3E60DFE60D0E3A4664"
/* nickname=TorKIT */
/* extrainfo=0 */
/* ===== */
,
"93.115.97.242:9030 orport=9001 id=B5212DB685A2A0FCFBAE425738E478D12361710D"
/* nickname=firstor */
/* extrainfo=0 */
/* ===== */
,
"193.11.114.46:9032 orport=9003 id=B83DC1558F0D34353BB992EF93AFEAFDB226A73E"
/* nickname=mdfnet3 */
/* extrainfo=0 */
/* ===== */
,
"85.248.227.164:444 orport=9002 id=B84F248233FEA90CAD439F292556A3139F6E1B82"
" ipv6=[2a00:1298:8011:212::164]:9004"
/* nickname=tollana */
/* extrainfo=0 */
/* ===== */
,
"51.15.179.153:110 orport=995 id=BB60F5BA113A0B8B44B7B37DE3567FE561E92F78"
" ipv6=[2001:bc8:3fec:500:7ea::]:995"
/* nickname=Casper04 */
/* extrainfo=0 */
/* ===== */
,
"198.96.155.3:8080 orport=5001 id=BCEDF6C193AA687AE471B8A22EBF6BC57C2D285E"
/* nickname=gurgle */
/* extrainfo=0 */
/* ===== */
,
"128.199.55.207:9030 orport=9001 id=BCEF908195805E03E92CCFE669C48738E556B9C5"
" ipv6=[2a03:b0c0:2:d0::158:3001]:9001"
/* nickname=EldritchReaper */
/* extrainfo=0 */
/* ===== */
,
"213.141.138.174:9030 orport=9001 id=BD552C165E2ED2887D3F1CCE9CFF155DDA2D86E6"
/* nickname=Schakalium */
/* extrainfo=0 */
/* ===== */
,
"148.251.190.229:9030 orport=9010 id=BF0FB582E37F738CD33C3651125F2772705BB8E8"
" ipv6=[2a01:4f8:211:c68::2]:9010"
/* nickname=quadhead */
/* extrainfo=0 */
/* ===== */
,
"212.47.233.250:9030 orport=9001 id=BF735F669481EE1CCC348F0731551C933D1E2278"
" ipv6=[2001:bc8:4400:2b00::1c:629]:9001"
/* nickname=freeway */
/* extrainfo=0 */
/* ===== */
,
"132.248.241.5:9130 orport=9101 id=C0C4F339046EB824999F711D178472FDF53BE7F5"
/* nickname=toritounam2 */
/* extrainfo=0 */
/* ===== */
,
"109.70.100.3:80 orport=443 id=C282248597D1C8522A2A7525E61C8B77BBC37614"
" ipv6=[2a03:e600:100::3]:443"
/* nickname=erbse */
/* extrainfo=0 */
/* ===== */
,
"50.7.74.170:9030 orport=9001 id=C36A434DB54C66E1A97A5653858CE36024352C4D"
" ipv6=[2001:49f0:d002:2::59]:443"
/* nickname=theia9 */
/* extrainfo=0 */
/* ===== */
,
"188.138.112.60:1433 orport=1521 id=C414F28FD2BEC1553024299B31D4E726BEB8E788"
/* nickname=zebra620 */
/* extrainfo=0 */
/* ===== */
,
"178.20.55.18:80 orport=443 id=C656B41AEFB40A141967EBF49D6E69603C9B4A11"
/* nickname=marcuse2 */
/* extrainfo=0 */
/* ===== */
,
"85.248.227.163:443 orport=9001 id=C793AB88565DDD3C9E4C6F15CCB9D8C7EF964CE9"
" ipv6=[2a00:1298:8011:212::163]:9003"
/* nickname=ori */
/* extrainfo=0 */
/* ===== */
,
"50.7.74.173:80 orport=443 id=C87A4D8B534F78FDF0F4639B55F121401FEF259C"
" ipv6=[2001:49f0:d002:2::54]:443"
/* nickname=theia4 */
/* extrainfo=0 */
/* ===== */
,
"176.31.103.150:9030 orport=9001 id=CBD0D1BD110EC52963082D839AC6A89D0AE243E7"
/* nickname=UV74S7mjxRcYVrGsAMw */
/* extrainfo=0 */
/* ===== */
,
"193.234.15.62:80 orport=443 id=CD0F9AA1A5064430B1DE8E645CBA7A502B27ED5F"
" ipv6=[2a00:1c20:4089:1234:a6a4:2926:d0af:dfee]:443"
/* nickname=jaures4 */
/* extrainfo=0 */
/* ===== */
,
"85.25.213.211:465 orport=80 id=CE47F0356D86CF0A1A2008D97623216D560FB0A8"
/* nickname=BeastieJoy61 */
/* extrainfo=0 */
/* ===== */
,
"50.7.74.172:80 orport=443 id=D1AFBF3117B308B6D1A7AA762B1315FD86A6B8AF"
" ipv6=[2001:49f0:d002:2::52]:443"
/* nickname=theia2 */
/* extrainfo=0 */
/* ===== */
,
"66.111.2.20:9030 orport=9001 id=D317C7889162E9EC4A1DA1A1095C2A0F377536D9"
" ipv6=[2610:1c0:0:5::20]:9001"
/* nickname=NYCBUG0 */
/* extrainfo=0 */
/* ===== */
,
"5.45.111.149:80 orport=443 id=D405FCCF06ADEDF898DF2F29C9348DCB623031BA"
" ipv6=[2a03:4000:6:2388:df98:15f9:b34d:443]:443"
/* nickname=gGDHjdcC6zAlM8k08lY */
/* extrainfo=0 */
/* ===== */
,
"12.235.151.200:9030 orport=9029 id=D5C33F3E203728EDF8361EA868B2939CCC43FAFB"
/* nickname=nx1tor */
/* extrainfo=0 */
/* ===== */
,
"212.83.166.62:80 orport=443 id=D7082DB97E7F0481CBF4B88CA5F5683399E196A3"
/* nickname=shhop */
/* extrainfo=0 */
/* ===== */
,
"54.36.237.163:80 orport=443 id=DB2682153AC0CCAECD2BD1E9EBE99C6815807A1E"
/* nickname=GermanCraft2 */
/* extrainfo=0 */
/* ===== */
,
"171.25.193.20:80 orport=443 id=DD8BD7307017407FCC36F8D04A688F74A0774C02"
" ipv6=[2001:67c:289c::20]:443"
/* nickname=DFRI0 */
/* extrainfo=0 */
/* ===== */
,
"83.212.99.68:80 orport=443 id=DDBB2A38252ADDA53E4492DDF982CA6CC6E10EC0"
" ipv6=[2001:648:2ffc:1225:a800:bff:fe3d:67b5]:443"
/* nickname=zouzounella */
/* extrainfo=0 */
/* ===== */
,
"166.70.207.2:9130 orport=9101 id=E41B16F7DDF52EBB1DB4268AB2FE340B37AD8904"
/* nickname=xmission1 */
/* extrainfo=0 */
/* ===== */
,
"185.100.86.182:9030 orport=8080 id=E51620B90DCB310138ED89EDEDD0A5C361AAE24E"
/* nickname=NormalCitizen */
/* extrainfo=0 */
/* ===== */
,
"212.47.244.38:8080 orport=443 id=E81EF60A73B3809F8964F73766B01BAA0A171E20"
/* nickname=Chimborazo */
/* extrainfo=0 */
/* ===== */
,
"185.4.132.148:80 orport=443 id=E8D114B3C78D8E6E7FEB1004650DD632C2143C9E"
" ipv6=[2a02:c500:2:f0::5492]:443"
/* nickname=libreonion1 */
/* extrainfo=0 */
/* ===== */
,
"195.154.105.170:9030 orport=9001 id=E947C029087FA1C3499BEF5D4372947C51223D8F"
/* nickname=dgplug */
/* extrainfo=0 */
/* ===== */
,
"131.188.40.188:1443 orport=11180 id=EBE718E1A49EE229071702964F8DB1F318075FF8"
" ipv6=[2001:638:a000:4140::ffff:188]:11180"
/* nickname=fluxe4 */
/* extrainfo=1 */
/* ===== */
,
"192.87.28.28:9030 orport=9001 id=ED2338CAC2711B3E331392E1ED2831219B794024"
" ipv6=[2001:678:230:3028:192:87:28:28]:9001"
/* nickname=SEC6xFreeBSD64 */
/* extrainfo=0 */
/* ===== */
,
"178.20.55.16:80 orport=443 id=EFAE44728264982224445E96214C15F9075DEE1D"
/* nickname=marcuse1 */
/* extrainfo=0 */
/* ===== */
,
"217.182.75.181:9030 orport=9001 id=EFEACD781604EB80FBC025EDEDEA2D523AEAAA2F"
/* nickname=Aerodynamik02 */
/* extrainfo=0 */
/* ===== */
,
"193.234.15.58:80 orport=443 id=F24F8BEA2779A79111F33F6832B062BED306B9CB"
" ipv6=[2a00:1c20:4089:1234:cdae:1b3e:cc38:3d45]:443"
/* nickname=jaures2 */
/* extrainfo=0 */
/* ===== */
,
"129.13.131.140:80 orport=443 id=F2DFE5FA1E4CF54F8E761A6D304B9B4EC69BDAE8"
" ipv6=[2a00:1398:5:f604:cafe:cafe:cafe:9001]:443"
/* nickname=AlleKochenKaffee */
/* extrainfo=0 */
/* ===== */
,
"37.187.102.108:80 orport=443 id=F4263275CF54A6836EE7BD527B1328836A6F06E1"
" ipv6=[2001:41d0:a:266c::1]:443"
/* nickname=EvilMoe */
/* extrainfo=0 */
/* ===== */
,
"5.199.142.236:9030 orport=9001 id=F4C0EDAA0BF0F7EC138746F8FEF1CE26C7860265"
/* nickname=tornodenumber9004 */
/* extrainfo=0 */
/* ===== */
,
"163.172.154.162:9030 orport=9001 id=F741E5124CB12700DA946B78C9B2DD175D6CD2A1"
" ipv6=[2001:bc8:47a0:162a::1]:9001"
/* nickname=rofltor06 */
/* extrainfo=0 */
/* ===== */
,
"78.47.18.110:443 orport=80 id=F8D27B163B9247B232A2EEE68DD8B698695C28DE"
" ipv6=[2a01:4f8:120:4023::110]:80"
/* nickname=fluxe3 */
/* extrainfo=1 */
/* ===== */
,
"91.143.88.62:80 orport=443 id=F9246DEF2B653807236DA134F2AEAB103D58ABFE"
/* nickname=Freebird31 */
/* extrainfo=1 */
/* ===== */
,
"149.56.45.200:9030 orport=9001 id=FE296180018833AF03A8EACD5894A614623D3F76"
" ipv6=[2607:5300:201:3000::17d3]:9002"
/* nickname=PyotrTorpotkinOne */
/* extrainfo=0 */
/* ===== */
,
"62.141.38.69:80 orport=443 id=FF9FC6D130FA26AE3AE8B23688691DC419F0F22E"
" ipv6=[2001:4ba0:cafe:ac5::]:443"
/* nickname=rinderwahnRelay3L */
/* extrainfo=0 */
/* ===== */
,
"193.11.164.243:9030 orport=9001 id=FFA72BD683BC2FCF988356E6BEC1E490F313FB07"
" ipv6=[2001:6b0:7:125::243]:9001"
/* nickname=Lule */
/* extrainfo=0 */
/* ===== */
,
"""
|
def make_readable(seconds):
if seconds >= 0 and seconds <= 359999:
hrs = seconds // 3600
seconds %= 3600
mins = seconds // 60
seconds %= 60
secs = seconds
hour = str('{:02d}'.format(hrs))
minute = str('{:02d}'.format(mins))
second = str('{:02d}'.format(secs))
time = f"{hour}:{minute}:{second}"
return time |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Giraph(MavenPackage):
"""Apache Giraph is an iterative graph processing system built
for high scalability."""
homepage = "https://giraph.apache.org/"
url = "https://downloads.apache.org/giraph/giraph-1.0.0/giraph-dist-1.0.0-src.tar.gz"
list_url = "https://downloads.apache.org/giraph/"
list_depth = 1
version('1.2.0', sha256='6206f4ad220ea42aa0c4abecce343e36026cf9c6e0a2853f1eb08543da452ad1')
version('1.1.0', sha256='181d94b8198c0f312d4611e24b0056b5181c8358a7ec89b0393661736cd19a4c')
depends_on('java@7:', type=('build', 'run'))
depends_on('maven@3.0.0:', type='build')
def install(self, spec, prefix):
giraph_path = join_path(self.stage.source_path,
'giraph-dist', 'target',
'giraph-{0}-for-hadoop-1.2.1-bin'
.format(spec.version),
'giraph-{0}-for-hadoop-1.2.1'
.format(spec.version))
with working_dir(giraph_path):
install_tree('.', prefix)
|
"""
Contains config variables unique to the user.
Copy this file to config.py and make any necessary changes.
"""
PYTHON_COMMAND = "python"
|
"""# `//ll:ll.bzl`
Rules for building C/C++ with an upstream LLVM/Clang toolchain.
Build files should import these rules via `@rules_ll//ll:defs.bzl`.
"""
load("//ll:providers.bzl", "LlCompilationDatabaseFragmentsInfo", "LlInfo")
load(
"//ll:internal_functions.bzl",
"resolve_binary_deps",
"resolve_library_deps",
)
load(
"//ll:actions.bzl",
"compile_objects",
"create_archive_library",
"expose_headers",
"link_bitcode_library",
"link_executable",
)
load(
"//ll:attributes.bzl",
"LL_BINARY_ATTRS",
"LL_LIBRARY_ATTRS",
)
def select_toolchain_type(ctx):
if ctx.attr.heterogeneous_mode in ["hip_nvidia", "hip_amd"]:
return "//ll:heterogeneous_toolchain_type"
return "//ll:toolchain_type"
def _ll_library_impl(ctx):
(
headers,
defines,
includes,
angled_includes,
transitive_hdrs,
transitive_defines,
transitive_includes,
transitive_angled_includes,
) = resolve_library_deps(ctx)
intermediary_objects, cdfs = compile_objects(
ctx,
headers = headers,
defines = defines,
includes = includes,
angled_includes = angled_includes,
toolchain_type = select_toolchain_type(ctx),
)
out_files = intermediary_objects
if ctx.attr.aggregate == "static":
out_file = create_archive_library(
ctx,
in_files = intermediary_objects,
toolchain_type = select_toolchain_type(ctx),
)
out_files = [out_file]
elif ctx.attr.aggregate == "bitcode":
out_file = link_bitcode_library(
ctx,
in_files = intermediary_objects,
toolchain_type = select_toolchain_type(ctx),
)
out_files = [out_file]
transitive_cdfs = [
dep[LlCompilationDatabaseFragmentsInfo].cdfs
for dep in ctx.attr.deps
]
return [
DefaultInfo(
files = depset(out_files),
),
LlInfo(
transitive_hdrs = transitive_hdrs,
transitive_defines = transitive_defines,
transitive_includes = transitive_includes,
transitive_angled_includes = transitive_angled_includes,
),
LlCompilationDatabaseFragmentsInfo(
cdfs = depset(cdfs, transitive = transitive_cdfs),
),
]
ll_library = rule(
implementation = _ll_library_impl,
executable = False,
attrs = LL_LIBRARY_ATTRS,
output_to_genfiles = True,
toolchains = [
"//ll:toolchain_type",
"//ll:heterogeneous_toolchain_type",
],
doc = """
Creates a static archive.
Example:
```python
ll_library(
srcs = ["my_library.cpp"],
)
```
""",
)
def _ll_binary_impl(ctx):
headers, defines, includes, angled_includes = resolve_binary_deps(ctx)
intermediary_objects, cdfs = compile_objects(
ctx,
headers = headers,
defines = defines,
includes = includes,
angled_includes = angled_includes,
toolchain_type = select_toolchain_type(ctx),
)
out_file = link_executable(
ctx,
in_files = intermediary_objects + ctx.files.deps,
toolchain_type = select_toolchain_type(ctx),
)
transitive_cdfs = [
dep[LlCompilationDatabaseFragmentsInfo].cdfs
for dep in ctx.attr.deps
]
return [
DefaultInfo(
files = depset([out_file]),
executable = out_file,
),
LlCompilationDatabaseFragmentsInfo(
cdfs = depset(cdfs, transitive = transitive_cdfs),
),
]
ll_binary = rule(
implementation = _ll_binary_impl,
executable = True,
attrs = LL_BINARY_ATTRS,
toolchains = [
"//ll:toolchain_type",
"//ll:heterogeneous_toolchain_type",
],
doc = """
Creates an executable.
Example:
```python
ll_binary(
srcs = ["my_executable.cpp"],
)
```
""",
)
|
epsilon_d_ = {
"epsilon": ["float", "0.03", "0.01 ... 0.3"],
}
distribution_d_ = {
"distribution": ["string", "normal", "normal, laplace, logistic, gumbel"],
}
n_neighbours_d_ = {
"n_neighbours": ["int", "3", "1 ... 10"],
}
p_accept_d_ = {
"p_accept": ["float", "0.1", "0.01 ... 0.3"],
}
repulsion_factor_d = {
"repulsion_factor": ["float", "5", "2 ... 10"],
}
annealing_rate_d = {
"annealing_rate": ["float", "0.97", "0.9 ... 0.99"],
}
start_temp_d = {
"start_temp": ["float", "1", "0.5 ... 1.5"],
}
alpha_d = {
"alpha": ["float", "1", "0.5 ... 2"],
}
gamma_d = {
"gamma": ["float", "2", "0.5 ... 5"],
}
beta_d = {
"beta": ["float", "0.5", "0.25 ... 3"],
}
sigma_d = {
"sigma": ["float", "0.5", "0.25 ... 3"],
}
step_size_d = {
"step_size": ["int", "1", "1 ... 1000"],
}
n_iter_restart_d = {
"n_iter_restart": ["int", "10", "5 ... 20"],
}
iters_p_dim_d = {
"iters_p_dim": ["int", "10", "5 ... 15"],
}
n_positions_d = {
"n_positions": ["int", "4", "2 ... 8"],
}
pattern_size_d = {
"pattern_size": ["float", "0.25", "0.1 ... 0.5"],
}
reduction_d = {
"reduction": ["float", "0.9", "0.75 ... 0.99"],
}
population_parallel_temp_d = {
"population": ["int", "5", "3 ... 15"],
}
n_iter_swap_parallel_temp_d = {
"n_iter_swap": ["int", "10", "5 ... 15"],
}
population_pso_d = {
"population": ["int", "10", "4 ... 15"],
}
inertia_d = {
"inertia": ["float", "0.5", "0.25 ... 0.75"],
}
cognitive_weight_d = {
"cognitive_weight": ["float", "0.5", "0.25 ... 0.75"],
}
social_weight_d = {
"social_weight": ["float", "0.5", "0.25 ... 0.75"],
}
temp_weight_d = {
"temp_weight": ["float", "0.2", "0.05 ... 0.3"],
}
population_evo_strat_d = {
"population": ["int", "10", "4 ... 15"],
}
mutation_rate_d = {
"mutation_rate": ["float", "0.7", "0.1 ... 0.9"],
}
crossover_rate_d = {
"crossover_rate": ["float", "0.3", "0.1 ... 0.9"],
}
gpr_bayes_opt_d = {
"gpr": ["class", "0.3", "-"],
}
xi_bayes_opt_d = {
"xi": ["float", "0.3", "0.1 ... 0.9"],
}
warm_start_smbo_d = {
"warm_start_smbo": ["pandas dataframe", "None", "-"],
}
max_sample_size_d = {
"max_sample_size": ["int", "10000000", "-"],
}
sampling_d = {
"sampling": ["dict", "{'random': 1000000}", "-"],
}
gamma_tpe_d = {
"gamma_tpe": ["float", "0.2", "0.05 ... 0.75"],
}
tree_regressor_d = {
"tree_regressor": [
"string",
"extra_tree",
"extra_tree, random_forest, gradient_boost",
],
}
tree_para_d = {
"tree_para": ["dict", "{'n_estimators': 100}", "-"],
}
xi_forest_opt_d = {
"xi": ["float", "0.03", "0.001 ... 0.1"],
}
|
def fatorial(n):
if n == 0:
return 1
else:
return n * fatorial(n - 1)
while True:
try:
entrada = input()
entrada = entrada.split()
fat1 = fatorial(int(entrada[0]))
fat2 = fatorial(int(entrada[1]))
print(fat1 + fat2)
except EOFError:
break |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
元组的使用
笔记:
1、元组在创建时间和占用的空间上面都优于列表。
2、元组中的元素是无法修改的:
如果不需要对元素进行添加、删除、修改的时候,可以考虑使用元组;
如果一个方法要返回多个值,使用元组也是不错的选择。
"""
# 定义元组
t = ('关茂柠', 25, True, '广东深圳')
print(t)
# 获取元组中的元素
print(t[0])
print(t[3])
# 遍历元组中的值
for member in t:
print(member)
# t[0] = '王大锤' # TypeError
print('-'*100)
# 变量t重新引用了新的元组原来的元组将被垃圾回收
t = ('王大锤', 20, True, '云南昆明')
print(t)
# 将元组转换成列表
person = list(t)
print(person)
# 列表是可以修改它的元素的
person[0] = '李小龙'
person[1] = 45
print(person)
print('-'*100)
# 将列表转换成元组
fruits_list = ['apple', 'banana', 'orange']
print(fruits_list)
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)
|
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.end = False
self.size = 0
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def add(self, key):
crawl = self.root
for c in key:
index = self._charToIndex(c)
if not crawl.children[index]:
crawl.children[index] = self.getNode()
crawl = crawl.children[index]
crawl.size += 1
crawl.end = True
def find(self, key):
crawl = self.root
for c in key:
index = self._charToIndex(c)
if not crawl.children[index]:
return 0
crawl = crawl.children[index]
return crawl.size
def contacts(queries):
trie = Trie()
results = []
for q in queries:
c, v = q[0], q[1]
if c == "add":
trie.add(v)
elif c == "find":
results.append(trie.find(v))
return results
trie = Trie()
trie.add("hack")
trie.add("hackerrank")
print(trie.find("hac"))
print(trie.find("hak")) |
# coding=utf-8
"""
This is exceptions used in graph package
"""
class GraphError(Exception):
"""
This is base graph error
"""
pass
class GraphTypeError(GraphError, TypeError):
"""
This error occurs when there is a type mismatch in this package
"""
pass
class GraphExistenceError(GraphError):
"""
This error occurs when there is a index mismatch in this package
"""
pass
|
class Database:
def __init__(self, row_counts):
self.row_counts = row_counts
self.max_row_count = max(row_counts)
n_tables = len(row_counts)
self.parents = list(range(n_tables))
def merge(self, src, dst):
src_parent = self.get_parent(src)
dst_parent = self.get_parent(dst)
if src_parent == dst_parent:
return False
# use union by rank heuristic:
# Rank array isn't necessary: we don't have any choice on how the union should be done
self.parents[src_parent] = dst_parent
self.row_counts[dst_parent] += self.row_counts[src_parent]
self.row_counts[src_parent] = 0
if self.max_row_count < self.row_counts[dst_parent]:
self.max_row_count = self.row_counts[dst_parent]
return True
# Time Complexity: O(log n)
# Space Complexity: O(1)
def get_parent(self, table):
# find parent
rootTable = table
while rootTable != self.parents[rootTable]:
rootTable = self.parents[rootTable]
#Compress Path
while table != rootTable:
parent = self.parents[table]
self.parents[table] = rootTable
table = parent
return rootTable
def main():
n_tables, n_queries = map(int, input().split())
counts = list(map(int, input().split()))
assert len(counts) == n_tables
db = Database(counts)
for i in range(n_queries):
dst, src = map(int, input().split())
db.merge(src - 1, dst - 1)
print(db.max_row_count)
if __name__ == "__main__":
main()
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 clegg <clegg@baratheon>
#
# Distributed under terms of the MIT license.
"""
Gem and Enchant Lookup Tables
"""
"""
To save some API calls we're going to keep this data here. It'll cover most gems.
"""
gem_lookup = {
# Old Gems - Not listed. Quality 1
# 9.0 Uncommon Gems
173121 : { 'quality' : 2, 'name' : 'Deadly Jewel Doublet', 'icon' : 'inv_jewelcrafting_90_cutuncommon_orange', 'stat' : '+12 Critical Strike' },
173122 : { 'quality' : 2, 'name' : 'Quick Jewel Doublet', 'icon' : 'inv_jewelcrafting_90_cutuncommon_yellow', 'stat' : '+12 Haste' },
173123 : { 'quality' : 2, 'name' : 'Versatile Jewel Doublet', 'icon' : 'inv_jewelcrafting_90_cutuncommon_blue', 'stat' : '+12 Versatility' },
173124 : { 'quality' : 2, 'name' : 'Masterful Jewel Doublet', 'icon' : 'inv_jewelcrafting_90_cutuncommon_purple', 'stat' : '+12 Mastery' },
173125 : { 'quality' : 2, 'name' : 'Revitalizing Jewel Doublet', 'icon' : 'inv_jewelcrafting_90_cutuncommon_red', 'stat' : '+133 health every 10 seconds for each gem socketed' },
173126 : { 'quality' : 2, 'name' : 'Straddling Jewel Doublet', 'icon' : 'inv_jewelcrafting_90_cutuncommon_green', 'stat' : '+13 speed for each gem socketed' },
# 9.0 Rare Gems
173127 : { 'quality' : 3, 'name' : 'Deadly Jewel Cluster', 'icon' : 'inv_jewelcrafting_90_rarecut_orange', 'stat' : '+16 Critical Strike' },
173128 : { 'quality' : 3, 'name' : 'Quick Jewel Cluster', 'icon' : 'inv_jewelcrafting_90_rarecut_yellow', 'stat' : '+16 Haste' },
173129 : { 'quality' : 3, 'name' : 'Versatile Jewel Cluster', 'icon' : 'inv_jewelcrafting_90_rarecut_blue', 'stat' : '+16 Versatility' },
173130 : { 'quality' : 3, 'name' : 'Masterful Jewel Cluster', 'icon' : 'inv_jewelcrafting_90_rarecut_purple', 'stat' : '+16 Mastery' }
}
"""
There does not seem to be any actual API for looking up enchants by ID. So this is all we have
The name is now provided by the Equipment Profile API, so it is unused. Leaving b/c it helps when reading.
"""
enchant_lookup = {
# Cloak
6202 : { 'quality' : 3, 'name' : "Fortified Speed", 'description' : "+20 Stamina and +30 Speed" },
6203 : { 'quality' : 3, 'name' : "Fortified Avoidance", 'description' : "+20 Stamina and +30 Avoidance" },
6204 : { 'quality' : 3, 'name' : "Fortified Leech", 'description' : "+20 Stamina and +30 Leech" },
6208 : { 'quality' : 3, 'name' : "Soul Vitality", 'description' : "+30 Stamina" },
# Chest
6216 : { 'quality' : 2, 'name' : "Sacred Stats", 'description' : "+20 Primary Stat" },
6213 : { 'quality' : 3, 'name' : "Eternal Bulwark", 'description' : "+25 Armor and +20 Strength/Agility" },
6214 : { 'quality' : 3, 'name' : "Eternal Skirmish", 'description' : "+20 Strength/Agility and Shadow Damage Auto-Attack" },
6217 : { 'quality' : 3, 'name' : "Eternal Bounds", 'description' : "+20 Intellect and +6% Mana" },
6230 : { 'quality' : 3, 'name' : "Eternal Stats", 'description' : "+30 Primary Stat" },
6265 : { 'quality' : 3, 'name' : "Eternal Insight", 'description' : "+20 Intellect and Shadow Damage Spells" },
# Primary
## Wrist
6219 : { 'quality' : 2, 'name' : "Illuminated Soul", 'description' : "+10 Intellect" },
6220 : { 'quality' : 3, 'name' : "Eternal Intellect", 'description' : "+15 Intellect" },
## Hands
6209 : { 'quality' : 2, 'name' : "Strength of Soul", 'description' : "+10 Strength" },
6210 : { 'quality' : 3, 'name' : "Eternal Strength", 'description' : "+15 Strength" },
## Feet
6212 : { 'quality' : 2, 'name' : "Agile Soul", 'description' : "+10 Agility" },
6211 : { 'quality' : 3, 'name' : "Eternal Agility", 'description' : "+15 Agility" },
# Ring
# Bargain
6163 : { 'quality' : 2, 'name' : "Bargain of Critical Strike", 'description' : "+12 Critical Strike" },
6165 : { 'quality' : 2, 'name' : "Bargain of Haste", 'description' : "+12 Haste" },
6167 : { 'quality' : 2, 'name' : "Bargain of Mastery", 'description' : "+12 Mastery" },
6169 : { 'quality' : 2, 'name' : "Bargain of Versatility", 'description' : "+12 Versatility" },
# Tenet
6164 : { 'quality' : 3, 'name' : "Tenet of Critical Strike", 'description' : "+16 Critical Strike" },
6166 : { 'quality' : 3, 'name' : "Tenet of Haste", 'description' : "+16 Haste" },
6168 : { 'quality' : 3, 'name' : "Tenet of Mastery", 'description' : "+16 Mastery" },
6170 : { 'quality' : 3, 'name' : "Tenet of Versatility", 'description' : "+16 Versatility" },
# Weapons - All Valid
# Engineering
6195 : { 'quality' : 3, 'name' : "Infra-green Reflex Sight", 'description' : "Occasionally increase Haste by 303 for 12 sec" },
6196 : { 'quality' : 3, 'name' : "Optical Target Embiggener", 'description' : "Occasionally increase Critical Strike by 303 for 12 sec" },
# Enchant
6223 : { 'quality' : 3, 'name' : "Lightless Force", 'description' : "Chance to send out a wave of Shadow energy, striking 5 enemies" },
6226 : { 'quality' : 3, 'name' : "Eternal Grace", 'description' : "Sometimes cause a burst of healing on the target of your helpful spells and abilities" },
6227 : { 'quality' : 3, 'name' : "Ascended Vigor", 'description' : "Sometimes increase your healing received by 12% for 10 sec" },
6228 : { 'quality' : 3, 'name' : "Sinful Revelation", 'description' : "Your attacks sometimes cause enemies to suffer an additional 6% damage from you for 10 sec" },
6229 : { 'quality' : 3, 'name' : "Celestial Guidance", 'description' : "Sometimes increase your primary stat by 5%" },
# DK Runeforges
3370 : { 'quality' : 4, 'name' : "Rune of the Razorice", 'description' : "Causes extra weapon damage as Frost damage and increases enemies' vulnerability to your Frost attacks by 3%, stacking up to 5 times" },
3847 : { 'quality' : 4, 'name' : "Rune of the Stoneskin Gargoyle", 'description' : "Increase Armor by 5% and all stats by 5%" },
3368 : { 'quality' : 4, 'name' : "Rune of the Fallen Crusader", 'description' : "Chance to heal for 6% and increases total Strength by 15% for 15 sec." },
6241 : { 'quality' : 4, 'name' : "Rune of Sanguination", 'description' : "Cuases Death Strike to deal increased the target's missing health. When you fall below 35% health, you heal for 48% of your maximum health over 8 sec" },
6242 : { 'quality' : 4, 'name' : "Rune of Spellwarding", 'description' : "Deflect 3% of all spell damage. Taking magic damage has a chance to create a shield that absorbs magic damage equal to 10% of your max health. Damaging the shield causes enemies' cast speed to be reduced by 10% for 6 sec" },
6243 : { 'quality' : 4, 'name' : "Rune of Hysteria", 'description' : "Increases maximum Runic Power by 20 and attacks have a chance to increase Runic Power generation by 20% for 8 sec" },
6244 : { 'quality' : 4, 'name' : "Rune of Unending Thirst", 'description' : "Increase movement speed by 5%. Killing an enemy causes you to heal for 5% of your max health and gain 10% Haste and movement speed" },
6245 : { 'quality' : 4, 'name' : "Rune of the Apocalypse", 'description' : "Your ghoul's attacks have a chance to apply a debuff to the target" }
}
|
# index_power
# Created by JKChang
# 16/04/2018, 14:49
# Tag:
# Description: You are given an array with positive numbers and a number N. You should find the N-th power of the
# element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first
# element has the index 0.
#
# Let's look at a few examples:
# - array = [1, 2, 3, 4] and N = 2, then the result is 32 == 9;
# - array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.
#
# Input: Two arguments. An array as a list of integers and a number as a integer.
#
# Output: The result as an integer.
def index_power(array, n):
"""
Find Nth power of the element with index N.
"""
if n > len(array) - 1:
return -1
return array[n] ** n
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert index_power([1, 2, 3, 4], 2) == 9, "Square"
assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube"
assert index_power([0, 1], 0) == 1, "Zero power"
assert index_power([1, 2], 3) == -1, "IndexError"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
# Find the Most Competitive Subsequence: https://leetcode.com/problems/find-the-most-competitive-subsequence/
# Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.
# An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
# We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.
# If so we simply keep increasing the result so long as we have >= k possible letters to be added
# by using a stack we can check if the number we are checking is smaller and can pop off the bigger so long as the above condition is true
class Solution:
def mostCompetitive(self, nums, k: int):
stack = []
addition = len(nums) - k
for num in nums:
while addition > 0 and len(stack) > 0 and stack[-1] > num:
stack.pop()
addition -= 1
stack.append(num)
while len(stack) != k:
stack.pop()
return stack
# The above works the trick is we need to figure out how many values we are allowed to remove while parsing so that we can always have
# the right amount of values in the subset. Then we can pop off any values if they are larger numbers on our parsing stack than our
# cur num
# This will run in O(N) for time and space and I believe it is optimal.
# Score Card
# Did I need hints? N
# Did you finish within 30 min? 15
# Was the solution optimal? Yea
# Were there any bugs? I forgot that I need to pop off all numbers
# 5 5 5 4 = 4.75
|
# Copyright (c) 2018 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
"""
================================================================================
================================================================================
================================================================================
"""
def grid_configure(frame, rows={}, columns={}):
"""
Put weighting on the given frame. Rows an collumns that ar not in rows and columns will get weight 1.
"""
for r in range(30):
if r in rows:
frame.grid_rowconfigure(r, weight=rows[r])
else:
frame.grid_rowconfigure(r, weight=1)
for c in range(30):
if c in columns:
frame.grid_columnconfigure(c, weight=columns[c])
else:
frame.grid_columnconfigure(c, weight=1)
"""
================================================================================
================================================================================
================================================================================
"""
|
"""
5. Longest Palindromic Substring
"""
class Solution:
def expand(self, s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right]
def longestPalindrome(self, s: str) -> str:
len_s = len(s)
if len_s < 2:
return s
res = ""
for i in range(len_s):
# 홀수인 경우
res1 = self.expand(s, i, i)
if len(res1) > len(res):
res = res1
# 짝수인 경우
res2 = self.expand(s, i, i+1)
if len(res2) > len(res):
res = res2
return res
if __name__ == '__main__':
print(Solution().longestPalindrome("babad"))
|
# Template 1. preorder DFS
# O(N) / O(H)
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
arr = []
def preorder(node):
if not node:
return
arr.append(node.val)
preorder(node.left)
preorder(node.right)
preorder(root)
return arr
# Template 2. inorder DFS
# O(N) / O(H)
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
arr = []
def inorder(node):
if not node:
return
inorder(node.left)
arr.append(node.val)
inorder(node.right)
inorder(root)
return arr
# Template 3. postorder DFS
# O(N) / O(H)
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
arr = []
def postorder(node):
if not node:
return
postorder(node.left)
postorder(node.right)
arr.append(node.val)
postorder(root)
return arr |
"""
Macro for supporting custom resource set typically defined in Gradle via source sets.
Bazel expects all resources to be in same root `res` directory but Gradle does not have this
limitation. This macro receives directory on file system and copies the required resources to
Bazel compatible `res` folder during build.
"""
def custom_res(target, dir_name, resource_files = []):
"""
This macro make sures the given `resource_files` are present in a bazel compatible folder by
copying them to correct directory.
Args:
target: The label of the target for which resources should be made compatible.
dir_name: The root name of the folder which needs to be fixed i.e the one that is not `res`
resource_files: The list of files that should be copied to. Usually a result of `glob` function.
Returns:
A list of generated resource_files in the correct `res` directory that can be specified as
input to android_library or android_binary rules
"""
new_root_dir = target + "_" + dir_name
fixed_resource_path = []
for old_resource_path in resource_files:
fixed_path = new_root_dir + "/" + old_resource_path.replace("/" + dir_name, "/res")
fixed_resource_path.append(fixed_path)
genrule_suffix = old_resource_path.replace("/", "_").replace(".", "_").replace("-", "_")
native.genrule(
name = "_" + target + "_" + genrule_suffix,
srcs = [old_resource_path],
outs = [fixed_path],
cmd = "cp $< $@",
)
return fixed_resource_path
|
"""Test Forex API"""
def test_forex_api_doc(client):
response = client.get("/api/forex/doc")
assert response.status_code == 200
def test_get_usd_rates(client):
response = client.get("/api/forex/rates/usd", follow_redirects=True)
assert response.status_code == 200
|
with open('artistsfollowed.txt') as af:
with open('/app/tosearch.txt', 'w') as ts:
for line in af:
if 'name' in line:
line = line.strip()
line = line.replace('name: ', '')
line = line.replace('\'', '')
line = line.replace(',', '')
ts.write(line + '\n')
|
#coding:utf-8
'''
filename:palindrome.py
chap:4
subject:17
conditions:输入一个5位数
solution:判断是否为回文数
'''
number = input('Enter a 5 digits number : ')
if number.isdigit() and len(number) == 5:
if number == number[::-1]:
print(f'{number} is palindrome.')
else:
print(f'{number} is not palindrome.')
else:
print('Your input is not pure digits or not 5 digits.')
|
SUSI_AGAT = "Agát"
SUSI_BLYSKAVICA = "Blýskavica"
SUSI_CIFERSKY_CECH = "Cíferský-cech"
SUSI_COMPETITION_ID = 9
SUSI_OUTDOOR_ROUND_NUMBER = 100
SUSI_AGAT_MAX_COEFFICIENT = 8
# If big hint is public, points won't be deducted for small hint regardless of
# whether it is public or not.
SUSI_POINTS_ALLOCATION = (
6, # How many points will be assigned for correct submit
2, # How many points will be deducted if small hint is public
4, # How many points will be deducted if big hint is public
0, # How many points will be assigned for wrong submit and after deadline submit
)
# How many days after the end of the round will the big hint be revealed
SUSI_BIG_HINT_DAYS = 4
SUSI_WRONG_SUBMITS_TO_PENALTY = 5
SUSI_YEARS_OF_CAMPS_HISTORY = 10
SUSI_CAMP_TYPE = "Suši sústredenie"
PUZZLEHUNT_PARTICIPATIONS_KEY_NAME = "Suši účasti na šifrovačkách"
|
class Evaluator:
""" A superclass for metrics evaluations"""
def __init__(self, qp_ens):
"""Class constructor.
Parameters
----------
qp_ens: qp.Ensemble object
PDFs as qp.Ensemble
"""
self._qp_ens = qp_ens
def evaluate(self): #pragma: no cover
"""
Evaluates the metric a function of the truth and prediction
Returns
-------
metric: dictionary
value of the metric and statistics thereof
"""
raise NotImplementedError
# class CRPS(Evaluator):
# ''' Continuous rank probability score (Gneiting et al., 2006)'''
#
# def __init__(self, sample, name="CRPS"):
# """Class constructor.
# Parameters
# ----------
# sample: `qp.ensemble`
# ensemble of PDFS
# name: `str`
# the name of the metric
# """
# super().__init__(sample, name)
#
#
# def evaluate(self):
# raise NotImplementedError
|
'''a Python program to print out a set containing all the colors from color_list_1
which are not present in color_list_2'''
def main():
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print("Original set elements:")
print(color_list_1)
print(color_list_2)
print("\nDifferenct of color_list_1 and color_list_2:")
print(color_list_1.difference(color_list_2))
print("\nDifferenct of color_list_2 and color_list_1:")
print(color_list_2.difference(color_list_1))
main () |
input = [
('Mamma Mia', ['ABBA']),
('Ghost Rule', ['DECO*27', 'Hatsune Miku']),
('Animals', ['Martin Garrix']),
('Remember The Name', ['Ed Sheeran', 'Eminem', '50 Cent']),
('404 Not Found', [])
]
def songTitle(song):
artists = ''
if len(song[1]) > 1:
for artist in range(len(song[1])):
artists += (song[1][artist] + ', ')
artists += ('and ' + song[1][-1] + ' - ')
elif len(song[1]) == 1:
artists = song[1][0] + ' - '
else:
artists = ''
return artists + song[0]
for song in input:
print(songTitle(song))
|
class FluidAudioDriver():
''' Represents the FluidSynth audio driver object as defined in audio.h.
This class is inspired by the FluidAudioDriver object from pyfluidsynth by MostAwesomeDude.
Member:
audio_driver -- The FluidSynth audio driver object (fluid_audio_driver_t).
handle -- The handle to the FluidSynth library. Should be FluidHandle but a raw handle will
probably work, too (FluidHandle).
'''
def __init__( self, handle, synth, settings ):
''' Create a new FluidSynth audio driver instance using given handle, synth and settings
objects. '''
self.handle = handle
self.audio_driver = handle.new_fluid_audio_driver( settings.settings, synth.synth )
def __del__(self):
''' Delete the audio driver. '''
self.handle.delete_fluid_audio_driver( self.audio_driver ) |
class Writer:
def __init__(self, outfile):
self.outfile = outfile
def writeHeader(self):
pass
def write(self, record):
pass
def writeFooter(self):
pass
|
"""
Pyformlang
==========
Pyformlang is a python module to perform operation on formal languages.
How to use the documentation
----------------------------
Documentation is available in two formats: docstrings directly
in the code and a readthedocs website: https://pyformlang.readthedocs.io.
Available subpackages
---------------------
regular_expression
Regular Expressions
finite_automaton
Finite automata (deterministic, non-deterministic, with/without epsilon
transitions
fst
Finite State Transducers
cfg
Context-Free Grammar
pda
Push-Down Automata
Indexed Grammar
Indexed Grammar
rsa
Recursive automaton
"""
__all__ = ["finite_automaton",
"regular_expression",
"cfg",
"fst",
"indexed_grammar",
"pda",
"rsa"]
|
def b2tc(number: int):
"""
Funcion devuelve el complemento de un numero entero el cual se define como "inversion de todos los bits".
:param number: numero entero
:type number: int
:return: cadena conforme a resultado inverso de bit (XOR)
:rtype: str
"""
b2int = int(bin(number)[2:]) # [2:] excluir `0b`
xor = ['0' if b == '1' else '1' for b in str(b2int)] # comprehension list
return ''.join(xor)
if __name__ == '__main__':
"""
-- Complemento a 2's --
Leer un numero entero, convertir a binario e imprimir complemento a 2's de la conversion rapida.
La conversion rapida comprende invertir todo los bits de un numero entero. En el sistema binario
se conoce como operacion XOR.
La conversion rapida es relativamente sencilla,
1ro. convertir a binario
2do. invertir bits
Tome en cuenta que este ejemplo NO ES la implementacion adecuada del metodo sino,
comprender un poco el uso de "comprehension list".
Fuente (https://es.wikipedia.org/wiki/Complemento_a_dos)
"""
num = 0
print("INGRESE NUMERO ENTERO")
try:
num = int(input("R: "))
except ValueError as ex:
raise RuntimeError("<EXCEPCION> Tipo de dato invalido") from ex
print("\nNUMERO ENTERO %d\n2b: %d\ncomplemento 2b: %s" % (num, int(bin(num)[2:]), b2tc(num)))
|
a='cdef'
b='ab'
print('a'/'b')
a=8
b='ab'
print('a'/'b')
|
## GroupID-8 (14114002_14114068) - Abhishek Jaisingh & Tarun Kumar
## Date: April 15, 2016
## bitwise_manipulations.py - Bitwise Manipulation Functions for Travelling Salesman Problem
def size(int_type):
length = 0
count = 0
while (int_type):
count += (int_type & 1)
length += 1
int_type >>= 1
return count
def length(int_type):
length = 0
count = 0
while (int_type):
count += (int_type & 1)
length += 1
int_type >>= 1
return length |
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
result = []
for v in ops:
length = len(result)
if v == '+':
if length >= 2:
result.append(result[length-1] + result[length-2])
elif v == 'D':
if length >= 1:
result.append(result[length-1]*2)
elif v == 'C':
if length >= 1:
result.pop()
else:
result.append(int(v))
return sum(result)
if __name__ == '__main__':
s = Solution()
print(s.calPoints(["5","2","C","D","+"]))
print(s.calPoints(["5","-2","4","C","D","9","+","+"]))
print(s.calPoints(["D","-2","C","C","D","9","+","C"])) |
print("To change the data type of data")
int_data=int(input("Enter the integer data:"))
dec_data=float(input("Enter the decimal data:"))
int_str=str(int_data)
print(int_str)
dec_int=int(dec_data)
print(dec_int)
dec_str=str(dec_data) |
# Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preço = float(input('Qual o preço do produto?'))
novo = preço - (preço * 5 / 100)
print('O produto que custava R${:.2f}, na promoção com desconto de 5% vai custar {:.2f}'.format(preço, novo))
|
# Personalizando a representação string de uma classe
class MinhasCores():
def __init__(self):
self.vermelho = 50
self.verde = 75
self.azul = 100
# Use getattr para retornar um valor de forma dinâmica
def __getattr__(self, attr):
if attr == "rgb":
return (self.vermelho, self.verde, self.azul)
else:
raise AttributeError
# Use setattr para retornar um valor de forma dinâmica
def __setattr__(self, attr, val):
if attr == "rgb":
self.vermelho = val[0]
self.verde = val[1]
self.azul = val[2]
else:
super().__setattr__(attr, val)
# Use dir para listar as propriedades disponíveis
def __dir__(self):
return ("vermelho", "verde", "azul", "rgb")
def main():
# Criando uma instância de MinhasCores
cores = MinhasCores()
# Defina o valor de um atributo
print(cores.rgb)
# Defina o valor de um atributo
cores.rgb = (125, 200, 86)
# rgb(75, 139, 190) # azul
# rgb(255, 232, 115) # amarelo
print(cores.rgb)
# Acesse um atributo específico
print(cores.vermelho)
# Liste os atributos disponíveis
print(dir(cores))
if __name__ == "__main__":
main()
|
# Time: O(l)
# Space: O(l)
# Given an integer n, find the closest integer (not including itself), which is a palindrome.
#
# The 'closest' is defined as absolute difference minimized between two integers.
#
# Example 1:
# Input: "123"
# Output: "121"
# Note:
# The input n is a positive integer represented by string, whose length will not exceed 18.
# If there is a tie, return the smaller one as answer.
class Solution(object):
def nearestPalindromic(self, n):
"""
:type n: str
:rtype: str
"""
l = len(n)
candidates = set((str(10**l + 1), str(10**(l - 1) - 1)))
prefix = int(n[:(l + 1)/2])
for i in map(str, (prefix-1, prefix, prefix+1)):
candidates.add(i + [i, i[:-1]][l%2][::-1])
candidates.discard(n)
return min(candidates, key=lambda x: (abs(int(x) - int(n)), int(x)))
|
@dataclass
class Point:
x: int
y: int
z: int
position = property()
@position.setter
def position(self, new_value):
if type(new_value) not in (list, tuple, set):
raise TypeError
elif len(new_value) != 3:
raise ValueError
else:
self.x, self.y, self.z = new_value
|
def get_sql_lite_conn_str(db_file: str):
db_file_stripped = db_file.strip()
if not db_file or not db_file_stripped:
# db_file = '../db/meet_app.db'
raise Exception("SQL lite DB file is not specified.")
return 'sqlite:///' + db_file_stripped |
# -*- coding: utf-8 -*-
__author__ = """Juan Eiros"""
__email__ = 'jeirosz@gmail.com'
|
# definitions used
# constants
DE = 'DE'
# variables
qhLen = None # number of rows of the quarter of an hour output vector (4 each hour)
header = None
zones = None
dataImport = None
dataExport = None
sumImport = None
sumExport = None
data = None
# output file names
output_file_name = 'GenerationAndLoad.csv'
# countries in the CWE area
countries_dict = {
'AT': ['DE'],
'BE': ['FR', 'NL'],
'FR': ['BE', 'DE'],
'DE': ['AT', 'FR', 'NL'],
'NL': ['BE', 'DE']
}
PSRTYPE_MAPPINGS = {
'A03': 'Mixed',
'A04': 'Generation',
'A05': 'Load',
'B01': 'Biomass',
'B02': 'Fossil Brown coal/Lignite',
'B03': 'Fossil Coal-derived gas',
'B04': 'Fossil Gas',
'B05': 'Fossil Hard coal',
'B06': 'Fossil Oil',
'B07': 'Fossil Oil shale',
'B08': 'Fossil Peat',
'B09': 'Geothermal',
'B10': 'Hydro Pumped Storage',
'B11': 'Hydro Run-of-river and poundage',
'B12': 'Hydro Water Reservoir',
'B13': 'Marine',
'B14': 'Nuclear',
'B15': 'Other renewable',
'B16': 'Solar',
'B17': 'Waste',
'B18': 'Wind Offshore',
'B19': 'Wind Onshore',
'B20': 'Other',
'B21': 'AC Link',
'B22': 'DC Link',
'B23': 'Substation',
'B24': 'Transformer'
}
# countries_dict = {
# #'AL': ['GR', 'ME', 'RS'],
# 'AT': ['CZ', 'DE', 'HU', 'IT', 'SI', 'CH'],
# #'BY': ['LT', 'UA'],
# 'BE': ['FR', 'LU', 'NL'],
# #'BA': ['HR', 'ME', 'RS'],
# 'BG': ['GR', 'MK', 'RO', 'RS', 'TR'],
# #'HR': ['BA', 'HU', 'RS', 'SI'],
# 'CZ': ['AT', 'DE', 'PL', 'SK'],
# 'DK': ['DE', 'NO', 'SE'],
# 'EE': ['FI', 'LV', 'RU'],
# #'MK': ['BG', 'GR', 'RS'],
# 'FI': ['EE', 'NO', 'RU', 'SE'],
# 'FR': ['BE', 'DE', 'IT', 'ES', 'CH'],
# 'DE': ['AT', 'CH', 'CZ', 'DK', 'FR', 'NL', 'PL', 'SE'],
# 'GR': ['AL', 'BG', 'IT', 'MK', 'TR'],
# 'HU': ['AT', 'HR', 'RO', 'RS', 'SK', 'UA'],
# 'IT': ['AT', 'FR', 'GR', 'MT', 'SI', 'CH'],
# 'LV': ['EE', 'LT', 'RU'],
# 'LT': ['BY', 'LV', 'PL', 'RU', 'SE'],
# #'MT': ['IT'],
# #'MD': ['UA'],
# 'ME': ['AL', 'BA', 'RS'],
# 'NL': ['BE', 'DE', 'NO'],
# 'NO': ['DK', 'FI', 'NL', 'SE'],
# 'PL': ['CZ', 'DE', 'LT', 'SK', 'SE', 'UA'],
# 'PT': ['ES'],
# 'RO': ['BG', 'HU', 'RS', 'UA'],
# #'RU': ['EE', 'FI', 'LV', 'LT', 'UA'],
# #'RS': ['AL', 'BA', 'BG', 'HR', 'HU', 'MK', 'ME', 'RO'],
# 'SK': ['CZ', 'HU', 'PL', 'UA'],
# 'SI': ['AT', 'HR', 'IT'],
# 'ES': ['FR', 'PT'],
# 'SE': ['DK', 'FI', 'DE', 'LT', 'NO', 'PL'],
# 'CH': ['AT', 'FR', 'DE', 'IT']
# #'TR': ['BG', 'GR'],
# #'UA': ['BY', 'HU', 'MD', 'PL', 'RO', 'RU', 'SK']
# }
|
class IteratorBase(object):
"""Базовый класс итератора"""
def first(self):
"""Возвращает первый элемент коллекции.
Если элемента не существует возбуждается исключение IndexError."""
raise NotImplementedError()
def last(self):
"""Возвращает последний элемент коллекции.
Если элемента не существует возбуждается исключение IndexError."""
raise NotImplementedError()
def next(self):
"""Возвращает следующий элемент коллекции"""
raise NotImplementedError()
def prev(self):
"""Возвращает предыдущий элемент коллекции"""
raise NotImplementedError()
def current_item(self):
"""Возвращает текущий элемент коллекции"""
raise NotImplementedError()
def is_done(self, index):
"""Возвращает истину если элемент с указанным индексом существует, иначе ложь"""
raise NotImplementedError()
def get_item(self, index):
"""Возвращает элемент коллекции с указанным индексом, иначе возбуждает исключение IndexError"""
raise NotImplementedError()
class Iterator(IteratorBase):
def __init__(self, list_=None):
self._list = list_ or []
self._current = 0
def first(self):
return self._list[0]
def last(self):
return self._list[-1]
def current_item(self):
return self._list[self._current]
def is_done(self, index):
last_index = len(self._list) - 1
return 0 <= index <= last_index
def next(self):
self._current += 1
if not self.is_done(self._current):
self._current = 0
return self.current_item()
def prev(self):
self._current -= 1
if not self.is_done(self._current):
self._current = len(self._list) - 1
return self.current_item()
def get_item(self, index):
if not self.is_done(index):
raise IndexError('Нет элемента с индексом: %d' % index)
return self._list[index]
it = Iterator(['one', 'two', 'three', 'four', 'five'])
print([it.prev() for i in range(5)]) # ['five', 'four', 'three', 'two', 'one']
print([it.next() for i in range(5)]) # ['two', 'three', 'four', 'five', 'one'] |
class StructureObject:
def __init__(self, name="", dir=""):
self.name = name
self.dir = dir
def getName(self): return self.name
def getDir(self): return self.dir
def getType(self): return type(self) |
def dbl_linear(n):
u = [1]
def func(nums):
global fin
new_nums = []
for i in nums:
new_nums.append(2 * i + 1)
new_nums.append(3 * i + 1)
u.extend(new_nums)
if len(u) > n*12:
fin = list(sorted(set(u)))
else:
func(new_nums)
return fin[n]
return func(u)
if __name__ == "__main__":
print(dbl_linear(10))
print(dbl_linear(500))
print(dbl_linear(60000))
|
def write(filename, content):
with open(filename, 'w') as file_object:
file_object.write(content)
def appendWrite(filename, content):
with open(filename, 'a') as file_object:
file_object.write(content)
|
# Copyright (c) 2021 Qianyun, Inc. All rights reserved.
# smartx
SMARTX_INSTANCE_STATE_STOPPED = 'stopped'
|
print('Bem vindo ao conversor de medidas')
nome = input('Digite seu nome: ')
m = float(input('Digite sua altura em metros: '))
print('{} sua altura em centimetros é de {}cm,\n e em '
'milimetros é de {}mm'.format(nome,m*100,m*1000))
|
for i in range (6):
for j in range (7):
if (i==0 and j %3!=0) or (i==1 and j % 3==0) or (i-j==2) or (i+j==8):
print("*",end=" ")
else:
print(end=" ")
print()
|
A, B, K = map(int, input().split())
if A >= K:
A -= K
print(A, B)
else:
A, B = 0, max(0, B - (K - A))
print(A, B)
|
lista=[]
def main():
n = int(input("Digite o número de ímpares que você deseja saber!!!: "))
x = 0
z = 0
while x < (n):
z = z + 1
if z % 2 != 0:
x = x + 1
print(z)
global lista
lista.append(z)
|
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
carry = 0
for i in range(len(digits) - 1, -1, -1):
if i == len(digits) - 1:
digits[i] += 1
else:
digits[i] = digits[i] + carry
if digits[i] == 10:
digits[i] = 0
carry = 1
else:
carry = 0
return digits if not carry else [1] + digits |
def close(n, smallest=10, d=10):
""" A sequence is near increasing if each element but the last two is smaller than all elements
following its subsequent element. That is, element i must be smaller than elements i + 2, i + 3, i + 4, etc.
Implement close, which takes a non-negative integer n and returns the largest near increasing sequence
of digits within n as an integer. The arguments smallest and d are part of the implementation; you must
determine their purpose. The only values you may use are integers and booleans (True and False) (no lists, strings, etc.).
Return the longest sequence of near-increasing digits in n.
>>> close(123)
123
>>> close(153)
153
>>> close(1523)
153
>>> close(15123)
1123
>>> close(11111111)
11
>>> close(985357)
557
>>> close(14735476)
143576
>>> close(812348567)
1234567
"""
if n == 0:
return ______
no = close(n//10, smallest, d)
if smallest > ______:
yes = ______
return ______(yes, no)
return ______
# ORIGINAL SKELETON FOLLOWS
# def close(n, smallest=10, d=10):
# """ A sequence is near increasing if each element but the last two is smaller than all elements
# following its subsequent element. That is, element i must be smaller than elements i + 2, i + 3, i + 4, etc.
# Implement close, which takes a non-negative integer n and returns the largest near increasing sequence
# of digits within n as an integer. The arguments smallest and d are part of the implementation; you must
# determine their purpose. The only values you may use are integers and booleans (True and False) (no lists, strings, etc.).
# Return the longest sequence of near-increasing digits in n.
# >>> close(123)
# 123
# >>> close(153)
# 153
# >>> close(1523)
# 153
# >>> close(15123)
# 1123
# >>> close(11111111)
# 11
# >>> close(985357)
# 557
# >>> close(14735476)
# 143576
# >>> close(812348567)
# 1234567
# """
# if n == 0:
# return ______
# no = close(n//10, smallest, d)
# if smallest > ______:
# yes = ______
# return ______(yes, no)
# return ______
|
#!/usr/bin/env python3
charlimit = 450
def isChan(chan, checkprefix):
if not chan:
return False
elif chan.startswith("#"):
return True
elif checkprefix and len(chan) >= 2 and not chan[0].isalnum() and chan[1] == "#":
return True
else:
return False
|
__title__ = 'MongoFlask'
__description__ = 'A Python Flask library for connecting a MongoDB instance to a Flask application'
__url__ = 'https://github.com/juanmanuel96/mongo-flask'
__version_info__ = ('0', '1', '3')
__version__ = '.'.join(__version_info__)
__author__ = 'Juan Vazquez'
__py_version__ = 3
|
JournalFame = {"4" : 1200,
"5" : 2400,
"6" : 4800,
"7" : 9600,
"8" : 19200}
FameGenerated = {"4": {"2Hweapon":720, "1Hweapon":540, "BigArmor":360, "SmallArmor":180},
"5": {"2Hweapon":2880, "1Hweapon":2160, "BigArmor":1440, "SmallArmor":720},
"6": {"2Hweapon":8640, "1Hweapon":6480, "BigArmor":4320, "SmallArmor":2160},
"7": {"2Hweapon":20640, "1Hweapon":15480, "BigArmor":10320, "SmallArmor":5160},
"8": {"2Hweapon":44640, "1Hweapon":33480, "BigArmor":22320, "SmallArmor":11160}}
treeType = {"B" : "Blacksmith",
"I" : "Imbuer",
"F" : "Fletcher"}
itemType = {"BattleAxe" : "1Hweapon",
"Halberd" : "2Hweapon",
"Great_Axe" : "2Hweapon",
"Boots" : "SmallArmor",
"Shield" : "SmallArmor",
"1H_Crossbow" : "1Hweapon",
"2H_Crossbow" : "2Hweapon",
"Armor" : "BigArmor",
"1H_Hammer" : "1Hweapon",
"2H_Hammer" : "2Hweapon",
"Helmet" : "SmallArmor",
"1H_Mace" : "1Hweapon",
"2H_Mace" : "2Hweapon",
"1H_Sword" : "1Hweapon",
"2H_Sword" : "2Hweapon",
"Robe" : "BigArmor",
"Sandals" : "SmallArmor",
"Cowl" : "SmallArmor",
"1H_Damage_Staff" : "1Hweapon",
"2H_Damage_Staff" : "2Hweapon",
"1H_Holy_Staff" : "1Hweapon",
"2H_Holy_Staff" : "2Hweapon",
"SpellTome" : "SmallArmor",
"Torch" : "SmallArmor",
"1H_Nature_Staff" : "1Hweapon",
"2H_Nature_staff" : "2Hweapon",
"1H_Dagger" : "1Hweapon",
"2H_Dagger" : "2Hweapon",
"Claws" : "2Hweapon",
"Staff" : "2Hweapon",
"1H_Spear" : "1Hweapon",
"Pike" : "2Hweapon",
"Glaive" : "2Hweapon",
"Jacket" : "BigArmor",
"Shoes" : "SmallArmor",
"Hood" : "SmallArmor"}
itemTree = {"BattleAxe" : "Blacksmith",
"Halberd" : "Blacksmith",
"Great_Axe" : "Blacksmith",
"Boots" : "Blacksmith",
"Shield" : "Blacksmith",
"1H_Crossbow" : "Blacksmith",
"2H_Crossbow" : "Blacksmith",
"Armor" : "Blacksmith",
"1H_Hammer" : "Blacksmith",
"2H_Hammer" : "Blacksmith",
"Helmet" : "Blacksmith",
"1H_Mace" : "Blacksmith",
"2H_Mace" : "Blacksmith",
"1H_Sword" : "Blacksmith",
"2H_Sword" : "Blacksmith",
"Robe" : "Imbuer",
"Sandals" : "Imbuer",
"Cowl" : "Imbuer",
"1H_Damage_Staff" : "Imbuer",
"2H_Damage_Staff" : "Imbuer",
"1H_Holy_Staff" : "Imbuer",
"2H_Holy_Staff" : "Imbuer",
"SpellTome" : "Imbuer",
"Torch" : "Fletcher",
"1H_Nature_Staff" : "Fletcher",
"2H_Nature_staff" : "Fletcher",
"1H_Dagger" : "Fletcher",
"2H_Dagger" : "Fletcher",
"Claws" : "Fletcher",
"Staff" : "Fletcher",
"1H_Spear" : "Fletcher",
"Pike" : "Fletcher",
"Glaive" : "Fletcher",
"Jacket" : "Fletcher",
"Shoes" : "Fletcher",
"Hood" : "Fletcher"}
clothCost = {"BattleAxe" : 0,
"Halberd" : 0,
"Great_Axe" : 0,
"Boots" : 0,
"Shield" : 0,
"1H_Crossbow" : 0,
"2H_Crossbow" : 0,
"Armor" : 0,
"1H_Hammer" : 0,
"2H_Hammer" : 12,
"Helmet" : 0,
"1H_Mace" : 8,
"2H_Mace" : 12,
"1H_Sword" : 0,
"2H_Sword" : 0,
"Robe" : 16,
"Sandals" : 8,
"Cowl" : 8,
"1H_Damage_Staff" : 0,
"2H_Damage_Staff" : 0,
"1H_Holy_Staff" : 8,
"2H_Holy_Staff" : 12,
"SpellTome" : 4,
"Torch" : 4,
"1H_Nature_Staff" : 8,
"2H_Nature_staff" : 12,
"1H_Dagger" : 0,
"2H_Dagger" : 0,
"Claws" : 0,
"Staff" : 0,
"1H_Spear" : 0,
"Pike" : 0,
"Glaive" : 0,
"Jacket" : 0,
"Shoes" : 0,
"Hood" : 0}
metalCost = {"BattleAxe" : 16,
"Halberd" : 12,
"Great_Axe" : 20,
"Boots" : 8,
"Shield" : 4,
"1H_Crossbow" : 8,
"2H_Crossbow" : 12,
"Armor" : 16,
"1H_Hammer" : 24,
"2H_Hammer" : 20,
"Helmet" : 8,
"1H_Mace" : 16,
"2H_Mace" : 20,
"1H_Sword" : 16,
"2H_Sword" : 20,
"Robe" : 0,
"Sandals" : 0,
"Cowl" : 0,
"1H_Damage_Staff" : 8,
"2H_Damage_Staff" : 12,
"1H_Holy_Staff" : 0,
"2H_Holy_Staff" : 0,
"SpellTome" : 0,
"Torch" : 0,
"1H_Nature_Staff" : 0,
"2H_Nature_staff" : 0,
"1H_Dagger" : 12,
"2H_Dagger" : 16,
"Claws" : 12,
"Staff" : 12,
"1H_Spear" : 8,
"Pike" : 12,
"Glaive" : 20,
"Jacket" : 0,
"Shoes" : 0,
"Hood" : 0}
woodCost = {"BattleAxe" : 8,
"Halberd" : 20,
"Great_Axe" : 12,
"Boots" : 0,
"Shield" : 4,
"1H_Crossbow" : 16,
"2H_Crossbow" : 20,
"Armor" : 0,
"1H_Hammer" : 0,
"2H_Hammer" : 0,
"Helmet" : 0,
"1H_Mace" : 0,
"2H_Mace" : 0,
"1H_Sword" : 0,
"2H_Sword" : 0,
"Robe" : 0,
"Sandals" : 0,
"Cowl" : 0,
"1H_Damage_Staff" : 16,
"2H_Damage_Staff" : 20,
"1H_Holy_Staff" : 16,
"2H_Holy_Staff" : 20,
"SpellTome" : 0,
"Torch" : 4,
"1H_Nature_Staff" : 16,
"2H_Nature_staff" : 20,
"1H_Dagger" : 0,
"2H_Dagger" : 0,
"Claws" : 0,
"Staff" : 0,
"1H_Spear" : 16,
"Pike" : 20,
"Glaive" : 12,
"Jacket" : 0,
"Shoes" : 0,
"Hood" : 0}
leatherCost = {"BattleAxe" : 0,
"Halberd" : 0,
"Great_Axe" : 0,
"Boots" : 0,
"Shield" : 0,
"1H_Crossbow" : 0,
"2H_Crossbow" : 0,
"Armor" : 0,
"1H_Hammer" : 0,
"2H_Hammer" : 0,
"Helmet" : 0,
"1H_Mace" : 0,
"2H_Mace" : 0,
"1H_Sword" : 8,
"2H_Sword" : 12,
"Robe" : 0,
"Sandals" : 0,
"Cowl" : 0,
"1H_Damage_Staff" : 0,
"2H_Damage_Staff" : 0,
"1H_Holy_Staff" : 0,
"2H_Holy_Staff" : 0,
"SpellTome" : 4,
"Torch" : 0,
"1H_Nature_Staff" : 0,
"2H_Nature_staff" : 0,
"1H_Dagger" : 12,
"2H_Dagger" : 16,
"Claws" : 20,
"Staff" : 20,
"1H_Spear" : 0,
"Pike" : 0,
"Glaive" : 0,
"Jacket" : 16,
"Shoes" : 8,
"Hood" : 8}
craftedItems = {"BattleAxe" : 0,
"Halberd" : 0,
"Great_Axe" : 0,
"Boots" : 0,
"Shield" : 0,
"1H_Crossbow" : 0,
"2H_Crossbow" : 0,
"Armor" : 0,
"1H_Hammer" : 0,
"2H_Hammer" : 0,
"Helmet" : 0,
"1H_Mace" : 0,
"2H_Mace" : 0,
"1H_Sword" : 0,
"2H_Sword" : 0,
"Robe" : 0,
"Sandals" : 0,
"Cowl" : 0,
"1H_Damage_Staff" : 0,
"2H_Damage_Staff" : 0,
"1H_Holy_Staff" : 0,
"2H_Holy_Staff" : 0,
"SpellTome" : 0,
"Torch" : 0,
"1H_Nature_Staff" : 0,
"2H_Nature_staff" : 0,
"1H_Dagger" : 0,
"2H_Dagger" : 0,
"Claws" : 0,
"Staff" : 0,
"1H_Spear" : 0,
"Pike" : 0,
"Glaive" : 0,
"Jacket" : 0,
"Shoes" : 0,
"Hood" : 0}
RRR = {"N" : 0.248,
"Y" : 0.479}
focusMessage = {"N" : "Focus was not used",
"Y" : "Focus was used"}
|
# -*- coding: utf-8 -*-
# Copyright 2017 Vector Creations Ltd
#
# 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.
"""This module implements the TCP replication protocol used by synapse to
communicate between the master process and its workers (when they're enabled).
Further details can be found in docs/tcp_replication.rst
Structure of the module:
* handler.py - the classes used to handle sending/receiving commands to
replication
* command.py - the definitions of all the valid commands
* protocol.py - the TCP protocol classes
* resource.py - handles streaming stream updates to replications
* streams/ - the definitons of all the valid streams
The general interaction of the classes are:
+---------------------+
| ReplicationStreamer |
+---------------------+
|
v
+---------------------------+ +----------------------+
| ReplicationCommandHandler |---->|ReplicationDataHandler|
+---------------------------+ +----------------------+
| ^
v |
+-------------+
| Protocols |
| (TCP/redis) |
+-------------+
Where the ReplicationDataHandler (or subclasses) handles incoming stream
updates.
"""
|
class ExtraException(Exception):
def __init__(self, message: str = None, **kwargs):
if message:
self.message = message
self.extra = kwargs
super().__init__(message, kwargs)
def __str__(self) -> str:
return self.message
class PackageNotFoundError(ExtraException, LookupError):
message = 'package not found'
class InvalidFieldsError(ExtraException, ValueError):
message = 'invalid fields'
|
class Solution:
# @param A : list of integers
# @return an integer
'''
Facebook Codelab
No hints or solutions needed
N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of current bulb. Given an initial state of all bulbs, find the minimum number of switches you have to press to turn on all the bulbs. You can press the same switch multiple times.
Input : [0 1 0 1]
Return : 4
'''
def bulbs(self, A):
if A is None:
return None
if len(A) == 0:
return 0
cnt = 0
rightFlipped = False
for i, v in enumerate(A):
if v ^ rightFlipped:
continue
else:
A[i] = 1
cnt += 1
rightFlipped = not rightFlipped
return cnt
if __name__ == "__main__":
A = [3, 0, 1, 0]
|
def main():
recursion()
def recursion():
count = [0]
num = b(5, 2, count)
print(num)
# print(sum(count))
print(count[0])
def b(n, k, count):
# count.append(1) ## count the number of stack frame
count[0] += 1
if k == 0 or k == n:
print('Base Case!')
return 2
else:
return b(n-1, k-1, count) + b(n-1, k, count)
if __name__ == '__main__':
main() |
#
# @lc app=leetcode.cn id=547 lang=python3
#
# [547] friend-circles
#
None
# @lc code=end |
"""
Memoization decorator.
"""
def memoize(f):
memos = {}
def memoized(*args):
if args not in memos: memos[args] = f(*args)
return memos[args]
return memoized
|
class CaseInsensitiveKey( object ):
def __init__( self, key ):
self.key = key
def __hash__( self ):
return hash( self.key.lower() )
def __eq__( self, other ):
return self.key.lower() == other.key.lower()
def __str__( self ):
return self.key
GROK_PATTERN_CONF = dict()
# Basic String
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'String' ) ] = 'DATA' # DATA or NOTSPACE ?
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Quote String' ) ] = 'QS'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'UUID' ) ] = 'UUID'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Log Level' ) ] = 'LOGLEVEL'
# Networking
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'IP' ) ] = 'IP'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Host/Domain' ) ] = 'HOST'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Host:Port' ) ] = 'HOSTPORT'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'IP or Host/Domain' ) ] = 'IPORHOST'
# Path
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Full URL' ) ] = 'URI' # http://www.google.com?search=mj
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Url Path' ) ] = 'URIPATHPARAM'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Unix Path' ) ] = 'UNIXPATH'
# Json
# GROK_PATTERN_CONF[ CaseInsensitiveKey( 'json' ) ] =
# Number
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Number' ) ] = 'NUMBER' # Integer/Long OR Float/Double
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Integer/Long' ) ] = 'INT'
# GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Float/Double' ) ] =
# Date
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Year' ) ] = 'YEAR'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Month' ) ] = 'MONTH'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Month Number' ) ] = 'MONTHNUM'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Day' ) ] = 'DAY'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Hour' ) ] = 'HOUR'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Minute' ) ] = 'MINUTE'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'Second' ) ] = 'SECOND'
# GROK_PATTERN_CONF[ CaseInsensitiveKey( ) ] = 'TZ'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'ISO8601' ) ] = 'TIMESTAMP_ISO8601'
GROK_PATTERN_CONF[ CaseInsensitiveKey( 'HTTPDATE' ) ] = 'HTTPDATE'
# GROK_PATTERN_CONF[ CaseInsensitiveKey( 'custom' ) ] = # custom # TODO
# GROK_PATTERN_CONF = {
# # Basic String
# 'String': 'DATA', # DATA or NOTSPACE ?
# 'Quote String': 'QS',
# 'UUID': 'UUID',
# 'Log Level': 'LOGLEVEL',
# # Networking
# 'IP': 'IP',
# 'Host/Domain': 'HOST',
# 'Host:Port': 'HOSTPORT',
# 'IP or Host/Domain': 'IPORHOST',
# # Path
# 'Full URL': 'URI', # http://www.google.com?search=mj
# 'Url Path': 'URIPATHPARAM',
# 'Unix Path': 'UNIXPATH',
# # Json
# 'json': '', # TODO json regular expression
# # Number
# 'Number': 'NUMBER', # Integer/Long OR Float/Double
# 'Integer/Long': 'INT',
# 'Float/Double': '',
# # Date
# 'Year': 'YEAR',
# 'Month': 'MONTH',
# 'Month Number': 'MONTHNUM',
# 'Day': 'DAY',
# 'Hour': 'HOUR',
# 'Minute': 'MINUTE',
# 'Second': 'SECOND',
# '': 'TZ',
# 'ISO8601': 'TIMESTAMP_ISO8601',
# 'HTTPDATE': 'HTTPDATE',
# 'custom': '', # custom # TODO
# } |
class ValueResolver:
def resolve(self, value):
if value.kind() == "id":
string = self._resolve_id_value(value)
elif value.kind() == "node":
string = f"Node({self.resolve(value.value)}.value)"
elif value.kind() == "arc":
string = f"Arc({self.resolve(value.source)}, {self.resolve(value.target)}, {self.resolve(value.weight)}.value, \"{value.type}\")"
elif value.kind() == "graph":
string = self._resolve_graph_value(value)
elif value.kind() == "num":
string = f"Num({value.value})"
elif value.kind() == "logic":
string = f"Logic({value.value})"
elif value.kind() == "nope":
string = "Nope()"
elif value.kind() == "fun_call":
string = self._resolve_fun_call(value.fun_call)
elif value.kind() == "binary_operation.summation":
string = self._resolve_summation(value)
elif value.kind() == "binary_operation.subtraction":
string = self._resolve_subtraction(value)
elif value.kind() == "binary_operation.multiplication":
string = self._resolve_multiplication(value)
elif value.kind() == "binary_operation.division":
string = self._resolve_division(value)
elif value.kind() == "binary_operation.and":
string = self._resolve_and(value)
elif value.kind() == "binary_operation.or":
string = self._resolve_or(value)
elif value.kind() == "unary_operation.not":
string = self._resolve_not(value)
elif value.kind() == "binary_operation.equal":
string = self._resolve_equal(value)
elif value.kind() == "binary_operation.not_equal":
string = self._resolve_not_equal(value)
elif value.kind() == "binary_operation.greater_or_equal":
string = self._resolve_greater_or_equal(value)
elif value.kind() == "binary_operation.less_or_equal":
string = self._resolve_less_or_equal(value)
elif value.kind() == "binary_operation.greater":
string = self._resolve_greater(value)
elif value.kind() == "binary_operation.less":
string = self._resolve_less(value)
string += f".cast(\"{value.cast_type}\")" if value.cast_type else ""
string += f"[{int(value.index.value)}]" if value.index else ""
return string
def _resolve_fun_call(self, statement):
return f"{statement.name}({self._resolve_array(statement.args)})"
def _resolve_summation(self, statement):
return f"{self.resolve(statement.left)}.summation({self.resolve(statement.right)})"
def _resolve_subtraction(self, statement):
return f"{self.resolve(statement.left)}.subtraction({self.resolve(statement.right)})"
def _resolve_multiplication(self, statement):
return f"{self.resolve(statement.left)}.multiplication({self.resolve(statement.right)})"
def _resolve_division(self, statement):
return f"{self.resolve(statement.left)}.division({self.resolve(statement.right)})"
def _resolve_and(self, statement):
return f"{self.resolve(statement.left)}.and_({self.resolve(statement.right)})"
def _resolve_or(self, statement):
return f"{self.resolve(statement.left)}.or_({self.resolve(statement.right)})"
def _resolve_not(self, statement):
return f"{self.resolve(statement.target)}.not_()"
def _resolve_equal(self, statement):
return f"{self.resolve(statement.left)}.equal({self.resolve(statement.right)})"
def _resolve_not_equal(self, statement):
return f"{self.resolve(statement.left)}.not_equal({self.resolve(statement.right)})"
def _resolve_greater_or_equal(self, statement):
return f"{self.resolve(statement.left)}.greater_or_equal({self.resolve(statement.right)})"
def _resolve_less_or_equal(self, statement):
return f"{self.resolve(statement.left)}.less_or_equal({self.resolve(statement.right)})"
def _resolve_greater(self, statement):
return f"{self.resolve(statement.left)}.greater({self.resolve(statement.right)})"
def _resolve_less(self, statement):
return f"{self.resolve(statement.left)}.less({self.resolve(statement.right)})"
def _resolve_id_value(self, statement):
if statement.index is not None:
return statement.name + f"[int({self.resolve(statement.index)}.value)]"
else:
return statement.name
def _resolve_graph_value(self, value):
return f"Graph([{self._resolve_array(value.elements)}])"
def _resolve_array(self, values):
values_ = [self.resolve(value) for value in values]
return ", ".join(values_)
|
""" Module docstring """
def _write_file_impl(ctx):
f = ctx.actions.declare_file("out.txt")
ctx.actions.write(f, "contents")
write_file = rule(
attrs = {},
implementation = _write_file_impl,
)
|
########################
### Feature combine ###
########################
#Combine Units:
df_tcad = merge_extraction(dfs=[df_tcad,df_units,gdf_16],val=['dba','type1','units','low','high','units_from_type','est_from_type','shape_area'])
replace_nan(df_tcad,['units_x','units_y','low','high'],val=0,reverse=True)
#Don't fill in any unit estimates from improvement data yet (will do that in handle missing) (the low high estimate ranges)
df_tcad.units_y = np.where(df_tcad.est_from_type, np.nan, df_tcad.units_y)
#Fill in missing in known data from 2016 with type data
df_tcad.units_x.fillna(df_tcad.units_y,inplace=True)
#Known units column
df_tcad['known']= np.where(df_tcad.units_x.notnull(), True,False)
#Where type data is larger then 2016 take the new value
#df_tcad.units_x = np.where((df_tcad.units_x < df_tcad.units_y), df_tcad.units_y, df_tcad.units_x)
#Get rid of type values
del df_tcad['units_y']
#Combine Locations:
df_tcad = merge_extraction(dfs=[df_tcad,gdf,df_locs],on='prop_id',val=['land_use','X','Y','geometry','shape_area'])
df_tcad.X_y.fillna(df_tcad.X_x,inplace=True)
df_tcad.Y_y.fillna(df_tcad.Y_x,inplace=True)
df_tcad.Y_x.fillna(df_tcad.Y_y,inplace=True)
df_tcad.X_x.fillna(df_tcad.X_y,inplace=True)
del df_tcad['X_y']
del df_tcad['Y_y']
df_tcad = df_tcad.merge(df_con,left_on='geo_id',right_on='TCAD ID',how='left')
df_tcad.Y_x.fillna(df_tcad.Latitude,inplace=True)
df_tcad.X_x.fillna(df_tcad.Longitude,inplace=True)
del df_tcad['Latitude']
del df_tcad['Longitude']
#Known location column
df_tcad['known_loc']= np.where(df_tcad.X_x.notnull(), True,False)
#Residential criteria
res = ['A1','A2','A3','A4','A5','B1','B2','B3','B4','E2','M1','XA']
res_type = ['ALT LIVING CTR', 'DORMITORY HIRISE', 'DORMITORY', 'APARTMENT 5-25', 'LUXURY HI-RISE APTS 100+', 'APARTMENT 100+', 'GARAGE APARTMENT', 'Accessory Dwelling Unit' 'FOURPLEX', 'MOHO DOUBLE PP'] #got rid of detail only
res_code = ['100','113','150','160','210','220','230','240','330']
df_tcad['res'] = df_tcad.code2.isin(res)
df_tcad['res'] = (df_tcad.res | (df_tcad.hs=='T') | df_tcad.type1.isin(res_type) | (df_tcad.type1.str.contains('CONDO',na=False)) | (df_tcad.type1.str.contains('DWELLING',na=False)) | (df_tcad.desc.str.contains('APARTMENT',na=False)) | (df_tcad.desc.str.contains('APARTMENT',na=False)) | df_tcad.type1.str.contains('APARTMENT',na=False) | df_tcad.type1.str.contains('APT',na=False) | df_tcad.type1.str.contains('DORM',na=False) | (df_tcad.type1.str.contains('MOHO',na=False)))
#df_tcad['res'] = (df_tcad.res | df_tcad.type1.isin(res_type) | (df_tcad.type1.str.contains('CONDO',na=False)) | (df_tcad.type1.str.contains('DWELLING',na=False)) | ((df_tcad.desc.str.contains('CONDO',na=False))&(~df_tcad.desc.str.contains('CONDO',na=False))) | (df_tcad.desc.str.contains('APARTMENT',na=False))))
#apts = df_tcad.loc[ df_tcad.type1.str.contains('APARTMENT',na=False) | df_tcad.type1.str.contains('APT',na=False) | df_tcad.type1.str.contains('DORM',na=False)| (df_tcad.type1.str.contains('CONDO',na=False))]
|
exports = {
"name": "Earth",
"aspects": {
"amulets": [
{
"item": "scholar",
"effect": "health",
"description": "Into the earth is the answer. "
"Into the earth lies existance. "
"Into the earth lies death and memory. "
"Less health for opponents"
},
{
"item": "stargazer",
"effect": "hit",
"description": "The stars blesses our earth. "
"More accurate attacks"
}
],
"potions": [
{
"item": "justice",
"effect": "health",
"description": "In the tomb, ancient spirits scream "
"for justice. Less health for opponents"
},
{
"item": "blood",
"effect": "hit",
"description": "Into the earth, lies the blood of "
"our ancestors. Raised hit ratio"
}
]
},
"traces": ['taurus', 'virgo', 'capricorn']
}
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyCarputils(PythonPackage):
"""The carputils framework for running simulations with the openCARP software."""
homepage = "https://www.opencarp.org"
git = "https://git.opencarp.org/openCARP/carputils.git"
maintainers = ['MarieHouillon']
version('master', branch='master')
# Version to use with openCARP 7.0
version('oc7.0', commit='4c04db61744f2fb7665594d7c810699c5c55c77c')
depends_on('git')
depends_on('python@:3.8', type=('build', 'run'))
depends_on('py-pip', type='build')
depends_on('py-numpy@1.14.5:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-python-dateutil', type='run')
depends_on('py-scipy@:1.5.4', type='run')
depends_on('py-matplotlib@:3.3.3', type='run')
depends_on('py-pandas@:1.1.4', type='run')
depends_on('py-tables@3.6.1', type='run')
depends_on('py-six@:1.14.0', type='run')
depends_on('py-ruamel-yaml', type='run')
|
def perfect_number(number):
printing = "It's not so perfect."
checker = number
nums = 0
proper_devisors_sum = 0
for num in range(1, int(checker)):
if int(checker) % num == 0:
nums += int(num)
if nums == int(checker):
printing = "We have a perfect number!"
return printing
print(perfect_number(str(input()))) |
class Car:
"""Defining a car with a class"""
def __init__(self, tillverkare, modell, year):
"""Initialisera delar som beskriver en bil"""
self.tillverkare = tillverkare
self.modell = modell
self.year = year
self.mil_tal = 230
def get_descriptive_name(self):
"""Visa ett beskrivande namn på ett formaterat sätt"""
car_item = f"{self.year} {self.tillverkare} {self.modell}"
return car_item.title()
def mil_tal_in(self):
"""Printa det antal mil en bil gått"""
print(f"Den här bilen har gått {self.mil_tal} kilometer")
def mil_update(self, kilometer):
"""Metod för att uppdatera kilometerantalet baserat på okänd input"""
if kilometer >= self.mil_tal:
self.mil_tal = kilometer
else:
print("Du kan inte rulla tillbaks kilometertalet!!")
min_bil = Car('bmw', 'M135i', 2020)
print(f"{min_bil.tillverkare}")
print(min_bil.get_descriptive_name())
min_bil.mil_update(231)
min_bil.mil_tal_in() |
# Get all available modules
# help("modules")
module_names = [ "micropython", "uhashlib", "uselect", "_onewire", "sys", "uheapq", "ustruct", "builtins", "uarray", "uio", "utime", "cmath", "ubinascii", "ujson", "utimeq", "firmware", "ubluetooth", "umachine", "uzlib", "gc", "ucollections", "uos", "hub", "uctypes", "urandom", "math", "uerrno", "ure" ]
# List of objects to be processed.
object_list_todo = list()
object_list_done = list()
# Loop over the builtin modules.
for object_name in module_names:
# Add them to the object list to be processed.
object_list_todo.append((object_name, __import__(object_name)))
object_list_done.append(object_name)
# Loop over all objects.
while len(object_list_todo) > 0:
object_name, object_handle = object_list_todo.pop(0)
# Reserve space in map, and ensure checks for whether we already have this module pass.
object_map = dict()
# Get contents of object.
object_entries = dir(object_handle)
# Loop over all entries in the object.
for object_entry in object_entries:
# Add them to the map for output.
object_map[object_entry] = (type(getattr(object_handle, object_entry)).__name__, str(getattr(object_handle, object_entry)))
# Add them to the object list to be processed.
if (not object_entry in object_list_done):
# Add them to the list for further processing if they are not a base type.
if ((not isinstance(getattr(object_handle, object_entry), (str, float, int, list, dict, set))) and (not type(getattr(object_handle, object_entry)).__name__ == "function")):
object_list_todo.append((object_entry, getattr(object_handle, object_entry)))
object_list_done.append(object_entry)
print("{} = {}".format(object_name, object_map))
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Summary Functions\n",
"\n",
"def get_summ_combined_county_annual(state, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns seller details such as addresses\n",
"\n",
" >>>get_summ_combined_county_annual('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'combined_county_annual?'\n",
" add_state = 'state=' + state\n",
" add_county = '&county=' + county\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_county + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" combined_county_annual_df = json_normalize(requests.get(full_url).json())\n",
" return combined_county_annual_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" \n",
" \n",
"def get_summ_combined_county_monthly(state, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns seller details such as addresses\n",
"\n",
" >>>get_summ_combined_county_monthly('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'combined_county_monthly?'\n",
" add_state = 'state=' + state\n",
" add_county = '&county=' + county\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_county + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" combined_county_monthly_df = json_normalize(requests.get(full_url).json())\n",
" return combined_county_monthly_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" \n",
"def get_summ_total_pharmacies_county(state, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns all pharmacy totals by county (Will be large and could take extra time to load)\n",
"\n",
" >>>get_summ_total_pharmacies_county('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'total_pharmacies_county?'\n",
" add_state = 'state=' + state\n",
" add_county = '&county=' + county\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_county + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" total_pharmacies_county_df = json_normalize(requests.get(full_url).json())\n",
" return total_pharmacies_county_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" \n",
"def get_summ_total_manufacturers_county(state, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns all Manufacturer totals by county (Will be large and could take extra time to load)\n",
"\n",
" >>>get_summ_total_manufacturers_county('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'total_manufacturers_county?'\n",
" add_state = 'state=' + state\n",
" add_county = '&county=' + county\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_county + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" total_manufacturers_county_df = json_normalize(requests.get(full_url).json())\n",
" return total_manufacturers_county_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" \n",
"def get_summ_total_distributors_county(state, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns all Distributor totals by county (Will be large and could take extra time to load)\n",
"\n",
" >>>get_summ_total_distributors_county('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'total_distributors_county?'\n",
" add_state = 'state=' + state\n",
" add_county = '&county=' + county\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_county + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" total_distributors_county_df = json_normalize(requests.get(full_url).json())\n",
" return total_distributors_county_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" \n",
"def get_summ_total_pharmacies_state(state,verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns all pharmacy totals by state (Will be large and could take extra time to load)\n",
"\n",
" >>>get_summ_total_pharmacies_state('OH')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'total_pharmacies_state?'\n",
" add_state = 'state=' + state\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" total_pharmacies_state_df = json_normalize(requests.get(full_url).json())\n",
" return total_pharmacies_state_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" \n",
"def get_summ_total_manufacturers_state(state,verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns all Manufacturer totals by state (Will be large and could take extra time to load) \n",
"\n",
" >>>get_summ_total_manufacturers_state('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'total_manufacturers_state?'\n",
" add_state = 'state=' + state\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" total_manufacturers_state_df = json_normalize(requests.get(full_url).json())\n",
" return total_manufacturers_state_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" \n",
"def get_summ_total_distributors_state(state,verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns all Distributor totals by state (Will be large and could take extra time to load) \n",
"\n",
" >>>get_summ_total_distributors_state('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'total_distributors_state?'\n",
" add_state = 'state=' + state\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" total_distributors_state_df = json_normalize(requests.get(full_url).json())\n",
" return total_distributors_state_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL and state are correct: ', full_url)\n",
"\n",
"def get_summ_combined_buyer_annual(state, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns summarized annual dosages of pharmacies and practitioners by state and county \n",
"\n",
" >>>get_summ_combined_buyer_annual('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'combined_buyer_annual?'\n",
" add_state = 'state=' + state\n",
" add_county = '&county=' + county\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_county + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" combined_buyer_annual_df = json_normalize(requests.get(full_url).json())\n",
" return combined_buyer_annual_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" \n",
"def get_summ_combined_buyer_monthly(state, year, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) -> pd.df\n",
" Returns dosages by pharmacy or practitioner by county, state, and yea \n",
"\n",
" >>>get_summ_combined_buyer_monthly('OH', 'Summit')\n",
" EXAMPLE OUTPUT\n",
" '''\n",
"\n",
" base_url = 'https://arcos-api.ext.nile.works/v1/'\n",
" function_url = 'combined_buyer_monthly?'\n",
" add_state = 'state=' + state\n",
" add_county = '&county=' + county\n",
" add_year = '&year=' + year\n",
" add_key = '&key=' + key\n",
" full_url = base_url + function_url + add_state + add_county + add_year + add_key\n",
"\n",
" if verification == True:\n",
" print(full_url)\n",
" combined_buyer_monthly_df = json_normalize(requests.get(full_url).json())\n",
" return combined_buyer_monthly_df\n",
" else:\n",
" print('Problem encountered, not returning data:')\n",
" print('Either verification == False')\n",
" print('Or problem with API encountered, please verify URL, state and county are correct: ', full_url)\n",
" "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.9"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|
# -*- coding: utf-8 -*-
def ventilation_rates(
number_of_chimneys_main_heating,
number_of_chimneys_secondary_heating,
number_of_chimneys_other,
number_of_open_flues_main_heating,
number_of_open_flues_secondary_heating,
number_of_open_flues_other,
number_of_intermittant_fans_total,
number_of_passive_vents_total,
number_of_flueless_gas_fires_total,
dwelling_volume,
air_permeability_value_q50,
number_of_storeys_in_the_dwelling,
structural_infiltration,
suspended_wooden_ground_floor_infiltration,
no_draft_lobby_infiltration,
percentage_of_windows_and_doors_draught_proofed,
number_of_sides_on_which_dwelling_is_sheltered,
monthly_average_wind_speed,
applicable_case,
mechanical_ventilation_air_change_rate_through_system,
exhaust_air_heat_pump_using_Appendix_N,
mechanical_ventilation_throughput_factor,
efficiency_allowing_for_in_use_factor,
):
"""Calculates the ventilation rates, Section 2.
:param number_of_chimneys_main_heating:
:type number_of_chimneys_main_heating: int
:param number_of_chimneys_secondary_heating:
:type number_of_chimneys_secondary_heating: int
:param number_of_chimneys_other:
:type number_of_chimneys_other: int
:param number_of_open_flues_main_heating:
:type number_of_open_flues_main_heating: int
:param number_of_open_flues_secondary_heating:
:type number_of_open_flues_secondary_heating: int
:param number_of_open_flues_other:
:type number_of_open_flues_other: int
:param number_of_intermittant_fans_total:
:type number_of_intermittant_fans_total: int
:param number_of_passive_vents_total:
:type number_of_passive_vents_total: int
:param number_of_flueless_gas_fires_total:
:type number_of_flueless_gas_fires_total: int
:param dwelling_volume: See (5).
:type dwelling_volume: float
:param air_permeability_value_q50: See (17). Use None if not carried out.
:type air_permeability_value_q50: float or None
:param number_of_storeys_in_the_dwelling: See (9).
:type number_of_storeys_in_the_dwelling: int
:param structural_infiltration: See (11).
:type structural_infiltration: float
:param suspended_wooden_ground_floor_infiltration: See (12).
:type suspended_wooden_ground_floor_infiltration: float
:param no_draft_lobby_infiltration: See (13).
:type no_draft_lobby_infiltration: float
:param percentage_of_windows_and_doors_draught_proofed: See (14).
:type percentage_of_windows_and_doors_draught_proofed: float
:param number_of_sides_on_which_dwelling_is_sheltered: See (19).
:type number_of_sides_on_which_dwelling_is_sheltered: int
:param monthly_average_wind_speed: A list of the monthly wind speeds.
12 items, from Jan to Dec, see (22).
:type monthly_average_wind_speed: list (float)
:param applicable_case: One of the following options:
'balanced mechanical ventilation with heat recovery';
'balanced mechanical ventilation without heat recovery';
'whole house extract ventilation or positive input ventilation from outside';
or 'natural ventilation or whole house positive input ventilation from loft'.
:type applicable_case: str
:param mechanical_ventilation_air_change_rate_through_system: See (23a).
:type mechanical_ventilation_air_change_rate_through_system: float
:param exhaust_air_heat_pump_using_Appendix_N:
True if exhaust air heat pump using Appendix N, otherwise False.
:type exhaust_air_heat_pump_using_Appendix_N: bool
:param mechanical_ventilation_throughput_factor: F_mv, see Equation N4.
:type mechanical_ventilation_throughput_factor: float
:param efficiency_allowing_for_in_use_factor: In %, see (23c).
:type efficiency_allowing_for_in_use_factor: float
:returns: A dictionary with keys of (
number_of_chimneys_total,
number_of_chimneys_m3_per_hour,
number_of_open_flues_total,
number_of_open_flues_m3_per_hour,
number_of_intermittant_fans_m3_per_hour,
number_of_passive_vents_m3_per_hour,
number_of_flueless_gas_fires_m3_per_hour,
infiltration_due_to_chimnneys_flues_fans_PSVs,
additional_infiltration,
window_infiltration,
infiltration_rate,
infiltration_rate2,
shelter_factor,
infiltration_rate_incorporating_shelter_factor,
wind_factor,
adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed,
exhaust_air_heat_pump_air_change_rate_through_system,
effective_air_change_rate
)
- **number_of_chimneys_total** (`int`) -
- **number_of_chimneys_m3_per_hour** (`float`) - See (6a).
- **number_of_open_flues_total** (`int`) -
- **number_of_open_flues_m3_per_hour** (`float`) - See (6b).
- **infiltration_due_to_chimenys_flues_fans_PSVs** (`float`) - See (8).
- **additional_infiltration** (`float`) - See (10).
- **window_infiltration** (`float`) - See (15).
- **infiltration_rate** (`float`) - See (16).
- **infiltration_rate2** (`float`) - See (18).
- **shelter_factor** (`float`) - See (20).
- **infiltration_rate_incorporating_shelter_factor** (`float`) - See (21).
- **wind_factor** list (`float`) - See (22a).
- **adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed**: list (`float`) - See (22b).
- **exhaust_air_heat_pump_air_change_rate_through_system** (`float`) - See (23b).
- **effective_air_change_rate** list (`float`) - See (25).
:rtype: dict
"""
# number_of_chimneys
number_of_chimneys_total=(number_of_chimneys_main_heating +
number_of_chimneys_secondary_heating +
number_of_chimneys_other)
number_of_chimneys_m3_per_hour=number_of_chimneys_total * 40.0
# number_of_open_flues
number_of_open_flues_total=(number_of_open_flues_main_heating +
number_of_open_flues_secondary_heating +
number_of_open_flues_other)
number_of_open_flues_m3_per_hour=number_of_open_flues_total * 20.0
# number_of_intermittant_fans
number_of_intermittant_fans_m3_per_hour=number_of_intermittant_fans_total * 10.0
# number_of_passive_vents
number_of_passive_vents_m3_per_hour=number_of_passive_vents_total * 10.0
# number_of_flueless_gas_fires
number_of_flueless_gas_fires_m3_per_hour=number_of_flueless_gas_fires_total * 40.0
# infiltration_due_to_chimenys_flues_fans_PSVs
infiltration_due_to_chimneys_flues_fans_PSVs=((number_of_chimneys_m3_per_hour +
number_of_open_flues_m3_per_hour +
number_of_intermittant_fans_m3_per_hour +
number_of_passive_vents_m3_per_hour +
number_of_flueless_gas_fires_m3_per_hour) /
dwelling_volume)
if air_permeability_value_q50 is None: # changed from 'air_permeability_value_q50 == 0:' on 4-FEB-2021
additional_infiltration=(number_of_storeys_in_the_dwelling-1)*0.1
window_infiltration=0.25 - (0.2 * percentage_of_windows_and_doors_draught_proofed / 100.0)
infiltration_rate=(infiltration_due_to_chimneys_flues_fans_PSVs +
additional_infiltration +
structural_infiltration +
suspended_wooden_ground_floor_infiltration +
no_draft_lobby_infiltration +
window_infiltration
)
infiltration_rate2=infiltration_rate
else:
additional_infiltration=None
window_infiltration=None
infiltration_rate=None
infiltration_rate2=((air_permeability_value_q50 / 20) +
infiltration_due_to_chimneys_flues_fans_PSVs)
# shelter_factor
shelter_factor = 1 - (0.075 * number_of_sides_on_which_dwelling_is_sheltered)
# infiltration_rate_incorporating_shelter_factor
infiltration_rate_incorporating_shelter_factor = (infiltration_rate2 *
shelter_factor)
# wind_factor
wind_factor=[None]*12
for i in range(12):
wind_factor[i]=monthly_average_wind_speed[i] / 4.0
# adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed
adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed=[None]*12
for i in range(12):
adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed[i] = (
infiltration_rate_incorporating_shelter_factor *
wind_factor[i]
)
# exhaust_air_heat_pump_air_change_rate_through_system
if applicable_case in ['balanced mechanical ventilation with heat recovery',
'balanced mechanical ventilation without heat recovery',
'whole house extract ventilation or positive input ventilation from outside']:
if exhaust_air_heat_pump_using_Appendix_N:
exhaust_air_heat_pump_air_change_rate_through_system = (
mechanical_ventilation_air_change_rate_through_system *
mechanical_ventilation_throughput_factor)
else:
exhaust_air_heat_pump_air_change_rate_through_system = \
mechanical_ventilation_air_change_rate_through_system
else:
exhaust_air_heat_pump_air_change_rate_through_system = None
# effective_air_change_rate
effective_air_change_rate=[None]*12
if applicable_case=='balanced mechanical ventilation with heat recovery':
for i in range(12):
effective_air_change_rate[i]=(
adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed[i] +
exhaust_air_heat_pump_air_change_rate_through_system *
(1.0 - efficiency_allowing_for_in_use_factor / 100.0)
)
elif applicable_case=='balanced mechanical ventilation without heat recovery':
for i in range(12):
effective_air_change_rate[i]=(
adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed[i] +
exhaust_air_heat_pump_air_change_rate_through_system)
elif applicable_case=='whole house extract ventilation or positive input ventilation from outside':
for i in range(12):
if (adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed[i]
< 0.5 * exhaust_air_heat_pump_air_change_rate_through_system):
effective_air_change_rate[i]=exhaust_air_heat_pump_air_change_rate_through_system
else:
effective_air_change_rate[i]=(
adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed[i] +
0.5 * exhaust_air_heat_pump_air_change_rate_through_system)
elif applicable_case=='natural ventilation or whole house positive input ventilation from loft':
for i in range(12):
if adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed[i]>1:
effective_air_change_rate[i]=adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed[i]
else:
effective_air_change_rate[i]=0.5 + (adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed[i]**2 * 0.5)
return dict(
number_of_chimneys_total=number_of_chimneys_total,
number_of_chimneys_m3_per_hour=number_of_chimneys_m3_per_hour,
number_of_open_flues_total=number_of_open_flues_total,
number_of_open_flues_m3_per_hour=number_of_open_flues_m3_per_hour,
number_of_intermittant_fans_m3_per_hour=number_of_intermittant_fans_m3_per_hour,
number_of_passive_vents_m3_per_hour=number_of_passive_vents_m3_per_hour,
number_of_flueless_gas_fires_m3_per_hour=number_of_flueless_gas_fires_m3_per_hour,
infiltration_due_to_chimneys_flues_fans_PSVs=infiltration_due_to_chimneys_flues_fans_PSVs,
additional_infiltration=additional_infiltration,
window_infiltration=window_infiltration,
infiltration_rate=infiltration_rate,
infiltration_rate2=infiltration_rate2,
shelter_factor=shelter_factor,
infiltration_rate_incorporating_shelter_factor=infiltration_rate_incorporating_shelter_factor,
wind_factor=wind_factor,
adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed=adjusted_infiltration_rate_allowing_for_shelter_and_wind_speed,
exhaust_air_heat_pump_air_change_rate_through_system=exhaust_air_heat_pump_air_change_rate_through_system,
effective_air_change_rate=effective_air_change_rate
) |
# -*- coding: utf-8 -*-
class ProxyMiddleware(object):
def __init__(self, proxy_url):
self.proxy_url = proxy_url
def process_request(self, request, spider):
request.meta['proxy'] = self.proxy_url
@classmethod
def from_crawler(cls, crawler):
return cls(
proxy_url=crawler.settings.get('PROXY_URL')
)
|
if 5 == 2:
print("aaaa")
print("sjjdjdd")
else :
print("else")
|
n = int(input())
print('*' * (2*n+1))
print('.' + '*' + ' ' * (2*n - 3) + '*' + '.')
for i in range(1, n-1):
print('.' + '.' * i + '*' + '@' * ((2*n-3) -2*i) + '*' + '.' * i + '.')
print('.' * n +'*' + '.' * n)
for i in range(1, n-1):
print('.' * ((n)-i) + '*' + ' ' * (i-1) + '@' + ' ' * (i-1) + '*' + '.' * ((n)-i))
print('.' + '*' + '@' * (2*n-3) + '*' + '.')
print('*' * (2*n+1)) |
""" 03 - Crie um script Python que leia dois números e tente mostrar a soma entre eles."""
print('=' * 6, ' DESAFIO 03 - SOMANDO DOIS NÚMEROS ', '=' * 6)
print('\n*** MODO QUE VAI DAR RUIM ***')
n1 = input('Digite um número: ')
n2 = input('Digite mais um número: ')
s = n1 + n2
print(f'A soma entre {n1} e {n2} é {s}.')
print('\n*** MODO QUE VAI DAR BOM ***')
n3 = int(input('Digite um número: '))
n4 = int(input('Digite mais um número: '))
s = n3 + n4
print(f'A soma entre {n3} e {n4} é {s}.')
|
class Enum:
def __init__(self,list):
self.list = list
def enume(self):
for index, val in enumerate(self.list,start=1):
print(index,val)
e1 = Enum([5,15,45,4,53])
e1.enume() |
# -*- coding: utf-8 -*-
# Copyright 2016 CloudFlare, Inc. All rights reserved.
#
# The contents of this file are 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.
"""
Defines pyPluribus specific exceptions.
"""
class TimeoutError(Exception):
"""Raised in case of exceeded runtime for a command."""
pass
class CommandExecutionError(Exception):
"""Raised in case the output cannot be retrieved."""
pass
class ConnectionError(Exception):
"""Raised when the connection with the pluribus device cannot be open."""
pass
class ConfigLoadError(Exception):
"""Raised when not able to upload configuration on the device"""
pass
class ConfigurationDiscardError(Exception):
"""Raised when not possible to discard a candidate configuration"""
pass
class MergeConfigError(Exception):
"""Raised when not able to merge the config"""
pass
class ReplaceConfigError(Exception):
"""Raised when not able to replace the config"""
pass
class RollbackError(Exception):
"""Raised in case of rollback failure."""
pass
|
"""Module defining linked list."""
class LinkedList(object):
"""Classic linked list data structure."""
def __init__(self, iterable=None):
"""Initialize LinkedList instance."""
self.head = None
self._length = 0
try:
for el in iterable:
self.push(el)
except TypeError:
self.head = iterable
def push(self, val):
"""Insert val at the head of linked list."""
self.head = Node(val, self.head)
self._length += 1
def pop(self):
"""Pop the first value off of the head and return it."""
if self.head is None:
raise IndexError("Cannot pop from an empty linked list.")
first = self.head.val
self.head = self.head.next
self._length -= 1
return first
def size(self):
"""Return length of linked list."""
return self._length
def search(self, val):
"""Will return the node from the list if present, otherwise none."""
search = self.head
while search:
if search.val == val:
return search
search = search.next
return None
def remove(self, node):
"""Remove a node from linked list."""
prev = None
curr = self.head
while curr:
if curr is node:
if prev:
prev.next = curr.next
else:
self.head = curr.next
self._length -= 1
prev = curr
curr = curr.next
def display(self):
"""Display linked list in tuple literal form."""
res = "("
curr = self.head
while curr:
val = curr.val
if type(val) is str:
val = "'" + val + "'"
else:
val = str(val)
res += val
if curr.next:
res += ', '
curr = curr.next
return res + ')'
def __len__(self):
"""Return length of linked_list."""
return self.size()
class Node(object):
"""Node class."""
def __init__(self, val, next=None):
"""Initialize Node instance."""
self.val = val
self.next = next
|
class UserState(object):
def __init__(self, user_id):
self.user_id = user_id
self.conversation_context = {}
self.conversation_started = False
self.user = None
self.ingredient_cuisine = None
self.recipe = None
|
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
cur = 1
k -= 1
while k > 0:
step, first, last = 0, cur, cur + 1
while first <= n:
step += min(last, n + 1) - first
first *= 10
last *= 10
if k >= step:
k -= step
cur += 1
else:
cur *= 10
k -= 1
return cur
|
mylines = []
with open('resume.txt', 'rt') as myfile:
for myline in myfile:
mylines.append(myline)
print("Name: ", end="")
for c in mylines[0]:
if c == "|":
break;
else:
print(c, end="")
|
"""
https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
"""
# time complexity: O(n), space complexity: O(1)
# I didn't come up with this solution. This is inspired by @yuyibestman in the discussion area.
# In the Wikipedia, it says this method actually came from Narayana Pandita in 14th century India. The method is:
# 1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
# 2. Find the largest index l greater than k such that a[k] < a[l].
# 3. Swap the value of a[k] with that of a[l].
# 4. Reverse the sequence from a[k + 1] up to and including the final element a[n].
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) <= 1:
return
# a decending ordered list cannot be larger, so we need to find the first ascending order pair.
# the only way to make a number larger is to make a small number larger, to do this, we have to find a digit that can be larger
# to make the result smallest, we should search from the right.
pos = None
for i in range(len(nums)-2, -1, -1):
if nums[i] < nums[i+1]:
pos = i
break
if pos is None:
nums.reverse()
return
# now we need to make the nums[pos] larger, but we cannot just find a larger number and replace nums[pos] by it because we need to make the result as small as possible. So we need to find the number that is larger than nums[pos] but it's the smallest on the right of nums[pos]
for i in range(len(nums)-1, pos, -1):
if nums[i] > nums[pos]:
nums[pos], nums[i] = nums[i], nums[pos]
break
# now we have make the number larger but the problem is that this is not the smallest result
# because the number to the right of nums[pos] is a decending ordered list. We have to make it a ascending ordered list to make it smallest possible result
i = pos + 1
j = len(nums) - 1
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
|
""" examples package.
Author:
- 2020-2021 Nicola Creati
- 2020-2021 Roberto Vidmar
Copyright:
2020-2021 Nicola Creati <ncreati@inogs.it>
2020-2021 Roberto Vidmar <rvidmar@inogs.it>
License:
MIT/X11 License (see
:download:`license.txt <../../../license.txt>`)
"""
|
class Interaction:
current_os = -1
logger = None
def __init__(self, current_os, logger):
self.current_os = current_os
self.logger = logger
def print_info(self):
self.logger.raw("This is interaction with Maya")
# framework interactions
def schema_item_double_click(self, param):
self.logger.raw(("Double click on schema item", param)) |
class GameObject:
# this is a generic object: the player, a monster, an item, the stairs...
# it's always represented by a character on screen.
def __init__(self, x, y, char, color):
self.x = x
self.y = y
self.char = char
self.color = color
def move(self, dx, dy, tile_map):
# move by the given amount, IFF the tile is not blocked
tile = tile_map[self.x + dx][self.y + dy]
if not tile.blocked:
self.x += dx
self.y += dy
def draw(self, console, visible_tiles, bg=None):
# draw the character that represents this object at its position
if visible_tiles is None or (self.x, self.y) in visible_tiles:
console.draw_char(self.x, self.y, self.char, self.color, bg=bg)
def clear(self, console, bg=None):
# erase the character that represents this object
console.draw_char(self.x, self.y, ' ', self.color, bg=bg)
|
dados = {'nome':'Pedro', 'idade':25}
dados['sexo'] = 'M'
print(dados.values())
print(dados.keys())
print('-=' * 30)
for k, v in dados.items():
print(f'O {k} é {v}') |
# coding:utf-8
'''
Created on 2013-11-27
@author: tong
'''
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
# 制作一个顺序编码, lastno 上一位, prestr 前缀, dig 编码位数
def makecode(lastno,prestr,dig):
if lastno:
maxno=lastno
else:
maxno='0'
codenum = prestr+str(int(maxno.lstrip(prestr))+1).zfill(dig-len(prestr))
return codenum
|
class Institution(object):
institution_name = None
website = None
industry = None
type = None
headquarters = None
company_size = None
founded = None
def __init__(self, name=None, website=None, industry=None, type=None, headquarters=None, company_size=None, founded=None):
self.name = name
self.website = website
self.industry = industry
self.type = type
self.headquarters = headquarters
self.company_size = company_size
self.founded = founded
class Experience(Institution):
from_date = None
to_date = None
description = None
position_title = None
duration = None
def __init__(self, from_date = None, to_date = None, description = None, position_title = None, duration = None, location = None):
self.from_date = from_date
self.to_date = to_date
self.description = description
self.position_title = position_title
self.duration = duration
self.location = location
def __repr__(self):
return "{position_title} at {company} from {from_date} to {to_date} for {duration} based at {location}".format( from_date = self.from_date, to_date = self.to_date, position_title = self.position_title, company = self.institution_name, duration = self.duration, location = self.location)
def __str__(self):
return "{company}, {location}\n {position_title}\n{from_date} - {to_date}".format( from_date = self.from_date, to_date = self.to_date, position_title = ('\n').join(self.position_title), company = self.institution_name, location = list(set(self.location)))
class Education(Institution):
from_date = None
to_date = None
description = None
degree = None
def __init__(self, from_date = None, to_date = None, description = None, degree = None):
self.from_date = from_date
self.to_date = to_date
self.description = description
self.degree = degree
def __repr__(self):
return "{degree} at {company} from {from_date} to {to_date}".format( from_date = self.from_date, to_date = self.to_date, degree = self.degree, company = self.institution_name)
def __str__(self):
return "{company}, {degree}\n{from_date} - {to_date}".format( from_date = self.from_date[-2:], to_date = self.to_date[-2:], degree = self.degree, company = self.institution_name)
class Scraper(object):
driver = None
def is_signed_in(self):
try:
self.driver.find_element_by_id("profile-nav-item")
return True
except:
pass
return False
def __find_element_by_class_name__(self, class_name):
try:
self.driver.find_element_by_class_name(class_name)
return True
except:
pass
return False
|
numero = int(input('Escreva um número inteiro: '))
i = 1
print('-' * 15)
print('Tabuada de', numero)
print('-' * 15)
while i < 11:
resultado = numero * i
print('{} * {} = {}'.format(numero, i, resultado))
i = i + 1
|
class Num2WordsAr(object):
def __init__(self) -> None:
super().__init__()
self.table_scales = ["", "ألف", "مليون", "مليار", "ترليون", "كوادرليون", "كوينتليون", "سكستليون"]
self.table_scales_p = ["", "آلاف", "ملايين", "مليارات"]
self.table_female = ["", "واحدة", "اثنتان", "ثلاثة", "أربعة", "خمسة", "ستة", "سبعة", "ثمانية", "تسعة", "عشرة"]
self.table_male = ["", "واحد", "اثنان", "ثلاث", "أربع", "خمس", "ست", "سبع", "ثمان", "تسع", "عشر"]
self.zero = "صفر"
self.on = "on"
self.sp_wa = " و"
self.tanween_letter = "ًا"
self.ahad = "أحد"
self.ehda = "إحدى"
self.indic_num_map = {"۰": "٠", "۱": "١", "۲": "٢", "۳": "٣", "۴": "٤", "۵": "٥", "۶": "٦", "۷": "٧", "۸": "٨",
"۹": "٩"}
def convert(self, num: int,
feminine: bool = False,
comma: bool = False,
split_hundred: bool = False,
miah: bool = False,
billions: bool = False,
text_to_follow: bool = False,
ag: bool = False,
subject: list = None,
legal: bool = False,
):
if num == 0:
return self.zero # if 0 or "0" then "zero"
triplet = ""
scale = ""
scale_pos = ""
scale_plural = ""
table_units = ""
table_11_19 = ""
number_in_words = ""
# // ---- Setup constants for the AG Option (Accusative / Genitive or Nominative case Grammar)
taa = "تا" if ag else "تي"
taan = "تان" if ag else "تين"
aa = "ا" if ag else "ي"
aan = "ان" if ag else "ين"
ethna = "اثنا" if ag else "اثني"
ethnan = "اثنان" if ag else "اثنين"
ethnata = "اثنتا" if ag else "اثنتي"
ethnatan = "اثنتان" if ag else "اثنتين"
woon = "ون" if ag else "ين"
is_subject = True if subject and len(subject) == 4 else False
if is_subject:
text_to_follow = True
num_str = str(num)
for ind, arb in self.indic_num_map.items():
num_str = num_str.replace(ind, arb)
miah = "مائة" if miah else "مئة"
table_units = self.table_male.copy()
table_11_19 = self.table_male.copy()
table_11_19[0] = self.table_female[10]
table_11_19[1] = self.ahad
table_11_19[2] = ethna
table_units[2] = ethnan
prefix_zeros = ""
for i in range(len(num_str) * 2 % 3):
prefix_zeros = prefix_zeros + "0"
num_str = prefix_zeros + num_str
digits = len(num_str)
while digits > 0:
triplet = int(num_str[(len(num_str) - digits):3]) > 0
last_triplet = not (int(num_str[:((len(num_str) - digits) + 3)]) > 0)
if triplet:
scale_pos = (digits / 3) - 1
scale = self.table_scales[scale_pos]
scale_plural = self.table_scales_p[scale_pos] if scale_pos < 4 else self.table_scales_p[
scale_pos] + "ات"
if billions:
scale = "بليون"
scale_plural = "بلايين"
number_in_words = number_in_words + self.one_triplet_to_words()
if not last_triplet:
number_in_words = number_in_words + "،" if comma else self.sp_wa
digits = digits - 3
def one_triplet_to_words(self):
return ""
n2w = Num2WordsAr()
n2w.convert(20)
|
class NoSuchPointError(ValueError):
pass
class Point(tuple):
"""
A point on an elliptic curve. This is a subclass of tuple (forced to a 2-tuple),
and also includes a reference to the underlying Curve.
"""
def __new__(self, x, y, curve):
return tuple.__new__(self, (x, y))
def __init__(self, x, y, curve):
self._curve = curve
super(Point, self).__init__()
self.check_on_curve()
def check_on_curve(self):
"""raise NoSuchPointError (which is a ValueError) if the point is not actually on the curve."""
if not self._curve.contains_point(*self):
raise NoSuchPointError('({},{}) is not on the curve {}'.format(self[0], self[1], self._curve))
def __add__(self, other):
"""Add one point to another point."""
return self._curve.add(self, other)
def __sub__(self, other):
"""Subtract one point from another point."""
return self._curve.add(self, -other)
def __mul__(self, e):
"""Multiply a point by an integer."""
return self._curve.multiply(self, e)
def __rmul__(self, other):
"""Multiply a point by an integer."""
return self * other
def __neg__(self):
"""Unary negation"""
return self.__class__(self[0], self._curve.p()-self[1], self._curve)
def curve(self):
"""The curve this point is on."""
return self._curve
|
#!/usr/bin/env python3
def insertion_sort(lst): #times
for i in range(1,len(lst)): #n - 1
while i > 0 and lst[i-1] > lst[i]: #(n - 1)n
lst[i], lst[i-1] = lst[i-1], lst[i] #(n - 1)n/2
i -= 1 #1
return lst
print(insertion_sort([6, 4, 3, 8, 5])) |
"""
sp_tool package
Sub-Packages are
* sharepoint - the core library
* tool - the frontend tool
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.