content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
#!/usr/local/bin/python
##/usr/bin/env python
import sys
#XXX hack
if __name__ == "__main__":
outputString = "invert:\n%s\n" % ( obfs(sys.argv[1])[0] )
#print( outputString )
| [
2,
48443,
14629,
14,
12001,
14,
8800,
14,
29412,
198,
2235,
14,
14629,
14,
8800,
14,
24330,
21015,
198,
198,
11748,
25064,
198,
198,
2,
43145,
8156,
628,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
2... | 2.130435 | 92 |
from flask_restful import Resource
from service import UserSocialService
from flask_jwt_extended import get_jwt_identity, jwt_required
| [
6738,
42903,
62,
2118,
913,
1330,
20857,
198,
6738,
2139,
1330,
11787,
20636,
16177,
198,
6738,
42903,
62,
73,
46569,
62,
2302,
1631,
1330,
651,
62,
73,
46569,
62,
738,
414,
11,
474,
46569,
62,
35827,
628
] | 3.675676 | 37 |
import json
# https://www.akershus.no/ansvarsomrader/opplering/akershusoppleringen/visma-inschool/
TARGET_FILE = "schools.json"
schoolString = """
<option value="https://asker-vgs.inschool.visma.no">Asker videregående skole</option>
<option value="https://bjertnes-vgs.inschool.visma.no">Bjertnes videregående skole</option>
<option value="https://bjorkelangen-vgs.inschool.visma.no">Bjørkelangen videregående skole</option>
<option value="https://bleiker-vgs.inschool.visma.no">Bleiker videregående skole</option>
<option value="https://dromtorp-vgs.inschool.visma.no">Drømtorp videregående skole</option>
<option value="https://donski-vgs.inschool.visma.no">Dønski videregående skole</option>
<option value="https://eidsvoll.inschool.visma.no">Eidsvoll videregående skole</option>
<option value="https://eikeli-vgs.inschool.visma.no">Eikeli videregående skole</option>
<option value="https://frogn-vgs.inschool.visma.no">Frogn videregående skole</option>
<option value="https://holmen-vgs.inschool.visma.no">Holmen videregående skole</option>
<option value="https://hvam-vgs.inschool.visma.no">Hvam videregående skole</option>
<option value="https://jessheim-vgs.inschool.visma.no">Jessheim videregående skole</option>
<option value="https://kjelle-vgs.inschool.visma.no">Kjelle videregående skole</option>
<option value="https://lillestrom-vgs.inschool.visma.no">Lillestrøm videregående skole</option>
<option value="https://lorenskog-vgs.inschool.visma.no">Lørenskog videregående skole</option>
<option value="https://mailand.inschool.visma.no">Mailand videregående skole</option>
<option value="https://nadderud-vgs.inschool.visma.no">Nadderud videregående skole</option>
<option value="https://nannestad-vgs.inschool.visma.no">Nannestad videregående skole</option>
<option value="https://nes-vgs.inschool.visma.no">Nes videregående skole</option>
<option value="https://nesbru-vgs.inschool.visma.no">Nesbru videregående skole</option>
<option value="https://nesodden-vgs.inschool.visma.no">Nesodden videregående skole</option>
<option value="https://roaldamundsen-vgs.inschool.visma.no">Roald Amundsen videregående skole</option>
<option value="https://rosenvilde-vgs.inschool.visma.no">Rosenvilde videregående skole</option>
<option value="https://rud-vgs.inschool.visma.no">Rud videregående skole</option>
<option value="https://raelingen-vgs.inschool.visma.no">Rælingen videregående skole</option>
<option value="https://sandvika-vgs.inschool.visma.no">Sandvika videregående skole</option>
<option value="https://skedsmo-vgs.inschool.visma.no">Skedsmo videregående skole</option>
<option value="https://ski-vgs.inschool.visma.no">Ski videregående skole</option>
<option value="https://solberg.inschool.visma.no">Solberg videregående skole</option>
<option value="https://stabekk-vgs.inschool.visma.no">Stabekk videregående skole</option>
<option value="https://strommen-vgs.inschool.visma.no">Strømmen videregående skole</option>
<option value="https://sorumsand-vgs.inschool.visma.no">Sørumsand videregående skole</option>
<option value="https://valler-vgs.inschool.visma.no">Valler videregående skole</option>
<option value="https://vestby-vgs.inschool.visma.no">Vestby videregående skole</option>
<option value="https://aas-vgs.inschool.visma.no">Ås videregående skole</option>
<option value="https://akershus.inschool.visma.no">Akershus skoleeier</option>
"""
if __name__ == "__main__":
main()
| [
11748,
33918,
198,
198,
2,
3740,
1378,
2503,
13,
3979,
7537,
13,
3919,
14,
504,
85,
945,
296,
81,
5067,
14,
10365,
75,
1586,
14,
3979,
7537,
10365,
75,
1586,
268,
14,
85,
38017,
12,
1040,
1251,
14,
198,
198,
51,
46095,
62,
25664,
... | 2.635031 | 1,296 |
from random import shuffle
aluno1 = str(input('Primeiro aluno: '))
aluno2 = str(input('Segundo aluno: '))
aluno3 = str(input('Terceiro aluno: '))
aluno4 = str(input('Quarto aluno: '))
lista = [aluno1, aluno2, aluno3, aluno4]
shuffle(lista)
print(f'A ordem de apresentação será{lista}') | [
6738,
4738,
1330,
36273,
198,
282,
36909,
16,
796,
965,
7,
15414,
10786,
26405,
7058,
435,
36909,
25,
705,
4008,
198,
282,
36909,
17,
796,
965,
7,
15414,
10786,
41030,
41204,
435,
36909,
25,
705,
4008,
198,
282,
36909,
18,
796,
965,
... | 2.394958 | 119 |
# Generated by Django 3.1.9 on 2021-05-12 05:36
from django.db import migrations
| [
2,
2980,
515,
416,
37770,
513,
13,
16,
13,
24,
319,
33448,
12,
2713,
12,
1065,
8870,
25,
2623,
198,
198,
6738,
42625,
14208,
13,
9945,
1330,
15720,
602,
628
] | 2.766667 | 30 |
import binascii
from eth_utils import int_to_big_endian
from rlp.utils import ALL_BYTES
from trie.constants import NIBBLE_TERMINATOR, hex_to_int, TT256
def encode_int(v):
"""encodes an integer into serialization"""
if not isinstance(v, int) or v < 0 or v >= TT256:
raise Exception("Integer invalid or out of range: %r" % v)
return int_to_big_endian(v)
def bin_to_nibbles(s):
"""convert string s to nibbles (half-bytes)
>>> bin_to_nibbles("")
[]
>>> bin_to_nibbles("h")
[6, 8]
>>> bin_to_nibbles("he")
[6, 8, 6, 5]
>>> bin_to_nibbles("hello")
[6, 8, 6, 5, 6, 12, 6, 12, 6, 15]
"""
return [hex_to_int[c] for c in encode_hex(s)]
def pack_nibbles(nibbles):
"""pack nibbles to binary
:param nibbles: a nibbles sequence. may have a terminator
"""
"""
hex char bits | node type partial path length
----------------------------------------------------------
0 0000 | extension even
1 0001 | extension odd
2 0010 | terminating (leaf) even
3 0011 | terminating (leaf) odd
"""
if nibbles[-1] == NIBBLE_TERMINATOR:
flags = 2
nibbles = nibbles[:-1]
else:
flags = 0
oddlen = len(nibbles) % 2
flags |= oddlen # set lowest bit if odd number of nibbles
if oddlen:
nibbles = [flags] + nibbles
else:
nibbles = [flags, 0] + nibbles
o = b''
for i in range(0, len(nibbles), 2):
o += ascii_chr(16 * nibbles[i] + nibbles[i + 1])
return o
def unpack_to_nibbles(bindata):
"""unpack packed binary data to nibbles
:param bindata: binary packed from nibbles
:return: nibbles sequence, may have a terminator
"""
o = bin_to_nibbles(bindata)
flags = o[0]
if flags & 2:
o.append(NIBBLE_TERMINATOR)
if flags & 1 == 1:
o = o[1:]
else:
o = o[2:]
return o
def starts_with(full, part) -> bool:
""" return True if part is prefix of full
"""
if len(full) < len(part):
return False
return full[:len(part)] == part
def zpad(x, l):
""" Left zero pad value `x` at least to length `l`.
>>> zpad('', 1)
'\x00'
>>> zpad('\xca\xfe', 4)
'\x00\x00\xca\xfe'
>>> zpad('\xff', 1)
'\xff'
>>> zpad('\xca\xfe', 2)
'\xca\xfe'
"""
return b'\x00' * max(0, l - len(x)) + x | [
11748,
9874,
292,
979,
72,
198,
198,
6738,
4555,
62,
26791,
1330,
493,
62,
1462,
62,
14261,
62,
437,
666,
198,
6738,
374,
34431,
13,
26791,
1330,
11096,
62,
17513,
51,
1546,
198,
198,
6738,
1333,
68,
13,
9979,
1187,
1330,
399,
9865,... | 2.080165 | 1,210 |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Officexlr Business Solutions Pvt Ltd. and Contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
import jwt, json, time
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
15069,
357,
66,
8,
13130,
11,
4452,
87,
14050,
7320,
23555,
18367,
83,
12052,
13,
290,
25767,
669,
198,
2,
1114,
5964,
1321,
11,
3387,
766,
5964,
13,
14116,
198,
... | 3.443038 | 79 |
from cx_Freeze import setup, Executable
executables = [
Executable(
'manageservice/manage-service.py',
base = None,
targetName = 'manage-service'
)
]
setup(
name='Manage Service',
version = '1.0.0',
description = 'A python service that can be used to pull a master branch from GitHub and start it',
executables = executables
)
| [
6738,
43213,
62,
11146,
2736,
1330,
9058,
11,
8393,
18187,
628,
198,
18558,
315,
2977,
796,
685,
198,
220,
220,
220,
220,
220,
220,
220,
8393,
18187,
7,
198,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
705,
805,
1095,
7... | 2.287293 | 181 |
lang_code = {'aar': 'Afar',
'abk': 'Abkhaz',
'ace': 'Achinese',
'ach': 'Acoli',
'ada': 'Adangme',
'ady': 'Adygei',
'afa': 'Afroasiatic (Other)',
'afh': 'Afrihili (Artificial language)',
'afr': 'Afrikaans',
'ain': 'Ainu',
'ajm': 'Aljamía',
'aka': 'Akan',
'akk': 'Akkadian',
'alb': 'Albanian',
'ale': 'Aleut',
'alg': 'Algonquian (Other)',
'alt': 'Altai',
'amh': 'Amharic',
'ang': 'English, Old (ca. 450-1100)',
'anp': 'Angika',
'apa': 'Apache languages',
'ara': 'Arabic',
'arc': 'Aramaic',
'arg': 'Aragonese',
'arm': 'Armenian',
'arn': 'Mapuche',
'arp': 'Arapaho',
'art': 'Artificial (Other)',
'arw': 'Arawak',
'asm': 'Assamese',
'ast': 'Bable',
'ath': 'Athapascan (Other)',
'aus': 'Australian languages',
'ava': 'Avaric',
'ave': 'Avestan',
'awa': 'Awadhi',
'aym': 'Aymara',
'aze': 'Azerbaijani',
'bad': 'Banda languages',
'bai': 'Bamileke languages',
'bak': 'Bashkir',
'bal': 'Baluchi',
'bam': 'Bambara',
'ban': 'Balinese',
'baq': 'Basque',
'bas': 'Basa',
'bat': 'Baltic (Other)',
'bej': 'Beja',
'bel': 'Belarusian',
'bem': 'Bemba',
'ben': 'Bengali',
'ber': 'Berber (Other)',
'bho': 'Bhojpuri',
'bih': 'Bihari (Other)',
'bik': 'Bikol',
'bin': 'Edo',
'bis': 'Bislama',
'bla': 'Siksika',
'bnt': 'Bantu (Other)',
'bos': 'Bosnian',
'bra': 'Braj',
'bre': 'Breton',
'btk': 'Batak',
'bua': 'Buriat',
'bug': 'Bugis',
'bul': 'Bulgarian',
'bur': 'Burmese',
'byn': 'Bilin',
'cad': 'Caddo',
'cai': 'Central American Indian (Other)',
'cam': 'Khmer',
'car': 'Carib',
'cat': 'Catalan',
'cau': 'Caucasian (Other)',
'ceb': 'Cebuano',
'cel': 'Celtic (Other)',
'cha': 'Chamorro',
'chb': 'Chibcha',
'che': 'Chechen',
'chg': 'Chagatai',
'chi': 'Chinese',
'chk': 'Chuukese',
'chm': 'Mari',
'chn': 'Chinook jargon',
'cho': 'Choctaw',
'chp': 'Chipewyan',
'chr': 'Cherokee',
'chu': 'Church Slavic',
'chv': 'Chuvash',
'chy': 'Cheyenne',
'cmc': 'Chamic languages',
'cop': 'Coptic',
'cor': 'Cornish',
'cos': 'Corsican',
'cpe': 'Creoles and Pidgins, English-based (Other)',
'cpf': 'Creoles and Pidgins, French-based (Other)',
'cpp': 'Creoles and Pidgins, Portuguese-based (Other)',
'cre': 'Cree',
'crh': 'Crimean Tatar',
'crp': 'Creoles and Pidgins (Other)',
'csb': 'Kashubian',
'cus': 'Cushitic (Other)',
'cze': 'Czech',
'dak': 'Dakota',
'dan': 'Danish',
'dar': 'Dargwa',
'day': 'Dayak',
'del': 'Delaware',
'den': 'Slavey',
'dgr': 'Dogrib',
'din': 'Dinka',
'div': 'Divehi',
'doi': 'Dogri',
'dra': 'Dravidian (Other)',
'dsb': 'Lower Sorbian',
'dua': 'Duala',
'dum': 'Dutch, Middle (ca. 1050-1350)',
'dut': 'Dutch',
'dyu': 'Dyula',
'dzo': 'Dzongkha',
'efi': 'Efik',
'egy': 'Egyptian',
'eka': 'Ekajuk',
'elx': 'Elamite',
'eng': 'English',
'enm': 'English, Middle (1100-1500)',
'epo': 'Esperanto',
'esk': 'Eskimo languages',
'esp': 'Esperanto',
'est': 'Estonian',
'eth': 'Ethiopic',
'ewe': 'Ewe',
'ewo': 'Ewondo',
'fan': 'Fang',
'fao': 'Faroese',
'far': 'Faroese',
'fat': 'Fanti',
'fij': 'Fijian',
'fil': 'Filipino',
'fin': 'Finnish',
'fiu': 'Finno-Ugrian (Other)',
'fon': 'Fon',
'fre': 'French',
'fri': 'Frisian',
'frm': 'French, Middle (ca. 1300-1600)',
'fro': 'French, Old (ca. 842-1300)',
'frr': 'North Frisian',
'frs': 'East Frisian',
'fry': 'Frisian',
'ful': 'Fula',
'fur': 'Friulian',
'gaa': 'Gã',
'gae': 'Scottish Gaelix',
'gag': 'Galician',
'gal': 'Oromo',
'gay': 'Gayo',
'gba': 'Gbaya',
'gem': 'Germanic (Other)',
'geo': 'Georgian',
'ger': 'German',
'gez': 'Ethiopic',
'gil': 'Gilbertese',
'gla': 'Scottish Gaelic',
'gle': 'Irish',
'glg': 'Galician',
'glv': 'Manx',
'gmh': 'German, Middle High (ca. 1050-1500)',
'goh': 'German, Old High (ca. 750-1050)',
'gon': 'Gondi',
'gor': 'Gorontalo',
'got': 'Gothic',
'grb': 'Grebo',
'grc': 'Greek, Ancient (to 1453)',
'gre': 'Greek, Modern (1453-)',
'grn': 'Guarani',
'gsw': 'Swiss German',
'gua': 'Guarani',
'guj': 'Gujarati',
'gwi': 'Gwich\'in',
'hai': 'Haida',
'hat': 'Haitian French Creole',
'hau': 'Hausa',
'haw': 'Hawaiian',
'heb': 'Hebrew',
'her': 'Herero',
'hil': 'Hiligaynon',
'him': 'Western Pahari languages',
'hin': 'Hindi',
'hit': 'Hittite',
'hmn': 'Hmong',
'hmo': 'Hiri Motu',
'hrv': 'Croatian',
'hsb': 'Upper Sorbian',
'hun': 'Hungarian',
'hup': 'Hupa',
'iba': 'Iban',
'ibo': 'Igbo',
'ice': 'Icelandic',
'ido': 'Ido',
'iii': 'Sichuan Yi',
'ijo': 'Ijo',
'iku': 'Inuktitut',
'ile': 'Interlingue',
'ilo': 'Iloko',
'ina': 'Interlingua (International Auxiliary Language Association)',
'inc': 'Indic (Other)',
'ind': 'Indonesian',
'ine': 'Indo-European (Other)',
'inh': 'Ingush',
'int': 'Interlingua (International Auxiliary Language Association)',
'ipk': 'Inupiaq',
'ira': 'Iranian (Other)',
'iri': 'Irish',
'iro': 'Iroquoian (Other)',
'ita': 'Italian',
'jav': 'Javanese',
'jbo': 'Lojban (Artificial language)',
'jpn': 'Japanese',
'jpr': 'Judeo-Persian',
'jrb': 'Judeo-Arabic',
'kaa': 'Kara-Kalpak',
'kab': 'Kabyle',
'kac': 'Kachin',
'kal': 'Kalâtdlisut',
'kam': 'Kamba',
'kan': 'Kannada',
'kar': 'Karen languages',
'kas': 'Kashmiri',
'kau': 'Kanuri',
'kaw': 'Kawi',
'kaz': 'Kazakh',
'kbd': 'Kabardian',
'kha': 'Khasi',
'khi': 'Khoisan (Other)',
'khm': 'Khmer',
'kho': 'Khotanese',
'kik': 'Kikuyu',
'kin': 'Kinyarwanda',
'kir': 'Kyrgyz',
'kmb': 'Kimbundu',
'kok': 'Konkani',
'kom': 'Komi',
'kon': 'Kongo',
'kor': 'Korean',
'kos': 'Kosraean',
'kpe': 'Kpelle',
'krc': 'Karachay-Balkar',
'krl': 'Karelian',
'kro': 'Kru (Other)',
'kru': 'Kurukh',
'kua': 'Kuanyama',
'kum': 'Kumyk',
'kur': 'Kurdish',
'kus': 'Kusaie',
'kut': 'Kootenai',
'lad': 'Ladino',
'lah': 'Lahndā',
'lam': 'Lamba (Zambia and Congo)',
'lan': 'Occitan (post 1500)',
'lao': 'Lao',
'lap': 'Sami',
'lat': 'Latin',
'lav': 'Latvian',
'lez': 'Lezgian',
'lim': 'Limburgish',
'lin': 'Lingala',
'lit': 'Lithuanian',
'lol': 'Mongo-Nkundu',
'loz': 'Lozi',
'ltz': 'Luxembourgish',
'lua': 'Luba-Lulua',
'lub': 'Luba-Katanga',
'lug': 'Ganda',
'lui': 'Luiseño',
'lun': 'Lunda',
'luo': 'Luo (Kenya and Tanzania)',
'lus': 'Lushai',
'mac': 'Macedonian',
'mad': 'Madurese',
'mag': 'Magahi',
'mah': 'Marshallese',
'mai': 'Maithili',
'mak': 'Makasar',
'mal': 'Malayalam',
'man': 'Mandingo',
'mao': 'Maori',
'map': 'Austronesian (Other)',
'mar': 'Marathi',
'mas': 'Maasai',
'max': 'Manx',
'may': 'Malay',
'mdf': 'Moksha',
'mdr': 'Mandar',
'men': 'Mende',
'mga': 'Irish, Middle (ca. 1100-1550)',
'mic': 'Micmac',
'min': 'Minangkabau',
'mis': 'Miscellaneous languages',
'mkh': 'Mon-Khmer (Other)',
'mla': 'Malagasy',
'mlg': 'Malagasy',
'mlt': 'Maltese',
'mnc': 'Manchu',
'mni': 'Manipuri',
'mno': 'Manobo languages',
'moh': 'Mohawk',
'mol': 'Moldavian',
'mon': 'Mongolian',
'mos': 'Mooré',
'mul': 'Multiple languages',
'mun': 'Munda (Other)',
'mus': 'Creek',
'mwl': 'Mirandese',
'mwr': 'Marwari',
'myn': 'Mayan languages',
'myv': 'Erzya',
'nah': 'Nahuatl',
'nai': 'North American Indian (Other)',
'nap': 'Neapolitan Italian',
'nau': 'Nauru',
'nav': 'Navajo',
'nbl': 'Ndebele (South Africa)',
'nde': 'Ndebele (Zimbabwe)',
'ndo': 'Ndonga',
'nds': 'Low German',
'nep': 'Nepali',
'new': 'Newari',
'nia': 'Nias',
'nic': 'Niger-Kordofanian (Other)',
'niu': 'Niuean',
'nno': 'Norwegian (Nynorsk)',
'nob': 'Norwegian (Bokmål)',
'nog': 'Nogai',
'non': 'Old Norse',
'nor': 'Norwegian',
'nqo': 'N\'Ko',
'nso': 'Northern Sotho',
'nub': 'Nubian languages',
'nwc': 'Newari, Old',
'nya': 'Nyanja',
'nym': 'Nyamwezi',
'nyn': 'Nyankole',
'nyo': 'Nyoro',
'nzi': 'Nzima',
'oci': 'Occitan (post-1500)',
'oji': 'Ojibwa',
'ori': 'Oriya',
'orm': 'Oromo',
'osa': 'Osage',
'oss': 'Ossetic',
'ota': 'Turkish, Ottoman',
'oto': 'Otomian languages',
'paa': 'Papuan (Other)',
'pag': 'Pangasinan',
'pal': 'Pahlavi',
'pam': 'Pampanga',
'pan': 'Panjabi',
'pap': 'Papiamento',
'pau': 'Palauan',
'peo': 'Old Persian (ca. 600-400 B.C.)',
'per': 'Persian',
'phi': 'Philippine (Other)',
'phn': 'Phoenician',
'pli': 'Pali',
'pol': 'Polish',
'pon': 'Pohnpeian',
'por': 'Portuguese',
'pra': 'Prakrit languages',
'pro': 'Provençal (to 1500)',
'pus': 'Pushto',
'que': 'Quechua',
'raj': 'Rajasthani',
'rap': 'Rapanui',
'rar': 'Rarotongan',
'roa': 'Romance (Other)',
'roh': 'Raeto-Romance',
'rom': 'Romani',
'rum': 'Romanian',
'run': 'Rundi',
'rup': 'Aromanian',
'rus': 'Russian',
'sad': 'Sandawe',
'sag': 'Sango (Ubangi Creole)',
'sah': 'Yakut',
'sai': 'South American Indian (Other)',
'sal': 'Salishan languages',
'sam': 'Samaritan Aramaic',
'san': 'Sanskrit',
'sao': 'Samoan',
'sas': 'Sasak',
'sat': 'Santali',
'scc': 'Serbian',
'scn': 'Sicilian Italian',
'sco': 'Scots',
'scr': 'Croatian',
'sel': 'Selkup',
'sem': 'Semitic (Other)',
'sga': 'Irish, Old (to 1100)',
'sgn': 'Sign languages',
'shn': 'Shan',
'sho': 'Shona',
'sid': 'Sidamo',
'sin': 'Sinhalese',
'sio': 'Siouan (Other)',
'sit': 'Sino-Tibetan (Other)',
'sla': 'Slavic (Other)',
'slo': 'Slovak',
'slv': 'Slovenian',
'sma': 'Southern Sami',
'sme': 'Northern Sami',
'smi': 'Sami',
'smj': 'Lule Sami',
'smn': 'Inari Sami',
'smo': 'Samoan',
'sms': 'Skolt Sami',
'sna': 'Shona',
'snd': 'Sindhi',
'snh': 'Sinhalese',
'snk': 'Soninke',
'sog': 'Sogdian',
'som': 'Somali',
'son': 'Songhai',
'sot': 'Sotho',
'spa': 'Spanish',
'srd': 'Sardinian',
'srn': 'Sranan',
'srp': 'Serbian',
'srr': 'Serer',
'ssa': 'Nilo-Saharan (Other)',
'sso': 'Sotho',
'ssw': 'Swazi',
'suk': 'Sukuma',
'sun': 'Sundanese',
'sus': 'Susu',
'sux': 'Sumerian',
'swa': 'Swahili',
'swe': 'Swedish',
'swz': 'Swazi',
'syc': 'Syriac',
'syr': 'Syriac, Modern',
'tag': 'Tagalog',
'tah': 'Tahitian',
'tai': 'Tai (Other)',
'taj': 'Tajik',
'tam': 'Tamil',
'tar': 'Tatar',
'tat': 'Tatar',
'tel': 'Telugu',
'tem': 'Temne',
'ter': 'Terena',
'tet': 'Tetum',
'tgk': 'Tajik',
'tgl': 'Tagalog',
'tha': 'Thai',
'tib': 'Tibetan',
'tig': 'Tigré',
'tir': 'Tigrinya',
'tiv': 'Tiv',
'tkl': 'Tokelauan',
'tlh': 'Klingon (Artificial language)',
'tli': 'Tlingit',
'tmh': 'Tamashek',
'tog': 'Tonga (Nyasa)',
'ton': 'Tongan',
'tpi': 'Tok Pisin',
'tru': 'Truk',
'tsi': 'Tsimshian',
'tsn': 'Tswana',
'tso': 'Tsonga',
'tsw': 'Tswana',
'tuk': 'Turkmen',
'tum': 'Tumbuka',
'tup': 'Tupi languages',
'tur': 'Turkish',
'tut': 'Altaic (Other)',
'tvl': 'Tuvaluan',
'twi': 'Twi',
'tyv': 'Tuvinian',
'udm': 'Udmurt',
'uga': 'Ugaritic',
'uig': 'Uighur',
'ukr': 'Ukrainian',
'umb': 'Umbundu',
'und': 'Undetermined',
'urd': 'Urdu',
'uzb': 'Uzbek',
'vai': 'Vai',
'ven': 'Venda',
'vie': 'Vietnamese',
'vol': 'Volapük',
'vot': 'Votic',
'wak': 'Wakashan languages',
'wal': 'Wolayta',
'war': 'Waray',
'was': 'Washoe',
'wel': 'Welsh',
'wen': 'Sorbian (Other)',
'wln': 'Walloon',
'wol': 'Wolof',
'xal': 'Oirat',
'xho': 'Xhosa',
'yao': 'Yao (Africa)',
'yap': 'Yapese',
'yid': 'Yiddish',
'yor': 'Yoruba',
'ypk': 'Yupik languages',
'zap': 'Zapotec',
'zbl': 'Blissymbolics',
'zen': 'Zenaga',
'zha': 'Zhuang',
'znd': 'Zande languages',
'zul': 'Zulu',
'zun': 'Zuni',
'zxx': None, # Omit 'No linguistic content'
'zza': 'Zaza',
' ': None,
'': None,
'|||': None,
'N/A': None
} | [
17204,
62,
8189,
796,
1391,
6,
64,
283,
10354,
705,
32,
16370,
3256,
198,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
705,
397,
74,
10354,
705,
4826,
14636,
1031,
3256,
198,
220,
220,
220,
220,
220,
220,
220,
220,
... | 1.514701 | 11,496 |
""" * endpoint: API endpoint relative path, when added to the base URL, creates the full path
* kind: type of record to be updated ('account' or 'visitor')
* group: type of Pendo attribute to be updated ('agent' or 'custom')
"""
# create and store {kind} for stream's url path
# build stream's endpoint for requests to Pendo
# build stream's url for requests to Pendo
| [
37811,
1635,
36123,
25,
7824,
36123,
3585,
3108,
11,
618,
2087,
284,
262,
2779,
10289,
11,
8075,
262,
1336,
3108,
198,
220,
220,
220,
1635,
1611,
25,
2099,
286,
1700,
284,
307,
6153,
19203,
23317,
6,
393,
705,
4703,
2072,
11537,
198,
... | 3.058824 | 136 |
__author__ = 'Jana Lasser'
__copyright__ = 'Copyright 2021, Patient Dynamics Simulation'
__credits__ = ['Jana Lasser', 'Ruggiero LoSardo','Michaela Kaleta']
__license__ = 'MIT'
__status__ = 'Dev'
# std imports
import warnings
from importlib import reload
from os.path import join
import argparse
# third party imports
import pandas as pd
import numpy as np
from scipy import sparse
# custom libraries
import Dynamics_Final as dyn
warnings.filterwarnings("ignore")
parser = argparse.ArgumentParser(description='Simulation of a primary care network '\
+ '\nCopyright (C) 2021 Jana Lasser & Ruggiero LoSardo & Michaela Kaleta')
parser.add_argument('-keep_dis','--keep_disconnected',type=int,\
help='Set 1 or 0 if initially disconnected doctors should be\n'+\
'kept in the simulation or excluded in the beginning.',\
default=1)
parser.add_argument('-sep','--separator',type=str,\
help='Separator used in the doctor .csv file',
default=',')
parser.add_argument('-src','--data_src',type=str,\
help='Path to the doctor information table and adjacency matrix.',
default='data')
parser.add_argument('-dst','--results_dst',type=str,\
help='Path to the directory in which results will be saved.',
default='results')
parser.add_argument('-iter','--number_of_iterations', type=int,\
help='Number of times every unique simulation configuration\n'+\
'will be run to gather statistics.',
default=100)
parser.add_argument('-shocks','--number_of_shocks', type=int,\
help="Number of times the system will be 'shocked', i.e. doctors\n"+\
"will be removed.",
default=5000)
parser.add_argument('-remove','--number_of_removed_doctors', type=int,\
help='Number of doctors that are removed in each shock.',
default=1)
parser.add_argument('-alpha','--teleport_probability', type=float,\
help='Probability of a patient to teleport to a random doctor\n'+\
'instead of going to the most likely doctor based on shared\n'+\
'patients, when displaced',
default=0.15)
parser.add_argument('-ms','--max_steps', type=int,\
help='Number of doctors a patient will visit after being\n'+\
'displaced to try and find a new doctor. After max_steps\n'+\
'is exceeded, the patient will give up and become "lost".',
default=10)
parser.add_argument('-th','--threshold', type=float,\
help='Threshold used for hour-based capacity calculation.',\
default=0.9)
parser.add_argument('-seed','--seed',type=str,\
help='Seed of the random number generator.',
default=None)
parser.add_argument('-max_dist','--max_distance',type=int,\
help='Maximal distance for patients to travel in the \n'+\
'network (in km).',
default=100)
parser.add_argument('-max_dist_trials','--max_distance_trials',type=int,\
help='Simulation trials to reach doc within maximal distance of patients.',
default=10)
parser.add_argument('-min_pats','--min_pats',type=int,\
help='Minimum number of shared patients in adjacency matrix, \n'+\
'otherwise entries are set to zero (filter weakest connections).',
default=2)
parser.add_argument('-covid_shock','--covid_shock',type=bool,\
help='Test larger shock with simultaneous removals.',
default=False)
parser.add_argument('-shock_size','--shock_size',type=int,\
help='Set shock size as percentage of physicians that is removed simultaneously.',
default=10)
parser.add_argument('-save_locations','--save_locations',type=bool,\
help='Save starting patient location and location \n'+\
'after x% of doctor removals.',
default=False)
parser.add_argument('-simadd','--simulation_information',type=str,\
help='String containing additional simulation information (parallelisation)\n'+\
'appended to the results file.',
default='')
# parse command line arguments supplied by the user
args = parser.parse_args()
data_src = args.data_src
results_dst = args.results_dst
sep = args.separator
iterations = args.number_of_iterations
shocks = args.number_of_shocks
N_remove = args.number_of_removed_doctors
alpha = args.teleport_probability
max_steps = args.max_steps
seed = args.seed
threshold = args.threshold
keep_dis = args.keep_disconnected
max_distance = args.max_distance
min_pats = args.min_pats
simadd = args.simulation_information
max_dist_trials = args.max_distance_trials
save_locs = args.save_locations
covid_shock = args.covid_shock
shock_size = args.shock_size
#seed = 42
# initialize random number generator
rng = np.random.default_rng(seed)
### list of all doctors to simulate over
doctors = list(['AM', 'KI', 'PSY', 'ORTR', 'URO', 'HNO', 'CH', 'NEU', 'RAD', 'DER', 'GGH', 'AU', 'IM'])
### pick patient type, capacity type and timeframe
ptype = 'total'
ctype = 'hour-based'
tf = 'quarterly'
network = 'Österreich'
if covid_shock == 1:
covid_shock = True
elif covid_shock == 0:
covid_shock = False
### lower num of iterations for covid shock
if covid_shock==True:
iterations = 10
### loop over all medical specialties
for doc in doctors:
# load doctor info file and define siminfo for result-filename
doc_file = 'doctor_info_bez={}_spec={}_ptype={}_ctype={}_tf={}_th={}.csv'\
.format(network, doc, ptype, ctype, tf, threshold)
siminfo = '{}_{}'.format(doc,'Final')
### define results DF to save into
results = pd.DataFrame(columns=['state','run', 'shock', 'avg_displacement',\
'N_lost_patients', 'free_capacity_state',\
'free_capacity_country','disconnected_capacity',\
'N_lost_patients_summed','N_lost_patients_state_summed',\
'avg_distance','incorrect_displacements'])
reload(dyn)
# load distance matrix between all docs that will never be changed
origin_distances = sparse.load_npz(join(data_src, 'DistanceMatrixDocs.npz'))
origin_distances = origin_distances.todense()
### initialize for checking covid shock
searching_pats = []
# number of times the simulation will be run to create statistics
for i in range(0, iterations):
# need to create docs and adj again for every iteration since
# these objects are modified by the simulation
docs, adj, disc_docs, dist_docs, patmat, patloc_state = dyn.DataSetup(doc_file, data_src, sep, keep_dis, max_distance, min_pats)
### total number of patients
totalNumOfPats = sum([d.NumOfPatients for d in docs])
### total number of docs in SIM + 10% of them
numofdocs = len(docs)
percdocs = np.round(numofdocs/100*10,0)
# number of times the system will be shocked in a single simulation
# set initial free/removed capacity to NaN, in case NW is disconnected
free_capacity_state = np.nan
free_capacity_country = np.nan
disc_capacity = np.nan
lost_pats_state = np.nan
if len(disc_docs)>0:
disc_capacity = np.sum([d.capacity - d.NumOfPatients for d in disc_docs])
lost_summed = 0 # can count lost patients overall, one value for country
for shock in range(0, shocks):
if len(docs)<=1:
print('# of displaced patients: ',lost_summed + docs[0].NumOfPatients)
break
### built-in covid-shock - remove 10% of docs simultaneously
if covid_shock == True:
N_remove = int(np.ceil(len(adj)*(0.01*shock_size)))
print(N_remove)
rem_indices = dyn.pick_doctors_to_remove(docs, N_remove, rng)
if len(rem_indices)==0:
break
### perform patient displacements and doctor removal
docs, adj, avg_displacement, lost, distance_mean, dist_docs, patmat, incorrect_summed, CS = \
dyn.equilibrate(docs,adj,dist_docs,rem_indices,alpha,max_steps,rng,shock,patmat,\
totalNumOfPats,lost_summed,origin_distances,max_distance,max_dist_trials,covid_shock)
lost_summed += lost ### update number of lost patients in country
### loop over states to get info in each to create results file
for st in np.arange(1,10,1):
free_capacity_state = np.sum([d.capacity - d.NumOfPatients for d in docs if d.state == st])
free_capacity_country = np.sum([d.capacity - d.NumOfPatients for d in docs])
lost_pats_state = len(patmat[(patloc_state[:,0]==st)&(patmat[:,1]==99999)])
results = results.append({'state':st,'run':i + 1,
'shock':shock + 1,
'avg_displacement':avg_displacement,
'N_lost_patients':lost,
'free_capacity_state':free_capacity_state,
'free_capacity_country':free_capacity_country,
'disconnected_capacity':disc_capacity,
'N_lost_patients_summed':lost_summed,
'N_lost_patients_state_summed':lost_pats_state,
'avg_distance':distance_mean,
'incorrect_displacements':incorrect_summed},
ignore_index = True)
### if patient locations should be saved up to some % of removed docs:
if (shock == percdocs) and (save_locs==True):
np.savetxt(join('locations', 'patient_locations_iter{}_shocks{}_remove{}_alpha{}_maxs{}_th{}_kd{}_maxdist{}_maxdisttrials{}_minpats{}_{}_itnr{}.csv'\
.format(iterations, shocks, N_remove, alpha, max_steps,
threshold, keep_dis, max_distance, max_dist_trials,
min_pats, doc, i)), patmat,delimiter = ',')
if covid_shock == True:
if len(CS) < max_steps:
CS = CS + list((np.zeros(max_steps-len(CS)).astype(int)))
searching_pats.append(CS)
print(CS)
break
print(doc, 'removed_docs:', shock, 'iter:', i, 'free_cap_country',
free_capacity_country,'disconnected_cap:', disc_capacity)
if covid_shock == False:
### save results for every medical specialty
results = results.reset_index(drop=True)
results.to_csv(join(results_dst, 'patient_dynamics_iter{}_shocks{}_remove{}_alpha{}_maxs{}_th{}_kd{}_maxdist{}_maxdisttrials{}_minpats{}_{}_{}.csv'\
.format(iterations, shocks, N_remove, alpha, max_steps,
threshold, keep_dis, max_distance, max_dist_trials,
min_pats, siminfo, simadd)), index=False)
elif covid_shock == True:
np.savetxt(join(results_dst,'searching_pats_{}_iter{}_shocksize{}.csv'.format(doc,iterations,shock_size)),searching_pats,delimiter=',')
results = results.reset_index(drop=True)
results.to_csv(join(results_dst, 'patient_dynamics_iter{}_shocks{}_remove{}_alpha{}_maxs{}_th{}_kd{}_maxdist{}_maxdisttrials{}_minpats{}_{}_{}_covidshock.csv'\
.format(iterations, shocks, N_remove, alpha, max_steps,
threshold, keep_dis, max_distance, max_dist_trials,
min_pats, siminfo, simadd)), index=False)
| [
834,
9800,
834,
796,
705,
41,
2271,
406,
24929,
6,
201,
198,
834,
22163,
4766,
834,
796,
705,
15269,
33448,
11,
35550,
33806,
41798,
6,
201,
198,
834,
66,
20696,
834,
796,
37250,
41,
2271,
406,
24929,
3256,
705,
49,
6837,
959,
78,
... | 2.049662 | 6,222 |
from .common_functions import * | [
6738,
764,
11321,
62,
12543,
2733,
1330,
1635
] | 3.875 | 8 |
import json
class Responses:
"""Class used to create the responses that will be sent through the http protocol"""
@staticmethod
def response(data: dict):
'''Create a ``json`` for http responses
Parameters
----------
data: dict
The data that will be sent
Returns
-------
response
A json response
'''
return json.dumps({
"data": {
** data
}
})
if __name__ == '__main__':
response = Responses()
print(response.ok_response({'test': 21}))
| [
11748,
33918,
628,
198,
4871,
20549,
274,
25,
628,
220,
220,
220,
37227,
9487,
973,
284,
2251,
262,
9109,
326,
481,
307,
1908,
832,
262,
2638,
8435,
37811,
628,
220,
220,
220,
2488,
12708,
24396,
198,
220,
220,
220,
825,
2882,
7,
78... | 2.211679 | 274 |
"""
Python 3
Script to dump CloudFormation templates
aws configure
configure your AWS credentials
you should have permission for listing and downloading CloudFormation stacks
"""
import os
import boto3
import requests
import yaml
import shutil
from cfn_flip import to_json
if __name__ == "__main__":
print("CloudFormationDumper: Script for dumping CloudFormation templates - Ajin Abraham")
out_dir = './cf_templates/'
if not os.path.exists(out_dir):
os.makedirs(out_dir)
else:
shutil.rmtree(out_dir)
os.makedirs(out_dir)
cfnd = CFNDumper(out_dir)
cfnd.get_cfns()
cfnd.get_templates()
print(f'[INFO] Finished Dumping CloudFormation templates to {out_dir}')
| [
37811,
198,
37906,
513,
198,
7391,
284,
10285,
10130,
8479,
341,
24019,
198,
8356,
17425,
198,
198,
11250,
495,
534,
30865,
18031,
198,
5832,
815,
423,
7170,
329,
13487,
290,
22023,
10130,
8479,
341,
24285,
198,
37811,
198,
11748,
28686,
... | 2.729008 | 262 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,
198,
6738,
42625,
14208,
13,
9945,
1330,
4981,
11,
15720,
602,
628
] | 2.891892 | 37 |
a1 = int(input('Digite o primeiro termo da PA: '))
r = int(input('Digite a razão da PA: '))
a10 = a1 + (10 * r)
for c in range(a1, a10, r):
print(c)
| [
64,
16,
796,
493,
7,
15414,
10786,
19511,
578,
267,
6994,
7058,
3381,
78,
12379,
8147,
25,
705,
4008,
198,
81,
796,
493,
7,
15414,
10786,
19511,
578,
257,
374,
1031,
28749,
12379,
8147,
25,
705,
4008,
198,
64,
940,
796,
257,
16,
1... | 2.125 | 72 |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: line3d.py
#
# Tests: mesh - 3D unstructured, single domain
# plots - Pseudocolor
# annotations - Line3D
#
# Programmer: Kathleen Biagas
# Date: August 27, 2015
#
# Modifications:
# Kathleen Biagas, Thu Apr 19 12:02:22 PDT 2018
# Remove lineStyle tests, no longer available.
#
# ----------------------------------------------------------------------------
# Set up the annotation colors, etc.
a = GetAnnotationAttributes()
a.backgroundColor = (255, 255, 255, 255)
a.foregroundColor = (0, 0, 0, 255)
a.backgroundMode = a.Solid
SetAnnotationAttributes(a)
# Open up the database and do a plot.
OpenDatabase(silo_data_path("globe.silo"))
AddPlot("Pseudocolor", "u")
DrawPlots()
# Create a Line3D object
line = CreateAnnotationObject("Line3D")
line.point1 = (0, -15, 0)
line.point2 = (0, 15, 0)
Test("line3d00")
line.width = 7
Test("Line3d01")
# Set the foreground color to see if it changes
a.foregroundColor = (0, 255, 255, 255)
SetAnnotationAttributes(a)
Test("line3d05")
# Test line color
a.foregroundColor = (255, 255, 255, 255)
SetAnnotationAttributes(a)
line.useForegroundForLineColor = 0
line.color = (255, 0, 255, 255)
Test("line3d06")
# Test arrow at start (flat)
line.arrow1Resolution = 1
line.arrow2Resolution = 1
line.arrow1Radius = 2
line.arrow2Radius = 2
line.arrow1Height = 5.6
line.arrow2Height = 5.6
line.arrow1 = 1
Test("line3d07")
# Test arrow at end
line.arrow1 = 0
line.arrow2 = 1
Test("line3d08")
# Test both arrows
line.arrow1 = 1
Test("line3d09")
# Tubes
line.arrow1 = 0
line.lineType = line.TUBE
line.tubeRadius = 0.3
# make the arrow a cone
line.arrow2Resolution = 15
line.arrow2Radius = 1
line.arrow2Height = 2.8
Test("line3d10")
# Create more line objects
nextLine = CreateAnnotationObject("Line3D")
nextLine.useForegroundForLineColor = 0
nextLine.color=(0, 255, 0, 255)
nextLine.point1=(-15, 0, 0)
nextLine.point2=(15, 0, 0)
nextLine.arrow2 = 1
nextLine.lineType = line.TUBE
nextLine.tubeRadius = 0.3
nextLine.arrow2Resolution = 15
nextLine.arrow2Radius = 1
nextLine.arrow2Height = 2.8
Test("line3d11")
# Start Removing lines
line.Delete()
Test("line3d12")
nextLine.Delete()
Test("line3d13")
Exit()
| [
2,
16529,
10541,
198,
2,
220,
42715,
1546,
25,
37862,
198,
2,
198,
2,
220,
6208,
8913,
25,
220,
1627,
18,
67,
13,
9078,
198,
2,
198,
2,
220,
30307,
25,
220,
220,
220,
220,
220,
19609,
220,
220,
220,
220,
220,
220,
220,
532,
51... | 2.699301 | 858 |
"""Provides access to PyDSS result data."""
from collections import defaultdict
from datetime import datetime
import json
import logging
import os
import re
from pathlib import Path
import h5py
import numpy as np
import pandas as pd
from PyDSS.common import DatasetPropertyType
from PyDSS.dataset_buffer import DatasetBuffer
from PyDSS.element_options import ElementOptions
from PyDSS.exceptions import InvalidParameter
from PyDSS.pydss_project import PyDssProject, RUN_SIMULATION_FILENAME
from PyDSS.reports.reports import Reports, REPORTS_DIR
from PyDSS.utils.dataframe_utils import read_dataframe, write_dataframe
from PyDSS.utils.utils import dump_data, load_data, make_json_serializable, \
make_timestamps
from PyDSS.value_storage import ValueStorageBase, get_dataset_property_type, \
get_time_step_path
logger = logging.getLogger(__name__)
class PyDssResults:
"""Interface to perform analysis on PyDSS output data."""
def __init__(
self, project_path=None, project=None, in_memory=False,
frequency=False, mode=False
):
"""Constructs PyDssResults object.
Parameters
----------
project_path : str | None
Load project from files in path
project : PyDssProject | None
Existing project object
in_memory : bool
If true, load all exported data into memory.
frequency : bool
If true, add frequency column to all dataframes.
mode : bool
If true, add mode column to all dataframes.
"""
options = ElementOptions()
if project_path is not None:
# TODO: handle old version?
self._project = PyDssProject.load_project(
project_path,
simulation_file=RUN_SIMULATION_FILENAME,
)
elif project is None:
raise InvalidParameter("project_path or project must be set")
else:
self._project = project
self._fs_intf = self._project.fs_interface
self._scenarios = []
filename = self._project.get_hdf_store_filename()
driver = "core" if in_memory else None
self._hdf_store = h5py.File(filename, "r", driver=driver)
if self._project.simulation_config.exports.export_results:
for name in self._project.list_scenario_names():
metadata = self._project.read_scenario_export_metadata(name)
scenario_result = PyDssScenarioResults(
name,
self.project_path,
self._hdf_store,
self._fs_intf,
metadata,
options,
frequency=frequency,
mode=mode,
)
self._scenarios.append(scenario_result)
def generate_reports(self):
"""Generate all reports specified in the configuration.
Returns
-------
list
list of report filenames
"""
return Reports.generate_reports(self)
def read_report(self, report_name):
"""Return the report data.
Parameters
----------
report_name : str
Returns
-------
str
"""
all_reports = Reports.get_all_reports()
if report_name not in all_reports:
raise InvalidParameter(f"invalid report name {report_name}")
report_cls = all_reports[report_name]
# This bypasses self._fs_intf because reports are always extracted.
reports_dir = os.path.join(self._project.project_path, REPORTS_DIR)
for filename in os.listdir(reports_dir):
name, ext = os.path.splitext(filename)
if name == os.path.splitext(report_cls.FILENAME)[0]:
path = os.path.join(reports_dir, filename)
if ext in (".json", ".toml"):
return load_data(path)
if ext in (".csv", ".h5"):
return read_dataframe(path)
raise InvalidParameter(f"did not find report {report_name} in {reports_dir}")
@property
def project(self):
"""Return the PyDssProject instance.
Returns
-------
PyDssProject
"""
return self._project
@property
def scenarios(self):
"""Return the PyDssScenarioResults instances for the project.
Returns
-------
list
list of PyDssScenarioResults
"""
return self._scenarios
def get_scenario(self, name):
"""Return the PyDssScenarioResults object for scenario with name.
Parameters
----------
name : str
Scenario name
Results
-------
PyDssScenarioResults
Raises
------
InvalidParameter
Raised if the scenario does not exist.
"""
for scenario in self._scenarios:
if name == scenario.name:
return scenario
raise InvalidParameter(f"scenario {name} does not exist")
@property
def hdf_store(self):
"""Return a handle to the HDF data store.
Returns
-------
h5py.File
"""
return self._hdf_store
@property
def project_path(self):
"""Return the path to the PyDSS project.
Returns
-------
str
"""
return self._project.project_path
def read_file(self, path):
"""Read a file from the PyDSS project.
Parameters
----------
path : str
Path to the file relative from the project directory.
Returns
-------
str
Contents of the file
"""
return self._fs_intf.read_file(path)
@property
def simulation_config(self):
"""Return the simulation configuration
Returns
-------
dict
"""
return self._project.simulation_config
class PyDssScenarioResults:
"""Contains results for one scenario."""
@staticmethod
def get_name_from_column(column):
"""Return the element name from the dataframe column. The dataframe should have been
returned from this class.
Parameters
----------
column : str
Returns
-------
str
"""
fields = column.split(ValueStorageBase.DELIMITER)
assert len(fields) > 1
return fields[0]
@property
def name(self):
"""Return the name of the scenario.
Returns
-------
str
"""
return self._name
def export_data(self, path=None, fmt="csv", compress=False):
"""Export data to path.
Parameters
----------
path : str
Output directory; defaults to scenario exports path
fmt : str
Filer format type (csv, h5)
compress : bool
Compress data
"""
if path is None:
path = os.path.join(self._project_path, "Exports", self._name)
os.makedirs(path, exist_ok=True)
self._export_element_timeseries(path, fmt, compress)
self._export_element_values(path, fmt, compress)
self._export_summed_element_timeseries(path, fmt, compress)
self._export_summed_element_values(path, fmt, compress)
def get_dataframe(self, element_class, prop, element_name, real_only=False, abs_val=False, **kwargs):
"""Return the dataframe for an element.
Parameters
----------
element_class : str
prop : str
element_name : str
real_only : bool
If dtype of any column is complex, drop the imaginary component.
abs_val : bool
If dtype of any column is complex, compute its absolute value.
kwargs
Filter on options; values can be strings or regular expressions.
Returns
-------
pd.DataFrame
Raises
------
InvalidParameter
Raised if the element is not stored.
"""
if element_name not in self._elem_props:
raise InvalidParameter(f"element {element_name} is not stored")
dataset = self._group[f"{element_class}/ElementProperties/{prop}"]
prop_type = get_dataset_property_type(dataset)
if prop_type == DatasetPropertyType.PER_TIME_POINT:
return self._get_elem_prop_dataframe(
element_class, prop, element_name, dataset, real_only=real_only,
abs_val=abs_val, **kwargs
)
elif prop_type == DatasetPropertyType.FILTERED:
return self._get_filtered_dataframe(
element_class, prop, element_name, dataset, real_only=real_only,
abs_val=abs_val, **kwargs
)
assert False, str(prop_type)
def get_filtered_dataframes(self, element_class, prop, real_only=False, abs_val=False):
"""Return the dataframes for all elements.
Calling this is much more efficient than calling get_dataframe for each
element.
Parameters
----------
element_class : str
prop : str
element_name : str
real_only : bool
If dtype of any column is complex, drop the imaginary component.
abs_val : bool
If dtype of any column is complex, compute its absolute value.
Returns
-------
dict
key = str (name), val = pd.DataFrame
The dict will be empty if no data was stored.
"""
if prop not in self.list_element_properties(element_class):
logger.debug("%s/%s is not stored", element_class, prop)
return {}
dataset = self._group[f"{element_class}/ElementProperties/{prop}"]
columns = DatasetBuffer.get_columns(dataset)
names = DatasetBuffer.get_names(dataset)
length = dataset.attrs["length"]
indices_df = self._get_indices_df()
data_vals = dataset[:length]
elem_data = defaultdict(list)
elem_timestamps = defaultdict(list)
# The time_step_dataset has these columns:
# 1. time step index
# 2. element index
# Each row describes the source data in the dataset row.
path = dataset.attrs["time_step_path"]
assert length == self._hdf_store[path].attrs["length"]
time_step_data = self._hdf_store[path][:length]
for i in range(length):
ts_index = time_step_data[:, 0][i]
elem_index = time_step_data[:, 1][i]
# TODO DT: more than one column?
val = data_vals[i, 0]
if real_only:
val = val.real
elif abs_val:
val = abs(val)
elem_data[elem_index].append(val)
elem_timestamps[elem_index].append(indices_df.iloc[ts_index, 0])
dfs = {}
for elem_index, vals in elem_data.items():
elem_name = names[elem_index]
cols = self._fix_columns(elem_name, columns)
dfs[elem_name] = pd.DataFrame(
vals,
columns=cols,
index=elem_timestamps[elem_index],
)
return dfs
def get_full_dataframe(self, element_class, prop, real_only=False, abs_val=False, **kwargs):
"""Return a dataframe containing all data. The dataframe is copied.
Parameters
----------
element_class : str
prop : str
real_only : bool
If dtype of any column is complex, drop the imaginary component.
abs_val : bool
If dtype of any column is complex, compute its absolute value.
kwargs
Filter on options; values can be strings or regular expressions.
Returns
-------
pd.DataFrame
"""
if prop not in self.list_element_properties(element_class):
raise InvalidParameter(f"property {prop} is not stored")
dataset = self._group[f"{element_class}/ElementProperties/{prop}"]
df = DatasetBuffer.to_dataframe(dataset)
if kwargs:
options = self._check_options(element_class, prop, **kwargs)
names = self._elems_by_class.get(element_class, set())
columns = ValueStorageBase.get_columns(df, names, options, **kwargs)
columns = list(columns)
columns.sort()
df = df[columns]
self._finalize_dataframe(df, dataset, real_only=real_only, abs_val=abs_val)
return df
def get_summed_element_total(self, element_class, prop, group=None):
"""Return the total value for a summed element property.
Parameters
----------
element_class : str
prop : str
group : str | None
Specify a group name if sum_groups was assigned.
Returns
-------
dict
Raises
------
InvalidParameter
Raised if the element class is not stored.
"""
if group is not None:
prop = ValueStorageBase.DELIMITER.join((prop, group))
if element_class not in self._summed_elem_props:
raise InvalidParameter(f"{element_class} is not stored")
if prop not in self._summed_elem_props[element_class]:
raise InvalidParameter(f"{prop} is not stored")
return self._summed_elem_props[element_class][prop]
def get_element_property_value(self, element_class, prop, element_name):
"""Return the number stored for the element property."""
if element_class not in self._elem_values_by_prop:
raise InvalidParameter(f"{element_class} is not stored")
if prop not in self._elem_values_by_prop[element_class]:
raise InvalidParameter(f"{prop} is not stored")
if element_name not in self._elem_values_by_prop[element_class][prop]:
raise InvalidParameter(f"{element_name} is not stored")
dataset = self._group[f"{element_class}/ElementProperties/{prop}"]
col_range = self._get_element_column_range(element_class, prop, element_name)
start = col_range[0]
length = col_range[1]
if length == 1:
return dataset[:][0][start]
return dataset[:][0][start: start + length]
def get_option_values(self, element_class, prop, element_name):
"""Return the option values for the element property.
element_class : str
prop : str
element_name : str
Returns
-------
list
"""
df = self.get_dataframe(element_class, prop, element_name)
return ValueStorageBase.get_option_values(df, element_name)
def get_summed_element_dataframe(self, element_class, prop, real_only=False, abs_val=False, group=None):
"""Return the dataframe for a summed element property.
Parameters
----------
element_class : str
prop : str
group : str | None
Specify a group name if sum_groups was assigned.
real_only : bool
If dtype of any column is complex, drop the imaginary component.
abs_val : bool
If dtype of any column is complex, compute its absolute value.
Returns
-------
pd.DataFrame
Raises
------
InvalidParameter
Raised if the element class is not stored.
"""
if group is not None:
prop = ValueStorageBase.DELIMITER.join((prop, group))
if element_class not in self._summed_elem_timeseries_props:
raise InvalidParameter(f"{element_class} is not stored")
if prop not in self._summed_elem_timeseries_props[element_class]:
raise InvalidParameter(f"{prop} is not stored")
elem_group = self._group[element_class]["SummedElementProperties"]
dataset = elem_group[prop]
df = DatasetBuffer.to_dataframe(dataset)
self._add_indices_to_dataframe(df)
if real_only:
for column in df.columns:
if df[column].dtype == complex:
df[column] = [x.real for x in df[column]]
elif abs_val:
for column in df.columns:
if df[column].dtype == complex:
df[column] = [abs(x) for x in df[column]]
return df
def iterate_dataframes(self, element_class, prop, real_only=False, abs_val=False, **kwargs):
"""Returns a generator over the dataframes by element name.
Parameters
----------
element_class : str
prop : str
real_only : bool
If dtype of any column is complex, drop the imaginary component.
abs_val : bool
If dtype of any column is complex, compute its absolute value.
kwargs : dict
Filter on options; values can be strings or regular expressions.
Returns
-------
tuple
Tuple containing the name or property and a pd.DataFrame
"""
for name in self.list_element_names(element_class):
if prop in self._elem_props[name]:
df = self.get_dataframe(
element_class, prop, name, real_only=real_only, abs_val=abs_val, **kwargs
)
yield name, df
def iterate_element_property_values(self):
"""Return a generator over all element properties stored as values.
Yields
------
tuple
element_class, property, element_name, value
"""
for elem_class in self._elem_values_by_prop:
for prop in self._elem_values_by_prop[elem_class]:
for name in self._elem_values_by_prop[elem_class][prop]:
val = self.get_element_property_value(elem_class, prop, name)
yield elem_class, prop, name, val
def list_element_classes(self):
"""Return the element classes stored in the results.
Returns
-------
list
"""
return self._elem_classes[:]
def list_element_names(self, element_class, prop=None):
"""Return the element names for a property stored in the results.
Parameters
----------
element_class : str
prop : str
Returns
-------
list
"""
# TODO: prop is deprecated
return sorted(list(self._elems_by_class.get(element_class, [])))
def list_element_properties(self, element_class, element_name=None):
"""Return the properties stored in the results for a class.
Parameters
----------
element_class : str
element_name : str | None
If not None, list properties only for that name.
Returns
-------
list
"""
if element_class not in self._props_by_class:
return []
if element_name is None:
return sorted(list(self._props_by_class[element_class]))
return self._elem_props.get(element_name, [])
def list_element_property_options(self, element_class, prop):
"""List the possible options for the element class and property.
Parameters
----------
element_class : str
prop : str
Returns
-------
list
"""
return self._options.list_options(element_class, prop)
def list_element_info_files(self):
"""Return the files describing the OpenDSS element objects.
Returns
-------
list
list of filenames (str)
"""
return self._metadata.get("element_info_files", [])
def list_summed_element_properties(self, element_class):
"""Return the properties stored for a class where the values are a sum
of all elements.
Parameters
----------
element_class : str
Returns
-------
list
Raises
------
InvalidParameter
Raised if the element_class is not stored.
"""
if element_class not in self._summed_elem_props:
raise InvalidParameter(f"class={element_class} is not stored")
return self._summed_elem_props[element_class]
def list_summed_element_time_series_properties(self, element_class):
"""Return the properties stored for a class where the values are a sum
of all elements.
Parameters
----------
element_class : str
Returns
-------
list
Raises
------
InvalidParameter
Raised if the element_class is not stored.
"""
if element_class not in self._summed_elem_timeseries_props:
raise InvalidParameter(f"class={element_class} is not stored")
return self._summed_elem_timeseries_props[element_class]
def read_element_info_file(self, filename):
"""Return the contents of file describing an OpenDSS element object.
Parameters
----------
filename : str
full path to a file (returned by list_element_info_files) or
an element class, like "Transformers"
Returns
-------
pd.DataFrame
"""
if "." not in filename:
actual = None
for _file in self.list_element_info_files():
basename = os.path.splitext(os.path.basename(_file))[0]
if basename.replace("Info", "") == filename:
actual = _file
if actual is None:
raise InvalidParameter(
f"element info file for {filename} is not stored"
)
filename = actual
return self._fs_intf.read_csv(filename)
def read_capacitor_changes(self):
"""Read the capacitor state changes from the OpenDSS event log.
Returns
-------
dict
Maps capacitor names to count of state changes.
"""
text = self.read_file(self._metadata.get("event_log", ""))
return _read_capacitor_changes(text)
def read_event_log(self):
"""Returns the event log for the scenario.
Returns
-------
list
list of dictionaries (one dict for each row in the file)
"""
text = self.read_file(self._metadata.get("event_log", ""))
return _read_event_log(text)
def read_pv_profiles(self):
"""Returns exported PV profiles for all PV systems.
Returns
-------
dict
"""
return self._fs_intf.read_scenario_pv_profiles(self._name)
def _check_options(self, element_class, prop, **kwargs):
"""Checks that kwargs are valid and returns available option names."""
for option in kwargs:
if not self._options.is_option_valid(element_class, prop, option):
raise InvalidParameter(
f"class={element_class} property={prop} option={option} is invalid"
)
return self._options.list_options(element_class, prop)
def read_feeder_head_info(self):
"""Read the feeder head information.
Returns
-------
dict
"""
return json.loads(self.read_file(f"Exports/{self._name}/FeederHeadInfo.json"))
def read_file(self, path):
"""Read a file from the PyDSS project.
Parameters
----------
path : str
Path to the file relative from the project directory.
Returns
-------
str
Contents of the file
"""
return self._fs_intf.read_file(path)
@staticmethod
def _read_capacitor_changes(event_log_text):
"""Read the capacitor state changes from an OpenDSS event log.
Parameters
----------
event_log_text : str
Text of event log
Returns
-------
dict
Maps capacitor names to count of state changes.
"""
capacitor_changes = {}
regex = re.compile(r"(Capacitor\.\w+)")
data = _read_event_log(event_log_text)
for row in data:
match = regex.search(row["Element"])
if match:
name = match.group(1)
if name not in capacitor_changes:
capacitor_changes[name] = 0
action = row["Action"].replace("*", "")
if action in ("OPENED", "CLOSED", "STEP UP"):
capacitor_changes[name] += 1
return capacitor_changes
def _read_event_log(event_log_text):
"""Return OpenDSS event log information.
Parameters
----------
event_log_text : str
Text of event log
Returns
-------
list
list of dictionaries (one dict for each row in the file)
"""
data = []
if not event_log_text:
return data
for line in event_log_text.split("\n"):
if line == "":
continue
tokens = [x.strip() for x in line.split(",")]
row = {}
for token in tokens:
name_and_value = [x.strip() for x in token.split("=")]
name = name_and_value[0]
value = name_and_value[1]
row[name] = value
data.append(row)
return data
| [
37811,
15946,
1460,
1895,
284,
9485,
5258,
50,
1255,
1366,
526,
15931,
198,
6738,
17268,
1330,
4277,
11600,
198,
6738,
4818,
8079,
1330,
4818,
8079,
198,
11748,
33918,
198,
11748,
18931,
198,
11748,
28686,
198,
11748,
302,
198,
6738,
3108... | 2.247629 | 11,283 |
__version__=''' $Id'''
__doc__='''basic tests.'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation
setOutDir(__name__)
import unittest
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
printLocation()
| [
834,
9641,
834,
28,
7061,
6,
720,
7390,
7061,
6,
201,
198,
834,
15390,
834,
28,
7061,
6,
35487,
5254,
2637,
7061,
201,
198,
6738,
989,
23912,
13,
8019,
13,
9288,
26791,
1330,
900,
7975,
35277,
11,
15883,
5606,
578,
1890,
9487,
274,
... | 2.530973 | 113 |
from numpy import *
from matplotlib import *
from pylab import *
if __name__ == "__main__":
x = arange(-2*pi,2*pi,0.01)
figure(1)
plot(x,sin(x))
xlabel('x')
ylabel('\dot{x}') | [
6738,
299,
32152,
1330,
1635,
198,
6738,
2603,
29487,
8019,
1330,
1635,
198,
6738,
279,
2645,
397,
1330,
1635,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
2124,
796,
610,
858,
32590,
17,
9,
... | 2.020202 | 99 |
#Define some basic colors
BLACK = ( 0, 0, 0)
BLUE = ( 50, 50, 255)
WHITE = (255, 255, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
GOLD = (255, 215, 0)
GOLDEN_ROD = (218, 165, 32)
| [
198,
198,
2,
7469,
500,
617,
4096,
7577,
198,
9148,
8120,
220,
220,
220,
220,
220,
796,
357,
220,
657,
11,
220,
220,
657,
11,
220,
220,
657,
8,
198,
9148,
8924,
220,
220,
220,
220,
220,
220,
796,
357,
2026,
11,
220,
2026,
11,
... | 1.673913 | 138 |
# encoding=utf-8
import numpy as np
def fusion(perm_score_sets, perm_list, ftype):
"""fusion method for combining scores output by different components
Args:
perm_score_sets (3d-array): List of permission scores. Each element
is the score set output by one method. The size of the element is
len(test_set) x len(perm_list). Each score array is listed according to perm_list.
perm_list (1d-array of string): List of training permissions.
type (String): The type of fusion functions, sum | anz | mnz | max | min |
borda_count
"""
type_list = ["max", "min", "sum", "anz", "mnz", "borda_count"]
ftype = ftype.lower()
if ftype not in type_list:
raise ValueError("Error fusion type: ", ftype)
perm_score_sets = np.array(perm_score_sets)
# test_num * len(perm_list)
new_scores = globals()[ftype+"_fusion"](perm_score_sets)
sorted_perm_index = np.argsort(-1.0 * new_scores, 1)
# each row: perm_i, perm_j, per_k (sorted)
return np.take(perm_list, sorted_perm_index)
| [
2,
21004,
28,
40477,
12,
23,
198,
198,
11748,
299,
32152,
355,
45941,
198,
198,
4299,
21748,
7,
16321,
62,
26675,
62,
28709,
11,
9943,
62,
4868,
11,
277,
4906,
2599,
198,
220,
220,
220,
37227,
69,
4241,
2446,
329,
19771,
8198,
5072,... | 2.571429 | 413 |
import struct
import re
__all__ = ["GlasgowConfig"]
class GlasgowConfig:
"""
Glasgow EEPROM configuration data.
:ivar int size:
Total size of configuration block (currently 64).
:ivar str[1] revision:
Revision letter, ``A``-``Z``.
:ivar str[16] serial:
Serial number, in ISO 8601 format.
:ivar int bitstream_size:
Size of bitstream flashed to ICE_MEM, or 0 if there isn't one.
:ivar bytes[16] bitstream_id:
Opaque string that uniquely identifies bitstream functionality,
but not necessarily any particular routing and placement.
Only meaningful if ``bitstream_size`` is set.
:ivar int[2] voltage_limit:
Maximum allowed I/O port voltage, in millivolts.
"""
size = 64
_encoding = "<B16sI16s2H"
@staticmethod
@staticmethod
def encode(self):
"""
Convert configuration to a byte array that can be loaded into memory or EEPROM.
"""
data = struct.pack(self._encoding,
self.encode_revision(self.revision),
self.serial.encode("ascii"),
self.bitstream_size,
self.bitstream_id,
self.voltage_limit[0],
self.voltage_limit[1])
return data.ljust(self.size, b"\x00")
@classmethod
def decode(cls, data):
"""
Parse configuration from a byte array loaded from memory or EEPROM.
Returns :class:`GlasgowConfiguration` or raises :class:`ValueError` if
the byte array does not contain a valid configuration.
"""
if len(data) != cls.size:
raise ValueError("Incorrect configuration length")
voltage_limit = [0, 0]
revision, serial, bitstream_size, bitstream_id, \
voltage_limit[0], voltage_limit[1] = \
struct.unpack_from(cls._encoding, data, 0)
return cls(cls.decode_revision(revision),
serial.decode("ascii"),
bitstream_size,
bitstream_id,
voltage_limit)
| [
11748,
2878,
198,
11748,
302,
628,
198,
834,
439,
834,
796,
14631,
9861,
292,
21175,
16934,
8973,
628,
198,
4871,
23995,
16934,
25,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
23995,
27254,
4805,
2662,
8398,
1366,
13,
628,
220,
220... | 2.166333 | 998 |
import numpy as np
"""
Helper script to convert original DSC data to the 'standard' Vanilla format I use for the data
"""
src = '../../data/hexevent'
trgt = '../../data/hexevent'
cons = np.load(f'{src}/cons_original_format.npy')
high = np.load(f'{src}/high_original_format.npy')
low = np.load(f'{src}/low_original_format.npy')
# original data somehow has 0 there
cons[:, -1, 4] = 1
cons = convert_hexevent_to_vanilla_format(cons)
low = convert_hexevent_to_vanilla_format(low)
high = convert_hexevent_to_vanilla_format(high)
total = len(cons) + len(high) + len(low)
print(f'Total number of exons: {total}')
print(f'Number of low PSI exons: {len(cons)}')
print(f'Number of high PSI exons: {len(high)}')
print(f'Number of cons exons: {len(low)}')
np.save(f'{src}/cons.npy', cons)
np.save(f'{src}/low.npy', low)
np.save(f'{src}/high.npy', high) | [
11748,
299,
32152,
355,
45941,
198,
198,
37811,
198,
47429,
4226,
284,
10385,
2656,
360,
6173,
1366,
284,
262,
705,
20307,
6,
33897,
5794,
314,
779,
329,
262,
1366,
198,
37811,
198,
198,
10677,
796,
705,
40720,
40720,
7890,
14,
33095,
... | 2.513353 | 337 |
import os
import json
from types import CodeType
import networkx as nx
from util.constant import *
from .utils import get_api_name_from_entity_id
from .config import HOMURA_COMMUNITY_API_RECOMMEND_STORE_PATH, COMMUNITY_RECOMMEND_ENTRY_THREADS_STORE_PATH, API_THREAD_ID_MAP_STORE_PATH, API_THREAD_ID_RESORT_MAP_STORE_PATH,APIDOC_DESCRIPTION_STORE_PATH, HOMURA_COMMUNITY_TAGS_RECOMMEND_STORE_PATH
from .concept_map.common import get_latest_concept_map, get_latest_community_map
# from .mysql_access.posts import DBPosts
from .community_info.so_thread_info_center import ThreadInfoCenter
| [
11748,
28686,
198,
11748,
33918,
198,
6738,
3858,
1330,
6127,
6030,
198,
11748,
3127,
87,
355,
299,
87,
198,
198,
6738,
7736,
13,
9979,
415,
1330,
1635,
198,
198,
6738,
764,
26791,
1330,
651,
62,
15042,
62,
3672,
62,
6738,
62,
26858,
... | 2.8 | 210 |
#!/usr/bin/env python3
import unittest
import torch
import learn2learn as l2l
import pytorch_lightning as pl
from learn2learn.utils.lightning import EpisodicBatcher
from learn2learn.algorithms import LightningANIL
if __name__ == "__main__":
unittest.main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
198,
11748,
555,
715,
395,
198,
11748,
28034,
198,
11748,
2193,
17,
35720,
355,
300,
17,
75,
198,
11748,
12972,
13165,
354,
62,
2971,
768,
355,
458,
198,
198,
6738,
2193,
17,
357... | 2.934066 | 91 |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/africa_bayes_svi_hmc_pyro.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="DXAlhAzkwGMP"
# # Bayesian linear regression in Pyro (for Africa GDP dataset)
#
# We compare (stochastic) variational inference with HMC for Bayesian linear regression. We use the example from sec 8.1 of [Statistical Rethinking ed 2](https://xcelab.net/rm/statistical-rethinking/).
# The code is modified from https://pyro.ai/examples/bayesian_regression.html and
# https://pyro.ai/examples/bayesian_regression_ii.html.
#
# For a NumPyro version (that uses Laplace approximation instead of SVI/ HMC), see https://fehiepsi.github.io/rethinking-numpyro/08-conditional-manatees.html.
# + colab={"base_uri": "https://localhost:8080/"} id="CaBMZERRwBcR" outputId="8d32e320-ab1e-4863-b5ba-05bdce5cefad"
# #!pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro
# !pip3 install pyro-ppl
# + id="icxereXfwToC"
import os
from functools import partial
import torch
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pyro
import pyro.distributions as dist
from pyro.nn import PyroSample
from pyro.infer.autoguide import AutoDiagonalNormal
from pyro.infer import Predictive
from pyro.infer import SVI, Trace_ELBO
from pyro.infer import MCMC, NUTS
pyro.set_rng_seed(1)
from torch import nn
from pyro.nn import PyroModule
# + [markdown] id="zToQkjg-whSm"
# # Data
#
# The dataset has 3 variables: $A$ (whether a country is in Africa or not), $R$ (its terrain ruggedness), and $G$ (the log GDP per capita in 2000). We want to preict $G$ from $A$, $R$, and $A \times R$. The response variable is very skewed, so we log transform it.
# + id="VosIzvMYxZQ6"
DATA_URL = "https://d2hg8soec8ck9v.cloudfront.net/datasets/rugged_data.csv"
data = pd.read_csv(DATA_URL, encoding="ISO-8859-1")
df = data[["cont_africa", "rugged", "rgdppc_2000"]]
df = df[np.isfinite(df.rgdppc_2000)]
df["rgdppc_2000"] = np.log(df["rgdppc_2000"])
# Dataset: Add a feature to capture the interaction between "cont_africa" and "rugged"
# ceofficeints are: beta_a, beta_r, beta_ar
df["cont_africa_x_rugged"] = df["cont_africa"] * df["rugged"]
data = torch.tensor(df[["cont_africa", "rugged", "cont_africa_x_rugged", "rgdppc_2000"]].values,
dtype=torch.float)
x_data, y_data = data[:, :-1], data[:, -1]
# + colab={"base_uri": "https://localhost:8080/", "height": 495} id="bQ13a_i7xxyS" outputId="f91801a7-c6d4-4955-c426-438484fd1ef4"
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 6), sharey=True)
african_nations = df[df["cont_africa"] == 1]
non_african_nations = df[df["cont_africa"] == 0]
sns.scatterplot(non_african_nations["rugged"],
non_african_nations["rgdppc_2000"],
ax=ax[0])
ax[0].set(xlabel="Terrain Ruggedness Index",
ylabel="log GDP (2000)",
title="Non African Nations")
sns.scatterplot(african_nations["rugged"],
african_nations["rgdppc_2000"],
ax=ax[1])
ax[1].set(xlabel="Terrain Ruggedness Index",
ylabel="log GDP (2000)",
title="African Nations");
# + id="oRVVnVGpx4an"
# + [markdown] id="iZnGZr9ryPEP"
# # Ordinary least squares
#
# We define the linear model as a simple neural network with no hidden layers. We fit it by using maximum likelihood, optimized by (full batch) gradient descent, as is standard for DNNs.
# + id="IjZLw7CCyzWH"
pyro.set_rng_seed(1)
#linear_reg_model = PyroModule[nn.Linear](3, 1)
linear_reg_model = nn.Linear(3, 1)
# + colab={"base_uri": "https://localhost:8080/"} id="dzYF0y6yzUZI" outputId="21619b64-a888-4cf6-f41a-6b4bbb62da8c"
print(type(linear_reg_model))
# + colab={"base_uri": "https://localhost:8080/"} id="YgmomZP-yYoA" outputId="a546855d-64e6-4212-e695-715b40e0d18b"
# Define loss and optimize
loss_fn = torch.nn.MSELoss(reduction='sum')
optim = torch.optim.Adam(linear_reg_model.parameters(), lr=0.05)
num_iterations = 1500
for j in range(num_iterations):
loss = train()
if (j + 1) % 200 == 0:
print("[iteration %04d] loss: %.4f" % (j + 1, loss.item()))
# + colab={"base_uri": "https://localhost:8080/"} id="Nkyu2Wo0yxw6" outputId="eb65c7e5-b464-47f0-d3e8-55bb99c69c64"
# Inspect learned parameters
print("Learned parameters:")
for name, param in linear_reg_model.named_parameters():
print(name, param.data.numpy())
# + colab={"base_uri": "https://localhost:8080/"} id="FjmDtKOy0Iki" outputId="5ef199c7-41eb-49ad-8a01-22de196de2ce"
mle_weights = linear_reg_model.weight.data.numpy().squeeze()
print(mle_weights)
mle_bias = linear_reg_model.bias.data.numpy().squeeze()
print(mle_bias)
mle_params = [mle_weights, mle_bias]
print(mle_params)
# + colab={"base_uri": "https://localhost:8080/", "height": 431} id="qaua5kICzCCM" outputId="6de29c48-7820-485f-f2ac-fce5f50ab2c1"
fit = df.copy()
fit["mean"] = linear_reg_model(x_data).detach().cpu().numpy()
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 6), sharey=True)
african_nations = fit[fit["cont_africa"] == 1]
non_african_nations = fit[fit["cont_africa"] == 0]
fig.suptitle("Regression Fit", fontsize=16)
ax[0].plot(non_african_nations["rugged"], non_african_nations["rgdppc_2000"], "o")
ax[0].plot(non_african_nations["rugged"], non_african_nations["mean"], linewidth=2)
ax[0].set(xlabel="Terrain Ruggedness Index",
ylabel="log GDP (2000)",
title="Non African Nations")
ax[1].plot(african_nations["rugged"], african_nations["rgdppc_2000"], "o")
ax[1].plot(african_nations["rugged"], african_nations["mean"], linewidth=2)
ax[1].set(xlabel="Terrain Ruggedness Index",
ylabel="log GDP (2000)",
title="African Nations");
# + [markdown] id="_BC19x7uzJCd"
# # Bayesian model
#
# To make a Bayesian version of the linear neural network, we need to use a Pyro module instead of a torch.nn.module. This lets us replace torch tensors containg the parameters with random variables, defined by PyroSample commands. We also specify the likelihood function by using a plate over the multiple observations.
# + id="TKIH76N_zJ3y"
# https://forum.pyro.ai/t/extra-dim-added-to-some-variables-when-using-predictive/2904/6
# + id="GtqHPETmt-r9" colab={"base_uri": "https://localhost:8080/"} outputId="630854ed-5917-4689-c497-2531d87a7d95"
# quick test of the model shapes
model = BayesianRegression(3, 1)
nuts_kernel = NUTS(model)
mcmc = MCMC(nuts_kernel, num_samples=10, warmup_steps=1)
mcmc.run(x_data, y_data)
predictive = Predictive(model, mcmc.get_samples(), return_sites=("obs", "mu", "_RETURN"))
hmc_samples_pred = predictive(x_data)
print(hmc_samples_pred.keys())
print(hmc_samples_pred['obs'].shape) # [S,170]
print(hmc_samples_pred['mu'].shape) # [S,170]
print(hmc_samples_pred['_RETURN'].shape) # [S,170]
# + [markdown] id="yJa76XkEBOvj"
# # Utilities
# + [markdown] id="MGadNJZJN9Zj"
# ## Summarize posterior
# + id="XJIn7L3QBQxn"
# + id="tlQ3ebQuLNX3"
# + [markdown] id="IzGDTNImOBWC"
# ## Plot posterior predictions
# + id="FFxwlrxINvpO"
# + [markdown] id="D5_w1RzE7dDP"
# # HMC inference
# + colab={"base_uri": "https://localhost:8080/"} id="aYVpPqAt4d39" outputId="3d9933d5-0ecc-4f8f-dcd7-02544cea6445"
pyro.set_rng_seed(1)
model = BayesianRegression(3, 1)
nuts_kernel = NUTS(model)
mcmc = MCMC(nuts_kernel, num_samples=500, warmup_steps=100)
mcmc.run(x_data, y_data)
# + id="ADaI_Exn-MyF" colab={"base_uri": "https://localhost:8080/"} outputId="78f102b4-f30b-4afc-c4f7-2f4cf8368169"
mcmc.diagnostics()
# + colab={"base_uri": "https://localhost:8080/"} id="llAcCKws7z7j" outputId="a4b20544-54fb-434c-f3d2-396221dc4941"
print(mcmc.get_samples().keys())
print(mcmc.get_samples()['linear.weight'].shape)
print(mcmc.get_samples()['linear.bias'].shape)
# + colab={"base_uri": "https://localhost:8080/"} id="xD6rjNeMBvdB" outputId="9c651ea1-3691-4529-de83-48a6e66bd261"
hmc_samples_torch = mcmc.get_samples()
summary_torch(hmc_samples_torch)
# + [markdown] id="XJ6m0hJ3DWgZ"
# ## Parameter posterior
# + colab={"base_uri": "https://localhost:8080/", "height": 822} id="ExWwOGYFB1-z" outputId="b9a6e364-8431-4a32-e764-ac4d7d1a7f99"
hmc_samples_params = {k: v.detach().cpu().numpy() for k, v in hmc_samples_torch.items()}
plot_param_post([hmc_samples_params], ['HMC'])
# + colab={"base_uri": "https://localhost:8080/"} id="vA26j9gfZTWQ" outputId="9b6af8b3-3586-426d-852c-c10483aadb68"
hmc_samples_params['linear.weight'].shape
# + colab={"base_uri": "https://localhost:8080/", "height": 520} id="dzFb2S8CqMRU" outputId="bd99ba82-a45b-41cd-a82e-0a99a7f917fb"
plot_param_post2d([hmc_samples_params], ['HMC'])
# + [markdown] id="bzxlvElIDZRk"
# ## Predictive posterior
# + colab={"base_uri": "https://localhost:8080/"} id="d79Q8d6Z-Cq0" outputId="31672b3e-ddd7-4f76-8835-3d8a46cd224e"
#predictive = Predictive(model, mcmc.get_samples(), return_sites=("obs", "_RETURN"))
predictive = Predictive(model, mcmc.get_samples(), return_sites=("obs", "mu", "_RETURN"))
hmc_samples_pred = predictive(x_data)
print(hmc_samples_pred.keys())
print(hmc_samples_pred['obs'].shape)
print(hmc_samples_pred['mu'].shape)
print(hmc_samples_pred['_RETURN'].shape)
# + colab={"base_uri": "https://localhost:8080/", "height": 404} id="OET6RbjdNz45" outputId="420a65b4-ccda-4c15-e4d5-10283ac17a8c"
plot_pred(hmc_samples_pred)
plt.savefig('linreg_africa_post_pred_hmc.pdf', dpi=300)
# + [markdown] id="izz11PXGzuor"
# # Diagonal Gaussian variational posterior
# + [markdown] id="bej6wzYp2gfJ"
# ## Fit
# + id="kSFDgjeZzxH7"
pyro.set_rng_seed(1)
model = BayesianRegression(3, 1)
guide = AutoDiagonalNormal(model)
adam = pyro.optim.Adam({"lr": 0.03})
svi = SVI(model, guide, adam, loss=Trace_ELBO())
# + colab={"base_uri": "https://localhost:8080/"} id="W8koXK66z7g3" outputId="79203810-a7ba-4a65-e27f-baad4d3ebe64"
pyro.clear_param_store()
num_iterations = 1000
for j in range(num_iterations):
# calculate the loss and take a gradient step
loss = svi.step(x_data, y_data)
if j % 100 == 0:
print("[iteration %04d] loss: %.4f" % (j + 1, loss / len(data)))
# + [markdown] id="7uzP3mpH2iGz"
# ## Parameter posterior
# + colab={"base_uri": "https://localhost:8080/"} id="aPdPvnPwX8Bi" outputId="3aa58737-c2e1-4fa9-a979-e590db6c98b2"
post = guide.get_posterior()
nsamples = 800
samples = post.sample(sample_shape=(nsamples,))
print(samples.shape) # [800,5]
print(torch.mean(samples,dim=0)) # transform(sigma), weights 0:2, bias
# + colab={"base_uri": "https://localhost:8080/"} id="B-Ue0NKjFT-z" outputId="c9d8747f-a88c-43bb-95f4-be719003282d"
# derive posterior quantiles for model parameters from the variational parameters
# note that we transform to the original parameter domain (eg sigma is in [0,10])
quant = guide.quantiles([0.5])
print(quant)
# + colab={"base_uri": "https://localhost:8080/"} id="DD64A-5YFKz6" outputId="69b2a744-9d6e-423a-b900-afd2678b6e01"
predictive = Predictive(model, guide=guide, num_samples=800,
return_sites=("sigma", "linear.bias", "linear.weight"))
diag_samples_pred = predictive(x_data, y_data)
print(diag_samples_pred.keys())
print(diag_samples_pred['sigma'].shape)
print(diag_samples_pred['linear.weight'].shape)
print(diag_samples_pred['linear.bias'].shape)
print(torch.mean(diag_samples_pred['sigma']))
print(torch.mean(diag_samples_pred['linear.weight'], dim=0))
print(torch.mean(diag_samples_pred['linear.bias']))
# + colab={"base_uri": "https://localhost:8080/", "height": 968} id="_1DG1ifuc0Yr" outputId="a63eb8ca-65e6-4e5c-ac7f-60df2f12e38e"
weights = np.reshape(samples[:,1:4].detach().cpu().numpy(), (-1, 1, 3))
bias = samples[:,4].detach().cpu().numpy()
diag_samples_params = {'linear.weight': weights, 'linear.bias': bias}
print(diag_samples_params['linear.weight'].shape)
plot_param_post([hmc_samples_params, diag_samples_params, ], ['HMC', 'Diag'])
plt.savefig('linreg_africa_post_marginals_hmc_diag.pdf', dpi=300)
# + colab={"base_uri": "https://localhost:8080/", "height": 585} id="xbEb4skycsv_" outputId="dd91ceee-8b4c-4c1e-8778-a1d7fca93b3a"
plot_param_post2d([hmc_samples_params, diag_samples_params], ['HMC', 'Diag'])
plt.savefig('linreg_africa_post_2d_hmc_diag.pdf', dpi=300)
# + [markdown] id="L798ffc32vBq"
# ## Posterior predictive
#
# We extract posterior predictive distribution for obs, and the return value of the model (which is the mean prediction).
# + colab={"base_uri": "https://localhost:8080/"} id="OL4XiD4f22BZ" outputId="2a3b53a6-4210-41e1-b1cd-b7868fd30d27"
predictive = Predictive(model, guide=guide, num_samples=800, return_sites=("obs", "_RETURN"))
diag_samples_pred = predictive(x_data)
print(diag_samples_pred.keys())
print(diag_samples_pred['_RETURN'].shape)
# + colab={"base_uri": "https://localhost:8080/", "height": 403} id="x2uQ62X14hFZ" outputId="b744aaf9-64d4-4df1-8b55-d2a3e8dab69a"
plot_pred(diag_samples_pred)
# + [markdown] id="YTGWsgzrdfSD"
# # Full Gaussian variational posterior
# + [markdown] id="XU3PsyB7d0Cy"
# ## Fit
# + id="L7_C_wdtdggs"
pyro.set_rng_seed(1)
model = BayesianRegression(3, 1)
from pyro.infer.autoguide import AutoMultivariateNormal, init_to_mean
guide = AutoMultivariateNormal(model, init_loc_fn=init_to_mean)
adam = pyro.optim.Adam({"lr": 0.03})
svi = SVI(model, guide, adam, loss=Trace_ELBO())
# + colab={"base_uri": "https://localhost:8080/"} id="MeeADsNady7D" outputId="466c1db7-0143-4c6a-e140-f741705c1a4b"
pyro.clear_param_store()
num_iterations = 1000
for j in range(num_iterations):
# calculate the loss and take a gradient step
loss = svi.step(x_data, y_data)
if j % 100 == 0:
print("[iteration %04d] loss: %.4f" % (j + 1, loss / len(data)))
# + [markdown] id="OA4lVTued1eM"
# ## Parameter posterior
# + colab={"base_uri": "https://localhost:8080/"} id="EmCc5TMEd2o_" outputId="4fbf6512-5813-48b8-f280-ad27a78edc79"
post = guide.get_posterior()
nsamples = 800
samples = post.sample(sample_shape=(nsamples,))
print(samples.shape) # [800,5]
print(torch.mean(samples,dim=0)) # transform(sigma), weights 0:2, bias
# + colab={"base_uri": "https://localhost:8080/"} id="2xs8IG76d7T1" outputId="63323a3c-4f6a-4500-b658-dcd238fbe7b4"
weights = np.reshape(samples[:,1:4].detach().cpu().numpy(), (-1, 1, 3))
bias = samples[:,4].detach().cpu().numpy()
full_samples_params = {'linear.weight': weights, 'linear.bias': bias}
print(full_samples_params['linear.weight'].shape)
# + colab={"base_uri": "https://localhost:8080/", "height": 952} id="RbOLfzFyd9kb" outputId="7d96d758-62ee-40d0-d26a-682ef645099f"
plot_param_post([hmc_samples_params, full_samples_params, ], ['HMC', 'Full'])
plt.savefig('linreg_africa_post_marginals_hmc_full.pdf', dpi=300)
# + colab={"base_uri": "https://localhost:8080/", "height": 585} id="POE4Zk6PeM9A" outputId="75f77af2-9b66-4824-9809-01a2fcf7cfd4"
plot_param_post2d([hmc_samples_params, full_samples_params], ['HMC', 'Full'])
plt.savefig('linreg_africa_post_2d_hmc_full.pdf', dpi=300)
# + [markdown] id="JPQ-unGcecSL"
# ## Predictive posterior
# + colab={"base_uri": "https://localhost:8080/", "height": 403} id="SxHj3gwpeSg1" outputId="bd8f9e73-81f1-4bc8-c539-8ad80bc146ee"
predictive = Predictive(model, guide=guide, num_samples=800, return_sites=("obs", "_RETURN"))
full_samples_pred = predictive(x_data)
plot_pred(full_samples_pred)
# + id="BVk4jyzNejjY"
| [
2,
11420,
198,
2,
474,
929,
88,
353,
25,
198,
2,
220,
220,
474,
929,
88,
5239,
25,
198,
2,
220,
220,
220,
220,
2420,
62,
15603,
341,
25,
198,
2,
220,
220,
220,
220,
220,
220,
7552,
25,
764,
9078,
198,
2,
220,
220,
220,
220,
... | 2.288902 | 6,857 |
print([i for i in [1, 2, 3 ,4 ,5 , 8, 13, 21, 34, 55, 89] if i <= 5])
| [
4798,
26933,
72,
329,
1312,
287,
685,
16,
11,
362,
11,
513,
837,
19,
837,
20,
837,
807,
11,
1511,
11,
2310,
11,
4974,
11,
5996,
11,
9919,
60,
611,
1312,
19841,
642,
12962,
198
] | 2 | 35 |
# -*- coding: utf-8 -*-
from urllib.parse import urljoin
from lxml import etree
from framework.core.linkextractors import BaseLinkExtractor
from framework.utils.href import HREF
class LxmlLinkExtractor(BaseLinkExtractor):
"""base class for extractor,base_url可以为'',否则必须是绝对url
"""
def _extract_links(self, response_text, response_encoding=None, response_url=''):
"""提取链接的具体实现,需要重载"""
if isinstance(response_text, bytes):
response_text = response_text.decode(response_encoding)
html = etree.HTML(response_text)
# 提取base_url
_base_url = html.base
# 确定base_url。优先级是初始化时指定的、从页面提取的、响应中的
base_url = self.base_url or _base_url or response_url
# base_url = urljoin(response_url, base_url)
elements = html.cssselect(self.selector)
_retval = []
for el in elements:
url = el.get(self.find_attr)
if url:
url = urljoin(base_url, url)
text = el.text
link = HREF(url, text)
_retval.append(link)
return _retval
def _process_links(self, links):
"""处理链接的具体实现,需要重载"""
return self.process(links)
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
6738,
2956,
297,
571,
13,
29572,
1330,
19016,
22179,
198,
198,
6738,
300,
19875,
1330,
2123,
631,
198,
198,
6738,
9355,
13,
7295,
13,
2815,
365,
742,
974,
669,
1330,
7... | 1.815315 | 666 |
from utils import ingest
INPUT_FILE = '02.in'
EXPECTED_ANSWERS = (1588178, 3783758, )
if __name__ == '__main__':
main()
| [
6738,
3384,
4487,
1330,
26151,
628,
198,
1268,
30076,
62,
25664,
796,
705,
2999,
13,
259,
6,
198,
49864,
9782,
1961,
62,
15037,
54,
4877,
796,
357,
1314,
3459,
23188,
11,
45473,
22318,
23,
11,
1267,
628,
628,
198,
198,
361,
11593,
3... | 2.298246 | 57 |
#########################################
## SPADE sibilant full analysis script ##
#########################################
## Processes and extracts linguistic and acoustic information pertaining to sibilants
## for *all* sibilant segments in the corpus
## Used for extracting data collected as part of the SPeech Across Dialects of English
## (SPADE) project.
## Input:
## - corpus name (e.g., Buckeye, SOTC)
## - corpus metadata (stored in a YAML file), which
## specifies the path to the audio, transcripts and metadata
## Output:
## - CSV of sibilant measures and linguistic information
## associated with the token
import yaml
import time
from datetime import datetime
import sys
import os
import argparse
base_dir = os.path.dirname(os.path.abspath(__file__))
script_dir = os.path.join(base_dir, 'Common')
sys.path.insert(0, script_dir)
import common
from polyglotdb import CorpusContext
from polyglotdb.utils import ensure_local_database_running
from polyglotdb.config import CorpusConfig
from polyglotdb.io.enrichment import enrich_lexicon_from_csv
## Process command-line arguments (corpus metadata, corpus reset, etc).
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('corpus_name', help='Name of the corpus')
parser.add_argument('-r', '--reset', help="Reset the corpus", action='store_true')
parser.add_argument('-b', '--baseline', help='Calculate baseline duration', action='store_true')
parser.add_argument('-d', '--docker', help="This script is being called from Docker", action='store_true')
args = parser.parse_args()
corpus_name = args.corpus_name
reset = args.reset
docker = args.docker
baseline = args.baseline
directories = [x for x in os.listdir(base_dir) if os.path.isdir(x) and x != 'Common']
if args.corpus_name not in directories:
print(
'The corpus {0} does not have a directory (available: {1}). Please make it with a {0}.yaml file inside.'.format(
args.corpus_name, ', '.join(directories)))
sys.exit(1)
corpus_conf = common.load_config(corpus_name)
print('Processing...')
# sanity check database access
common.check_database(corpus_name)
ignored_speakers = corpus_conf.get('ignore_speakers', [])
stressed_vowels = corpus_conf.get('stressed_vowels', [])
if reset:
common.reset(corpus_name)
ip = common.server_ip
if docker:
ip = common.docker_ip
## start processing the corpus
with ensure_local_database_running(corpus_name, port=common.server_port, ip=ip, token=common.load_token()) as params:
config = CorpusConfig(corpus_name, **params)
config.formant_source = 'praat'
# Common set up
## Check if the corpus already exists as a database: if not, import the audio and
## transcripts and store in graph format
common.loading(config, corpus_conf['corpus_directory'], corpus_conf['input_format'])
## Add information to the corpus regarding lexical, speaker, and linguistic information
## These functions are defined in common.py
common.lexicon_enrichment(config, corpus_conf['unisyn_spade_directory'], corpus_conf['dialect_code'])
common.speaker_enrichment(config, corpus_conf['speaker_enrichment_file'])
common.basic_enrichment(config, corpus_conf['vowel_inventory'] + corpus_conf['extra_syllabic_segments'], corpus_conf['pauses'])
## Call the siblant analysis function
## the specifics of the sibilant acoustic analysis is found in common.py; the segments
## over which it applies is defined in the corpus-specific YAML file (under
## 'sibilant_segments'). Change the list of segments in order to change over what phones
## the sibilant enrichment/extraction applies
common.sibilant_acoustic_analysis(config, corpus_conf['sibilant_segments'], ignored_speakers=ignored_speakers)
## Once the set of sibilant tokens have been enriched for acoustic measures,
## extract the data in tabular (CSV) format. Columns included in this output file
## are defined in the function at the beginning of this script
sibilant_full_export(config, corpus_name, corpus_conf['dialect_code'], corpus_conf['speakers'], ignored_speakers=ignored_speakers)
print('Finishing up!')
| [
29113,
7804,
2,
198,
2235,
6226,
19266,
264,
571,
37794,
1336,
3781,
4226,
22492,
198,
29113,
7804,
2,
198,
198,
2235,
10854,
274,
290,
32139,
29929,
290,
26071,
1321,
27113,
284,
264,
571,
346,
1187,
198,
2235,
329,
1635,
439,
9,
264... | 2.96334 | 1,473 |
import threading
from queue import Empty, Full
from time import time
from .container import Container
from .adapter.database import DatabaseWarning
| [
11748,
4704,
278,
198,
6738,
16834,
1330,
33523,
11,
6462,
198,
6738,
640,
1330,
640,
198,
6738,
764,
34924,
1330,
43101,
198,
6738,
764,
324,
3429,
13,
48806,
1330,
24047,
20361,
628,
198
] | 4.545455 | 33 |
import aiohttp
import discord
import discord.ext.commands
from discord.ext import commands
from discord import Webhook, AsyncWebhookAdapter
| [
11748,
257,
952,
4023,
198,
11748,
36446,
198,
11748,
36446,
13,
2302,
13,
9503,
1746,
198,
6738,
36446,
13,
2302,
1330,
9729,
198,
6738,
36446,
1330,
5313,
25480,
11,
1081,
13361,
13908,
25480,
47307,
628,
198
] | 3.944444 | 36 |
import random
import numpy as np
import matplotlib.pyplot as plt
x = [random.gauss(3, 1) for _ in range(400)]
y = [random.gauss(4, 2) for _ in range(400)]
bins = np.linspace(-10, 10, 100)
plt.hist(x, bins, alpha=0.5, label='x')
plt.hist(y, bins, alpha=0.5, label='y')
plt.legend(loc='upper left')
plt.title('Title 1')
plt.title('Title 2')
plt.show()
| [
11748,
4738,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
198,
87,
796,
685,
25120,
13,
4908,
1046,
7,
18,
11,
352,
8,
329,
4808,
287,
2837,
7,
7029,
15437,
198,
88,
796,
6... | 2.292208 | 154 |
from src import utils
from src.Logging import Logger as log
from . import colors
import itertools
COMMIT_URL = "https://github.com/%s/commit/%s"
COMMIT_RANGE_URL = "https://github.com/%s/compare/%s...%s"
CREATE_URL = "https://github.com/%s/tree/%s"
PR_COMMIT_RANGE_URL = "https://github.com/%s/pull/%s/files/%s..%s"
PR_COMMIT_URL = "https://github.com/%s/pull/%s/commits/%s"
DEFAULT_EVENT_CATEGORIES = ["ping", "code", "pr", "issue", "repo"]
EVENT_CATEGORIES = {
"ping": ["ping"], # new webhook received
"code": ["push", "commit_comment"],
"pr-minimal": [
"pull_request/opened",
"pull_request/closed",
"pull_request/reopened",
],
"pr": [
"pull_request/opened",
"pull_request/closed",
"pull_request/reopened",
"pull_request/edited",
"pull_request/assigned",
"pull_request/unassigned",
"pull_request_review",
"pull_request/locked",
"pull_request/unlocked",
"pull_request_review_comment",
],
"pr-all": ["pull_request", "pull_request_review", "pull_request_review_comment"],
"pr-review-minimal": [
"pull_request_review/submitted",
"pull_request_review/dismissed",
],
"pr-review-comment-minimal": [
"pull_request_review_comment/created",
"pull_request_review_comment/deleted",
],
"issue-minimal": [
"issues/opened",
"issues/closed",
"issues/reopened",
"issues/deleted",
"issues/transferred",
],
"issue": [
"issues/opened",
"issues/closed",
"issues/reopened",
"issues/deleted",
"issues/edited",
"issues/assigned",
"issues/unassigned",
"issues/locked",
"issues/unlocked",
"issues/transferred",
"issue_comment",
],
"issue-all": ["issues", "issue_comment"],
"issue-comment-minimal": ["issue_comment/created", "issue_comment/deleted"],
"repo": [
"create", # a repository, branch or tag has been created
"delete", # same as above but deleted
"release",
"fork",
],
"team": ["membership"],
"star": [
# "watch" is a misleading name for this event so this add "star" as an
# alias for "watch"
"watch"
],
}
COMMENT_ACTIONS = {
"created": "commented",
"edited": "edited a comment",
"deleted": "deleted a comment",
}
COMMENT_MAX = 100
CHECK_RUN_CONCLUSION = {
"success": "passed",
"failure": "failed",
"neutral": "finished",
"cancelled": "was cancelled",
"timed_out": "timed out",
"action_required": "requires action",
}
CHECK_RUN_FAILURES = ["failure", "cancelled", "timed_out", "action_required"]
| [
6738,
12351,
1330,
3384,
4487,
198,
6738,
12351,
13,
11187,
2667,
1330,
5972,
1362,
355,
2604,
198,
6738,
764,
1330,
7577,
198,
11748,
340,
861,
10141,
628,
198,
9858,
36393,
62,
21886,
796,
366,
5450,
1378,
12567,
13,
785,
14,
4,
82,... | 2.229014 | 1,227 |
import argparse
import logging
import os
import sys
import threading
from typing import Optional
from orangeshare import Orangeshare
def get_args() -> argparse.Namespace:
"""
Gets all commandline arguments and validates them.
:return: The arguments
"""
parser = argparse.ArgumentParser(description='A small python server that accepts requests from an apple shortcut to allow sharing all sorts of media from iOS with any desktop OS')
parser.add_argument('--version', required=False, action='count', default=0, help="Print the Version")
parser.add_argument('-p', '--api-port', required=False, type=int, help="Port number of the api server (default: 7615)", metavar="<port>", default=7615)
parser.add_argument('-u', '--ui-port', required=False, type=int, help="Port number of the UI server (default: 7616)", metavar="<port>", default=7616)
parser.add_argument('-o', '--open-ui', required=False, action='count', help="Open the server controls in the browser")
if sys.platform == "win32":
parser.add_argument('-t', '--tray-icon', required=False, action='count', help="Run with tray icon")
parser.add_argument('-i', '--inactive-tray', required=False, action='count', help="Start inactive when run in tray")
parser.add_argument('-v', '--verbose', required=False, action='count', default=0, help="Enable verbose output")
# internal flags
# if this is started inside a windows installation
parser.add_argument('--windows-installation', required=False, action='count', default=0, help=argparse.SUPPRESS)
# if this is started as part of the gnome extension
parser.add_argument('--gnome-extension', required=False, action='count', default=0, help=argparse.SUPPRESS)
args = parser.parse_args()
if args.version:
from orangeshare import __version__
print(__version__)
exit(0)
return args
orangeshare: Optional[Orangeshare] = None
def start_in_tray(api_port: int = 7615, ui_port: int = 7616, active=True, open_ui: bool = False):
"""
Creates a tray icon and starts and stops Orange Share from its actions
:param api_port: The port to run the API on
:param ui_port: The port to run the UI on
:param active: If it should be started as active or inactive
:param open_ui: If the UI should be opened each time
"""
from pystray import Icon as icon, Menu as menu, MenuItem as item
from PIL import Image
image_active = Image.open(os.path.join(os.path.abspath(os.path.dirname(__file__)), "logo/white.png"))
image_inactive = Image.open(os.path.join(os.path.abspath(os.path.dirname(__file__)), "logo/gray.png"))
i = icon(
'Orange Share',
image_inactive,
"Orange Share",
menu=menu(
item(
get_start_stop_text,
start_stop),
item(
"Settings",
open_settings),
item(
"Exit",
exit_app)
)
)
if active:
start_stop(icon)
i.run()
if __name__ == '__main__':
main()
| [
11748,
1822,
29572,
198,
11748,
18931,
198,
11748,
28686,
198,
11748,
25064,
198,
11748,
4704,
278,
198,
6738,
19720,
1330,
32233,
198,
198,
6738,
393,
648,
5069,
533,
1330,
1471,
648,
5069,
533,
628,
198,
4299,
651,
62,
22046,
3419,
46... | 2.664666 | 1,166 |
"""
specialized utilities and PDSVersionConverter / PDS4Writer subclasses for
converting m3 products.
"""
from ast import literal_eval
import datetime as dt
import os
import re
import shutil
import numpy as np
import pandas as pd
import rasterio
from toolz import merge
from converter import PDSVersionConverter, PDS4Writer, template_tags
from converter_utils import fitsify, null_bytes_to_na, get_from_and_apply, \
reloc, eqloc
# utilities
# what m3 'base names' look like
M3_BASENAME_PATTERN = re.compile(
r"M3([GT])(20\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d).*?(?=[_.])",
flags=re.I
)
def interpret_m3_basename(path):
"""
extracts m3 basename, mode, and iso-formatted time from a filename.
"""
filename = re.search(M3_BASENAME_PATTERN, path)
if filename is None:
raise ValueError("No M3 file base name found in this string.")
return {
"mode": "global" if filename.group(1) == "G" else "target",
"time": dt.datetime(
int(filename.group(2)),
int(filename.group(3)),
int(filename.group(4)),
int(filename.group(5)),
int(filename.group(6)),
).isoformat()
+ "Z",
"basename": filename.group(0)[:18],
"filename": filename.group(0),
}
def m3_generic_tags(label):
"""
get values for tags found in all m3 observational products
"""
get_pds3 = get_from_and_apply(label)
return {
"{product_id}": get_pds3("PRODUCT_ID"),
"{detector_temperature}": get_pds3("DETECTOR_TEMPERATURE"),
"{start_time}": get_pds3("START_TIME", func=dt.datetime.isoformat),
"{stop_time}": get_pds3("STOP_TIME", func=dt.datetime.isoformat),
"{spacecraft_clock_start}": get_pds3("SPACECRAFT_CLOCK_START_COUNT"),
"{spacecraft_clock_stop}": get_pds3("SPACECRAFT_CLOCK_STOP_COUNT"),
"{orbit_number}": get_pds3("ORBIT_NUMBER"),
"{instrument_mode_id}": get_pds3("INSTRUMENT_MODE_ID").capitalize(),
"{swath_length}": get_pds3("CH1:SWATH_LENGTH", "value"),
"{swath_width}": get_pds3("CH1:SWATH_WIDTH", "value"),
"{product_creation_time}": get_pds3(
"PRODUCT_CREATION_TIME", func=dt.datetime.isoformat
),
"{software_name}": get_pds3("SOFTWARE_NAME"),
"{software_version}": get_pds3("SOFTWARE_VERSION_ID"),
}
def m3_orientation_tags(label):
"""
construct template tags for m3 orientation model attributes
from PDS3 labels. used in L1B and L2 products
"""
get_pds3 = get_from_and_apply(label)
# these attributes should always be present
tag_dictionary = {
"{spacecraft_yaw_direction}": get_pds3(
"CH1:SPACECRAFT_YAW_DIRECTION"
).capitalize(),
"{orbit_limb_direction}": get_pds3(
"CH1:ORBIT_LIMB_DIRECTION").capitalize(),
"{solar_distance}": get_pds3("SOLAR_DISTANCE",
func=lambda x: str(x.value)),
}
# initialize blank values for all attitude-dependent tags
for tag in [
"{orientation_epoch_time}",
"{spacecraft_rotation_rate}",
"{initial_spacecraft_orientation_tag}",
"{initial_roll_tag}",
"{initial_pitch_tag}",
"{initial_yaw_tag}",
"{close_initial_spacecraft_orientation_tag}",
"{spacecraft_orientation_rates_tag}",
"{roll_rate_tag}",
"{pitch_rate_tag}",
"{yaw_rate_tag}",
"{close_spacecraft_orientation_rates_tag}",
"{spacecraft_orientation_axis_vector_tag}",
"{x_unit_tag}",
"{y_unit_tag}",
"{z_unit_tag}",
"{close_spacecraft_orientation_axis_vector_tag}",
"{spacecraft_orientation_tag}",
"{roll_tag}",
"{pitch_tag}",
"{yaw_tag}",
"{close_spacecraft_orientation_tag}",
]:
tag_dictionary[tag] = ""
# should always be present
spacecraft_orientation = get_pds3("SPACECRAFT_ORIENTATION")
# this variable is basically the entirety of model 1
if "N/A" not in spacecraft_orientation:
# populate model 1
spacecraft_orientation = literal_eval(spacecraft_orientation)
tag_dictionary[
"{spacecraft_orientation_tag}"
] = "<chan1:Spacecraft_Orientation>"
tag_dictionary["{roll_tag}"] = (
"""<chan1:roll unit="deg">"""
+ str(spacecraft_orientation[0])
+ "</chan1:roll>"
)
tag_dictionary["{pitch_tag}"] = (
"""<chan1:pitch unit="deg">"""
+ str(spacecraft_orientation[1])
+ "</chan1:pitch>"
)
tag_dictionary["{yaw_tag}"] = (
"""<chan1:yaw unit="deg">"""
+ str(spacecraft_orientation[2])
+ "</chan1:yaw>"
)
tag_dictionary[
"{close_spacecraft_orientation_tag}"
] = "</chan1:Spacecraft_Orientation>"
initial_orientation = get_pds3("CH1:INITIAL_SC_ORIENTATION")
if "N/A" not in initial_orientation:
initial_orientation = literal_eval(initial_orientation)
tag_dictionary[
"{initial_spacecraft_orientation_tag}"
] = "<chan1:Initial_Spacecraft_Orientation>"
tag_dictionary["{initial_roll_tag}"] = (
"""<chan1:roll unit="deg">"""
+ str(initial_orientation[0])
+ "</chan1:roll>"
)
tag_dictionary["{initial_pitch_tag}"] = (
"""<chan1:pitch unit="deg">"""
+ str(initial_orientation[1])
+ "</chan1:pitch>"
)
tag_dictionary["{initial_yaw_tag}"] = (
"""<chan1:yaw unit="deg">""" + str(
initial_orientation[2]) + "</chan1:yaw>"
)
tag_dictionary[
"{close_initial_spacecraft_orientation_tag}"
] = "</chan1:Initial_Spacecraft_Orientation>"
orientation_epoch_time = get_pds3("CH1:SC_ORIENTATION_EPOCH_TDB_TIME")
if "N/A" not in orientation_epoch_time:
tag_dictionary["{orientation_epoch_time}"] = (
"""<chan1:orientation_epoch_time unit="s">"""
+ orientation_epoch_time
+ "</chan1:orientation_epoch_time>"
)
rotation_axis_vector = get_pds3("CH1:SC_ROTATION_AXIS_VECTOR")
if "N/A" not in rotation_axis_vector:
# get model 3 data. ok throwing errors here if it's not all present,
# means we need to check this process.
rotation_axis_vector = literal_eval(rotation_axis_vector)
tag_dictionary["{spacecraft_rotation_rate}"] = (
"""<chan1:spacecraft_rotation_rate unit="deg/s">"""
+ get_pds3("CH1:SC_ROTATION_RATE")
+ "</chan1:spacecraft_rotation_rate>"
)
tag_dictionary[
"{spacecraft_orientation_axis_vector_tag}"
] = "<chan1:Spacecraft_Orientation_Axis_Vector>"
tag_dictionary["{x_unit_tag}"] = (
"<chan1:x_unit>" + str(
rotation_axis_vector[0]) + "</chan1:x_unit>"
)
tag_dictionary["{y_unit_tag}"] = (
"<chan1:y_unit>" + str(
rotation_axis_vector[1]) + "</chan1:y_unit>"
)
tag_dictionary["{z_unit_tag}"] = (
"<chan1:z_unit>" + str(
rotation_axis_vector[2]) + "</chan1:z_unit>"
)
tag_dictionary[
"{close_spacecraft_orientation_axis_vector_tag}"
] = "</chan1:Spacecraft_Orientation_Axis_Vector>"
orientation_rate = get_pds3("CH1:SC_ORIENTATION_RATE")
if "N/A" not in orientation_rate:
# get model 2 data. ok throwing errors here if it's not all present,
# means we need to check this process.
orientation_rate = literal_eval(orientation_rate)
tag_dictionary[
"{spacecraft_orientation_rates_tag}"
] = "<chan1:Spacecraft_Orientation_Rates>"
tag_dictionary["{roll_rate_tag}"] = (
"""<chan1:roll_rate unit="deg/s">"""
+ str(orientation_rate[0])
+ "</chan1:roll_rate>"
)
tag_dictionary["{pitch_rate_tag}"] = (
"""<chan1:pitch_rate unit="deg/s">"""
+ str(orientation_rate[1])
+ "</chan1:pitch_rate>"
)
tag_dictionary["{yaw_rate_tag}"] = (
"""<chan1:yaw_rate unit="deg/s">"""
+ str(orientation_rate[2])
+ "</chan1:yaw_rate>"
)
tag_dictionary[
"{close_spacecraft_orientation_rates_tag}"
] = "</chan1:Spacecraft_Orientation_Rates>"
return tag_dictionary
def m3_latlon_tags(writer, product_index="./directories/m3/m3_index.csv"):
"""
PDSVersionConverter -> dict
reads lat/lon bounds directly out of an L1B product's LOC file bounds,
or out of an index for L0 and L2 products
"""
if "L1B" in writer.filename:
try:
return {
"{minimum_latitude}": np.min(writer.LOC_IMAGE[1]),
"{maximum_latitude}": np.max(writer.LOC_IMAGE[1]),
"{minimum_longitude}": np.min(writer.LOC_IMAGE[0]),
"{maximum_longitude}": np.max(writer.LOC_IMAGE[0]),
}
except (IndexError, AttributeError):
print(
"LOC image not loaded. Using placeholder 0"
+ " value for lat/lon in label."
)
return {
"{minimum_latitude}": 0,
"{maximum_latitude}": 0,
"{minimum_longitude}": 0,
"{maximum_longitude}": 0,
}
else:
try:
basename = interpret_m3_basename(writer.filename)[
"basename"].lower()
table = pd.read_csv(product_index)
product_line = eqloc(table, "basename", basename)
return {
"{minimum_latitude}": product_line.minimum_latitude.iloc[0],
"{maximum_latitude}": product_line.maximum_latitude.iloc[0],
"{minimum_longitude}": product_line.minimum_longitude.iloc[0],
"{maximum_longitude}": product_line.maximum_longitude.iloc[0],
}
except (FileNotFoundError, IndexError, KeyError):
print(
"Product not found in index, or index not found. Perhaps the "
"corresponding L1B product should be converted first. Using "
"placeholder 0 value for lat/lon in label."
)
return {
"{minimum_latitude}": 0,
"{maximum_latitude}": 0,
"{minimum_longitude}": 0,
"{maximum_longitude}": 0,
}
# conversion classes
# some of these are repetitive. they are intended to make it easy
# to add additional behavior during liens or reprocessing efforts.
class M3L0Converter(PDSVersionConverter):
"""
implements business logic for M3 L0-specific PDS version conversion
"""
def generate_tag_mapping(self):
"""
make a dictionary of mappings to tags in PDS4 label template.
no arguments, looks for parameters in self.LABEL.
"""
get_pds3 = get_from_and_apply(self.LABEL)
m3_info = interpret_m3_basename(self.filename)
try:
clock_file_size = str(os.stat(self.clock_file).st_size)
fits_file_size = str(os.stat(self.fits_image_file).st_size)
except (AttributeError, TypeError, FileNotFoundError):
print(
"Converted prefix table and/or FITS image files have not "
+ "been written yet or were not found. Using placeholder "
+ "9999 value for file sizes in label."
)
clock_file_size = "9999"
fits_file_size = "9999"
l0_dictionary = {
"{basename_lower}": m3_info["basename"].lower(),
"{line_samples}": get_pds3("L0_FILE", "L0_IMAGE", "LINE_SAMPLES"),
# in many (perhaps all) of the target-mode L0 PDS3 labels,
# the line prefix tables are incorrectly specified as having
# many more rows than they do, so that field can't be used to
# generate new labels.
"{rows}": get_pds3("L0_FILE", "L0_IMAGE", "LINES"),
"{bands}": get_pds3("L0_FILE", "L0_IMAGE", "BANDS"),
"{file_records}": get_pds3("L0_FILE", "FILE_RECORDS"),
"{record_bytes}": get_pds3("L0_FILE", "RECORD_BYTES"),
"{clock_file_size}": clock_file_size,
"{fits_file_size}": fits_file_size,
}
generic_dictionary = m3_generic_tags(self.LABEL)
if '{minimum_longitude}' in template_tags(self.template):
# i.e., if it's not a 'lonely' EDR product with no reduced
# friends in the archive
latlon_dictionary = m3_latlon_tags(self)
else:
latlon_dictionary = {}
return merge(l0_dictionary, generic_dictionary, latlon_dictionary)
def write_pds4(
self,
output_directory,
write_product_files=True,
write_label_file=True,
clean=False
):
"""
output file objects and label for a PDS4 product corresponding to
this object.
(string containing output directory -> None)
"""
print("Converting " + self.filename + " to PDS4.")
self.fits_image_file = output_directory + self.pds4_root + ".fits"
self.clock_file = output_directory + self.pds4_root + "_clock_table.csv"
if write_product_files:
self.FITS_IMAGE.writeto(self.fits_image_file, overwrite=True)
self.PREFIX_DATAFRAME.to_csv(
self.clock_file,
index=False,
header=False,
# PDS4 DSV records must terminate with CRLF! therefore only
# Windows machines will produce compliant output by default.
# the following argument corrects this.
line_terminator="\r\n",
)
if clean:
del self.FITS_IMAGE
del self.PREFIX_DATAFRAME
self.convert_label(
output_directory, write_label_file, label_name=self.pds4_root
)
class M3L1BConverter(PDSVersionConverter):
"""
implements business logic for M3 L1B-specific PDS version conversion
"""
def generate_tag_mapping(self):
"""
make a dictionary of mappings to tags in PDS4 label template.
no arguments, looks for parameters in self.LABEL.
"""
get_pds3 = get_from_and_apply(self.LABEL)
m3_info = interpret_m3_basename(self.filename)
try:
obs_file_size = str(os.stat(self.obs_file).st_size)
loc_file_size = str(os.stat(self.loc_file).st_size)
rdn_file_size = str(os.stat(self.rdn_file).st_size)
except (AttributeError, FileNotFoundError):
print(
"Converted prefix table and/or FITS image files have not "
+ "been written yet or were not found. Using placeholder "
+ "9999 value for file sizes in label."
)
obs_file_size = "9999"
loc_file_size = "9999"
rdn_file_size = "9999"
# note that the LOC, RDN, and OBS files all have the same number
# of lines and samples.
l1b_dictionary = {
"{basename_lower}": m3_info["basename"].lower(),
"{lines}": get_pds3("RDN_FILE", "RDN_IMAGE", "LINES"),
"{samples}": get_pds3("RDN_FILE", "RDN_IMAGE", "LINE_SAMPLES"),
"{rdn_bands}": get_pds3("RDN_FILE", "RDN_IMAGE", "BANDS"),
"{rdn_file_size}": rdn_file_size,
"{loc_file_size}": loc_file_size,
"{obs_file_size}": obs_file_size,
"{rad_gain_file}": get_pds3("CH1:RAD_GAIN_FACTOR_FILE_NAME")[
:-4].lower(),
"{spectral_calibration_file}": get_pds3(
"CH1:SPECTRAL_CALIBRATION_FILE_NAME"
)[:-4].lower(),
}
generic_dictionary = m3_generic_tags(self.LABEL)
orientation_dictionary = m3_orientation_tags(self.LABEL)
latlon_dictionary = m3_latlon_tags(self)
return merge(
l1b_dictionary,
latlon_dictionary,
generic_dictionary,
orientation_dictionary,
)
def write_pds4(
self,
output_directory,
write_product_files=True,
write_label_file=True,
index_file="./directories/m3/m3_index.csv",
clean=False
):
"""
output file objects and label for a PDS4 product corresponding to
this object.
(string containing output directory -> None)
"""
print("Converting " + self.filename + " to PDS4.")
self.rdn_file = output_directory + self.pds4_root + "_rdn.fits"
self.loc_file = output_directory + self.pds4_root + "_loc.fits"
self.obs_file = output_directory + self.pds4_root + "_obs.fits"
self.tim_file = output_directory + self.pds4_root + "_tim.tab"
if write_product_files:
self.fits_loc_image.writeto(self.loc_file, overwrite=True)
self.fits_rdn_image.writeto(self.rdn_file, overwrite=True)
self.fits_obs_image.writeto(self.obs_file, overwrite=True)
self.UTC_TIME_TABLE[1] = self.UTC_TIME_TABLE[1] + "Z"
self.UTC_TIME_TABLE.to_csv(
self.tim_file,
index=False,
header=False,
# PDS4 DSV records must terminate with CRLF! therefore only
# Windows machines will produce compliant output by default.
# the following argument corrects this.
line_terminator="\r\n",
)
self.convert_label(
output_directory, write_label_file, label_name=self.pds4_root
)
if clean:
del self.fits_loc_image
del self.fits_rdn_image
del self.fits_obs_image
# deleting these two here because they are actually used
# in these writing functions
del self.UTC_TIME_TABLE
del self.LOC_IMAGE
if index_file is not None:
basename = interpret_m3_basename(self.filename)["basename"].lower()
lat_series = pd.Series(
{
"basename": basename,
"minimum_latitude": self.tag_mapping["{minimum_latitude}"],
"maximum_latitude": self.tag_mapping["{maximum_latitude}"],
"minimum_longitude": self.tag_mapping[
"{minimum_longitude}"],
"maximum_longitude": self.tag_mapping[
"{maximum_longitude}"],
"start_time": self.tag_mapping["{start_time}"],
"stop_time": self.tag_mapping["{stop_time}"],
}
)
try:
index = pd.read_csv(index_file)
if len(reloc(index, "basename", basename)) > 0:
index.drop(reloc(index, "basename", basename).index,
inplace=True)
index = index.append(lat_series, ignore_index=True)
index.to_csv(index_file, index=False)
except FileNotFoundError:
pd.DataFrame(lat_series).T.to_csv(
index_file,
index=False
)
class M3L2Converter(PDSVersionConverter):
"""
implements business logic for M3 L1B-specific PDS version conversion
"""
def generate_tag_mapping(self):
"""
make a dictionary of mappings to tags in PDS4 label template.
no arguments, looks for parameters in self.LABEL.
"""
get_pds3 = get_from_and_apply(self.LABEL)
m3_info = interpret_m3_basename(self.filename)
try:
rfl_file_size = str(os.stat(self.sup_file).st_size)
sup_file_size = str(os.stat(self.sup_file).st_size)
except (AttributeError, FileNotFoundError):
print(
"Converted FITS image files have not "
+ "been written yet or were not found. Using placeholder "
+ "9999 value for file sizes in label."
)
rfl_file_size = "9999"
sup_file_size = "9999"
# note that the RFL and SUP files have the same number
# of lines and samples.
l2_dictionary = {
"{basename_lower}": m3_info["basename"].lower(),
"{lines}": get_pds3("RFL_FILE", "RFL_IMAGE", "LINES"),
"{samples}": get_pds3("RFL_FILE", "RFL_IMAGE", "LINE_SAMPLES"),
"{rfl_bands}": get_pds3("RFL_FILE", "RFL_IMAGE", "BANDS"),
"{rfl_file_size}": rfl_file_size,
"{sup_file_size}": sup_file_size,
"{rad_gain_file}": get_pds3("CH1:RAD_GAIN_FACTOR_FILE_NAME")[
:-4].lower(),
"{spectral_calibration_file}": get_pds3(
"CH1:SPECTRAL_CALIBRATION_FILE_NAME"
)[:-4].lower(),
"{stat_pol}": get_pds3("CH1:STATISTICAL_POLISHER_FILE_NAME")[
:-4].lower(),
"{photo_corr}": get_pds3("CH1:PHOTOMETRY_CORR_FILE_NAME")[
:-4].lower(),
"{solar_spec}": get_pds3("CH1:SOLAR_SPECTRUM_FILE_NAME")[
:-4].lower(),
"{thermal_correction_flag}": "true"
if get_pds3("CH1:THERMAL_CORRECTION_FLAG") == "Y"
else "false",
}
generic_dictionary = m3_generic_tags(self.LABEL)
orientation_dictionary = m3_orientation_tags(self.LABEL)
latlon_dictionary = m3_latlon_tags(self)
return merge(
l2_dictionary,
generic_dictionary,
orientation_dictionary,
latlon_dictionary,
)
def write_pds4(
self,
output_directory,
write_product_files=True,
write_label_file=True,
clean=False
):
"""
output file objects and label for a PDS4 product corresponding to
this object.
(string containing output directory -> None)
"""
print("Converting " + self.filename + " to PDS4.")
self.rfl_file = output_directory + self.pds4_root + "_rfl.fits"
self.sup_file = output_directory + self.pds4_root + "_sup.fits"
if write_product_files:
self.fits_rfl_image.writeto(self.rfl_file, overwrite=True)
self.fits_sup_image.writeto(self.sup_file, overwrite=True)
if clean:
del self.fits_rfl_image
del self.fits_sup_image
self.convert_label(
output_directory, write_label_file, label_name=self.pds4_root
)
"""
Note that we do not even apply _pdr_ to any of these calibration images. This
is basically because no useful product-level metadata is given in the PDS3
archive for these files. They do not have PDS3 labels; their ENVI headers are
minimal and contain only array format specifications. It is a waste of time
to do anything but transform them to _numpy_ arrays as quickly as possible.
"""
class M3BDEWriter(PDS4Writer):
"""
implements business logic for writing PDS4 versions of M3 BDE files.
basically identical to the flat field writer below.
"""
def generate_tag_mapping(self):
"""
make a dictionary of mappings to tags in PDS4 label template.
"""
m3_info = interpret_m3_basename(self.filename)
return {
"{basename}": m3_info["basename"],
"{basename_lower}": m3_info["basename"].lower(),
"{nominal_product_time}": m3_info["time"],
"{file_records}": 260 if m3_info["mode"] == "target" else 86,
"{mode_samples}": 640 if m3_info["mode"] == "target" else 320,
"{mode_lines}": 260 if m3_info["mode"] == "target" else 86,
"{mode_file_size}": 671040 if m3_info[
"mode"] == "target" else 115200,
}
def write_pds4(
self,
output_directory,
write_product_files=True,
write_label_file=True,
):
"""
output file objects and label for a PDS4 product corresponding to
this object.
(string containing output directory -> None)
"""
print("Converting " + self.filename + " to PDS4.")
self.fits_image_file = output_directory + self.pds4_root + ".fits"
if write_product_files:
# these are 2D images; they have a single 'band' to rasterio
self.FITS_IMAGE.writeto(self.fits_image_file, overwrite=True)
self.write_label(output_directory, write_label_file,
label_name=self.pds4_root)
class M3FlatFieldWriter(PDS4Writer):
"""
implements business logic for writing PDS4 versions of M3 flat field files
"""
def generate_tag_mapping(self):
"""
make a dictionary of mappings to tags in PDS4 label template.
"""
m3_info = interpret_m3_basename(self.filename)
return {
"{basename}": m3_info["basename"],
"{basename_lower}": m3_info["basename"].lower(),
"{nominal_product_time}": m3_info["time"],
"{mode_samples}": 640 if m3_info["mode"] == "target" else 320,
"{mode_lines}": 260 if m3_info["mode"] == "target" else 86,
"{mode_file_size}": 671040 if m3_info[
"mode"] == "target" else 115200,
}
def write_pds4(
self,
output_directory,
write_product_files=True,
write_label_file=True,
):
"""
output file objects and label for a PDS4 product corresponding to
this object.
(string containing output directory -> None)
"""
print("Converting " + self.filename + " to PDS4.")
# all of the images we need to convert in this way seem to have ENVI
# headers that are handled well by rasterio; moreover, since they
# don't have PDS3
# labels, we can't assemble a struct format specification without
# referencing
# the ENVI headers _anyway_, so just using rasterio.
self.fits_image_file = output_directory + self.pds4_root + ".fits"
if write_product_files:
# these are 2D images; they have a single 'band' to rasterio
envi_img = rasterio.open(self.filename).read(1)
self.FITS_IMAGE = fitsify(envi_img)
print("Writing image to " + self.fits_image_file)
self.FITS_IMAGE.writeto(self.fits_image_file, overwrite=True)
self.write_label(output_directory, write_label_file,
label_name=self.pds4_root)
class M3PipelineLogWriter(PDS4Writer):
"""
implements business logic for writing PDS4 versions of M3 reduction
pipeline logs
"""
def generate_tag_mapping(self):
"""
make a dictionary of mappings to tags in PDS4 label template.
"""
m3_info = interpret_m3_basename(self.filename)
return {"{basename_lower}": m3_info["basename"].lower()}
def write_pds4(
self,
output_directory,
write_product_files=True,
write_label_file=True,
):
"""
output file objects and label for a PDS4 product corresponding to
this object.
(string containing output directory -> None)
"""
self.logfile = output_directory + self.pds4_root + ".txt"
if write_product_files:
print("Copying log to " + self.logfile)
shutil.copyfile(self.filename, self.logfile)
self.write_label(output_directory, write_label_file,
label_name=self.pds4_root)
class M3SSCWriter(PDS4Writer):
"""
implements business logic for writing PDS4 versions of M3 smooth shape
curve labels
"""
def generate_tag_mapping(self):
"""
make a dictionary of mappings to tags in PDS4 label template.
"""
m3_info = interpret_m3_basename(self.filename)
return {"{basename_lower}": m3_info["basename"].lower()}
def write_pds4(
self,
output_directory,
write_product_files=True,
write_label_file=True,
):
"""
output file objects and label for a PDS4 product corresponding to
this object.
(string containing output directory -> None)
"""
self.logfile = output_directory + self.pds4_root + ".txt"
if write_product_files:
print("Copying SSC to " + self.logfile)
shutil.copyfile(self.filename, self.logfile)
self.write_label(output_directory, write_label_file,
label_name=self.pds4_root)
class M3BrowseWriter(PDS4Writer):
"""
implements business logic for writing M3 browse labels.
Probably unnecessarily complicated.
"""
def generate_tag_mapping(self):
"""
make a dictionary of mappings to tags in PDS4 label template.
"""
return {
"{basename}": self.basename,
"{delete:" + self.mode + "}": True
}
def write_pds4(
self,
output_directory,
write_product_files=True,
write_label_file=True,
):
"""
output file objects and label for a PDS4 product corresponding to
this object. (string containing output directory -> None)
"""
if self.mode == 'target':
if self.band_name == 'thermal':
self.output_file_1 = self.basename + '_thermal_250.jpg'
else:
self.output_file_1 = self.basename + '_albedo_46.jpg'
self.output_file_2 = self.basename + '_albedo_84.jpg'
self.output_file_3 = self.basename + '_albedo_105.jpg'
else:
if self.band_name == 'thermal':
self.output_file_1 = self.basename + '_thermal_84.jpg'
else:
self.output_file_1 = self.basename + '_albedo_46.jpg'
if write_product_files:
print("Copying browse images to " + output_directory)
shutil.copyfile(
self.filename,
output_directory + self.output_file_1
)
for file_pair in [
[self.second_image_path, self.output_file_2],
[self.third_image_path, self.output_file_3]
]:
if file_pair[1] is None:
continue
shutil.copyfile(
file_pair[0],
output_directory + file_pair[1]
)
self.write_label(
output_directory,
write_label_file,
label_name=self.basename + '_' + self.band_name
)
| [
37811,
201,
198,
20887,
1143,
20081,
290,
350,
5258,
14815,
3103,
332,
353,
1220,
350,
5258,
19,
34379,
850,
37724,
329,
201,
198,
1102,
48820,
285,
18,
3186,
13,
201,
198,
37811,
201,
198,
6738,
6468,
1330,
18875,
62,
18206,
201,
198... | 1.971649 | 16,296 |
# -*- coding: utf-8 -*-
__author__ = """Julien Duponchelle"""
__email__ = 'julien@duponchelle.info'
__version__ = '0.9.0'
from .serialization import serialize
from .deserialization import deserialize, _flat, _resolve, _parse_included
# keeps backwards compatibility
parse = deserialize
__all__ = ['serialize', 'deserialize', '_flat', '_resolve', '_parse_included']
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
834,
9800,
834,
796,
37227,
16980,
2013,
360,
27287,
29232,
293,
37811,
198,
834,
12888,
834,
796,
705,
73,
377,
2013,
31,
646,
79,
261,
29232,
293,
13,
10951,
6,... | 2.781955 | 133 |
"""Integration test cases for the raceplans route."""
from copy import deepcopy
from datetime import datetime
from json import dumps
import os
from aiohttp import hdrs
from aiohttp.test_utils import TestClient as _TestClient
from aioresponses import aioresponses
import jwt
import pytest
from pytest_mock import MockFixture
@pytest.fixture
def token() -> str:
"""Create a valid token."""
secret = os.getenv("JWT_SECRET")
algorithm = "HS256"
payload = {"identity": os.getenv("ADMIN_USERNAME"), "roles": ["admin"]}
return jwt.encode(payload, secret, algorithm) # type: ignore
@pytest.fixture
def token_unsufficient_role() -> str:
"""Create a valid token."""
secret = os.getenv("JWT_SECRET")
algorithm = "HS256"
payload = {"identity": "user", "roles": ["user"]}
return jwt.encode(payload, secret, algorithm) # type: ignore
@pytest.fixture
async def new_raceplan_interval_start() -> dict:
"""Create a raceplan object."""
return {
"event_id": "event_1",
"no_of_contestants": 32,
"races": [
{
"raceclass": "G16",
"order": 1,
"start_time": datetime.fromisoformat("2021-08-31 12:00:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"event_id": "event_1",
"raceplan_id": "",
"start_entries": [],
"results": {},
"datatype": "interval_start",
},
{
"raceclass": "G16",
"order": 2,
"start_time": datetime.fromisoformat("2021-08-31 12:15:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"event_id": "event_1",
"raceplan_id": "",
"start_entries": [],
"results": {},
"datatype": "interval_start",
},
{
"raceclass": "G16",
"order": 3,
"start_time": datetime.fromisoformat("2021-08-31 12:03:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"event_id": "event_1",
"raceplan_id": "",
"start_entries": [],
"results": {},
"datatype": "interval_start",
},
{
"raceclass": "G16",
"order": 4,
"start_time": datetime.fromisoformat("2021-08-31 12:45:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"event_id": "event_1",
"raceplan_id": "",
"start_entries": [],
"results": {},
"datatype": "interval_start",
},
],
}
@pytest.fixture
async def raceplan_interval_start() -> dict:
"""Create a mock raceplan object."""
return {
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"no_of_contestants": 32,
"races": [
{
"raceclass": "G16",
"order": 1,
"start_time": datetime.fromisoformat("2021-08-31 12:00:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"id": "190e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"raceplan_id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"start_entries": [],
"results": {},
"datatype": "interval_start",
},
{
"raceclass": "G16",
"order": 2,
"start_time": datetime.fromisoformat("2021-08-31 12:15:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"raceplan_id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"start_entries": [],
"results": {},
"datatype": "interval_start",
},
{
"raceclass": "G16",
"order": 3,
"start_time": datetime.fromisoformat("2021-08-31 12:30:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"id": "390e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"raceplan_id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"start_entries": [],
"results": {},
"datatype": "interval_start",
},
{
"raceclass": "G16",
"order": 4,
"start_time": datetime.fromisoformat("2021-08-31 12:45:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"id": "490e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"raceplan_id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"start_entries": [],
"results": {},
"datatype": "interval_start",
},
],
}
@pytest.fixture
async def new_raceplan_individual_sprint() -> dict:
"""Create a mock raceplan object."""
return {
"event_id": "event_1",
"no_of_contestants": 32,
"races": [
{
"raceclass": "G16",
"order": 1,
"start_time": datetime.fromisoformat("2021-08-31 12:00:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"event_id": "event_1",
"raceplan_id": "",
"start_entries": [],
"results": {},
"datatype": "individual_sprint",
},
{
"raceclass": "G16",
"order": 2,
"start_time": datetime.fromisoformat("2021-08-31 12:15:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"event_id": "event_1",
"raceplan_id": "",
"start_entries": [],
"results": {},
"datatype": "individual_sprint",
},
{
"raceclass": "G16",
"order": 3,
"start_time": datetime.fromisoformat("2021-08-31 12:30:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"event_id": "event_1",
"raceplan_id": "",
"start_entries": [],
"results": {},
"datatype": "individual_sprint",
},
{
"raceclass": "G16",
"order": 4,
"start_time": datetime.fromisoformat("2021-08-31 12:45:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"event_id": "event_1",
"raceplan_id": "",
"start_entries": [],
"results": {},
"datatype": "individual_sprint",
},
],
}
@pytest.fixture
async def raceplan_individual_sprint() -> dict:
"""Create a mock raceplan object."""
return {
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"no_of_contestants": 32,
"races": [
{
"raceclass": "G16",
"order": 1,
"start_time": datetime.fromisoformat("2021-08-31 12:00:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"datatype": "individual_sprint",
"id": "190e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"raceplan_id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"start_entries": [],
},
{
"raceclass": "G16",
"order": 2,
"start_time": datetime.fromisoformat("2021-08-31 12:15:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"datatype": "individual_sprint",
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"raceplan_id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"start_entries": [],
},
{
"raceclass": "G16",
"order": 3,
"start_time": datetime.fromisoformat("2021-08-31 12:30:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"datatype": "individual_sprint",
"id": "390e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"raceplan_id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"start_entries": [],
},
{
"raceclass": "G16",
"order": 4,
"start_time": datetime.fromisoformat("2021-08-31 12:45:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"datatype": "individual_sprint",
"id": "490e70d5-0933-4af0-bb53-1d705ba7eb95",
"event_id": "event_1",
"raceplan_id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"start_entries": [],
},
],
}
@pytest.fixture
async def new_raceplan_unsupported_datatype() -> dict:
"""Create a raceplan object."""
return {
"event_id": "event_1",
"no_of_contestants": 8,
"races": [
{
"raceclass": "G16",
"order": 1,
"start_time": datetime.fromisoformat("2021-08-31 12:00:00"),
"no_of_contestants": 8,
"max_no_of_contestants": 10,
"start_entries": [],
"results": {},
"datatype": "unsupported",
},
],
}
@pytest.mark.integration
async def test_create_raceplan(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
new_raceplan_interval_start: dict,
raceplan_interval_start: dict,
) -> None:
"""Should return 405 Method Not Allowed."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.services.raceplans_service.create_id",
return_value=RACEPLAN_ID,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.create_raceplan",
return_value=RACEPLAN_ID,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.update_raceplan",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.races_adapter.RacesAdapter.create_race",
side_effect=raceplan_interval_start["races"],
)
request_body = dumps(
new_raceplan_interval_start, indent=4, sort_keys=True, default=str
)
headers = {
hdrs.CONTENT_TYPE: "application/json",
hdrs.AUTHORIZATION: f"Bearer {token}",
}
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.post("/raceplans", headers=headers, data=request_body)
assert resp.status == 405
@pytest.mark.integration
async def test_get_raceplan_by_id(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return OK, and a body containing one raceplan."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.races_adapter.RacesAdapter.get_race_by_id",
side_effect=raceplan_interval_start["races"],
)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.get(f"/raceplans/{RACEPLAN_ID}")
assert resp.status == 200
assert "application/json" in resp.headers[hdrs.CONTENT_TYPE]
body = await resp.json()
assert type(body) is dict
assert body["id"] == RACEPLAN_ID
assert body["event_id"] == raceplan_interval_start["event_id"]
assert len(body["races"]) == len(raceplan_interval_start["races"])
for race in body["races"]:
assert race["raceclass"]
assert race["order"]
assert race["start_time"]
@pytest.mark.integration
async def test_get_raceplan_by_event_id(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return OK, and a body containing one raceplan."""
EVENT_ID = raceplan_interval_start["event_id"]
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=[raceplan_interval_start],
)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.get(f"/raceplans?eventId={EVENT_ID}")
assert resp.status == 200
assert "application/json" in resp.headers[hdrs.CONTENT_TYPE]
body = await resp.json()
assert type(body) is list
assert len(body) == 1
assert body[0]["id"] == RACEPLAN_ID
assert body[0]["event_id"] == raceplan_interval_start["event_id"]
assert len(body[0]["races"]) == len(raceplan_interval_start["races"])
for race in body[0]["races"]:
assert race["raceclass"]
assert race["order"]
assert race["start_time"]
@pytest.mark.integration
async def test_get_raceplan_by_event_id_individual_sprint(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_individual_sprint: dict,
) -> None:
"""Should return OK, and a body containing one raceplan."""
EVENT_ID = raceplan_individual_sprint["event_id"]
RACEPLAN_ID = raceplan_individual_sprint["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=[raceplan_individual_sprint],
)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.get(f"/raceplans?eventId={EVENT_ID}")
assert resp.status == 200
assert "application/json" in resp.headers[hdrs.CONTENT_TYPE]
body = await resp.json()
assert type(body) is list
assert len(body) == 1
assert body[0]["id"] == RACEPLAN_ID
assert body[0]["event_id"] == raceplan_individual_sprint["event_id"]
assert len(body[0]["races"]) == len(raceplan_individual_sprint["races"])
for race in body[0]["races"]:
assert race["raceclass"]
assert race["order"]
assert race["start_time"]
@pytest.mark.integration
async def test_update_raceplan_by_id(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return No Content."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.update_raceplan",
return_value=RACEPLAN_ID,
)
headers = {
hdrs.CONTENT_TYPE: "application/json",
hdrs.AUTHORIZATION: f"Bearer {token}",
}
request_body = dumps(raceplan_interval_start, indent=4, sort_keys=True, default=str)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.put(
f"/raceplans/{RACEPLAN_ID}", headers=headers, data=request_body
)
assert resp.status == 204
@pytest.mark.integration
async def test_get_all_raceplans(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return OK and a valid json body."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_all_raceplans",
return_value=[raceplan_interval_start],
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.get("/raceplans")
assert resp.status == 200
assert "application/json" in resp.headers[hdrs.CONTENT_TYPE]
raceplans = await resp.json()
assert type(raceplans) is list
assert len(raceplans) > 0
assert RACEPLAN_ID == raceplans[0]["id"]
@pytest.mark.integration
async def test_get_all_raceplans_individual_sprint(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_individual_sprint: dict,
) -> None:
"""Should return OK and a valid json body."""
RACEPLAN_ID = raceplan_individual_sprint["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_all_raceplans",
return_value=[raceplan_individual_sprint],
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.get("/raceplans")
assert resp.status == 200
assert "application/json" in resp.headers[hdrs.CONTENT_TYPE]
body = await resp.json()
assert type(body) is list
assert len(body) > 0
assert RACEPLAN_ID == body[0]["id"]
@pytest.mark.integration
async def test_delete_raceplan_by_id(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return No Content."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.delete_raceplan",
return_value=RACEPLAN_ID,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.races_adapter.RacesAdapter.get_race_by_id",
side_effect=raceplan_interval_start["races"],
)
mocker.patch(
"race_service.adapters.races_adapter.RacesAdapter.delete_race",
return_value=None,
)
headers = {hdrs.AUTHORIZATION: f"Bearer {token}"}
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.delete(f"/raceplans/{RACEPLAN_ID}", headers=headers)
assert resp.status == 204
# Bad cases
@pytest.mark.integration
async def test_update_raceplan_by_id_missing_mandatory_property(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return 422 HTTPUnprocessableEntity."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.update_raceplan",
return_value=RACEPLAN_ID,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
headers = {
hdrs.CONTENT_TYPE: "application/json",
hdrs.AUTHORIZATION: f"Bearer {token}",
}
request_body = {"id": RACEPLAN_ID}
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.put(
f"/raceplans/{RACEPLAN_ID}", headers=headers, json=request_body
)
assert resp.status == 422
@pytest.mark.integration
async def test_update_raceplan_by_id_different_id_in_body(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return 422 HTTPUnprocessableEntity."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.update_raceplan",
return_value=RACEPLAN_ID,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
headers = {
hdrs.CONTENT_TYPE: "application/json",
hdrs.AUTHORIZATION: f"Bearer {token}",
}
update_body = deepcopy(raceplan_interval_start)
update_body["id"] = "different_id"
request_body = dumps(update_body, indent=4, sort_keys=True, default=str)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.put(
f"/raceplans/{RACEPLAN_ID}", headers=headers, data=request_body
)
assert resp.status == 422
# Unauthorized cases:
@pytest.mark.integration
async def test_update_raceplan_by_id_no_authorization(
client: _TestClient, mocker: MockFixture, raceplan_interval_start: dict
) -> None:
"""Should return 401 Unauthorized."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.update_raceplan",
return_value=RACEPLAN_ID,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
headers = {
hdrs.CONTENT_TYPE: "application/json",
hdrs.AUTHORIZATION: f"Bearer {token}",
}
request_body = dumps(raceplan_interval_start, indent=4, sort_keys=True, default=str)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=401)
resp = await client.put(
f"/raceplans/{RACEPLAN_ID}", headers=headers, data=request_body
)
assert resp.status == 401
@pytest.mark.integration
async def test_delete_raceplan_by_id_no_authorization(
client: _TestClient, mocker: MockFixture, raceplan_interval_start: dict
) -> None:
"""Should return 401 Unauthorized."""
RACEPLAN_ID = raceplan_interval_start["id"]
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.delete_raceplan",
return_value=RACEPLAN_ID,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=401)
resp = await client.delete(f"/raceplans/{RACEPLAN_ID}")
assert resp.status == 401
# Forbidden:
@pytest.mark.integration
async def test_update_raceplan_insufficient_role(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return 403 Forbidden."""
RACEPLAN_ID = "does-not-exist"
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=raceplan_interval_start,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.update_raceplan",
return_value=True,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=[raceplan_interval_start],
)
headers = {
hdrs.CONTENT_TYPE: "application/json",
hdrs.AUTHORIZATION: f"Bearer {token}",
}
request_body = dumps(raceplan_interval_start, indent=4, sort_keys=True, default=str)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=403)
resp = await client.put(
f"/raceplans/{RACEPLAN_ID}", headers=headers, data=request_body
)
assert resp.status == 403
# NOT FOUND CASES:
@pytest.mark.integration
async def test_get_raceplan_not_found(
client: _TestClient, mocker: MockFixture, token: MockFixture
) -> None:
"""Should return 404 Not found."""
RACEPLAN_ID = "does-not-exist"
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.get(f"/raceplans/{RACEPLAN_ID}")
assert resp.status == 404
@pytest.mark.integration
async def test_update_raceplan_not_found(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
raceplan_interval_start: dict,
) -> None:
"""Should return 404 Not found."""
RACEPLAN_ID = "does-not-exist"
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.update_raceplan",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
headers = {
hdrs.CONTENT_TYPE: "application/json",
hdrs.AUTHORIZATION: f"Bearer {token}",
}
request_body = dumps(raceplan_interval_start, indent=4, sort_keys=True, default=str)
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.put(
f"/raceplans/{RACEPLAN_ID}", headers=headers, data=request_body
)
assert resp.status == 404
@pytest.mark.integration
async def test_delete_raceplan_not_found(
client: _TestClient, mocker: MockFixture, token: MockFixture
) -> None:
"""Should return 404 Not found."""
RACEPLAN_ID = "does-not-exist"
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_id",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.delete_raceplan",
return_value=None,
)
mocker.patch(
"race_service.adapters.raceplans_adapter.RaceplansAdapter.get_raceplan_by_event_id",
return_value=None,
)
headers = {hdrs.AUTHORIZATION: f"Bearer {token}"}
with aioresponses(passthrough=["http://127.0.0.1"]) as m:
m.post("http://users.example.com:8081/authorize", status=204)
resp = await client.delete(f"/raceplans/{RACEPLAN_ID}", headers=headers)
assert resp.status == 404
| [
37811,
34500,
1358,
1332,
2663,
329,
262,
3234,
489,
504,
6339,
526,
15931,
198,
6738,
4866,
1330,
2769,
30073,
198,
6738,
4818,
8079,
1330,
4818,
8079,
198,
6738,
33918,
1330,
45514,
198,
11748,
28686,
198,
198,
6738,
257,
952,
4023,
1... | 2.007807 | 14,602 |
"""
Unit tests of components in pgic.py. This should be run via pytest
"""
import numpy as np
import pgs_correct.pgic as pgic
import pytest
###########################################
###########################################
###########################################
###########################################
arg_to_flag_dict = {
"" : "",
" " : " ",
"abc" : "abc",
"ab_c" : "ab-c",
"a_b_c" : "a-b-c"
}
flag_to_arg_dict = {arg_to_flag_dict[arg] : arg for arg in arg_to_flag_dict}
test_arg_flag_pairs = list(arg_to_flag_dict.items())
test_flag_arg_pairs = list(flag_to_arg_dict.items())
test_args = list(arg_to_flag_dict.keys())
test_flags = list(flag_to_arg_dict.keys())
###########################################
# TODO(jonbjala) Was just starting to write these tests when we had our meeting, so I'm just
# block commenting these for now. If I can fit them in with the MVP delivery, then great, but if
# not, then it's not critical.
# test_gcta_base_settings = InternalNamespace()
# test_gcta_base_settings.pheno_file = None
# test_gcta_base_settings.bfile = None
# test_gcta_base_settings.gcta_exec = None
# test_gcta_base_settings.grm = None
# test_gcta_base_settings.grm_cutoff = 0.25
# class TestValidateGCTAInputs:
# #########
# @pytest.mark.parametrize("user_args, parsed_args, settings",
# [
# ({})
# ]
# )
# def test_nogcta_nogctaflags_noerrors(self, user_args, parsed_args, settings):
# validate_gcta_inputs(user_args, parsed_args, settings)
# #########
# @pytest.mark.parametrize("user_args, parsed_args, settings", [])
# def test_gcta_allgctaflags_noerrors(self, user_args, parsed_args, settings):
# validate_gcta_inputs(user_args, parsed_args, settings)
# #########
# @pytest.mark.parametrize("user_args, parsed_args, settings", [])
# def test_nogcta_withgctaflags_noforce_errors(self, user_args, parsed_args, settings):
# settings.force = false
# with pytest.raises(RuntimeError):
# validate_gcta_inputs(user_args, parsed_args, settings)
# #########
# @pytest.mark.parametrize("user_args, parsed_args, settings", [])
# def test_nogcta_withgctaflags_withforce_errors(self, user_args, parsed_args, settings):
# settings.force = true
# validate_gcta_inputs(user_args, parsed_args, settings) # TODO(check stderr for warning?)
# #########
# @pytest.mark.parametrize("user_args, parsed_args, settings", [])
# def test_gcta_missinggctaflags_errors(self, user_args, parsed_args, settings):
# with pytest.raises(RuntimeError):
# validate_gcta_inputs(user_args, parsed_args, settings)
# #########
# @pytest.mark.parametrize("user_args, parsed_args, settings", [])
# def test_gcta_wrongexec_errors(self, user_args, parsed_args, settings):
# with pytest.raises(NameError):
# validate_gcta_inputs(user_args, parsed_args, settings)
###########################################
| [
37811,
198,
26453,
5254,
286,
6805,
287,
23241,
291,
13,
9078,
13,
220,
770,
815,
307,
1057,
2884,
12972,
9288,
198,
37811,
198,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
279,
14542,
62,
30283,
13,
6024,
291,
355,
23241,
291,
19... | 2.490148 | 1,218 |
import os
import uuid
import time
import logging
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
from src.data import CarDataset
from src.data import batchfy,test_batchfy
from src.utils import to_device,write_to_txt
from src.evaluate import evaluate_dataset,draw_result,test_raw_dataset
from src.model import IGANN,TEIGANN
from config import get_parse_args
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger()
if __name__ == "__main__":
main()
| [
11748,
28686,
198,
11748,
334,
27112,
198,
11748,
640,
198,
11748,
18931,
198,
11748,
299,
32152,
355,
45941,
198,
198,
11748,
28034,
198,
11748,
28034,
13,
40085,
355,
6436,
198,
11748,
28034,
13,
20471,
355,
299,
77,
198,
198,
6738,
1... | 2.953125 | 192 |
from .device import Device
from .peripheral import Peripheral
from .sample import Sample
from .measurement import Measurement
def jsonToDeviceDict(json):
"""Convert json to list of Device objects."""
deviceDict = {}
for jsonDevice in json:
mac = jsonDevice.get("mac")
address = jsonDevice.get("address")
name = jsonDevice.get("name")
description = jsonDevice.get("description")
location = jsonDevice.get("location")
type = jsonDevice.get("type")
battery = jsonDevice.get("battery")
version =jsonDevice.get("version")
status = jsonDevice.get("status")
peripherals = jsonDevice.get("peripherals")
peripheralList = jsonToPeripheralDict(peripherals, mac)
deviceDict.update({mac : Device(address, peripheralList, name, description, location, type, battery, version, mac, status)})
return deviceDict
def jsonToPeripheralDict(json, parentMac):
"""Convert json to list of Peripheral objects."""
peripheralDict = {}
for peripheral in json:
identifier = peripheral.get("identifier")
samplingRate = peripheral.get("sampling_rate")
lastUpdated = peripheral.get("last_updated")
color = peripheral.get("color")
icon = peripheral.get("icon")
text = peripheral.get("text")
classification = peripheral.get("class")
measurements = peripheral.get("measurements")
measurementList = jsonToMeasurementList(measurements)
peripheralDict.update({ identifier : Peripheral(samplingRate, identifier, lastUpdated, color, icon, text, classification, parentMac, measurementList)})
return peripheralDict
def jsonToMeasurementList(json):
"""Convert json to list of measurements"""
measurementList = []
for measurement in json:
unit = measurement.get("unit")
rounding = measurement.get("round")
datatype = measurement.get("datatype")
origin = measurement.get("origin")
decimals = measurement.get("decimals")
name = measurement.get("name")
formula = measurement.get("formula")
measurementList.append(Measurement(unit, rounding, datatype, origin, decimals, name, formula))
return measurementList
def jsonToSampleList(json):
"""Convert json to list of Sample objects"""
sampleList = []
parentId = json["identifier"]
for data in json["data"]:
unit = data["unit"]
value = data["value"]
datatype = data["datatype"]
measurement = data["measurement"]
timestamp = data["timestamp"]
sampleList.append(Sample(unit, value, datatype, measurement, timestamp, parentId))
return sampleList | [
6738,
764,
25202,
1330,
16232,
198,
6738,
764,
525,
10803,
282,
1330,
2448,
10803,
282,
198,
6738,
764,
39873,
1330,
27565,
198,
6738,
764,
1326,
5015,
434,
1330,
24291,
434,
198,
198,
4299,
33918,
2514,
24728,
35,
713,
7,
17752,
2599,
... | 2.824635 | 958 |
import os
import instaloader
if __name__ == "__main__":
user=input("Enter Insta Account: ")
picture_download(user)
| [
11748,
28686,
198,
11748,
916,
282,
1170,
263,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
2836,
28,
15414,
7203,
17469,
2262,
64,
10781,
25,
366,
8,
198,
220,
220,
220,
4286,
62,
15002,
7,... | 2.344828 | 58 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
############################################################
# @Author : Sean
# @Date : 2022-02-22 19:05:52
# @LastEditors : Sean
# @LastEditTime : 2022-03-10 15:26:49
# @Description : 这是由 Sean 创建
# @FilePath : /run.py
# @Copyright : Copyright ©2019-2022 Sean,Inc
############################################################
from captcha_app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=5000) | [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
40477,
12,
23,
532,
9,
12,
198,
29113,
14468,
7804,
4242,
198,
2,
2488,
13838,
220,
220,
220,
220,
220,
220,
1058,
11465,
198,
2,
2488,
10430,
220,
220,
... | 2.666667 | 198 |
from forms_api.fields.base_field import Field
from forms_api.html import generate_submit
| [
6738,
5107,
62,
15042,
13,
25747,
13,
8692,
62,
3245,
1330,
7663,
198,
6738,
5107,
62,
15042,
13,
6494,
1330,
7716,
62,
46002,
628
] | 3.75 | 24 |
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from myapp import models | [
6738,
42625,
14208,
13,
9288,
1330,
6208,
20448,
198,
6738,
42625,
14208,
13,
6371,
82,
1330,
9575,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
27530,
1330,
11787,
198,
198,
6738,
616,
1324,
1330,
4981
] | 3.621622 | 37 |
# Copyright 2020 Open Climate Tech Contributors
#
# 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.
# ==============================================================================
"""
Diff two images with offset to avoid negative numbers
result = (128 + a/2) - b/2
"""
import os, sys
from firecam.lib import settings
from firecam.lib import collect_args
from firecam.lib import goog_helper
from firecam.lib import img_archive
import logging
from PIL import Image
import cv2
import numpy as np
if __name__=="__main__":
main()
| [
2,
15069,
12131,
4946,
13963,
9634,
25767,
669,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846,
351,
262,
13789,
13,
198,
... | 3.794118 | 272 |
# Third party code
#
# The following code are copied or modified from:
# https://github.com/ray-project/ray/blob/master/python/ray/rllib/utils/filter.py
import numpy as np
class SharedNoiseTable(object):
"""Shared noise table used by learner and actor.
Learner and actor will create a same noise table by passing the same seed.
With the same noise table, learner and actor can communicate the noises by
index of noise table instead of numpy array of noises.
"""
| [
2,
10467,
2151,
2438,
198,
2,
198,
2,
383,
1708,
2438,
389,
18984,
393,
9518,
422,
25,
198,
2,
3740,
1378,
12567,
13,
785,
14,
2433,
12,
16302,
14,
2433,
14,
2436,
672,
14,
9866,
14,
29412,
14,
2433,
14,
81,
297,
571,
14,
26791,... | 3.398601 | 143 |
n, m = [int(i) for i in input().split()]
a = [input().split() for i in range(n)]
while n%2==0:
if a[:n//2] == a[n//2:n][::-1]:
n //= 2
else:
break
print(n)
| [
77,
11,
285,
796,
685,
600,
7,
72,
8,
329,
1312,
287,
5128,
22446,
35312,
3419,
60,
198,
64,
796,
685,
15414,
22446,
35312,
3419,
329,
1312,
287,
2837,
7,
77,
15437,
198,
4514,
299,
4,
17,
855,
15,
25,
198,
220,
220,
220,
611,
... | 1.836735 | 98 |
from .motifprogram import MotifProgram
import os
from subprocess import Popen, PIPE
class Yamda(MotifProgram):
"""
Predict motifs using YAMDA.
Reference: Quang et al., 2018, https://doi.org/10.1093/bioinformatics/bty396
"""
def _parse_params(self, params=None):
"""
Parse parameters.
Combine default and user-defined parameters.
"""
prm = super._parse_params(params, needs_background=True)
prm["strand"] = ""
if not prm["single"]:
prm["strand"] = " --revcomp "
return prm
def _run_program(self, bin, fastafile, params=None):
"""
Run YAMDA and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict, optional
Optional parameters. For some of the tools required parameters
are passed using this dictionary.
Returns
-------
motifs : list of Motif instances
The predicted motifs.
stdout : str
Standard out of the tool.
stderr : str
Standard error of the tool.
"""
params = self._parse_params(params)
outfile = os.path.join(self.tmpdir, "motifs.txt")
stdout = ""
stderr = ""
cmd = "%s -i %s -j %s -n %s -w %s -oc %s %s" % (
bin,
fastafile,
params["background"],
params["number"],
params["width"],
self.tmpdir,
params["strand"],
)
print(cmd)
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.tmpdir)
out, err = p.communicate()
stdout += out.decode()
stderr += err.decode()
motifs, stdout, stderr = self._read_and_label_motifs(
outfile, stdout, stderr, fmt="meme"
)
return motifs, stdout, stderr
| [
6738,
764,
27926,
361,
23065,
1330,
6543,
361,
15167,
198,
11748,
28686,
198,
6738,
850,
14681,
1330,
8099,
268,
11,
350,
4061,
36,
628,
198,
4871,
14063,
6814,
7,
47733,
361,
15167,
2599,
628,
220,
220,
220,
37227,
198,
220,
220,
220... | 2.073998 | 973 |
# -*- coding: utf-8 -*-
# ███╗ ███╗ █████╗ ███╗ ██╗██╗ ██████╗ ██████╗ ███╗ ███╗██╗ ██████╗
# ████╗ ████║██╔══██╗████╗ ██║██║██╔════╝██╔═══██╗████╗ ████║██║██╔═══██╗
# ██╔████╔██║███████║██╔██╗ ██║██║██║ ██║ ██║██╔████╔██║██║██║ ██║
# ██║╚██╔╝██║██╔══██║██║╚██╗██║██║██║ ██║ ██║██║╚██╔╝██║██║██║ ██║
# ██║ ╚═╝ ██║██║ ██║██║ ╚████║██║╚██████╗╚██████╔╝██║ ╚═╝ ██║██║╚██████╔╝
# ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═════╝
# [+] @GorpoOrko 2020 - Telegram Bot and Personal Assistant [+]
# | TCXS Project Hacker Team - https://tcxsproject.com.br |
# | Telegram: @GorpoOrko Mail:gorpoorko@protonmail.com |
# [+] Github Gorpo Dev: https://github.com/gorpo [+]
from config import bot, bot_username
from db_handler import conn, cursor
from .admins import is_admin
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
23287,
9968,
22880,
245,
220,
220,
23287,
9968,
22880,
245,
23287,
20503,
22880,
245,
23287,
9968,
22880,
245,
220,
220,
23287,
8115,
22880,
245,
9968,
22880,
245,
2328... | 1.43266 | 594 |
# Project Euler 11 - Largest product in a grid
# GitHub: urtuba
import numpy as np
def load_2d_array(filename: str) -> np.ndarray:
'''
Reads a txt file into 2d numpy integer array.
:param filename: name of the txt file.
:return: 2d numpy array
'''
with open(filename, 'r') as file:
array_2d = np.loadtxt(filename, dtype=np.int32, ndmin=2)
return array_2d
def largest_product_of_quarts(array_2d: np.ndarray) -> int:
'''
Returns largest product of four adjacent integers in the given 2D array.
Adjacency can occur horizontally, vertically or diagonally.
:param array_2d: 2d array, n x n.
:return: largest product of 4 adjacent numbers
'''
# hidden helper functions
# actual function body
rows_max = _max_quart_product_of_rows(array_2d)
cols_max = _max_quart_product_of_cols(array_2d)
diags_max = _max_quart_product_of_diags(array_2d)
return max(rows_max, cols_max, diags_max)
if __name__ == '__main__':
matrix = load_2d_array('s011-input.txt')
result = largest_product_of_quarts(matrix)
print (result) | [
2,
4935,
412,
18173,
1367,
532,
406,
853,
395,
1720,
287,
257,
10706,
198,
2,
21722,
25,
2956,
83,
22013,
198,
198,
11748,
299,
32152,
355,
45941,
198,
198,
4299,
3440,
62,
17,
67,
62,
18747,
7,
34345,
25,
965,
8,
4613,
45941,
13,... | 2.504525 | 442 |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from datetime import datetime, timezone
from pathlib import Path
# Due to the way the filesystem is mocked in unit tests, values should not be Path instances.
# The file in which general CLI configuration is stored
GENERAL_CONFIG_PATH = str(Path("~/.lean/config").expanduser())
# The file in which credentials are stored
CREDENTIALS_CONFIG_PATH = str(Path("~/.lean/credentials").expanduser())
# The file in which we store when we last checked for updates
CACHE_PATH = str(Path("~/.lean/cache").expanduser())
# The default name of the file containing the Lean engine configuration
DEFAULT_LEAN_CONFIG_FILE_NAME = "lean.json"
# The default name of the directory containing the market data
DEFAULT_DATA_DIRECTORY_NAME = "data"
# The name of the file in containing the project configuration
PROJECT_CONFIG_FILE_NAME = "config.json"
# The default Docker image used when running the LEAN engine locally
DEFAULT_ENGINE_IMAGE = "quantconnect/lean:latest"
# The default Docker image used when running a Jupyter Lab environment locally
DEFAULT_RESEARCH_IMAGE = "quantconnect/research:latest"
# The creation timestamp of the first image supporting .NET 5
DOTNET_5_IMAGE_CREATED_TIMESTAMP = datetime(2021, 5, 6, 21, 32, 26, tzinfo=timezone.utc)
# The base url of the QuantConnect API
# This url should end with a forward slash
API_BASE_URL = "https://www.quantconnect.com/api/v2/"
# The interval in hours at which the CLI checks for updates to itself
UPDATE_CHECK_INTERVAL_CLI = 24
# The interval in hours at which the CLI checks for updates to Docker images that are being ran
UPDATE_CHECK_INTERVAL_DOCKER_IMAGE = 24 * 14
| [
2,
19604,
1565,
4825,
1340,
48842,
13,
9858,
532,
9755,
2890,
15007,
11,
2295,
6477,
278,
34884,
13,
198,
2,
45661,
43749,
410,
16,
13,
15,
13,
15069,
33448,
16972,
13313,
10501,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11... | 3.548837 | 645 |
import random
from timeit import timeit
if __name__ == '__main__':
# Correctness
print(main([10, 2, 3, 4, 5, 11, 6, 7, 8, 9], 19)) # True
print(main([10, 2, 3, 4, 5, 11, 6, 7, 8, 9], 40)) # False
items = [random.choice(range(10_000)) for _ in range(10_000)]
res1 = timeit("main(items, 17)", number=10, globals=globals())
print(res1) # Duration
| [
11748,
4738,
198,
6738,
640,
270,
1330,
640,
270,
628,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
1303,
22941,
1108,
198,
220,
220,
220,
3601,
7,
12417,
26933,
940,
11,
362,
11,
513,
11,
... | 2.348101 | 158 |
import os
import subprocess
import pytest
from pre_commit_hooks.destroyed_symlinks import find_destroyed_symlinks
from pre_commit_hooks.destroyed_symlinks import main
TEST_SYMLINK = 'test_symlink'
TEST_SYMLINK_TARGET = '/doesnt/really/matters'
TEST_FILE = 'test_file'
TEST_FILE_RENAMED = f'{TEST_FILE}_renamed'
@pytest.fixture
| [
11748,
28686,
198,
11748,
850,
14681,
198,
198,
11748,
12972,
9288,
198,
198,
6738,
662,
62,
41509,
62,
25480,
82,
13,
41659,
276,
62,
37047,
28751,
1330,
1064,
62,
41659,
276,
62,
37047,
28751,
198,
6738,
662,
62,
41509,
62,
25480,
8... | 2.581395 | 129 |
import numpy as np
from itertools import combinations
from tabulate import tabulate
from scipy.stats import wilcoxon, ttest_rel, ttest_ind
import matplotlib.pyplot as plt
from tabulate import tabulate
from matplotlib import rcParams
### E1 get end
np.set_printoptions(precision=3)
alpha = 0.05
results = np.load("results2.npy")
optimized = np.load("optimized.npy")
optimized = np.moveaxis(optimized, 0, 1)
"""
# Dimensions are
# 0 - replication
# 1 - stream
# 2 - base_estimator
# 3 - method
# 4 - chunk
# 5 - metric
"""
# Flatten replication, chunks and metric
results = np.mean(results, axis=(4, 5))
# stream, replication
results = np.moveaxis(results, 0, 3)
# SEA, WAEdef, AWE, AUE, WAEopt
results = np.concatenate((results, optimized[:, :, np.newaxis, :]), axis=2)
"""
# Dimensions are
# 0 - stream
# 1 - base_estimator
# 2 - method
# 3 - replication
"""
# Analysis
met = ["SEA", "AWE", "AUE", "NSE", "OALE", "(d) WAE", "(o) WAE"]
bases = ["GNB", "HT", "MLP"]
analyze_scores = []
analyze_stat = []
for i, stream in enumerate(results):
print("Stream", i)
for j, base_estimator in enumerate(stream):
print(bases[j])
# Statistical analysis
mean_results = np.mean(base_estimator, axis=1)
best_idx = np.argmax(mean_results)
a = base_estimator[best_idx]
full_p = np.array(
[
[ttest_ind(a, b).pvalue < alpha for a in base_estimator]
for b in base_estimator
]
)
full_T = np.array(
[
[ttest_ind(a, b).statistic < 0 for a in base_estimator]
for b in base_estimator
]
)
tested = full_p * full_T
for k, method in enumerate(base_estimator):
b = base_estimator[k]
better_then = np.where(tested[k])[0] + 1
if met[k] == "AUE":
analyze_scores.append(np.mean(method))
print(
"%.3f" % np.mean(method),
)
analyze_stat.append(", ".join(["%i" % z for z in better_then]))
print(
", ".join(["%i" % z for z in better_then]),
)
print(tabulate(np.array([analyze_scores]), floatfmt=".3f", tablefmt="latex_booktabs"))
print(tabulate(np.array([analyze_stat]), tablefmt="latex_booktabs"))
| [
11748,
299,
32152,
355,
45941,
198,
6738,
340,
861,
10141,
1330,
17790,
198,
6738,
7400,
5039,
1330,
7400,
5039,
198,
6738,
629,
541,
88,
13,
34242,
1330,
39716,
1073,
23813,
11,
256,
9288,
62,
2411,
11,
256,
9288,
62,
521,
198,
11748... | 2.107047 | 1,121 |
from .apiattr import ApiAttributeMixin
from .files import GoogleDriveFile
from .files import GoogleDriveFileList
from .auth import LoadAuth
import auth
class GoogleDrive(ApiAttributeMixin, object):
"""Main Google Drive class."""
def __init__(self, auth=None):
"""Create an instance of GoogleDrive.
:param auth: authorized GoogleAuth instance.
:type auth: pydrive2.auth.GoogleAuth.
"""
ApiAttributeMixin.__init__(self)
self.auth = auth
def CreateFile(self, metadata=None):
"""Create an instance of GoogleDriveFile with auth of this instance.
This method would not upload a file to GoogleDrive.
:param metadata: file resource to initialize GoogleDriveFile with.
:type metadata: dict.
:returns: pydrive2.files.GoogleDriveFile -- initialized with auth of this
instance.
"""
return GoogleDriveFile(auth=self.auth, metadata=metadata)
def ListFile(self, param=None):
"""Create an instance of GoogleDriveFileList with auth of this instance.
This method will not fetch from Files.List().
:param param: parameter to be sent to Files.List().
:type param: dict.
:returns: pydrive2.files.GoogleDriveFileList -- initialized with auth of
this instance.
"""
return GoogleDriveFileList(auth=self.auth, param=param)
@LoadAuth
def GetAbout(self):
"""Return information about the Google Drive of the auth instance.
:returns: A dictionary of Google Drive information like user, usage, quota etc.
"""
return self.auth.service.about().get().execute(http=self.http) | [
6738,
764,
15042,
35226,
1330,
5949,
72,
33682,
35608,
259,
198,
6738,
764,
16624,
1330,
3012,
24825,
8979,
198,
6738,
764,
16624,
1330,
3012,
24825,
8979,
8053,
198,
6738,
764,
18439,
1330,
8778,
30515,
198,
11748,
6284,
628,
198,
4871,
... | 2.992687 | 547 |
{
"make_global_settings": [
["CC", "/usr/bin/clang"],
["CXX", "/usr/bin/clang++"]
],
"targets": [
{
"target_name": "OSLogger",
"sources": ["OSLogger.mm", "functions.cc"],
"include_dirs": ["<!(node -e \"require('nan')\")"],
"xcode_settings": {
"CC": "clang",
"MACOSX_DEPLOYMENT_TARGET": "10.14",
"CLANG_CXX_LIBRARY": "libc++",
"OTHER_CPLUSPLUSFLAGS" : ["-std=gnu++14", "-stdlib=libc++"],
"OTHER_CFLAGS": [
"-ObjC",
"-xobjective-c"
],
}
}
]
}
| [
90,
198,
220,
366,
15883,
62,
20541,
62,
33692,
1298,
685,
198,
220,
220,
220,
14631,
4093,
1600,
12813,
14629,
14,
8800,
14,
565,
648,
33116,
198,
220,
220,
220,
14631,
34,
8051,
1600,
12813,
14629,
14,
8800,
14,
565,
648,
4880,
89... | 1.791798 | 317 |
from datetime import datetime, timedelta
import logging
from math import ceil
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse, reverse_lazy
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.utils import timezone
from django.views.generic import CreateView, DeleteView, FormView, ListView, TemplateView, UpdateView, View
from zentral.core.incidents.models import MachineIncident
from zentral.core.stores import frontend_store
from zentral.utils.prometheus import BasePrometheusMetricsView
from .forms import (MetaBusinessUnitForm,
MetaBusinessUnitSearchForm, MachineGroupSearchForm,
MergeMBUForm, MBUAPIEnrollmentForm, AddMBUTagForm, AddMachineTagForm,
CreateTagForm, UpdateTagForm,
MacOSAppSearchForm)
from .models import (BusinessUnit,
MetaBusinessUnit, MachineGroup,
MetaMachine,
MetaBusinessUnitTag, MachineTag, Tag, Taxonomy,
OSXApp, OSXAppInstance)
from .utils import (get_prometheus_inventory_metrics,
BundleFilter, BundleFilterForm,
MachineGroupFilter, MetaBusinessUnitFilter, OSXAppInstanceFilter,
MSQuery)
logger = logging.getLogger("zentral.contrib.inventory.views")
TAG_COLOR_PRESETS = {
"green": "61bd4f",
"yellow": "f2d600",
"orange": "ffab4a",
"red": "eb5a46",
"purple": "c377e0",
"blue": "0079bf",
"sky": "00c2e0",
"lime": "51e898",
"pink": "ff80ce",
"black": "4d4d4d",
"grey": "b6bbbf"
}
| [
6738,
4818,
8079,
1330,
4818,
8079,
11,
28805,
12514,
198,
11748,
18931,
198,
6738,
10688,
1330,
2906,
346,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
19816,
1040,
1330,
23093,
37374,
35608,
259,
198,
6738,
42625,
14208,
13,
... | 2.391129 | 744 |
from selector import get_user
from utils.hashing import decode_token, verify_password
| [
6738,
31870,
1330,
651,
62,
7220,
198,
6738,
3384,
4487,
13,
71,
2140,
1330,
36899,
62,
30001,
11,
11767,
62,
28712,
628,
198
] | 3.826087 | 23 |
from datetime import date
from django.core.cache import cache
from django.db.models import Q,F
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponse,HttpRequest
from django.views.generic import ListView, DetailView
from blog.models import Post, Category, Tag
from config.models import Sidebar
# Create your views here.
# function view
# def post_list(requset:HttpRequest, category_id=None, tag_id=None):
#
# tag = None
# category = None
# if tag_id:
# tag, post_list = Post.get_by_tag(tag_id)
#
# elif category_id:
# category, post_list = Post.get_by_category(category_id)
# else:
# post_list = Post.latest_post()
# context = {
# 'tag':tag,
# 'category':category,
# 'post_list':post_list,
# 'sidebars':Sidebar.get_all(),
# 'test':Post.get_hots()
# }
# context.update(Category.get_navs())
# print(context)
# return render(requset, 'blog/list.html', context=context)
#
# def post_detail(requset:HttpRequest, post_id):
# try:
# print(post_id)
# post = Post.objects.get(pk=post_id)
# except Exception:
# post = None
#
# context = {
# 'post':post,
# 'sidebars': Sidebar.get_all(),
# }
# context.update(Category.get_navs())
# return render(requset, 'blog/detail.html', context=context)
# class view
# 心得 queryset -> get_context_data -> get_pagenate_by -> get_context_obj_name -> paginate_queryset -> get_template_names | [
6738,
4818,
8079,
1330,
3128,
198,
198,
6738,
42625,
14208,
13,
7295,
13,
23870,
1330,
220,
12940,
198,
6738,
42625,
14208,
13,
9945,
13,
27530,
1330,
1195,
11,
37,
198,
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
198,
6738,
42625... | 2.348348 | 666 |
#!/usr/bin/env python
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB
storage = FileStorage('Data.fs')
db = DB(storage)
connection = db.open()
root = connection.root()
print root.keys()
print root.items()
print
print 'account-list-1:'
for aa in root['account-list-1']:
print aa.__dict__
print
print 'account-list-2:'
for aa in root['account-list-2']:
print aa.__dict__
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
628,
198,
6738,
1168,
3727,
33,
13,
8979,
31425,
1330,
9220,
31425,
198,
6738,
1168,
3727,
33,
13,
11012,
1330,
20137,
198,
198,
35350,
796,
9220,
31425,
10786,
6601,
13,
9501,
11537,
198,
... | 2.684564 | 149 |
import jwt
from django.conf import settings
from rest_framework import authentication, exceptions
from .models import User
class JWTAuthentication(authentication.BaseAuthentication):
"""Configure JWT Here"""
def get_authentication_credencials(self, request, token):
"""
Try to authenticate the given credentials. If authentication is
successful, return the user and token. If not, throw an error.
"""
payload = self.decode_token(token)
user = self.get_user(payload)
if not user.is_verified:
msg = ("This user account is not verified. " +
"Check your email for activation link")
raise exceptions.AuthenticationFailed(msg)
return (user, token)
def get_verification_credencials(self, request, token):
"""
Try to authenticate the given credentials. If authentication is
successful, return the user and token. If not, throw an error.
"""
payload = self.decode_token(token)
user = self.get_user(payload)
return (user, token)
| [
11748,
474,
46569,
198,
198,
6738,
42625,
14208,
13,
10414,
1330,
6460,
198,
198,
6738,
1334,
62,
30604,
1330,
18239,
11,
13269,
198,
6738,
764,
27530,
1330,
11787,
628,
198,
4871,
449,
54,
5603,
315,
6925,
3299,
7,
41299,
3299,
13,
1... | 2.619718 | 426 |
from rest_framework.exceptions import APIException
| [
6738,
1334,
62,
30604,
13,
1069,
11755,
1330,
7824,
16922,
628
] | 4.727273 | 11 |
from flask import Blueprint, render_template
main_blueprint = Blueprint("main", __name__, template_folder="templates")
@main_blueprint.route("/")
@main_blueprint.route("/main")
def main():
"""
View method to render the home.html page - https://www.abhishekpednekar.com/
Returns
-------
home.html: html / jinja2 template
"""
return render_template("home.html")
| [
6738,
42903,
1330,
39932,
11,
8543,
62,
28243,
198,
198,
12417,
62,
17585,
4798,
796,
39932,
7203,
12417,
1600,
11593,
3672,
834,
11,
11055,
62,
43551,
2625,
11498,
17041,
4943,
628,
198,
31,
12417,
62,
17585,
4798,
13,
38629,
7203,
14,... | 2.903704 | 135 |
import random
import time
from twisted.internet import reactor | [
11748,
4738,
198,
11748,
640,
198,
6738,
19074,
13,
37675,
1330,
21905
] | 5.166667 | 12 |
from datetime import datetime
from time import sleep
from typing import List, Tuple
from rich.console import Group
from rich.live import Live
from rich.panel import Panel
from ..controller import GithubPullRequestController, GitlabPullRequestController, PullRequestController
from ..layout import (
RenderLayoutManager,
generate_layout,
generate_log_table,
generate_progress_tracker,
generate_tree_layout,
)
from .controller import render_config_table
from .helpers import get_configuration
from .settings import (
GITHUB_DEFAULT_PAGE_SIZE,
GITHUB_TOKEN,
GITHUB_URL,
GITHUB_USER,
GITLAB_TOKEN,
GITLAB_URL,
GITLAB_USER,
REVIEWS_DELAY_REFRESH,
REVIEWS_GITHUB_REPOSITORY_CONFIGURATION,
REVIEWS_GITLAB_REPOSITORY_CONFIGURATION,
REVIEWS_LABEL_CONFIGURATION,
REVIEWS_PATH_TO_CONFIG,
)
logs: List[Tuple[str, str]] = []
def add_log_event(message: str) -> List[Tuple[str, str]]:
"""adds a log event to a list of logs and displays the top 20."""
global logs
logs = logs[-20:]
logs.append((str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")), f"[white]{message}"))
return logs
def single_render(provider: str) -> None:
"""Renders the Terminal UI Dashboard once before closing the application"""
configuration = None
body = None
if provider == "gitlab":
configuration = get_configuration(config=REVIEWS_GITLAB_REPOSITORY_CONFIGURATION)
body = GitlabPullRequestController().render(configuration=configuration)
else:
configuration = get_configuration(config=REVIEWS_GITHUB_REPOSITORY_CONFIGURATION)
body = GithubPullRequestController().render(configuration=configuration)
layout_manager = RenderLayoutManager(layout=generate_layout(log=False, footer=False))
layout_manager.render_layout(
progress_table=None,
body=body,
pull_request_component=generate_tree_layout(configuration=configuration),
log_component=None,
)
with Live(
renderable=layout_manager.layout,
refresh_per_second=5,
transient=False,
screen=False,
):
add_log_event(message="updated")
def render(provider: str) -> None:
"""Renders Terminal UI Dashboard"""
(
job_progress,
overall_progress,
overall_task,
progress_table,
) = generate_progress_tracker()
# initial load should be from database
add_log_event(message="initializing...")
configuration = None
controller: PullRequestController
if provider == "gitlab":
configuration = get_configuration(config=REVIEWS_GITLAB_REPOSITORY_CONFIGURATION)
controller = GitlabPullRequestController()
else:
configuration = get_configuration(config=REVIEWS_GITHUB_REPOSITORY_CONFIGURATION)
controller = GithubPullRequestController()
layout_manager = RenderLayoutManager(layout=generate_layout())
layout_manager.render_layout(
progress_table=progress_table,
body=Panel(
Group(),
title="Activity",
border_style="blue",
),
pull_request_component=generate_tree_layout(configuration=configuration),
log_component=generate_log_table(logs=logs),
)
with Live(layout_manager.layout, refresh_per_second=5, screen=True):
while True:
if not overall_progress or overall_progress.finished:
(
job_progress,
overall_progress,
overall_task,
progress_table,
) = generate_progress_tracker()
add_log_event(message="waiting...")
# update view (blocking operation)
layout_manager.render_layout(
progress_table=progress_table,
body=controller.render(configuration=configuration),
pull_request_component=generate_tree_layout(configuration=configuration),
log_component=generate_log_table(logs=logs),
)
delay = REVIEWS_DELAY_REFRESH * 0.01
while not overall_progress.finished:
sleep(delay)
for job in job_progress.tasks:
if not job.finished:
job_progress.advance(job.id)
completed = sum(task.completed for task in job_progress.tasks)
overall_progress.update(overall_task, completed=completed)
add_log_event(message="updated")
def render_config(show: bool) -> None:
"""Renders a table displaying configuration used by Reviews."""
configurations = [
{
"name": "GITHUB_TOKEN",
"value": GITHUB_TOKEN if show else "".join("*" for _ in range(len(GITHUB_TOKEN))),
},
{"name": "GITHUB_USER", "value": GITHUB_USER},
{"name": "GITHUB_URL", "value": GITHUB_URL},
{
"name": "GITLAB_TOKEN",
"value": GITLAB_TOKEN if show else "".join("*" for _ in range(len(GITLAB_TOKEN))),
},
{"name": "GITLAB_USER", "value": GITLAB_USER},
{"name": "GITLAB_URL", "value": GITLAB_URL},
{"name": "REVIEWS_PATH_TO_CONFIG", "value": f"{REVIEWS_PATH_TO_CONFIG}"},
{
"name": "GITHUB_DEFAULT_PAGE_SIZE",
"value": f"{GITHUB_DEFAULT_PAGE_SIZE}",
},
{"name": "REVIEWS_DELAY_REFRESH", "value": f"{REVIEWS_DELAY_REFRESH}"},
{
"name": "REVIEWS_GITHUB_REPOSITORY_CONFIGURATION",
"value": ", ".join(REVIEWS_GITHUB_REPOSITORY_CONFIGURATION),
},
{
"name": "REVIEWS_GITLAB_REPOSITORY_CONFIGURATION",
"value": ", ".join(REVIEWS_GITLAB_REPOSITORY_CONFIGURATION),
},
{
"name": "REVIEWS_LABEL_CONFIGURATION",
"value": ", ".join(REVIEWS_LABEL_CONFIGURATION),
},
]
render_config_table(configurations=configurations)
| [
6738,
4818,
8079,
1330,
4818,
8079,
198,
6738,
640,
1330,
3993,
198,
6738,
19720,
1330,
7343,
11,
309,
29291,
198,
198,
6738,
5527,
13,
41947,
1330,
4912,
198,
6738,
5527,
13,
12583,
1330,
7547,
198,
6738,
5527,
13,
35330,
1330,
18810,
... | 2.25947 | 2,640 |
from nightwatch.model import API
# TODO: Add CMake support.
"""
cmake_minimum_required(VERSION 3.12)
find_package(PkgConfig REQUIRED)
pkg_check_modules(GLIB REQUIRED glib-2.0)
include_directories(${GLIB_INCLUDE_DIRS})
link_directories(${GLIB_LIBRARY_DIRS} ../../cmake-build-debug/guestlib ../../cmake-build-debug/worker ../../cmake-build-debug/common)
add_definitions(${GLIB_CFLAGS_OTHER} -D_GNU_SOURCE
-Wno-unused-but-set-variable -Wno-unused-variable -Wno-unused-function
-Wno-discarded-qualifiers -Wno-discarded-array-qualifiers
-Wno-deprecated-declarations -Wno-unused-result
-Wl,-z,defs -fvisibility=hidden)
link_directories(../../common)
add_library(guestlib SHARED {api.c_library_spelling})
add_executable(worker {api.c_worker_spelling})
target_include_directories(guestlib PUBLIC . ../../guestlib/include)
target_link_libraries(guestlib common-guest guestliblib)
target_include_directories(worker PUBLIC . ../../worker/include)
target_link_libraries(worker common-worker workerlib tensorflow ${GLIB_LIBRARIES})
"""
| [
6738,
1755,
8340,
13,
19849,
1330,
7824,
628,
198,
198,
2,
16926,
46,
25,
3060,
327,
12050,
1104,
13,
198,
37811,
198,
11215,
539,
62,
39504,
62,
35827,
7,
43717,
513,
13,
1065,
8,
198,
19796,
62,
26495,
7,
47,
10025,
16934,
4526,
... | 2.590244 | 410 |
import keyboard
import time
import os
while True:
if keyboard.is_pressed('Windows')and keyboard.is_pressed('`'):
delay()
time.sleep(5)
| [
11748,
10586,
201,
198,
11748,
640,
201,
198,
11748,
28686,
201,
198,
4514,
6407,
25,
201,
198,
220,
220,
220,
611,
10586,
13,
271,
62,
45477,
10786,
11209,
11537,
392,
10586,
13,
271,
62,
45477,
10786,
63,
6,
2599,
201,
198,
220,
2... | 2.41791 | 67 |
# -*- coding: utf-8 -*-
import numpy as np
import torch
from torch.utils.data import Sampler
class CategoriesSampler(Sampler):
"""A Sampler to sample a FSL task.
Args:
Sampler (torch.utils.data.Sampler): Base sampler from PyTorch.
"""
def __init__(
self,
label_list,
label_num,
episode_size,
episode_num,
way_num,
image_num,
):
"""Init a CategoriesSampler and generate a label-index list.
Args:
label_list (list): The label list from label list.
label_num (int): The number of unique labels.
episode_size (int): FSL setting.
episode_num (int): FSL setting.
way_num (int): FSL setting.
image_num (int): FSL setting.
"""
super(CategoriesSampler, self).__init__(label_list)
self.episode_size = episode_size
self.episode_num = episode_num
self.way_num = way_num
self.image_num = image_num
label_list = np.array(label_list)
self.idx_list = []
for label_idx in range(label_num):
ind = np.argwhere(label_list == label_idx).reshape(-1)
ind = torch.from_numpy(ind)
self.idx_list.append(ind)
def __iter__(self):
"""Random sample a FSL task batch(multi-task).
Yields:
torch.Tensor: The stacked tensor of a FSL task batch(multi-task).
"""
batch = []
for i_batch in range(self.episode_num):
classes = torch.randperm(len(self.idx_list))[: self.way_num]
for c in classes:
idxes = self.idx_list[c.item()]
pos = torch.randperm(idxes.size(0))[: self.image_num]
batch.append(idxes[pos])
if len(batch) == self.episode_size * self.way_num:
batch = torch.stack(batch).reshape(-1)
yield batch
batch = []
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
28034,
198,
6738,
28034,
13,
26791,
13,
7890,
1330,
3409,
20053,
628,
198,
4871,
45486,
16305,
20053,
7,
16305,
20053,
2599,
198... | 2.035343 | 962 |
import os
import numpy as np
import numpy.typing as npt
from dataclasses import dataclass
from bicpl.types import SurfProp, Colour
@dataclass(frozen=True)
class PolygonObj:
"""
Polygonal mesh in `.obj` file format.
http://www.bic.mni.mcgill.ca/users/mishkin/mni_obj_format.pdf
Note: the data representation is neither efficient nor easy to work with.
`PolygonObj` directly corresponds to the file format spec. It might be
easier to work with proxy objects or just matrices instead.
"""
surfprop: SurfProp
"""
Surface properties for the polygons.
"""
n_points: int
"""
Number of distinct vertices in the aggregate polygon object.
"""
point_array: npt.NDArray[np.float32]
"""
List of distinct vertices that define this group of polygons. Note that vertices may
be reused if the end indices and indices fields are set appropriately.
"""
normals: npt.NDArray[np.float32]
"""
List of point normals for each point.
"""
nitems: int
"""
Number of polygons defined.
"""
colour_flag: int
"""
A flag indicating the number of colours allocated in this object. A value of
zero specifies that single colour applies to all line segments. A value of one
specifies that colours are specified on a per-item basis. A value of two specifies
that colours are specified on a per-vertex basis.
"""
colour_table: tuple[Colour, ...]
"""
The RGB colour values to be associated with the polygons. The length of this
section may be either 1 (if `colour_flag` is 0), `nitems` (if `colour_flag` is 1) or
`npoints` (if `colour_flag` is 2).
"""
end_indices: tuple[int, ...]
"""
This is a list of length nitems that specifies the index of the element in the indices
list associated with each successive polygon.
"""
indices: tuple[int, ...]
"""
A list of integer indices into the `point_array` that specifies how each of the vertices
is assigned to each polygon.
"""
def neighbor_graph(self, triangles_only=True) -> tuple[set[int], ...]:
"""
Produces a tuple of the same length as `point_array` with values being
sets of indices into `point_array` that are immediate neighbors with
the corresponding vertex.
"""
# maybe move this to a proxy object?
prev = 0
neighbors = tuple(set() for _ in self.point_array)
for i in self.end_indices:
shape = self.indices[prev:i]
if triangles_only and len(shape) != 3:
raise ValueError('Found shape that is not a triangle')
for vertex in shape:
for neighbor in shape:
if neighbor != vertex:
neighbors[vertex].add(neighbor)
prev = i
return neighbors
def save(self, filename: str | os.PathLike):
"""
Write this object to a file.
"""
with open(filename, 'w') as out:
header = ['P', self.surfprop.A, self.surfprop.D,
self.surfprop.S, self.surfprop.SE,
self.surfprop.T, self.n_points]
out.write(_list2str(header) + '\n')
for point in self.point_array:
out.write(' ' + _list2str(point) + '\n')
for vector in self.normals:
out.write(' ' + _list2str(vector) + '\n')
out.write(f'\n {self.nitems}\n')
out.write(f' {self.colour_flag} {_serialize_colour_table(self.colour_table)}\n\n')
for i in range(0, self.nitems, 8):
out.write(' ' + _list2str(self.end_indices[i:i + 8]) + '\n')
for i in range(0, len(self.indices), 8):
out.write(' ' + _list2str(self.indices[i:i + 8]) + '\n')
@classmethod
def from_file(cls, filename: str | os.PathLike) -> 'PolygonObj':
"""
Parse an `.obj` file.
"""
with open(filename, 'r') as f:
data = f.readlines()
return cls.from_str('\n'.join(data))
@classmethod
def from_str(cls, s: str) -> 'PolygonObj':
"""
Parse `.obj` data.
"""
data = s.split()
if data[0] != 'P':
raise ValueError('Only Polygons supported')
sp = tuple(float(value) for value in data[1:6])
surfprop = SurfProp(A=sp[0], D=sp[1], S=sp[2], SE=int(sp[3]), T=int(sp[4]))
n_points = int(data[6])
start = 7
end = n_points * 3 + start
point_array = [np.float32(x) for x in data[start:end]]
point_array = np.reshape(point_array, (n_points, 3,))
start = end
end = n_points * 3 + start
normals = [np.float32(x) for x in data[start:end]]
normals = np.reshape(normals, (n_points, 3,))
nitems = int(data[end])
colour_flag = int(data[end+1])
if colour_flag != 0:
raise ValueError('colour_flag is not 0')
start = end + 2
end = start + 4
colour_table = (Colour(tuple(np.float32(x) for x in data[start:end])),)
start = end
end = start + nitems
end_indices = tuple(int(i) for i in data[start:end])
start = end
end = start + end_indices[-1] + 1
indices = tuple(int(i) for i in data[start:end])
return cls(
surfprop=surfprop,
n_points=n_points,
point_array=point_array,
normals=normals,
nitems=nitems,
colour_flag=colour_flag,
colour_table=colour_table,
end_indices=end_indices,
indices=indices
)
@classmethod
def from_data(cls, verts: npt.NDArray[np.float32], faces: npt.NDArray[np.int32], normals: npt.NDArray[np.float32],
surfprop: SurfProp = SurfProp(A=0.3, D=0.3, S=0.4, SE=10, T=1),
colour_flag=0, colour_table=(Colour((1, 1, 1, 1)),)):
"""
Create a `.obj` from raw data.
Paremeters
----------
verts: (V, 3) array
Spatial coordinates for V unique mesh vertices.
faces: (F, 3) array
Define triangular faces via referencing vertex indices from `verts`.
normals: (V, 3) array
The normal direction at each vertex.
"""
n_points = len(verts)
nitems = len(faces)
return cls(
surfprop=surfprop,
n_points=n_points,
point_array=verts,
normals=normals,
nitems=nitems,
colour_flag=colour_flag,
colour_table=colour_table,
end_indices=tuple(range(3, (nitems + 1) * 3, 3)),
indices=tuple(faces.flatten())
)
def _list2str(array):
"""
Join a list with spaces between elements.
"""
return ' '.join(str(a) for a in array)
| [
11748,
28686,
198,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
299,
32152,
13,
774,
13886,
355,
299,
457,
198,
6738,
4818,
330,
28958,
1330,
4818,
330,
31172,
198,
6738,
275,
291,
489,
13,
19199,
1330,
43771,
24331,
11,
38773,
628,
... | 2.190219 | 3,149 |
"""empty message
Revision ID: 247c9e7de059
Revises: None
Create Date: 2015-12-02 15:03:20.582541
"""
# revision identifiers, used by Alembic.
revision = '247c9e7de059'
down_revision = None
from alembic import op
import sqlalchemy as sa
| [
37811,
28920,
3275,
198,
198,
18009,
1166,
4522,
25,
30179,
66,
24,
68,
22,
2934,
46712,
198,
18009,
2696,
25,
6045,
198,
16447,
7536,
25,
1853,
12,
1065,
12,
2999,
1315,
25,
3070,
25,
1238,
13,
3365,
1495,
3901,
198,
198,
37811,
19... | 2.659341 | 91 |
r"""
Interface to LattE integrale programs
"""
#*****************************************************************************
# Copyright (C) 2017 Vincent Delecroix <vincent.delecroix@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.cpython.string import str_to_bytes, bytes_to_str
from subprocess import Popen, PIPE
from sage.misc.misc import SAGE_TMP
from sage.rings.integer import Integer
from sage.features.latte import Latte
def count(arg, ehrhart_polynomial=False, multivariate_generating_function=False, raw_output=False, verbose=False, **kwds):
r"""
Call to the program count from LattE integrale
INPUT:
- ``arg`` -- a cdd or LattE description string
- ``ehrhart_polynomial``, ``multivariate_generating_function`` -- to
compute Ehrhart polynomial or multivariate generating function instead of
just counting points
- ``raw_output`` -- if ``True`` then return directly the output string from LattE
- For all other options of the count program, consult the LattE manual
OUTPUT:
Either a string (if ``raw_output`` if set to ``True``) or an integer (when
counting points), or a polynomial (if ``ehrhart_polynomial`` is set to
``True``) or a multivariate THING (if ``multivariate_generating_function``
is set to ``True``)
EXAMPLES::
sage: from sage.interfaces.latte import count # optional - latte_int
sage: P = 2 * polytopes.cube()
Counting integer points from either the H or V representation::
sage: count(P.cdd_Hrepresentation(), cdd=True) # optional - latte_int
125
sage: count(P.cdd_Vrepresentation(), cdd=True) # optional - latte_int
125
Ehrhart polynomial::
sage: count(P.cdd_Hrepresentation(), cdd=True, ehrhart_polynomial=True) # optional - latte_int
64*t^3 + 48*t^2 + 12*t + 1
Multivariate generating function currently only work with ``raw_output=True``::
sage: opts = {'cdd': True,
....: 'multivariate_generating_function': True,
....: 'raw_output': True}
sage: cddin = P.cdd_Hrepresentation()
sage: print(count(cddin, **opts)) # optional - latte_int
x[0]^2*x[1]^(-2)*x[2]^(-2)/((1-x[1])*(1-x[2])*(1-x[0]^(-1)))
+ x[0]^(-2)*x[1]^(-2)*x[2]^(-2)/((1-x[1])*(1-x[2])*(1-x[0]))
+ x[0]^2*x[1]^(-2)*x[2]^2/((1-x[1])*(1-x[2]^(-1))*(1-x[0]^(-1)))
+ x[0]^(-2)*x[1]^(-2)*x[2]^2/((1-x[1])*(1-x[0])*(1-x[2]^(-1)))
+ x[0]^2*x[1]^2*x[2]^(-2)/((1-x[2])*(1-x[1]^(-1))*(1-x[0]^(-1)))
+ x[0]^(-2)*x[1]^2*x[2]^(-2)/((1-x[2])*(1-x[0])*(1-x[1]^(-1)))
+ x[0]^2*x[1]^2*x[2]^2/((1-x[2]^(-1))*(1-x[1]^(-1))*(1-x[0]^(-1)))
+ x[0]^(-2)*x[1]^2*x[2]^2/((1-x[0])*(1-x[2]^(-1))*(1-x[1]^(-1)))
TESTS:
Testing raw output::
sage: from sage.interfaces.latte import count # optional - latte_int
sage: P = polytopes.cuboctahedron()
sage: cddin = P.cdd_Vrepresentation()
sage: count(cddin, cdd=True, raw_output=True) # optional - latte_int
'19'
sage: count(cddin, cdd=True, raw_output=True, ehrhart_polynomial=True) # optional - latte_int
' + 1 * t^0 + 10/3 * t^1 + 8 * t^2 + 20/3 * t^3'
sage: count(cddin, cdd=True, raw_output=True, multivariate_generating_function=True) # optional - latte_int
'x[0]^(-1)*x[1]^(-1)/((1-x[0]*x[2])*(1-x[0]^(-1)*x[1])*...x[0]^(-1)*x[2]^(-1)))\n'
Testing the ``verbose`` option::
sage: n = count(cddin, cdd=True, verbose=True, raw_output=True) # optional - latte_int
This is LattE integrale ...
...
Invocation: count '--redundancy-check=none' --cdd /dev/stdin
...
Total Unimodular Cones: ...
Maximum number of simplicial cones in memory at once: ...
<BLANKLINE>
**** The number of lattice points is: ****
Total time: ... sec
Trivial input for which LattE's preprocessor does all the work::
sage: P = Polyhedron(vertices=[[0,0,0]])
sage: cddin = P.cdd_Hrepresentation()
sage: count(cddin, cdd=True, raw_output=False) # optional - latte_int
1
Testing the runtime error::
sage: P = Polyhedron(rays=[[0,1], [1,0]])
sage: cddin = P.cdd_Hrepresentation()
sage: count(cddin, cdd=True, raw_output=False) # optional - latte_int
Traceback (most recent call last):
...
RuntimeError: LattE integrale program failed (exit code 1):
This is LattE integrale ...
...
The polyhedron is unbounded.
"""
# Check that LattE is present
Latte().require()
arg = str_to_bytes(arg)
args = ['count']
if ehrhart_polynomial and multivariate_generating_function:
raise ValueError
if ehrhart_polynomial:
args.append('--ehrhart-polynomial')
elif multivariate_generating_function:
args.append('--multivariate-generating-function')
if 'redundancy_check' not in kwds:
args.append('--redundancy-check=none')
for key,value in kwds.items():
if value is None or value is False:
continue
key = key.replace('_','-')
if value is True:
args.append('--{}'.format(key))
else:
args.append('--{}={}'.format(key, value))
if multivariate_generating_function:
from sage.misc.temporary_file import tmp_filename
filename = tmp_filename()
with open(filename, 'w') as f:
f.write(bytes_to_str(arg))
args += [filename]
else:
args += ['/dev/stdin']
# The cwd argument is needed because latte
# always produces diagnostic output files.
latte_proc = Popen(args,
stdin=PIPE, stdout=PIPE,
stderr=(None if verbose else PIPE),
cwd=str(SAGE_TMP))
ans, err = latte_proc.communicate(arg)
if err:
err = bytes_to_str(err)
ret_code = latte_proc.poll()
if ret_code:
if err is None:
err = ", see error message above"
else:
err = ":\n" + err
raise RuntimeError("LattE integrale program failed (exit code {})".format(ret_code) + err.strip())
ans = bytes_to_str(ans)
if ehrhart_polynomial:
ans = ans.splitlines()[-2]
if raw_output:
return ans
else:
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import QQ
R = PolynomialRing(QQ, 't')
return R(ans)
elif multivariate_generating_function:
with open(filename + '.rat') as f:
ans = f.read()
if raw_output:
return ans
else:
raise NotImplementedError("there is no Sage object to handle multivariate series from LattE, use raw_output=True")
else:
if ans: # Sometimes (when LattE's preproc does the work), no output appears on stdout.
ans = ans.splitlines()[-1]
if not ans:
# opening a file is slow (30e-6s), so we read the file
# numOfLatticePoints only in case of a IndexError above
with open(SAGE_TMP+'/numOfLatticePoints', 'r') as f:
ans = f.read()
if raw_output:
return ans
else:
return Integer(ans)
def integrate(arg, polynomial=None, algorithm='triangulate', raw_output=False, verbose=False, **kwds):
r"""
Call to the function integrate from LattE integrale.
INPUT:
- ``arg`` -- a cdd or LattE description string.
- ``polynomial`` -- multivariate polynomial or valid LattE polynomial description string.
If given, the valuation parameter of LattE is set to integrate, and is set to volume otherwise.
- ``algorithm`` -- (default: 'triangulate') the integration method. Use 'triangulate' for
polytope triangulation or 'cone-decompose' for tangent cone decomposition method.
- ``raw_output`` -- if ``True`` then return directly the output string from LattE.
- ``verbose`` -- if ``True`` then return directly verbose output from LattE.
- For all other options of the integrate program, consult the LattE manual.
OUTPUT:
Either a string (if ``raw_output`` if set to ``True``) or a rational.
EXAMPLES::
sage: from sage.interfaces.latte import integrate # optional - latte_int
sage: P = 2 * polytopes.cube()
sage: x, y, z = polygen(QQ, 'x, y, z')
Integrating over a polynomial over a polytope in either the H or V representation::
sage: integrate(P.cdd_Hrepresentation(), x^2*y^2*z^2, cdd=True) # optional - latte_int
4096/27
sage: integrate(P.cdd_Vrepresentation(), x^2*y^2*z^2, cdd=True) # optional - latte_int
4096/27
Computing the volume of a polytope in either the H or V representation::
sage: integrate(P.cdd_Hrepresentation(), cdd=True) # optional - latte_int
64
sage: integrate(P.cdd_Vrepresentation(), cdd=True) # optional - latte_int
64
Polynomials given as a string in LattE description are also accepted::
sage: integrate(P.cdd_Hrepresentation(), '[[1,[2,2,2]]]', cdd=True) # optional - latte_int
4096/27
TESTS:
Testing raw output::
sage: from sage.interfaces.latte import integrate # optional - latte_int
sage: P = polytopes.cuboctahedron()
sage: cddin = P.cdd_Vrepresentation()
sage: x, y, z = polygen(QQ, 'x, y, z')
sage: f = 3*x^2*y^4*z^6 + 7*y^3*z^5
sage: integrate(cddin, f, cdd=True, raw_output=True) # optional - latte_int
'629/47775'
Testing the ``verbose`` option to integrate over a polytope::
sage: ans = integrate(cddin, f, cdd=True, verbose=True, raw_output=True) # optional - latte_int
This is LattE integrale ...
...
Invocation: integrate --valuation=integrate --triangulate --redundancy-check=none --cdd --monomials=... /dev/stdin
...
Testing triangulate algorithm::
sage: from sage.interfaces.latte import integrate # optional - latte_int
sage: P = polytopes.cuboctahedron()
sage: cddin = P.cdd_Vrepresentation()
sage: integrate(cddin, algorithm='triangulate', cdd=True) # optional - latte_int
20/3
Testing convex decomposition algorithm::
sage: from sage.interfaces.latte import integrate # optional - latte_int
sage: P = polytopes.cuboctahedron()
sage: cddin = P.cdd_Vrepresentation()
sage: integrate(cddin, algorithm='cone-decompose', cdd=True) # optional - latte_int
20/3
Testing raw output::
sage: from sage.interfaces.latte import integrate # optional - latte_int
sage: P = polytopes.cuboctahedron()
sage: cddin = P.cdd_Vrepresentation()
sage: integrate(cddin, cdd=True, raw_output=True) # optional - latte_int
'20/3'
Testing polynomial given as a string in LattE description::
sage: from sage.interfaces.latte import integrate # optional - latte_int
sage: P = polytopes.cuboctahedron()
sage: integrate(P.cdd_Hrepresentation(), '[[3,[2,4,6]],[7,[0, 3, 5]]]', cdd=True) # optional - latte_int
629/47775
Testing the ``verbose`` option to compute the volume of a polytope::
sage: from sage.interfaces.latte import integrate # optional - latte_int
sage: P = polytopes.cuboctahedron()
sage: cddin = P.cdd_Vrepresentation()
sage: ans = integrate(cddin, cdd=True, raw_output=True, verbose=True) # optional - latte_int
This is LattE integrale ...
...
Invocation: integrate --valuation=volume --triangulate --redundancy-check=none --cdd /dev/stdin
...
Testing the runtime error::
sage: P = Polyhedron(rays=[[1,0],[0,1]])
sage: P._volume_latte() # optional - latte_int
Traceback (most recent call last):
...
RuntimeError: LattE integrale program failed (exit code -6):
This is LattE integrale ...
...
determinant: nonsquare matrix
"""
# Check that LattE is present
Latte().require()
arg = str_to_bytes(arg)
from sage.rings.rational import Rational
args = ['integrate']
got_polynomial = True if polynomial is not None else False
if got_polynomial:
args.append('--valuation=integrate')
else:
args.append('--valuation=volume')
if algorithm=='triangulate':
args.append('--triangulate')
elif algorithm=='cone-decompose':
args.append('--cone-decompose')
if 'redundancy_check' not in kwds:
args.append('--redundancy-check=none')
for key,value in kwds.items():
if value is None or value is False:
continue
key = key.replace('_','-')
if value is True:
args.append('--{}'.format(key))
else:
args.append('--{}={}'.format(key, value))
if got_polynomial:
if not isinstance(polynomial, str):
# transform polynomial to LattE description
monomials_list = to_latte_polynomial(polynomial)
else:
monomials_list = str(polynomial)
from sage.misc.temporary_file import tmp_filename
filename_polynomial = tmp_filename()
with open(filename_polynomial, 'w') as f:
f.write(monomials_list)
args += ['--monomials=' + filename_polynomial]
args += ['/dev/stdin']
# The cwd argument is needed because latte
# always produces diagnostic output files.
latte_proc = Popen(args,
stdin=PIPE, stdout=PIPE,
stderr=(None if verbose else PIPE),
cwd=str(SAGE_TMP))
ans, err = latte_proc.communicate(arg)
if err:
err = bytes_to_str(err)
ret_code = latte_proc.poll()
if ret_code:
if err is None:
err = ", see error message above"
else:
err = ":\n" + err
raise RuntimeError("LattE integrale program failed (exit code {})".format(ret_code) + err.strip())
ans = bytes_to_str(ans)
ans = ans.splitlines()
ans = ans[-5].split()
assert(ans[0]=='Answer:')
ans = ans[1]
if raw_output:
return ans
else:
return Rational(ans)
def to_latte_polynomial(polynomial):
r"""
Helper function to transform a polynomial to its LattE description.
INPUT:
- ``polynomial`` -- a multivariate polynomial.
OUTPUT:
A string that describes the monomials list and exponent vectors.
TESTS:
Testing a polynomial in three variables::
sage: from sage.interfaces.latte import to_latte_polynomial
sage: x, y, z = polygens(QQ, 'x, y, z')
sage: f = 3*x^2*y^4*z^6 + 7*y^3*z^5
sage: to_latte_polynomial(f)
'[[3, [2, 4, 6]], [7, [0, 3, 5]]]'
sage: to_latte_polynomial(x.parent().zero())
'[]'
Testing a univariate polynomial::
sage: x = polygen(QQ, 'x')
sage: to_latte_polynomial((x-1)^2)
'[[1, [0]], [-2, [1]], [1, [2]]]'
sage: to_latte_polynomial(x.parent().zero())
'[]'
"""
if polynomial == 0:
return str([])
from sage.rings.polynomial.polydict import ETuple
coefficients_list = polynomial.coefficients()
# transform list of exponents into a list of lists.
# this branch handles the multivariate/univariate case
if isinstance(polynomial.exponents()[0], ETuple):
exponents_list = [list(exponent_vector_i) for exponent_vector_i in polynomial.exponents()]
else:
exponents_list = [[exponent_vector_i] for exponent_vector_i in polynomial.exponents()]
# assuming that the order in coefficients() and exponents() methods match
monomials_list = [list(monomial_i)
for monomial_i
in zip(coefficients_list, exponents_list)]
return str(monomials_list)
| [
81,
37811,
198,
39317,
284,
406,
1078,
36,
4132,
81,
1000,
4056,
198,
37811,
198,
2,
17174,
17174,
4557,
35625,
198,
2,
220,
220,
220,
220,
220,
220,
15069,
357,
34,
8,
2177,
18653,
42226,
19915,
844,
1279,
7114,
1087,
13,
2934,
293... | 2.264036 | 7,249 |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://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.
#
# When you publish or redistribute any data created with VulnerableCode or any VulnerableCode
# derivative work, you must accompany this data with the following acknowledgment:
#
# Generated with VulnerableCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# VulnerableCode should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
# VulnerableCode is a free software tool from nexB Inc. and others.
# Visit https://github.com/nexB/vulnerablecode/ for support and download.
import os
import yaml
from unittest import TestCase
from unittest.mock import patch, MagicMock
from packageurl import PackageURL
from vulnerabilities.data_source import Advisory, Reference
from vulnerabilities.importers.alpine_linux import AlpineDataSource
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEST_DATA = os.path.join(BASE_DIR, "test_data", "alpine", "v3.11")
| [
2,
198,
2,
15069,
357,
66,
8,
220,
497,
87,
33,
3457,
13,
290,
1854,
13,
1439,
2489,
10395,
13,
198,
2,
2638,
1378,
12413,
65,
13,
785,
290,
3740,
1378,
12567,
13,
785,
14,
12413,
33,
14,
85,
38828,
8189,
14,
198,
2,
383,
569,... | 3.743478 | 460 |
import urllib
#urllib2是一个标准库,安装python之后就自带了,并且只在于python2中
#在python3中,已经把urllib,urllib2等的合并为一个包urllib了。 | [
11748,
2956,
297,
571,
198,
198,
2,
333,
297,
571,
17,
42468,
31660,
10310,
103,
43718,
229,
49035,
228,
41753,
241,
171,
120,
234,
22522,
231,
35318,
29412,
45298,
28938,
236,
22887,
109,
164,
229,
103,
30585,
99,
12859,
228,
171,
12... | 0.981132 | 106 |
import os
import shutil
if __name__ == '__main__':
path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
dirs_to_remove = ['output']
clean_output(path, dirs_to_remove)
| [
11748,
28686,
198,
11748,
4423,
346,
628,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
3108,
796,
28686,
13,
6978,
13,
15908,
3672,
7,
418,
13,
6978,
13,
15908,
3672,
7,
418,
13,
6978,
13,
... | 2.414634 | 82 |
from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
dc_dc = SchLib(tool=SKIDL).add_parts(*[
Part(name='ADP1108',dest=TEMPLATE,tool=SKIDL,keywords='switching buck boost converter step-down step-up',description='Micropower DC-DC conveter, step-up or step-down operation, 2V-30Vin, adjustable output voltage',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*', 'DIP*W7.62mm*'],do_erc=True,aliases=['LT1108', 'ADP1108-3.3', 'ADP1108-5', 'ADP1108-12'],pins=[
Pin(num='1',name='ILIM',do_erc=True),
Pin(num='2',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='SW1',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='SW2',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='AO',func=Pin.OPENCOLL,do_erc=True),
Pin(num='7',name='SET',do_erc=True),
Pin(num='8',name='FB/SENSE',do_erc=True)]),
Part(name='ADP2108',dest=TEMPLATE,tool=SKIDL,keywords='Voltage regulator switching buck fixed output analog',description='3MHz switching buck regulator, 600mA fixed output voltage in SOT23-5 package',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='Vin',do_erc=True),
Pin(num='2',name='GND',do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='SW',do_erc=True)]),
Part(name='ADP5054',dest=TEMPLATE,tool=SKIDL,keywords='quad regulator dcdc buck synchronizable parallel',description='250kHz to 2MHz, 6A/6A/2A/2A Quad Buck Regulator, -40 to +125C',ref_prefix='U',num_units=1,fplist=['TQFP*48*1EP'],do_erc=True,pins=[
Pin(num='1',name='BST3',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='PGND3',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='PGND3',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='SW3',func=Pin.PWROUT,do_erc=True),
Pin(num='5',name='SW3',func=Pin.PWROUT,do_erc=True),
Pin(num='6',name='PVIN3',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='PVIN4',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='SW4',func=Pin.PWROUT,do_erc=True),
Pin(num='9',name='SW4',func=Pin.PWROUT,do_erc=True),
Pin(num='10',name='PGND4',func=Pin.PWRIN,do_erc=True),
Pin(num='20',name='COMP2',func=Pin.UNSPEC,do_erc=True),
Pin(num='30',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='40',name='COMP1',func=Pin.UNSPEC,do_erc=True),
Pin(num='11',name='PGND4',func=Pin.PWRIN,do_erc=True),
Pin(num='21',name='EN2',do_erc=True),
Pin(num='31',name='DL1',func=Pin.OUTPUT,do_erc=True),
Pin(num='41',name='FB1',do_erc=True),
Pin(num='12',name='BST4',func=Pin.PWRIN,do_erc=True),
Pin(num='22',name='PVIN2',func=Pin.PWRIN,do_erc=True),
Pin(num='32',name='BST1',func=Pin.PWRIN,do_erc=True),
Pin(num='42',name='RT',func=Pin.UNSPEC,do_erc=True),
Pin(num='13',name='CFG34',do_erc=True),
Pin(num='23',name='PVIN2',func=Pin.PWRIN,do_erc=True),
Pin(num='33',name='SW1',func=Pin.PWROUT,do_erc=True),
Pin(num='43',name='VDD',func=Pin.PWROUT,do_erc=True),
Pin(num='14',name='EN4',do_erc=True),
Pin(num='24',name='PVIN2',func=Pin.PWRIN,do_erc=True),
Pin(num='34',name='SW1',func=Pin.PWROUT,do_erc=True),
Pin(num='44',name='SYNC/MODE',func=Pin.UNSPEC,do_erc=True),
Pin(num='15',name='COMP4',func=Pin.UNSPEC,do_erc=True),
Pin(num='25',name='SW2',func=Pin.PWROUT,do_erc=True),
Pin(num='35',name='SW1',func=Pin.PWROUT,do_erc=True),
Pin(num='45',name='VREG',func=Pin.PWROUT,do_erc=True),
Pin(num='16',name='FB4',do_erc=True),
Pin(num='26',name='SW2',func=Pin.PWROUT,do_erc=True),
Pin(num='36',name='PVIN1',func=Pin.PWRIN,do_erc=True),
Pin(num='46',name='FB3',do_erc=True),
Pin(num='17',name='PWRGD',func=Pin.OPENCOLL,do_erc=True),
Pin(num='27',name='SW2',func=Pin.PWROUT,do_erc=True),
Pin(num='37',name='PVIN1',func=Pin.PWRIN,do_erc=True),
Pin(num='47',name='COMP3',func=Pin.UNSPEC,do_erc=True),
Pin(num='18',name='CFG12',do_erc=True),
Pin(num='28',name='BST2',func=Pin.PWRIN,do_erc=True),
Pin(num='38',name='PVIN1',func=Pin.PWRIN,do_erc=True),
Pin(num='48',name='EN3',do_erc=True),
Pin(num='19',name='FB2',do_erc=True),
Pin(num='29',name='DL2',func=Pin.OUTPUT,do_erc=True),
Pin(num='39',name='EN1',do_erc=True),
Pin(num='49',name='EPAD',func=Pin.PWRIN,do_erc=True)]),
Part(name='APE1707H-33-HF',dest=TEMPLATE,tool=SKIDL,keywords='Adjustable 2A 150KHz PWM Buck DC/DC',description='Adjustable 2A, 150KHz PWM Buck DC/DC Converter, TO252-5 (D-PAK)',ref_prefix='U',num_units=1,fplist=['TO?252*', 'D?PAK*', 'DPAK*'],do_erc=True,aliases=['APE1707H-50-HF', 'APE1707H-12-HF', 'APE1707H-HF'],pins=[
Pin(num='1',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='VSS',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~EN~',do_erc=True)]),
Part(name='APE1707M-33-HF',dest=TEMPLATE,tool=SKIDL,keywords='Adjustable 2A 150KHz PWM Buck DC/DC',description='Adjustable 2A, 150KHz PWM Buck DC/DC Converter, SO8',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,aliases=['APE1707M-50-HF', 'APE1707M-12-HF', 'APE1707M-HF'],pins=[
Pin(num='1',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='FB',do_erc=True),
Pin(num='4',name='~EN~',do_erc=True),
Pin(num='5',name='VSS',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='VSS',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VSS',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VSS',func=Pin.PWRIN,do_erc=True)]),
Part(name='BD9001F',dest=TEMPLATE,tool=SKIDL,keywords='DC-DC Step-Down Switching Regulator',description='48V 2A, Flexible Step-Down Switching Regulator, SO8',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='FB',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='INV',do_erc=True),
Pin(num='6',name='RT',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VIN',func=Pin.PWRIN,do_erc=True)]),
Part(name='BD9778F',dest=TEMPLATE,tool=SKIDL,keywords='DC-DC Step-Down Switching Regulator',description='35V 2A, Flexible Step-Down Switching Regulator, SO8',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='FB',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='INV',do_erc=True),
Pin(num='5',name='EN',func=Pin.PASSIVE,do_erc=True),
Pin(num='6',name='RT',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='PVIN',func=Pin.PWRIN,do_erc=True)]),
Part(name='BD9778HFP',dest=TEMPLATE,tool=SKIDL,keywords='DC-DC Step-Down Switching Regulator',description='35V 2A, Flexible Step-Down Switching Regulator, HRP7',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='FB',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='INV',do_erc=True),
Pin(num='6',name='RT',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='EN',func=Pin.PASSIVE,do_erc=True)]),
Part(name='BD9781HFP',dest=TEMPLATE,tool=SKIDL,keywords='DC-DC Step-Down Switching Regulator',description='35V 4A, Flexible Step-Down Switching Regulator, HRP7',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='RT',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',func=Pin.PASSIVE,do_erc=True),
Pin(num='6',name='INV',do_erc=True),
Pin(num='7',name='EN/SYNC',func=Pin.PASSIVE,do_erc=True)]),
Part(name='BD9G341EFJ',dest=TEMPLATE,tool=SKIDL,keywords='BD9G341EFJ, Buck Converter',description='12V-76V input voltage range 3A output current',ref_prefix='U',num_units=1,fplist=['HTSOP*'],do_erc=True,pins=[
Pin(num='1',name='LX',func=Pin.PASSIVE,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='VC',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='RT',do_erc=True),
Pin(num='6',name='EN',do_erc=True),
Pin(num='7',name='BST',do_erc=True),
Pin(num='8',name='VCC',func=Pin.PWRIN,do_erc=True)]),
Part(name='GL2576-3.3SF8DR',dest=TEMPLATE,tool=SKIDL,keywords='Adjustable 3A 52KHz Buck DC/DC',description='Adjustable 3A, 52KHz Step Down Converter, SO8',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,aliases=['GL2576-5.0SF8DR', 'GL2576-12SF8DR', 'GL2576-15SF8DR', 'GL2576-ASF8DR'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='FB',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='~ON~/OFF',do_erc=True),
Pin(num='5',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='GND',func=Pin.PWRIN,do_erc=True)]),
Part(name='GL2576-3.3TA5PR',dest=TEMPLATE,tool=SKIDL,keywords='Adjustable 3A 52KHz Buck DC/DC',description='Adjustable 3A, 52KHz Step Down Converter, TD2P-5',ref_prefix='U',num_units=1,do_erc=True,aliases=['GL2576-5.0TA5PR', 'GL2576-12TA5PR', 'GL2576-15TA5PR', 'GL2576-ATA5PR'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='GL2576-3.3TA5R',dest=TEMPLATE,tool=SKIDL,keywords='Adjustable 3A 52KHz Buck DC/DC',description='Adjustable 3A, 52KHz Step Down Converter, TO263-5 (D2-PAK)',ref_prefix='U',num_units=1,fplist=['TO?263*', 'D2-PAK-5*'],do_erc=True,aliases=['GL2576-5.0TA5R', 'GL2576-12TA5R', 'GL2576-15TA5R', 'GL2576-ATA5R'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='GL2576-3.3TB5T',dest=TEMPLATE,tool=SKIDL,keywords='Adjustable 3A 52KHz Buck DC/DC',description='Adjustable 3A, 52KHz Step Down Converter, TO220-5',ref_prefix='U',num_units=1,fplist=['TO?220*'],do_erc=True,aliases=['GL2576-5.0TB5T', 'GL2576-12TB5T', 'GL2576-15TB5T', 'GL2576-ATB5T'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VOUT',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='IS31LT3360',dest=TEMPLATE,tool=SKIDL,keywords='Switching LED driver',description='Constant current LED driver, internal switch, up to 40V/1.2A, SOT-89-5',ref_prefix='U',num_units=1,fplist=['SOT-23*', 'SOT-23*'],do_erc=True,pins=[
Pin(num='1',name='LX',func=Pin.OPENCOLL,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='ADJ',do_erc=True),
Pin(num='4',name='ISENSE',do_erc=True),
Pin(num='5',name='VIN',func=Pin.PWRIN,do_erc=True)]),
Part(name='ISL8117',dest=TEMPLATE,tool=SKIDL,keywords='PWM step down buck converter controller synchronous POL',description='Synchronous step-down PWM controller, 4.5v to 60v input, 0.6v to 54v output',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='EXTBIAS',do_erc=True),
Pin(num='2',name='EN',do_erc=True),
Pin(num='3',name='CLKOUT',do_erc=True),
Pin(num='4',name='MOD/SYNC',do_erc=True),
Pin(num='5',name='PGOOD',do_erc=True),
Pin(num='6',name='RT',do_erc=True),
Pin(num='7',name='SS/TRK',do_erc=True),
Pin(num='8',name='FB',do_erc=True),
Pin(num='9',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='LGATE/OCS',do_erc=True),
Pin(num='11',name='VCC5V',func=Pin.PWRIN,do_erc=True),
Pin(num='12',name='ISEN',do_erc=True),
Pin(num='13',name='PHASE',do_erc=True),
Pin(num='14',name='UGATE',func=Pin.OUTPUT,do_erc=True),
Pin(num='15',name='BOOT',do_erc=True),
Pin(num='16',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='17',name='SGND',func=Pin.PWRIN,do_erc=True)]),
Part(name='L5973D',dest=TEMPLATE,tool=SKIDL,keywords='step down buck regulator',description='2.5A step down switching regulator',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*1EP*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,pins=[
Pin(num='1',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='SYNC',func=Pin.BIDIR,do_erc=True),
Pin(num='3',name='INH',do_erc=True),
Pin(num='4',name='COMP',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='VREF',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='EP',func=Pin.PASSIVE,do_erc=True)]),
Part(name='LM2574HVH-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator Adjustable 500mA HV',description='LM2574N, Adjustable Output, 0.5A Step-Down VR, High Votage Input',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*'],do_erc=True,aliases=['LM2574HVH-3.3', 'LM2574HVH-5', 'LM2574HVH-15', 'LM2574HVH-ADJ'],pins=[
Pin(num='1',name='FB',do_erc=True),
Pin(num='2',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='ON/~OFF',do_erc=True),
Pin(num='4',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='OUT',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM2574N-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator Adjustable 500mA',description='Adjustable Output, 0.5A Step-Down VR',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*'],do_erc=True,aliases=['LM2574N-3.3', 'LM2574N-5', 'LM2574N-15', 'LM2574N-ADJ'],pins=[
Pin(num='1',name='FB',do_erc=True),
Pin(num='2',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='ON/~OFF',do_erc=True),
Pin(num='4',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='OUT',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM2576HVS-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator 3A Adjustable High Voltage',description='TO-263, Adjustable Output 3A Step-Down VR High Voltage Input',ref_prefix='U',num_units=1,fplist=['TO?263*'],do_erc=True,aliases=['LM2576HVS-3.3', 'LM2576HVS-5', 'LM2576HVS-15', 'LM2576HVS-ADJ'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='LM2576HVT-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator 3A Adjustable High Voltage',description='LM2576HVS, TO-220-5, Adjustable Output 3A Step-Down VR High Voltage Input',ref_prefix='U',num_units=1,fplist=['TO?220*'],do_erc=True,aliases=['LM2576HVT-3.3', 'LM2576HVT-5', 'LM2576HVT-15', 'LM2576HVT-ADJ'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='LM2576S-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator 3A Adjustable',description='TO-263, Adjustable Output 3A Step-Down VR',ref_prefix='U',num_units=1,fplist=['TO?263*'],do_erc=True,aliases=['LM2576S-3.3', 'LM2576S-5', 'LM2576S-15', 'LM2576S-ADJ', 'LM2575BU-ADJ', 'LM2575-3.3BU', 'LM2575-5.0BU', 'LM2575-12BU'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='LM2576T-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator 3A Adjustable',description='LM2576S, TO-220-5, Adjustable Output 3A Step-Down VR',ref_prefix='U',num_units=1,fplist=['TO?220*'],do_erc=True,aliases=['LM2576T-3.3', 'LM2576T-5', 'LM2576T-15', 'LM2576T-ADJ', 'LM2575BT-ADJ', 'LM2575-3.3BT', 'LM2575-5.0BT', 'LM2575-12BT'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='LM2595S-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator 1A Adjustable',description='Adjustable Output 1A Step-Down VR',ref_prefix='U',num_units=1,fplist=['TO?263*'],do_erc=True,aliases=['LM2595S-3.3', 'LM2595S-5', 'LM2595S-ADJ'],pins=[
Pin(num='1',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF',do_erc=True)]),
Part(name='LM2595T-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator 1A Adjustable',description='Adjustable Output 1A Step-Down VR',ref_prefix='U',num_units=1,fplist=['TO?220*'],do_erc=True,aliases=['LM2595T-3.3', 'LM2595T-5', 'LM2595T-ADJ'],pins=[
Pin(num='1',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='LM2596S-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator Adjustable 3A',description='TO-263, Adjustable 3A Step-Down VR',ref_prefix='U',num_units=1,fplist=['TO?263*'],do_erc=True,aliases=['LM2596S-5', 'LM2596S-3.3', 'LM2596S-ADJ'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='LM2596T-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator Adjustable 3A',description='TO220-5, Adjustable 3A 150kHz Step-Down VR',ref_prefix='U',num_units=1,fplist=['TO?220*'],do_erc=True,aliases=['LM2596T-5', 'LM2596T-3.3', 'LM2596T-ADJ'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='OUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~ON~/OFF',do_erc=True)]),
Part(name='LM2672M-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator',description='Adjustable Output, 1A Step-Down VR',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,aliases=['LM2672M-3.3', 'LM2672M-5.0', 'LM2672M-ADJ'],pins=[
Pin(num='1',name='CB',do_erc=True),
Pin(num='2',name='SS',do_erc=True),
Pin(num='3',name='SYNC',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VSW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM2672N-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator',description='Adjustable Output, 1A Step-Down VR',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*'],do_erc=True,aliases=['LM2672N-3.3', 'LM2672N-5.0', 'LM2672N-ADJ'],pins=[
Pin(num='1',name='CB',do_erc=True),
Pin(num='2',name='SS',do_erc=True),
Pin(num='3',name='SYNC',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VSW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM2674M-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator',description='Adjustable Output, 500 mA Step-Down VR',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,aliases=['LM2674M-3.3', 'LM2674M-5.0', 'LM2674M-ADJ'],pins=[
Pin(num='1',name='CB',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VSW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM2674N-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator',description='LM2674M, Adjustable Output, 500 mA Step-Down VR',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*'],do_erc=True,aliases=['LM2674N-3.3', 'LM2674N-5.0', 'LM2674N-ADJ'],pins=[
Pin(num='1',name='CB',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VSW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM2675M-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator Adjustable',description='Adjustable Output, 1A Step-Down VR',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,aliases=['LM2675M-3.3', 'LM2675M-5', 'LM2675M-ADJ'],pins=[
Pin(num='1',name='CB',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VSW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM2675N-12',dest=TEMPLATE,tool=SKIDL,keywords='SIMPLE SWITCHER® Step-Down Voltage Regulator Adjustable',description='LM2675M, Adjustable Output, 1A Step-Down VR',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*'],do_erc=True,aliases=['LM2675N-3.3', 'LM2675N-5', 'LM2675N-ADJ'],pins=[
Pin(num='1',name='CB',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='VSW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM2734',dest=TEMPLATE,tool=SKIDL,keywords='Miniature Step-Down Buck Voltage Regulator',description='Thin SOT 1-A Load Step-Down DC-DC Regulator',ref_prefix='U',num_units=1,fplist=['SOT-23*'],do_erc=True,pins=[
Pin(num='1',name='BOOST',do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='FB',do_erc=True),
Pin(num='4',name='EN',do_erc=True),
Pin(num='5',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM3407MY',dest=TEMPLATE,tool=SKIDL,keywords='LED Step-Down Switching Regulator',description='LED Lighting CC Floating Buck Switching Regulator, eMSOP-8',ref_prefix='U',num_units=1,fplist=['eMSOP-8*'],do_erc=True,pins=[
Pin(num='1',name='ISNS',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='DIM',do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='FS',func=Pin.OUTPUT,do_erc=True),
Pin(num='5',name='VIN',do_erc=True),
Pin(num='6',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='LX',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM3578',dest=TEMPLATE,tool=SKIDL,keywords='POWER REGUL',description='Switching Regulator (adjustable)',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='E-',do_erc=True),
Pin(num='2',name='E+',do_erc=True),
Pin(num='3',name='CAP_OSC',do_erc=True),
Pin(num='4',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='E',func=Pin.OPENEMIT,do_erc=True),
Pin(num='6',name='C',func=Pin.OPENCOLL,do_erc=True),
Pin(num='7',name='CUR_LIM',do_erc=True),
Pin(num='8',name='VP+',do_erc=True)]),
Part(name='LM3670MF',dest=TEMPLATE,tool=SKIDL,keywords='DC-DC buck conveter step down voltage regulator',description='Miniature Step-Down DC-DC Converter, 2.5V < Vin < 5.5V',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM5006MM',dest=TEMPLATE,tool=SKIDL,keywords='Constant On-Time Buck Switching Regulator',description='600 mA, 80V Constant On-Time Buck Switching Regulator',ref_prefix='U',num_units=1,fplist=['MSOP-10*'],do_erc=True,pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='BST',do_erc=True),
Pin(num='3',name='LG',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='UV',do_erc=True),
Pin(num='6',name='UVO',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='FB',do_erc=True),
Pin(num='8',name='RT/SD',do_erc=True),
Pin(num='9',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='VIN',func=Pin.PWRIN,do_erc=True)]),
Part(name='LM5007MM',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down Switching Regulator',description='700 mA, 80V Step-Down Switching Regulator',ref_prefix='U',num_units=1,fplist=['MSOP-8*'],do_erc=True,pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='BST',do_erc=True),
Pin(num='3',name='RCL',do_erc=True),
Pin(num='4',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='RON/SD',do_erc=True),
Pin(num='7',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VIN',do_erc=True)]),
Part(name='LM5007SD',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down Switching Regulator',description='700 mA, 80V Step-Down Switching Regulator',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='BST',do_erc=True),
Pin(num='3',name='RCL',do_erc=True),
Pin(num='4',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='RON/SD',do_erc=True),
Pin(num='7',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VIN',do_erc=True)]),
Part(name='LM5008MM',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down Switching Regulator',description='500 mA, 100V Step-Down Switching Regulator',ref_prefix='U',num_units=1,fplist=['MSOP-8*'],do_erc=True,pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='BST',do_erc=True),
Pin(num='3',name='RCL',do_erc=True),
Pin(num='4',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='RON/SD',do_erc=True),
Pin(num='7',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VIN',do_erc=True)]),
Part(name='LM5008SD',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down Switching Regulator',description='500 mA, 100V Step-Down Switching Regulator',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='BST',do_erc=True),
Pin(num='3',name='RCL',do_erc=True),
Pin(num='4',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='RON/SD',do_erc=True),
Pin(num='7',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VIN',do_erc=True)]),
Part(name='LM5008SDC',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down Switching Regulator',description='500 mA, 100V Step-Down Switching Regulator',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='BST',do_erc=True),
Pin(num='3',name='RCL',do_erc=True),
Pin(num='4',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='RON/SD',do_erc=True),
Pin(num='7',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VIN',do_erc=True)]),
Part(name='LM5009MM',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down Switching Regulator',description='150 mA, 100V Step-Down Switching Regulator',ref_prefix='U',num_units=1,fplist=['MSOP-8*'],do_erc=True,pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='BST',do_erc=True),
Pin(num='3',name='RCL',do_erc=True),
Pin(num='4',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='RON/SD',do_erc=True),
Pin(num='7',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VIN',do_erc=True)]),
Part(name='LM5017MR',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down Switching Regulator High Voltage',description='600 mA, 100V Step-Down Switching Regulator',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VIN',do_erc=True),
Pin(num='3',name='ULVO',do_erc=True),
Pin(num='4',name='RON',do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='BST',do_erc=True),
Pin(num='8',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM5017SD',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down Switching Regulator High Voltage High Frequency',description='600 mA, 100V Step-Down Switching Regulator',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='RTN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VIN',do_erc=True),
Pin(num='3',name='ULVO',do_erc=True),
Pin(num='4',name='RON',do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='VCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='BST',do_erc=True),
Pin(num='8',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LM5165X',dest=TEMPLATE,tool=SKIDL,keywords='step-down dc-dc buck regulator fixed 3V3',description='150mA Step-Down Conveter, 3V-65V input, 3.3V fixed output voltage, DFN10 package',ref_prefix='U',num_units=1,fplist=['DFN*1EP*3x3mm*Pitch0.5mm*'],do_erc=True,aliases=['LM5165Y', 'LM5165'],pins=[
Pin(num='1',name='SW',func=Pin.PWROUT,do_erc=True),
Pin(num='2',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='ILIM',do_erc=True),
Pin(num='4',name='SS',do_erc=True),
Pin(num='5',name='RT',do_erc=True),
Pin(num='6',name='PGOOD',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='EN',do_erc=True),
Pin(num='8',name='FB/VOUT',do_erc=True),
Pin(num='9',name='HYS',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='11',name='PAD',func=Pin.PWRIN,do_erc=True)]),
Part(name='LMR10510XMF',dest=TEMPLATE,tool=SKIDL,keywords='Miniature Step-Up Boost Voltage Regulator',description='LM64010, 1A, 40Vout Step-Up Voltage Regulator, 1.6MHz Frequency, SOT-23-5',ref_prefix='U',num_units=1,fplist=['SOT-23-5*'],do_erc=True,aliases=['LM2731XMF', 'LM2731YMF', 'LM27313XMF', 'LM2733XMF', 'LM2733YMF', 'LM2735XMF', 'LMR10510YMF', 'LMR62014XMF', 'LMR62421XMF', 'LMR64010XMF'],pins=[
Pin(num='1',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='FB',do_erc=True),
Pin(num='4',name='EN',do_erc=True),
Pin(num='5',name='VIN',do_erc=True)]),
Part(name='LMR10510YSD',dest=TEMPLATE,tool=SKIDL,keywords='Miniature Step-Up Boost SEPIC Voltage Regulator',description='2.1A, 24Vout Step-Up Voltage Regulator, 1.6MHz Frequency',ref_prefix='U',num_units=1,do_erc=True,aliases=['LMR62421XSD'],pins=[
Pin(num='1',name='FB',do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='VIND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='VINA',do_erc=True),
Pin(num='6',name='EN',do_erc=True)]),
Part(name='LMR16006YQ',dest=TEMPLATE,tool=SKIDL,keywords='simple-switcher buck step-down voltage-regulator',description='Simple Switcher Buck Regulator, Vin=4-40V, Iout=600mA, Fixed 5.0V output voltage, SOT-23-6 package',ref_prefix='U',num_units=1,fplist=['SOT-23*'],do_erc=True,aliases=['LMR16006YQ3', 'LMR16006YQ5'],pins=[
Pin(num='1',name='CB',do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='FB',do_erc=True),
Pin(num='4',name='~SHDN',do_erc=True),
Pin(num='5',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LT1054',dest=TEMPLATE,tool=SKIDL,keywords='monolithic bipolar switched capacitor voltage converter regulator inverter doubler shutdown',description='Switched-Capacitor Voltage Converter with Regulator, output current 100mA, operating range 3.5V to 15V, low loss 1.1V at 100mA',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*'],do_erc=True,pins=[
Pin(num='1',name='FB/SHDN',do_erc=True),
Pin(num='2',name='CAP+',do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='CAP-',do_erc=True),
Pin(num='5',name='VOUT',func=Pin.PWROUT,do_erc=True),
Pin(num='6',name='VREF',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='OSC',do_erc=True),
Pin(num='8',name='V+',func=Pin.PWRIN,do_erc=True)]),
Part(name='LT1073',dest=TEMPLATE,tool=SKIDL,keywords='Micropower DC/DC Converter',description='Micropower DC/DC Converter Adjustable and Fixed 5V, 12V',ref_prefix='U',num_units=1,fplist=['SOIC-8*', 'DIP*W7.62mm*'],do_erc=True,pins=[
Pin(num='1',name='Ilim',do_erc=True),
Pin(num='2',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='SW1',do_erc=True),
Pin(num='4',name='SW2',do_erc=True),
Pin(num='5',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='A0',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='SET',do_erc=True),
Pin(num='8',name='SENSE',do_erc=True)]),
Part(name='LT1372',dest=TEMPLATE,tool=SKIDL,description='Set up/step down switching regulator',ref_prefix='U',num_units=1,do_erc=True,aliases=['LT1373'],pins=[
Pin(num='1',name='Vc',do_erc=True),
Pin(num='2',name='FB+',do_erc=True),
Pin(num='3',name='FB-',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='S/S',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='GND_S',do_erc=True),
Pin(num='7',name='GND',do_erc=True),
Pin(num='8',name='Vsw',do_erc=True)]),
Part(name='LT1945',dest=TEMPLATE,tool=SKIDL,keywords='switched voltage converter regulator inverter double shutdown positive negative',description='Dual Micropower DC/DC Converter with Positive and Negative Outputs',ref_prefix='U',num_units=1,fplist=['MSOP-10*'],do_erc=True,pins=[
Pin(num='1',name='NFB1',do_erc=True),
Pin(num='2',name='~SHDN1',do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='~SHDN2',do_erc=True),
Pin(num='5',name='FB2',do_erc=True),
Pin(num='6',name='SW2',func=Pin.PWROUT,do_erc=True),
Pin(num='7',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='V_IN',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='SW1',func=Pin.PWROUT,do_erc=True)]),
Part(name='LT3430',dest=TEMPLATE,tool=SKIDL,keywords='REGUL POWER',description='Hight Voltage Step-down switching regulator (synchronous) 3 A',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='VIN',do_erc=True),
Pin(num='4',name='VIN',do_erc=True),
Pin(num='5',name='SW',func=Pin.PASSIVE,do_erc=True),
Pin(num='6',name='BOOST',do_erc=True),
Pin(num='8',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='Bias',do_erc=True),
Pin(num='11',name='COMP',do_erc=True),
Pin(num='12',name='FB(1.22V)',do_erc=True),
Pin(num='14',name='SYNC',do_erc=True),
Pin(num='15',name='SHDN',do_erc=True),
Pin(num='16',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='17',name='GND',func=Pin.PWRIN,do_erc=True)]),
Part(name='LT3439',dest=TEMPLATE,tool=SKIDL,description='Low EMI DC/DC converter.',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='COLA',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='Rsl',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='SYNC',func=Pin.PASSIVE,do_erc=True),
Pin(num='6',name='Ct',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='Rt',func=Pin.PASSIVE,do_erc=True),
Pin(num='10',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='11',name='~SHDN~',do_erc=True),
Pin(num='13',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='COLB',func=Pin.OUTPUT,do_erc=True),
Pin(num='16',name='PGND',func=Pin.PWRIN,do_erc=True)]),
Part(name='LT3757EMSE',dest=TEMPLATE,tool=SKIDL,description='Boost, flyback, SEPIC and inverting regulator (MSOP package)',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='VC',do_erc=True),
Pin(num='2',name='FBX',do_erc=True),
Pin(num='3',name='SS',do_erc=True),
Pin(num='4',name='RT',do_erc=True),
Pin(num='5',name='SYNC',do_erc=True),
Pin(num='6',name='SENSE',do_erc=True),
Pin(num='7',name='GATE',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='INTVCC',func=Pin.OUTPUT,do_erc=True),
Pin(num='9',name='~SHDN~/UVLO',do_erc=True),
Pin(num='10',name='VIN',do_erc=True),
Pin(num='11',name='GND',func=Pin.PWRIN,do_erc=True)]),
Part(name='LTC1044',dest=TEMPLATE,tool=SKIDL,keywords='monolithic CMOS switched capacitor voltage converter invert double divide multiply boost',description='Switched-Capacitor Voltage Converter, 1.5V to 10.0V operating supply voltage, 10mA with a 0.5V output drop',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*'],do_erc=True,aliases=['MAX1044', 'ICL7660'],pins=[
Pin(num='1',name='BOOST',do_erc=True),
Pin(num='2',name='CAP+',do_erc=True),
Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='CAP-',do_erc=True),
Pin(num='5',name='VOUT',func=Pin.PWROUT,do_erc=True),
Pin(num='6',name='LV',do_erc=True),
Pin(num='7',name='OSC',do_erc=True),
Pin(num='8',name='V+',func=Pin.PWRIN,do_erc=True)]),
Part(name='LTC1307',dest=TEMPLATE,tool=SKIDL,keywords='POWER',description='Switching Regulator (Single cell micropower)',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='Vc',do_erc=True),
Pin(num='2',name='FeedBack',do_erc=True),
Pin(num='3',name='SHDW',do_erc=True),
Pin(num='4',name='GND',do_erc=True),
Pin(num='5',name='SW',func=Pin.OPENCOLL,do_erc=True),
Pin(num='6',name='VIN',do_erc=True),
Pin(num='7',name='LBI',do_erc=True),
Pin(num='8',name='LBO',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LTC1624',dest=TEMPLATE,tool=SKIDL,keywords='POWER',description='Switching Regulator Controller',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='ISENSE',do_erc=True),
Pin(num='2',name='Ith/RUN',do_erc=True),
Pin(num='3',name='SET',do_erc=True),
Pin(num='4',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='SW',do_erc=True),
Pin(num='6',name='TG',func=Pin.OPENCOLL,do_erc=True),
Pin(num='7',name='BOOST',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VIN',do_erc=True)]),
Part(name='LTC1878',dest=TEMPLATE,tool=SKIDL,keywords='REGUL POWER',description='Synchronous Step-Down Regulator',ref_prefix='U',num_units=1,do_erc=True,aliases=['LTC1878EMS8'],pins=[
Pin(num='1',name='RUN',do_erc=True),
Pin(num='2',name='ITH',do_erc=True),
Pin(num='3',name='VFB',do_erc=True),
Pin(num='4',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='6',name='VIN',do_erc=True),
Pin(num='7',name='SYNC',do_erc=True),
Pin(num='8',name='PLL_LPF',func=Pin.BIDIR,do_erc=True)]),
Part(name='LTC3429',dest=TEMPLATE,tool=SKIDL,keywords='boost step-up DC/DC synchronous',description='600mA, 500kHz Micropower Synchronous Boost Converter with Output Disconnect, Continuous Switching at Light Loads, TSOT-23 6-Lead Package',ref_prefix='U',num_units=1,fplist=['TSOT-23*', 'SOT-23*'],do_erc=True,aliases=['LTC3429B'],pins=[
Pin(num='1',name='SW',do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='FB',do_erc=True),
Pin(num='4',name='~SHDN',do_erc=True),
Pin(num='5',name='VOUT',func=Pin.PWROUT,do_erc=True),
Pin(num='6',name='VIN',func=Pin.PWRIN,do_erc=True)]),
Part(name='LTC3442',dest=TEMPLATE,tool=SKIDL,description='Micropower Synchronous Buck-Boost DC/DC Converter with Automatic Burst Mode Operation',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='SHDN/SS',do_erc=True),
Pin(num='2',name='RT',do_erc=True),
Pin(num='3',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='SW1',func=Pin.BIDIR,do_erc=True),
Pin(num='5',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='SW2',func=Pin.BIDIR,do_erc=True),
Pin(num='7',name='BURST',do_erc=True),
Pin(num='8',name='VOUT',func=Pin.PWROUT,do_erc=True),
Pin(num='9',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='RLIM',do_erc=True),
Pin(num='11',name='VC',do_erc=True),
Pin(num='12',name='FB',do_erc=True),
Pin(num='13',name='PGND',func=Pin.PWRIN,do_erc=True)]),
Part(name='LTC3525',dest=TEMPLATE,tool=SKIDL,keywords='fixed boost step-up DC/DC synchronous',description='Fixed 3V, 400mA Micropower Synchronous Step-Up DC/DC Converter with Output Disconnect',ref_prefix='U',num_units=1,fplist=['SC70*'],do_erc=True,aliases=['LTC3525-3', 'LTC3525-3.3', 'LTC3525-5', 'LTC3525D-3.3', 'LTC3525L-3'],pins=[
Pin(num='1',name='~SHDN',do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='VOUT',func=Pin.PWROUT,do_erc=True),
Pin(num='5',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='SW',do_erc=True)]),
Part(name='LTC3630',dest=TEMPLATE,tool=SKIDL,keywords='buck dc-dc switcher switching',description='High efficiency 76V 500mA synchronous step-down converter',ref_prefix='U',num_units=1,fplist=['DFN*', 'MSOP*'],do_erc=True,aliases=['LTC3630A'],pins=[
Pin(num='1',name='SW',func=Pin.PWROUT,do_erc=True),
Pin(num='2',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='3',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='5',name='RUN',do_erc=True),
Pin(num='6',name='Vprg2',func=Pin.BIDIR,do_erc=True),
Pin(num='7',name='Vprg1',func=Pin.BIDIR,do_erc=True),
Pin(num='8',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='Vfb',do_erc=True),
Pin(num='10',name='SS',do_erc=True),
Pin(num='11',name='Iset',do_erc=True),
Pin(num='12',name='FBO',do_erc=True),
Pin(num='13',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='14',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='15',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='16',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='17',name='GND',func=Pin.PWRIN,do_erc=True)]),
Part(name='LTC3886',dest=TEMPLATE,tool=SKIDL,keywords='step down switch manager I2C telemetry fault current sense',description='60V dual output buck output with digital power system management',ref_prefix='U',num_units=1,fplist=['QFN*'],do_erc=True,pins=[
Pin(num='1',name='SW0',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='TG0',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='Isense0+',do_erc=True),
Pin(num='5',name='Isense0-',do_erc=True),
Pin(num='6',name='TSNS0',do_erc=True),
Pin(num='7',name='Vsense0+',do_erc=True),
Pin(num='8',name='Vsense0-',do_erc=True),
Pin(num='9',name='Isense1+',do_erc=True),
Pin(num='10',name='Isense1-',do_erc=True),
Pin(num='20',name='RUN1',do_erc=True),
Pin(num='30',name='Vdd33',func=Pin.PWROUT,do_erc=True),
Pin(num='40',name='BOOST1',func=Pin.OUTPUT,do_erc=True),
Pin(num='50',name='BG0',func=Pin.OUTPUT,do_erc=True),
Pin(num='11',name='Ithr0',do_erc=True),
Pin(num='21',name='ASEL0',do_erc=True),
Pin(num='31',name='Ith1',do_erc=True),
Pin(num='12',name='Ith0',do_erc=True),
Pin(num='22',name='ASEL1',do_erc=True),
Pin(num='32',name='Ithr1',do_erc=True),
Pin(num='42',name='BG1',func=Pin.OUTPUT,do_erc=True),
Pin(num='52',name='BOOST0',func=Pin.OUTPUT,do_erc=True),
Pin(num='13',name='SYNC',do_erc=True),
Pin(num='23',name='Vout_cfg0',do_erc=True),
Pin(num='33',name='PGOOD1',func=Pin.OUTPUT,do_erc=True),
Pin(num='43',name='EXTVcc',func=Pin.PWRIN,do_erc=True),
Pin(num='53',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='SCL',do_erc=True),
Pin(num='24',name='Vout_cfg1',do_erc=True),
Pin(num='34',name='PGOOD0',func=Pin.OUTPUT,do_erc=True),
Pin(num='44',name='INTVcc',func=Pin.PWROUT,do_erc=True),
Pin(num='15',name='SDA',func=Pin.BIDIR,do_erc=True),
Pin(num='25',name='FREQ_CFG',do_erc=True),
Pin(num='35',name='Vsense1+',do_erc=True),
Pin(num='16',name='~ALERT',func=Pin.OUTPUT,do_erc=True),
Pin(num='26',name='PHAS_CFG',do_erc=True),
Pin(num='36',name='TSNS1',do_erc=True),
Pin(num='46',name='Iin-',do_erc=True),
Pin(num='17',name='~FAULT0',func=Pin.OUTPUT,do_erc=True),
Pin(num='27',name='Vdd25',func=Pin.PWROUT,do_erc=True),
Pin(num='47',name='Iin+',do_erc=True),
Pin(num='18',name='~FAULT1',func=Pin.OUTPUT,do_erc=True),
Pin(num='28',name='WP',do_erc=True),
Pin(num='38',name='TG1',func=Pin.OUTPUT,do_erc=True),
Pin(num='48',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='19',name='RUN0',do_erc=True),
Pin(num='29',name='SHARE_CLK',do_erc=True),
Pin(num='39',name='SW1',func=Pin.OUTPUT,do_erc=True)]),
Part(name='LTC3890',dest=TEMPLATE,tool=SKIDL,keywords='switching buck converter regulator dual-output',description='60V dual 2-phase synchronous step-down DC/DC controller in QFN-32 package',ref_prefix='U',num_units=1,fplist=['QFN*'],do_erc=True,pins=[
Pin(num='1',name='SENSE1-',do_erc=True),
Pin(num='2',name='FREQ',do_erc=True),
Pin(num='3',name='PHASMD',do_erc=True),
Pin(num='4',name='CLKOUT',func=Pin.OUTPUT,do_erc=True),
Pin(num='5',name='PLL/MODE',do_erc=True),
Pin(num='6',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='RUN1',do_erc=True),
Pin(num='8',name='RUN2',do_erc=True),
Pin(num='9',name='SENSE2-',do_erc=True),
Pin(num='10',name='SENSE2+',do_erc=True),
Pin(num='20',name='EXTVcc',func=Pin.PWRIN,do_erc=True),
Pin(num='30',name='ITH1',func=Pin.OUTPUT,do_erc=True),
Pin(num='11',name='VFB2',do_erc=True),
Pin(num='21',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='31',name='VFB1',do_erc=True),
Pin(num='12',name='ITH2',func=Pin.OUTPUT,do_erc=True),
Pin(num='22',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='32',name='SENSE1+',do_erc=True),
Pin(num='13',name='SS2',do_erc=True),
Pin(num='23',name='BG1',func=Pin.OUTPUT,do_erc=True),
Pin(num='33',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='PGOOD2',func=Pin.OUTPUT,do_erc=True),
Pin(num='24',name='BOOST1',func=Pin.OUTPUT,do_erc=True),
Pin(num='15',name='TG2',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='SW1',func=Pin.OUTPUT,do_erc=True),
Pin(num='16',name='SW2',func=Pin.OUTPUT,do_erc=True),
Pin(num='26',name='TG1',func=Pin.OUTPUT,do_erc=True),
Pin(num='17',name='BOOST2',func=Pin.OUTPUT,do_erc=True),
Pin(num='27',name='PGOOD1',func=Pin.OUTPUT,do_erc=True),
Pin(num='18',name='BG2',func=Pin.OUTPUT,do_erc=True),
Pin(num='28',name='I_Lim',do_erc=True),
Pin(num='19',name='INTVcc',func=Pin.PWROUT,do_erc=True),
Pin(num='29',name='SS1',do_erc=True)]),
Part(name='LTC3890-1',dest=TEMPLATE,tool=SKIDL,keywords='switching buck converter regulator dual-output',description='60V dual 2-phase synchronous step-down DC/DC controller in SSOP-28 package',ref_prefix='U',num_units=1,fplist=['SSOP*'],do_erc=True,pins=[
Pin(num='1',name='ITH1',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='VFB1',do_erc=True),
Pin(num='3',name='SENSE1+',do_erc=True),
Pin(num='4',name='SENSE1-',do_erc=True),
Pin(num='5',name='FREQ',do_erc=True),
Pin(num='6',name='PLL/MODE',do_erc=True),
Pin(num='7',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='RUN1',do_erc=True),
Pin(num='9',name='RUN2',do_erc=True),
Pin(num='10',name='SENSE2-',do_erc=True),
Pin(num='20',name='EXTVcc',func=Pin.PWRIN,do_erc=True),
Pin(num='11',name='SENSE2+',do_erc=True),
Pin(num='21',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='12',name='VFB2',do_erc=True),
Pin(num='22',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='13',name='ITH2',func=Pin.OUTPUT,do_erc=True),
Pin(num='23',name='BG1',func=Pin.OUTPUT,do_erc=True),
Pin(num='14',name='SS2',do_erc=True),
Pin(num='24',name='BOOST1',func=Pin.OUTPUT,do_erc=True),
Pin(num='15',name='TG2',func=Pin.OUTPUT,do_erc=True),
Pin(num='25',name='SW1',func=Pin.OUTPUT,do_erc=True),
Pin(num='16',name='SW2',func=Pin.OUTPUT,do_erc=True),
Pin(num='26',name='TG1',func=Pin.OUTPUT,do_erc=True),
Pin(num='17',name='BOOST2',func=Pin.OUTPUT,do_erc=True),
Pin(num='27',name='PGOOD1',func=Pin.OUTPUT,do_erc=True),
Pin(num='18',name='BG2',func=Pin.OUTPUT,do_erc=True),
Pin(num='28',name='SS1',do_erc=True),
Pin(num='19',name='INTVcc',func=Pin.PWROUT,do_erc=True)]),
Part(name='MAX15062A',dest=TEMPLATE,tool=SKIDL,keywords='step-down dc-dc switching regulator',description='60V, 300mA, synchronous step-down dc-dc converter, adjustable output voltage',ref_prefix='U',num_units=1,fplist=['DFN*2x2mm*Pitch0.5mm*'],do_erc=True,aliases=['MAX15062B', 'MAX15062C'],pins=[
Pin(num='1',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='EN/UVLO',do_erc=True),
Pin(num='3',name='VCC',func=Pin.PWROUT,do_erc=True),
Pin(num='4',name='FB/Vout',do_erc=True),
Pin(num='5',name='MODE',do_erc=True),
Pin(num='6',name='~RESET',func=Pin.OPENCOLL,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='LX',func=Pin.PWROUT,do_erc=True)]),
Part(name='MAX5035AUPA',dest=TEMPLATE,tool=SKIDL,keywords='Adjustable 1A Step-Down Converter 76V',description='Adjustable 1A, High-Efficiency Step-Down DC-DC Converter, Vin 76V, PDIP-8',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*'],do_erc=True,aliases=['MAX5035BUPA', 'MAX5035CUPA', 'MAX5035DUPA'],pins=[
Pin(num='1',name='BST',func=Pin.PASSIVE,do_erc=True),
Pin(num='2',name='VD',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF~',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='LX',func=Pin.PWRIN,do_erc=True)]),
Part(name='MAX5035AUSA',dest=TEMPLATE,tool=SKIDL,keywords='Adjustable 1A Step-Down Converter 76V',description='Adjustable 1A, High-Efficiency Step-Down DC-DC Converter, Vin 76V, SO8',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,aliases=['MAX5035AASA', 'MAX5035BUSA', 'MAX5035BASA', 'MAX5035CUSA', 'MAX5035CASA', 'MAX5035DUSA', 'MAX5035DASA', 'MAX5035EUSA', 'MAX5035EASA'],pins=[
Pin(num='1',name='BST',func=Pin.PASSIVE,do_erc=True),
Pin(num='2',name='VD',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='ON/~OFF~',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='LX',func=Pin.PWRIN,do_erc=True)]),
Part(name='MAX777',dest=TEMPLATE,tool=SKIDL,keywords='switching regulator boost step-up dc-dc',description='Low voltage input, step-up, DC-DC converter',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='ILIM',do_erc=True),
Pin(num='2',name='IN',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='LX',func=Pin.PASSIVE,do_erc=True),
Pin(num='6',name='OUT',func=Pin.PWROUT,do_erc=True),
Pin(num='7',name='~SHDN',do_erc=True)]),
Part(name='MC34063',dest=TEMPLATE,tool=SKIDL,keywords='smps buck boost inverting',description='1.5A step up/down/inverting switching regulator',ref_prefix='U',num_units=1,fplist=['DIP*W7.62mm*', 'SOIC*3.9x4.9mm*Pitch1.27mm*', 'DFN*'],do_erc=True,pins=[
Pin(num='1',name='SwC',func=Pin.PASSIVE,do_erc=True),
Pin(num='2',name='SwE',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='TC',do_erc=True),
Pin(num='4',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='Vfb',do_erc=True),
Pin(num='6',name='Vin(VCC)',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='Ipk',do_erc=True),
Pin(num='8',name='DC',func=Pin.PASSIVE,do_erc=True)]),
Part(name='MCP16301',dest=TEMPLATE,tool=SKIDL,keywords='switching buck converter power-supply voltage regulator',description='4.7 to 36V Input, 1A output, integrated switch step-down regulator, SOT-23-6 package',ref_prefix='U',num_units=1,fplist=['SOT?23*'],do_erc=True,aliases=['MCP16301H'],pins=[
Pin(num='1',name='BOOST',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='Vfb',do_erc=True),
Pin(num='4',name='EN',do_erc=True),
Pin(num='5',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='SW',func=Pin.PWROUT,do_erc=True)]),
Part(name='MCP16311-MNY',dest=TEMPLATE,tool=SKIDL,keywords='switching buck converter power-supply voltage regulator',description='30V Input, 1A output, integrated switch step-down regulator, PWM modulation, DFN-8 package',ref_prefix='U',num_units=1,fplist=['DFN*1EP*3x2mm*Pitch0.5mm*'],do_erc=True,aliases=['MCP16312-MNY'],pins=[
Pin(num='1',name='Vfb',do_erc=True),
Pin(num='2',name='Vcc',func=Pin.PWROUT,do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='Pgnd',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='SW',func=Pin.PWROUT,do_erc=True),
Pin(num='7',name='BOOST',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='Agnd',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='PAD',func=Pin.PWRIN,do_erc=True)]),
Part(name='MCP16311-MS',dest=TEMPLATE,tool=SKIDL,keywords='switching buck converter power-supply voltage regulator',description='30V Input, 1A output, integrated switch step-down regulator with, modulation, MSOP-8 package',ref_prefix='U',num_units=1,fplist=['MSOP*3x3mm*Pitch0.65mm*'],do_erc=True,aliases=['MCP16312-MS'],pins=[
Pin(num='1',name='Vfb',do_erc=True),
Pin(num='2',name='Vcc',func=Pin.PWROUT,do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='Pgnd',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='SW',func=Pin.PWROUT,do_erc=True),
Pin(num='7',name='BOOST',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='Agnd',func=Pin.PWRIN,do_erc=True)]),
Part(name='MCP1640-CH',dest=TEMPLATE,tool=SKIDL,keywords='Step-Up Boost DC-DC Regulator Adjustable',description='Synchronous Boost Regulator, Adjustable Output 2.0V-5.5V, PWM Only Input to Output Bypass, SOT23',ref_prefix='U',num_units=1,fplist=['SOT?23*'],do_erc=True,aliases=['MCP1640B-CH', 'MCP1640C-CH', 'MCP1640D-CH'],pins=[
Pin(num='1',name='SW',do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='VFB',do_erc=True),
Pin(num='5',name='VOUT',func=Pin.PWROUT,do_erc=True),
Pin(num='6',name='VIN',func=Pin.PWRIN,do_erc=True)]),
Part(name='MCP1640-MC',dest=TEMPLATE,tool=SKIDL,keywords='Step-Up Boost DC-DC Regulator Adjustable',description='Synchronous Boost Regulator, Adjustable Output 2.0V-5.5V, PWM Only Input to Output Bypass, DFN',ref_prefix='U',num_units=1,fplist=['DFN*1EP*3x2mm*Pitch0.5mm*'],do_erc=True,aliases=['MCP1640B-MC', 'MCP1640C-MC', 'MCP1640D-MC'],pins=[
Pin(num='1',name='VFB',do_erc=True),
Pin(num='2',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='EN',do_erc=True),
Pin(num='5',name='SW',do_erc=True),
Pin(num='6',name='VOUTP',func=Pin.PWROUT,do_erc=True),
Pin(num='7',name='VOUTS',func=Pin.PWROUT,do_erc=True),
Pin(num='8',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='9',name='PAD',func=Pin.PASSIVE,do_erc=True)]),
Part(name='MCP1650',dest=TEMPLATE,tool=SKIDL,keywords='boost controller',description='750 kHz Boost Controller from 3.3V up to 100V, 5W.',ref_prefix='U',num_units=1,fplist=['MSOP*3x3mm*Pitch0.65mm*'],do_erc=True,pins=[
Pin(num='1',name='EXT',func=Pin.OPENEMIT,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='CS',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~SHDN',do_erc=True),
Pin(num='6',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='7',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='8',name='Vin',func=Pin.PWRIN,do_erc=True)]),
Part(name='MCP1651',dest=TEMPLATE,tool=SKIDL,keywords='boost controller',description='750 kHz Boost Controller from 3.3V up to 100V, 5W.',ref_prefix='U',num_units=1,fplist=['MSOP*3x3mm*Pitch0.65mm*'],do_erc=True,pins=[
Pin(num='1',name='EXT',func=Pin.OPENEMIT,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='CS',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~SHDN',do_erc=True),
Pin(num='6',name='LBI',do_erc=True),
Pin(num='7',name='~LBO',func=Pin.OPENEMIT,do_erc=True),
Pin(num='8',name='Vin',func=Pin.PWRIN,do_erc=True)]),
Part(name='MCP1652',dest=TEMPLATE,tool=SKIDL,keywords='boost controller',description='750 kHz Boost Controller from 3.3V up to 100V, 5W.',ref_prefix='U',num_units=1,fplist=['MSOP*3x3mm*Pitch0.65mm*'],do_erc=True,pins=[
Pin(num='1',name='EXT',func=Pin.OPENEMIT,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='CS',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='~SHDN',do_erc=True),
Pin(num='6',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='7',name='PG',func=Pin.OPENEMIT,do_erc=True),
Pin(num='8',name='Vin',func=Pin.PWRIN,do_erc=True)]),
Part(name='MCP1653',dest=TEMPLATE,tool=SKIDL,keywords='boost controller',description='750 kHz Boost Controller from 3.3V up to 100V, 5W.',ref_prefix='U',num_units=1,fplist=['MSOP*3x3mm*Pitch0.5mm*'],do_erc=True,pins=[
Pin(num='1',name='EXT',func=Pin.OPENEMIT,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='CS',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='6',name='~SHDN',do_erc=True),
Pin(num='7',name='LBI',do_erc=True),
Pin(num='8',name='~LBO',func=Pin.OPENEMIT,do_erc=True),
Pin(num='9',name='PG',func=Pin.OUTPUT,do_erc=True),
Pin(num='10',name='Vin',func=Pin.PWRIN,do_erc=True)]),
Part(name='MIC2177',dest=TEMPLATE,tool=SKIDL,keywords='REGUL POWER',description='Step-down switching regulator (synchronous) 2.5 A',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='VIN',do_erc=True),
Pin(num='2',name='VIN',do_erc=True),
Pin(num='3',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='4',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='SW',func=Pin.PASSIVE,do_erc=True),
Pin(num='9',name='VIN',do_erc=True),
Pin(num='10',name='Sense',do_erc=True),
Pin(num='20',name='SHDN',do_erc=True),
Pin(num='11',name='AUTO',do_erc=True),
Pin(num='12',name='FB',do_erc=True),
Pin(num='13',name='COMP',do_erc=True),
Pin(num='14',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='15',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='16',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='17',name='SGND',func=Pin.PWRIN,do_erc=True),
Pin(num='18',name='SYNC',do_erc=True),
Pin(num='19',name='Bias',do_erc=True)]),
Part(name='NID60',dest=TEMPLATE,tool=SKIDL,keywords='60W, 250KHz Buck DC/DC',description='60W, 250kHz Step Down Converter',ref_prefix='U',num_units=1,do_erc=True,aliases=['NID60S24-5', 'NID60S24-15', 'NID60S48-24', 'NID60S24-12'],pins=[
Pin(num='1',name='Vout',func=Pin.PWROUT,do_erc=True),
Pin(num='2',name='Vout',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='Vout',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='Vout',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='11',name='RC',do_erc=True)]),
Part(name='ST1CC40PHR',dest=TEMPLATE,tool=SKIDL,keywords='DC/DC Buck Conwerter 3A Low Voltage Input LED Lighting',description="DC/DC Buck CC Converter for LED's, Vin 18V, 3A, Power SO-8 (Preliminary)",ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='VIN_A',do_erc=True),
Pin(num='2',name='SGND',func=Pin.PWROUT,do_erc=True),
Pin(num='3',name='FB',do_erc=True),
Pin(num='3',name='~ON~/OFF',do_erc=True),
Pin(num='4',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='VIN_SW',do_erc=True),
Pin(num='7',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='ST1S10PHR',dest=TEMPLATE,tool=SKIDL,keywords='DC/DC Buck Conwerter 3A Low Voltage Input',description='DC/DC Buck Converter, Vin 18V, 3A, Power SO-8',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='VIN_A',do_erc=True),
Pin(num='2',name='INH',do_erc=True),
Pin(num='2',name='PGND',func=Pin.PWROUT,do_erc=True),
Pin(num='3',name='FB',do_erc=True),
Pin(num='4',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='SYNC',func=Pin.BIDIR,do_erc=True),
Pin(num='6',name='VIN_SW',do_erc=True),
Pin(num='7',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='ST1S10PUR',dest=TEMPLATE,tool=SKIDL,keywords='DC/DC Buck Conwerter 3A Low Voltage Input',description='ST1S10PHR, DC/DC Buck Converter, Vin 18V, 3A, DFN-8 (4x4mm)',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='VIN_A',do_erc=True),
Pin(num='2',name='INH',do_erc=True),
Pin(num='2',name='PGND',func=Pin.PWROUT,do_erc=True),
Pin(num='3',name='FB',do_erc=True),
Pin(num='4',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='SYNC',func=Pin.BIDIR,do_erc=True),
Pin(num='6',name='VIN_SW',do_erc=True),
Pin(num='7',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='ST1S14PHR',dest=TEMPLATE,tool=SKIDL,keywords='DC/DC Buck Conwerter 3A',description='DC/DC Buck Converter, Vin 48V, 3A, Power SO-8',ref_prefix='U',num_units=1,do_erc=True,pins=[
Pin(num='1',name='BST',do_erc=True),
Pin(num='2',name='PG',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='~EN1~',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='EN2',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',do_erc=True),
Pin(num='8',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='TEN20-2411WIN',dest=TEMPLATE,tool=SKIDL,keywords='TRACO DC/DC',description='Isolated DC/DC Converter, Vin=18-75V, Vout=15V@1.33A',ref_prefix='U',num_units=1,fplist=['DCDC?Conv?TRACO?TEN20?xxxx*'],do_erc=True,aliases=['TEN20-2410WIN', 'TEN20-2412WIN', 'TEN20-2413WIN', 'TEN20-4810WIN', 'TEN20-4811WIN', 'TEN20-4812WIN', 'TEN20-4813WIN'],pins=[
Pin(num='1',name='VIN+',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VIN-',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='VOUT+',func=Pin.PWROUT,do_erc=True),
Pin(num='4',name='TRIM',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='VOUT-',func=Pin.PWROUT,do_erc=True),
Pin(num='6',name='ON/~OFF',do_erc=True)]),
Part(name='TEN20-2421WIN',dest=TEMPLATE,tool=SKIDL,keywords='TRACO DC/DC',description='Isolated DC/DC Dual Supply Converter, Vin=18-75V, Vout=+-15V@665mA',ref_prefix='U',num_units=1,fplist=['DCDC?Conv?TRACO?TEN20?xxxx*'],do_erc=True,aliases=['TEN20-2422WIN', 'TEN20-2423WIN', 'TEN20-4821WIN', 'TEN20-4822WIN', 'TEN20-4823WIN'],pins=[
Pin(num='1',name='VIN+',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VIN-',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='VOUT+',func=Pin.PWROUT,do_erc=True),
Pin(num='4',name='CM',func=Pin.PWROUT,do_erc=True),
Pin(num='5',name='VOUT-',func=Pin.PWROUT,do_erc=True),
Pin(num='6',name='ON/~OFF',do_erc=True)]),
Part(name='TL497',dest=TEMPLATE,tool=SKIDL,keywords='buck regulator',description='500 mA step up/step down switching regulator',ref_prefix='U',num_units=1,do_erc=True,aliases=['TL497A'],pins=[
Pin(num='1',name='Comp',do_erc=True),
Pin(num='2',name='Inhbt',do_erc=True),
Pin(num='3',name='Freq',do_erc=True),
Pin(num='4',name='Substrate',do_erc=True),
Pin(num='5',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='Cath.',do_erc=True),
Pin(num='7',name='Anode',do_erc=True),
Pin(num='8',name='Emit',func=Pin.OUTPUT,do_erc=True),
Pin(num='9',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='10',name='Coll',do_erc=True),
Pin(num='11',name='Base_Tr',func=Pin.UNSPEC,do_erc=True),
Pin(num='12',name='BaseDrv',func=Pin.UNSPEC,do_erc=True),
Pin(num='13',name='Curr_Lim',do_erc=True),
Pin(num='14',name='VCC',func=Pin.PWRIN,do_erc=True)]),
Part(name='TPS5430DDA',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down DC-DC Switching Regulator',description='23V 3A, Step Down Swift Converter, HSOIC8',ref_prefix='U',num_units=1,fplist=['*SO*'],do_erc=True,aliases=['TPS5431DDA'],pins=[
Pin(num='1',name='BOOT',do_erc=True),
Pin(num='4',name='VSENSE',do_erc=True),
Pin(num='5',name='EN',do_erc=True),
Pin(num='6',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VIN',do_erc=True),
Pin(num='8',name='PH',func=Pin.OUTPUT,do_erc=True),
Pin(num='9',name='PAD',func=Pin.PASSIVE,do_erc=True)]),
Part(name='TPS54360DDA',dest=TEMPLATE,tool=SKIDL,keywords='Step-Down DC-DC Switching Regulator High Voltage High Frequency',description='60V 3.5 A, Step Down DC-DC Converter with Eco-mode, HSOIC8',ref_prefix='U',num_units=1,fplist=['*SO*'],do_erc=True,aliases=['TPS54340DDA'],pins=[
Pin(num='1',name='BOOT',do_erc=True),
Pin(num='2',name='VIN',do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='RT/CLK',do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='COMP',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='8',name='SW',func=Pin.OUTPUT,do_erc=True),
Pin(num='9',name='PAD',func=Pin.PASSIVE,do_erc=True)]),
Part(name='TPS560200',dest=TEMPLATE,tool=SKIDL,keywords='Voltage regulator switching buck fixed output analog',description='17V step-down regulator, 500mA output in SOT23-5 package',ref_prefix='U',num_units=1,fplist=['SOT-23*'],do_erc=True,pins=[
Pin(num='1',name='EN',do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='PH',func=Pin.PWROUT,do_erc=True),
Pin(num='4',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',do_erc=True)]),
Part(name='TPS60500DGS',dest=TEMPLATE,tool=SKIDL,keywords='Regulator Step-Down Charge Pump TPS Texas Instruments Ti',description='250mA Step-Down Charge Pump Regulator, 1.5V',ref_prefix='U',num_units=1,fplist=['MSOP-10*'],do_erc=True,aliases=['TPS60501DGS', 'TPS60502DGS', 'TPS60503DGS'],pins=[
Pin(num='1',name='~EN',do_erc=True),
Pin(num='2',name='PG',func=Pin.OPENCOLL,do_erc=True),
Pin(num='3',name='C2-',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='C2+',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='VIN',do_erc=True),
Pin(num='6',name='C1+',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='VOUT',func=Pin.PWROUT,do_erc=True),
Pin(num='8',name='C1-',func=Pin.PASSIVE,do_erc=True),
Pin(num='9',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='FB',do_erc=True)]),
Part(name='TPS61200',dest=TEMPLATE,tool=SKIDL,keywords='boost step-up DC/DC synchronous',description='Fixed 5V Output, Low Input Voltage Synchronous Boost Converter With 1.3-A Switches, VSON (10) Package',ref_prefix='U',num_units=1,fplist=['S-PVSON-N10', 'S-PWSON-N10'],do_erc=True,aliases=['TPS61201', 'TPS61202'],pins=[
Pin(num='1',name='VAUX',func=Pin.BIDIR,do_erc=True),
Pin(num='2',name='VOUT',func=Pin.PWROUT,do_erc=True),
Pin(num='3',name='L',do_erc=True),
Pin(num='4',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='EN',do_erc=True),
Pin(num='7',name='UVLO',do_erc=True),
Pin(num='8',name='PS',do_erc=True),
Pin(num='9',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='FB',do_erc=True),
Pin(num='11',name='PAD',func=Pin.PWRIN,do_erc=True)]),
Part(name='TPS62170',dest=TEMPLATE,tool=SKIDL,keywords='step-down dc-dc buck regulator',description='Step-Down Conveter, 0.5A, 3V-17V input, 5.0V fixed output',ref_prefix='U',num_units=1,fplist=['DFN*1EP*2x2mm*Pitch0.5mm*'],do_erc=True,aliases=['TPS62171', 'TPS62172', 'TPS62173'],pins=[
Pin(num='1',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='VOS',do_erc=True),
Pin(num='7',name='SW',func=Pin.PWROUT,do_erc=True),
Pin(num='8',name='PG',func=Pin.OUTPUT,do_erc=True),
Pin(num='9',name='PAD',func=Pin.PWRIN,do_erc=True)]),
Part(name='TPS62177',dest=TEMPLATE,tool=SKIDL,keywords='step-down dc-dc buck regulator',description='Step-Down Conveter, 0.5A, 4.75V-28V input, 3.3V fixed output, with Sleep Mode',ref_prefix='U',num_units=1,fplist=['DFN*1EP*2x3mm*Pitch0.5mm*'],do_erc=True,aliases=['TPS62175'],pins=[
Pin(num='1',name='PGND',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='VIN',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='NC',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='FB',do_erc=True),
Pin(num='6',name='AGND',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='PG',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='~SLEEP',do_erc=True),
Pin(num='9',name='SW',func=Pin.PWROUT,do_erc=True),
Pin(num='10',name='VOS',do_erc=True),
Pin(num='11',name='PAD',func=Pin.PWRIN,do_erc=True)]),
Part(name='TPS62200DBV',dest=TEMPLATE,tool=SKIDL,keywords='TPS62208DBV Step-Down DC-DC Converter SOT-23-5',description='SOT-23-5, High-Efficiency Step-Down DC-DC Converter, 1.875V',ref_prefix='U',num_units=1,fplist=['SOT?23*'],do_erc=True,aliases=['TPS62201DBV', 'TPS62202DBV', 'TPS62203DBV', 'TPS62204DBV', 'TPS62205DBV', 'TPS62207DBV', 'TPS62208DBV'],pins=[
Pin(num='1',name='VI',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='EN',do_erc=True),
Pin(num='4',name='FB',do_erc=True),
Pin(num='5',name='SW',func=Pin.OUTPUT,do_erc=True)]),
Part(name='TSR_1-2450',dest=TEMPLATE,tool=SKIDL,keywords='dc-dc traco buck',description='9V 1A, step-down regulator, 12-36Vin, TO-220 compatible, replacement for LMxx linear regulators, -40°C to +85°C',ref_prefix='U',num_units=1,fplist=['DCDC?Conv?TRACO?TSR-1*'],do_erc=True,aliases=['TSR_1-2412', 'TSR_1-2415', 'TSR_1-2418', 'TSR_1-2425', 'TSR_1-2433', 'TSR_1-2465', 'TSR_1-2490', 'TSR_1-24120', 'TSR_1-24150'],pins=[
Pin(num='1',name='Vin',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='Vout',func=Pin.PWROUT,do_erc=True)])])
| [
6738,
1341,
312,
75,
1330,
14277,
2389,
43,
11,
309,
3620,
6489,
6158,
11,
2142,
11,
13727,
11,
3059,
25835,
198,
198,
18831,
2389,
43,
62,
8019,
62,
9641,
796,
705,
15,
13,
15,
13,
16,
6,
198,
198,
17896,
62,
17896,
796,
3059,
... | 1.917387 | 42,245 |
############################################
# Project: PyAN
# File: chat_state.py
# By: ProgrammingIncluded
# Website: ProgrammingIncluded.com
# Desc: File to hold chat screen and logic.
############################################
import input_buffer as ib
import connect as cnt
from command import print_buf
import command as cmd
import asyncio
from datetime import datetime
from aiohttp import ClientSession
import json
# File to handle chats.
# Keeps track of new chat data, currently written chat info,
# as well as submitting chat to server.
# Right tightly coupled with input_buffer in order to allow proper processing
# of input. input_buffer calls chat_state functions directly.
# TODO: High Chat Check
# Feature to allow checking of chat to be based of need, not fixed rate.
# Two Conditions for checking chat to be more than normal.
# A Message was recently sent.
# Inactively over HCC_INACT.
# Once HCC starts, chat checks every HCC_CHAT_PERIOD.
HCC = False
HCC_INACT = 30 # 30 seconds.
HCC_CHAT_PERIOD = 3
NON_HCC_CHAT_PERIOD = 3
CHAT_DATA = []
DISPLAY_BUF = ""
MAX_CHAT = 1000
MAX_DISPLAY = 10
# Value to store text buffer
CUR_BUF = ""
# From left to right
CURSOR = 0
LAST_SEND = datetime.now()
####################################
# Chat Exposed Functions #
####################################
# Function to move the cursor by offset
# Function to move the cursor to the end.
# Funciton to move the cursor to the start.
# Function to delete backward in the input chat state.
# Function to delete forward in the input chat state.
# Function to clear the input of the chat state.
# Constructor like function to initiate the state. Called only once per state init.
# Update state function called before display.
# Display state function called after update. Write to buffer.
####################################
# Helper Functions and Subroutines #
####################################
# Function to send current message buffer and clear it
# Functionc alled by send_msg to send the message asynchronously.
# async def send_msg_async():
# Function to update the chat screen.
# Called by chat_update_task so requires async.
# Background task to continue to update the commandline.
| [
29113,
7804,
4242,
198,
2,
4935,
25,
9485,
1565,
198,
2,
9220,
25,
8537,
62,
5219,
13,
9078,
198,
2,
2750,
25,
30297,
818,
10341,
198,
2,
15887,
25,
30297,
818,
10341,
13,
785,
198,
2,
39373,
25,
9220,
284,
1745,
8537,
3159,
290,
... | 3.742475 | 598 |
from math import sqrt, acos, pi
from model.model import Model
from data_processing import csv_processing
from sympy import *
from sympy.abc import x, y, z
from scipy.optimize import fsolve
import math
csv_data = csv_processing.get_data('data/data2.csv')
# 叉乘
# data1##############################################################
# ans_min= 103512, curve length = 103652
# [0, 503, 200, 80, 237, 170, 278, 369, 214, 397, 612]
# ans_min= 103603, curve length = 103733
# [0, 503, 200, 80, 237, 170, 278, 369, 214, 67, 612]
# ans_min= 103611, curve length = 103765
# [0, 503, 200, 80, 237, 170, 278, 369, 214, 397, 18, 612]
# ans_min= 103613, curve length = 103762
# [0, 503, 200, 80, 237, 170, 278, 369, 214, 67, 397, 612]
# ans_min= 103614, curve length = 103763
# [0, 503, 200, 80, 237, 170, 278, 369, 214, 397, 302, 612]
# data2############################################################
# ans_min= 109336, curve length = 109533.611637498
# [0, 163, 114, 8, 309, 305, 123, 45, 160, 92, 93, 61, 292, 326]
# ans_min= 109813, curve length = 110093.870199261
# [0, 163, 114, 8, 309, 305, 123, 45, 160, 92, 93, 61, 292, 135, 326]
# ans_min= 114059, curve length = 114357.829792971
# [0, 163, 114, 8, 309, 305, 123, 45, 160, 92, 93, 38, 110, 99, 326]
# ans_min= 114395, curve length = 114800.401777845
# [0, 163, 114, 8, 309, 305, 123, 45, 160, 92, 93, 38, 287, 99, 326]
# ans_min= 114672, curve length = 115114.138909153
# [0, 163, 114, 8, 309, 305, 123, 45, 160, 92, 93, 38, 287, 61, 326]
# 第一组数据,使用data1
# 第二组数据,使用data2
# array = [0, 503, 200, 80, 237, 170, 278, 369, 214, 397, 612]
# array = [0, 163, 114, 8, 309, 305, 123, 45, 160, 92, 93, 61, 292, 326]
# array = [0, 503, 69, 506, 371, 183, 194, 450, 113, 485, 248, 612]
array = [0, 163, 114, 8, 309, 305, 123, 45, 160, 92, 93, 61, 292, 326]
count = 0
start = array[0]
length = []
# 切线
qdX = []
qdY = []
qdZ = []
qdX.append(0)
qdY.append(50000)
qdZ.append(5000)
# 圆心
yX = []
yY = []
yZ = []
# 法向量
fX = []
fY = []
fZ = []
# 校验点
xx = []
yy = []
zz = []
xx.append(csv_data[start][1])
yy.append(csv_data[start][2])
zz.append(csv_data[start][3])
for i in range(1, len(array)):
# 设置入射和出射方向向量 (a, b, c)
if i == 1:
outdirVector = Vector([csv_data[array[i]][1] - csv_data[start][1], csv_data[array[i]][2] - csv_data[start][2], csv_data[array[i]][3] - csv_data[start][3]])
length.append(((csv_data[array[i]][1] - csv_data[start][1]) ** 2 +
(csv_data[array[i]][2] - csv_data[start][2]) ** 2 +
(csv_data[array[i]][3] - csv_data[start][3]) ** 2) ** 0.5)
start = array[i]
xx.append(int(csv_data[array[i]][1]))
yy.append(int(csv_data[array[i]][2]))
zz.append(int(csv_data[array[i]][3]))
# qiedianX = csv_data[start][1]
# qiedianY = csv_data[start][2]
# qiedianZ = csv_data[start][3]
continue
else:
indirVector = outdirVector
xx.append(int(csv_data[array[i]][1]))
yy.append(int(csv_data[array[i]][2]))
zz.append(int(csv_data[array[i]][3]))
# 起始点 (x0, y0, z0)
begin = Vector([csv_data[start][1], csv_data[start][2], csv_data[start][3]])
# 目标点 (x1, y1, z1)
end = Vector([csv_data[array[i]][1], csv_data[array[i]][2], csv_data[array[i]][3]])
# 垂直向量 (m, n, k)
# temp 为两点之间的方向向量
temp = Vector([csv_data[array[i]][1] - csv_data[start][1], csv_data[array[i]][2] - csv_data[start][2], csv_data[array[i]][3] - csv_data[start][3]])
t = indirVector.crossProduct(temp)
fX.append(int(t.coordinates[0]/10000))
fY.append(int(t.coordinates[1]/10000))
fZ.append(int(t.coordinates[2]/10000))
#print('t: ', t.coordinates[0])
A = indirVector.coordinates[0] * begin.coordinates[0] + indirVector.coordinates[1] * begin.coordinates[1] + indirVector.coordinates[2] * begin.coordinates[2]
B = end.coordinates[0] * t.coordinates[0] + end.coordinates[1] * t.coordinates[1] + end.coordinates[2] * t.coordinates[2]
aa = solve([indirVector.coordinates[0] * x + indirVector.coordinates[1] * y + indirVector.coordinates[2] * z - A,
t.coordinates[0] * x + t.coordinates[1] * y + t.coordinates[2] * z - B,
(x - begin.coordinates[0])**2 + (y - begin.coordinates[1])**2 + (z - begin.coordinates[2])**2 - 40000], [x, y, z])
# 圆心坐标 从第二个点开始的
yuanX1 = aa[0][0]
yuanY1 = aa[0][1]
yuanZ1 = aa[0][2]
yuanX2 = aa[1][0]
yuanY2 = aa[1][1]
yuanZ2 = aa[1][2]
dis1 = ((end.coordinates[0] - yuanX1)**2 + (end.coordinates[1] - yuanY1)**2 + (end.coordinates[2] - yuanZ1)**2)**0.5
dis2 = ((end.coordinates[0] - yuanX2)**2 + (end.coordinates[1] - yuanY2)**2 + (end.coordinates[2] - yuanZ2)**2)**0.5
if dis1 < dis2:
yuanX = yuanX1
yuanY = yuanY1
yuanZ = yuanZ1
else:
yuanX = yuanX2
yuanY = yuanY2
yuanZ = yuanZ2
yX.append(int(yuanX))
yY.append(int(yuanY))
yZ.append(int(yuanZ))
# print(aa)
print('x: ', yuanX, 'y: ', yuanY, 'z: ', yuanZ)
# 求切点 从第二个点开始
bb = solve([(x - yuanX)**2 + (y - yuanY)**2 + (z - yuanZ)**2 - 40000,
(x - yuanX) * t.coordinates[0] + (y - yuanY) * t.coordinates[1] + (z - yuanZ) * t.coordinates[2],
(x - yuanX) * (x - end.coordinates[0]) + (y - yuanY) * (y - end.coordinates[1]) + (z - yuanZ) * (z - end.coordinates[2])],
[x, y, z])
#print(bb)
#break
# 选点
qiedianX1 = bb[0][0]
qiedianY1 = bb[0][1]
qiedianZ1 = bb[0][2]
qiedianX2 = bb[1][0]
qiedianY2 = bb[1][1]
qiedianZ2 = bb[1][2]
# 按切点与目标点连线与方向向量的夹角选择切点
# 如果是第一次,切点即入射点
if i == 1:
qiedianX = begin.coordinates[0]
qiedianY = begin.coordinates[1]
qiedianZ = begin.coordinates[2]
else:
# 先求夹角
try:
qiedianEnd1 = math.acos(((end.coordinates[0] - qiedianX1) * indirVector.coordinates[0] + (end.coordinates[1] - qiedianY1) * indirVector.coordinates[1] + (end.coordinates[2] - qiedianZ1) * indirVector.coordinates[2])
/ ((end.coordinates[0] - qiedianX1)**2 + (end.coordinates[1] - qiedianY1)**2 + (end.coordinates[2] - qiedianZ1))**0.5
/ (indirVector.coordinates[0]**2 + indirVector.coordinates[1]**2 + indirVector.coordinates[2]**2)**0.5)
except:
qiedianEnd1 = 1
pass
try:
qiedianEnd2 = math.acos(((end.coordinates[0] - qiedianX2) * indirVector.coordinates[0] + (end.coordinates[1] - qiedianY2) * indirVector.coordinates[1] + (end.coordinates[2] - qiedianZ2) * indirVector.coordinates[2])
/ ((end.coordinates[0] - qiedianX2)**2 + (end.coordinates[1] - qiedianY2)**2 + (end.coordinates[2] - qiedianZ2))**0.5
/ (indirVector.coordinates[0]**2 + indirVector.coordinates[1]**2 + indirVector.coordinates[2]**2)**0.5)
except:
qiedianEnd2 = 1
pass
if qiedianEnd1 > qiedianEnd2:
qiedianX = qiedianX1
qiedianY = qiedianY1
qiedianZ = qiedianZ1
qdX.append(int(qiedianX))
qdY.append(int(qiedianY))
qdZ.append(int(qiedianZ))
else:
qiedianX = qiedianX2
qiedianY = qiedianY2
qiedianZ = qiedianZ2
qdX.append(int(qiedianX))
qdY.append(int(qiedianY))
qdZ.append(int(qiedianZ))
print('qx: ', qiedianX, 'qy: ', qiedianY, 'qz: ', qiedianZ)
#break
outdirVector = Vector([csv_data[array[i]][1] - qiedianX, csv_data[array[i]][2] - qiedianY, csv_data[array[i]][3] - qiedianZ])
# calculate the huchang
if i == 1:
length.append(((end.coordinates[0] - begin.coordinates[0]) ** 2 +
(end.coordinates[1] - begin.coordinates[1]) ** 2 +
(end.coordinates[2] - begin.coordinates[2]) ** 2) ** 0.5)
else:
jiajiao = math.acos((outdirVector.coordinates[0] * indirVector.coordinates[0] +
outdirVector.coordinates[1] * indirVector.coordinates[1] +
outdirVector.coordinates[2] * indirVector.coordinates[2]) /
((outdirVector.coordinates[0] ** 2 + outdirVector.coordinates[1] ** 2 +
outdirVector.coordinates[2] ** 2) ** 0.5) /
(indirVector.coordinates[0] ** 2 + indirVector.coordinates[1] ** 2 +
indirVector.coordinates[2] ** 2) ** 0.5)
# print(jiajiao)
huchang = 200 * jiajiao
print(huchang)
yuanxinju = (40000 + ((end.coordinates[0] - yuanX) ** 2 + (end.coordinates[1] - yuanY) ** 2 + (
end.coordinates[2] - yuanZ) ** 2)) ** 0.5
# print('a: ', end.coordinates[0], 'b: ', end.coordinates[1], 'c: ', end.coordinates[2])
print(yuanxinju)
length.append(huchang + yuanxinju)
count += 1
# print(count)
print(length[count - 1])
start = array[i]
print('qx =', qdX)
print('qy =', qdY)
print('qz =', qdZ)
print('yuanxinX =', yX)
print('yuanxinY =', yY)
print('yuanxinZ =', yZ)
print('fx =', fX)
print('fy =', fY)
print('fz =', fZ)
print('x =', xx)
print('y =', yy)
print('z =', zz)
sum = 0
for i in range(len(length)):
sum += length[i]
print('length =', length)
print('the length is: ', sum)
| [
6738,
10688,
1330,
19862,
17034,
11,
936,
418,
11,
31028,
198,
6738,
2746,
13,
19849,
1330,
9104,
198,
6738,
1366,
62,
36948,
1330,
269,
21370,
62,
36948,
198,
6738,
10558,
88,
1330,
1635,
198,
6738,
10558,
88,
13,
39305,
1330,
2124,
... | 1.871437 | 5,017 |
from distutils.core import setup
setup(name='inbox_personal_parser',
version='1.0',
install_requires=[
'matplotlib', 'numpy','pandas'
],
py_modules=['inbox_personal_parser']
)
| [
6738,
1233,
26791,
13,
7295,
1330,
9058,
198,
40406,
7,
3672,
11639,
259,
3524,
62,
22682,
62,
48610,
3256,
198,
220,
220,
220,
220,
220,
2196,
11639,
16,
13,
15,
3256,
198,
220,
220,
220,
220,
220,
2721,
62,
47911,
41888,
198,
220,... | 2.226804 | 97 |
"""
pgoapi - Pokemon Go API
Copyright (c) 2016 tjado <https://github.com/tejado>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
Author: tjado <https://github.com/tejado>
"""
import time
import struct
import logging
import os
import sys
import platform
from json import JSONEncoder
from binascii import unhexlify
# other stuff
from google.protobuf.internal import encoder
from geopy.geocoders import GoogleV3
from s2sphere import LatLng, Angle, Cap, RegionCoverer, math
log = logging.getLogger(__name__)
EARTH_RADIUS = 6371000 # radius of Earth in meters
# JSON Encoder to handle bytes
def long_to_bytes(val, endianness='big'):
"""
Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
convert ``val``, a :func:`long`, to a byte :func:`str`.
:param long val: The value to pack
:param str endianness: The endianness of the result. ``'big'`` for
big-endian, ``'little'`` for little-endian.
If you want byte- and word-ordering to differ, you're on your own.
Using :ref:`string formatting` lets us use Python's C innards.
"""
# one (1) hex digit per four (4) bits
width = val.bit_length()
# unhexlify wants an even multiple of eight (8) bits, but we don't
# want more digits than we need (hence the ternary-ish 'or')
width += 8 - ((width % 8) or 8)
# format width specifier: four (4) bits per hex digit
fmt = '%%0%dx' % (width // 4)
# prepend zero (0) to the width, to zero-pad the output
s = unhexlify(fmt % val)
if endianness == 'little':
# see http://stackoverflow.com/a/931095/309233
s = s[::-1]
return s
| [
37811,
201,
198,
79,
2188,
15042,
532,
14878,
1514,
7824,
201,
198,
15269,
357,
66,
8,
1584,
256,
73,
4533,
1279,
5450,
1378,
12567,
13,
785,
14,
660,
73,
4533,
29,
201,
198,
5990,
3411,
318,
29376,
7520,
11,
1479,
286,
3877,
11,
... | 2.846723 | 946 |
from ._cube_lattice import cube_lattice
from ._sphere_lattice import sphere_lattice
| [
6738,
47540,
40296,
62,
75,
1078,
501,
1330,
23441,
62,
75,
1078,
501,
198,
6738,
47540,
2777,
1456,
62,
75,
1078,
501,
1330,
16558,
62,
75,
1078,
501,
198
] | 2.896552 | 29 |
# coding=utf-8
from totalvoice.cliente.api.helper import utils
from totalvoice.cliente.api.helper.routes import Routes
from totalvoice.cliente.api.totalvoice import Totalvoice
import json, requests
| [
2,
19617,
28,
40477,
12,
23,
198,
198,
6738,
2472,
38888,
13,
16366,
68,
13,
15042,
13,
2978,
525,
1330,
3384,
4487,
198,
6738,
2472,
38888,
13,
16366,
68,
13,
15042,
13,
2978,
525,
13,
81,
448,
274,
1330,
39602,
274,
198,
6738,
2... | 3.225806 | 62 |
from decimal import Decimal
from unittest import TestCase
from dirtyjson.compat import StringIO
import dirtyjson
| [
6738,
32465,
1330,
4280,
4402,
198,
6738,
555,
715,
395,
1330,
6208,
20448,
198,
6738,
11841,
17752,
13,
5589,
265,
1330,
10903,
9399,
198,
198,
11748,
11841,
17752,
628
] | 3.965517 | 29 |
import logging
import sys
import time
from pprint import pformat
from rich.logging import RichHandler
from rich.console import Console
from swordfish.endpoints import EndPoint
from swordfish.minotour_api import MinotourAPI
from swordfish.utils import validate_mt_connection, write_toml_file, get_original_toml_settings, get_device, get_run_id, \
update_extant_targets, _get_preset_behaviours, create_toml_data_directory, write_out_timestamped_toml
from grpc import RpcError
DEFAULT_FREQ = 60
formatter = logging.Formatter(
"[%(asctime)s] %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S"
)
handler = RichHandler()
handler.setFormatter(formatter)
f_handler = logging.FileHandler("swordfish.log")
f_handler.setFormatter(formatter)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.addHandler(f_handler)
console = Console()
def monitor(args, sf_version):
"""
Monitor the ARTIC task amplicons in minoTour
Parameters
----------
toml_file: pathlib.Path
Path to the toml file
position: minknow_api.manager.FlowCellPosition
The position that the swordfish run is being performed on
mt_key: str
The uuid API token provided on the minoTour profile details page
frequency: int
The frequency that we check for updates in minotour at, in seconds
mt_host: str
Address minotour is hosted at
mt_port: int
The port that minoTour is accesible on the host at
threshold: int
The coverage threshold to unblock an amplicon at
no_minknow: bool
Whether we are using minknow or not. We should be, this is only really for testing
sf_version: str
The version of swordfish package
Returns
-------
None
"""
if args.subparser_name == "breakpoints":
logger.warning("Breakpoints is experimental, use at your own risk!")
toml_file = args.toml
mt_key = args.mt_key
frequency = args.freq
mt_host = args.mt_host
no_minknow = args.no_minknow
mt_port = args.mt_port
artic = True
if args.subparser_name == "balance":
threshold = args.threshold
else:
artic = False
reads_per_bin = args.reads_bin
exp_ploidy = args.exp_ploidy
min_diff = args.min_diff
if not args.toml.is_file():
sys.exit(f"TOML file not found at {args.toml}")
# Check MinoTour key is provided
if args.mt_key is None and not args.simple:
sys.exit("No MinoTour access token provided")
# Check MinoTour polling frequency
# todo, move checks into utils
if args.freq < DEFAULT_FREQ:
sys.exit(f"-f/--freq cannot be lower than {DEFAULT_FREQ}")
if artic:
if args.threshold > 1000:
sys.exit("-t/--threshold cannot be more than 1000")
mt_api = MinotourAPI(host_address=mt_host, port_number=mt_port, api_key=mt_key)
validate_mt_connection(mt_api, version=sf_version)
# Get run id from minknow
run_id = get_run_id(args)
while True:
# Polling loop
# Poll for update
og_settings_dict, _ = get_original_toml_settings(toml_file)
# Check run is present in minoTour
run_json, status = mt_api.get_json(EndPoint.VALIDATE_TASK, run_id=run_id, second_slug="run", third_slug=args.subparser_name)
if status == 404:
logger.warning(f"Run with id {run_id} not found. Trying again in {frequency} seconds.")
time.sleep(frequency)
continue
logger.info(pformat(run_json))
job_json, status = mt_api.get_json(EndPoint.VALIDATE_TASK, run_id=run_id, second_slug="task", third_slug=args.subparser_name)
if status == 404:
# Todo attempt to start a task ourselves
task = "Artic" if artic else "Minimap2+CNV"
logger.warning(f"{task} task not found for run {run_json['name']}.\n"
f"Please start one in the minoTour interface. Checking again in {frequency} seconds.")
time.sleep(frequency)
continue
# Todo at this point post the original toml
if artic:
logger.info("Run information and Artic task found in minoTour. Fetching TOML information...")
data, status = mt_api.get_json(EndPoint.GET_COORDS, run_id=run_id, threshold=threshold)
else:
# check for behaviours provided, and if there are none, use as provided by minoTour
data_dir = create_toml_data_directory(run_json["name"])
logger.info(f"{args.b_toml} provided for behaviour.")
behaviours = _get_preset_behaviours(args.b_toml)
logger.info("Run information and Minimap + CNV task found in minoTour. Fetching task information...")
job_master_data, status = mt_api.get_json(EndPoint.TASK_INFO, swordify=False, flowcell_pk=run_json["flowcell"])
logger.info("Run information and Minimap + CNV task information retrieved. Fetching TOML information...")
data, status = mt_api.get_json(EndPoint.BREAKPOINTS, swordify=False, job_master_pk=job_master_data["id"], reads_per_bin=reads_per_bin, exp_ploidy=exp_ploidy, min_diff=min_diff)
# write the json into the data dir
write_out_timestamped_toml(data, data_dir)
data = update_extant_targets(data, args.toml, behaviours)
if status == 200:
og_settings_dict["conditions"].update(data)
write_toml_file(og_settings_dict, toml_file)
elif status == 204:
logger.warning(f"No barcode found in minoTour for this ARTIC task. Trying again in {frequency} seconds.")
time.sleep(frequency)
| [
11748,
18931,
198,
11748,
25064,
198,
11748,
640,
198,
6738,
279,
4798,
1330,
279,
18982,
198,
198,
6738,
5527,
13,
6404,
2667,
1330,
3998,
25060,
198,
6738,
5527,
13,
41947,
1330,
24371,
198,
198,
6738,
8429,
11084,
13,
437,
13033,
133... | 2.435415 | 2,338 |
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Service for tracking CAS reference from RBE and looking them up by
builder and commit.
RBE is the Remote Build Execution used for building and storing the result
in Content Addressable Storage (CAS).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
from dashboard.api import api_request_handler
from dashboard.common import utils
from dashboard.pinpoint.models import cas
from dashboard.pinpoint.models import change as change_module
# pylint: disable=abstract-method
class CASReference(api_request_handler.ApiRequestHandler):
"""Handler for managing RBE-CAS references.
A post request adds new CAS information.
A get request looks up an CAS digest from the builder, commit, and target.
"""
def get(self, *_):
"""Look up a RBE-CAS digest.
Args:
builder_name: The name of the builder that produced the CAS.
change: The Change the CAS is for, as a JSON string.
target: The CAS target.
"""
# Get parameters.
parameters = (
('builder_name', str),
('change', lambda x: change_module.Change.FromDict(json.loads(x))),
('target', str),
)
try:
# pylint: disable=unbalanced-tuple-unpacking
builder_name, change, target = self._ValidateParameters(parameters)
except (KeyError, TypeError, ValueError) as e:
self.response.set_status(400)
self.response.write(e)
return
# Get.
try:
cas_instance, cas_digest = cas.Get(builder_name, change, target)
except KeyError as e:
self.response.set_status(404)
self.response.write(e)
return
self.response.write(
json.dumps({
'cas_instance': cas_instance,
'cas_digest': cas_digest,
}))
def Post(self, *args, **kwargs):
"""Add new RBE-CAS information.
Args:
builder_name: The name of the builder that produced the CAS.
change: The Change the CAS is for, as a JSON string.
cas_instance: The hostname of the server where the CAS are stored.
cas_map: A JSON dict mapping the target names to the CAS digests.
"""
del args, kwargs # Unused.
# Get parameters.
parameters = (
('builder_name', str),
('change', lambda x: change_module.Change.FromDict(json.loads(x))),
('cas_instance', str),
('cas_map', json.loads),
)
try:
# pylint: disable=unbalanced-tuple-unpacking
builder_name, change, cas_instance, cas_map = (
self._ValidateParameters(parameters))
except (KeyError, TypeError, ValueError) as e:
self.response.set_status(400)
self.response.write(json.dumps({'error': str(e)}))
return
# Put information into the datastore.
cas_references = [(builder_name, change, target, cas_instance,
cas_digest)
for target, cas_digest in cas_map.items()]
cas.Put(cas_references)
# Respond to the API user.
self.response.write(json.dumps(cas_references))
def _ValidateParameters(self, parameters):
"""Ensure the right parameters are present and valid.
Args:
parameters: Iterable of (name, converter) tuples where name is the
parameter name and converter is a function used to validate
and convert that parameter into its internal representation.
Returns:
A list of parsed parameter values.
Raises:
TypeError: The wrong parameters are present.
ValueError: The parameters have invalid values.
"""
parameter_names = tuple(parameter_name for parameter_name, _ in parameters)
for given_parameter in self.request.params:
if given_parameter not in parameter_names:
raise TypeError('Unknown parameter: %s' % given_parameter)
parameter_values = []
for parameter_name, parameter_converter in parameters:
if parameter_name not in self.request.params:
raise TypeError('Missing parameter: %s' % parameter_name)
parameter_value = self.request.get(parameter_name)
if not parameter_value:
raise ValueError('Empty parameter: %s' % parameter_name)
parameter_value = parameter_converter(parameter_value)
parameter_values.append(parameter_value)
return parameter_values
| [
2,
15069,
33448,
383,
18255,
1505,
46665,
13,
1439,
2489,
10395,
13,
198,
2,
5765,
286,
428,
2723,
2438,
318,
21825,
416,
257,
347,
10305,
12,
7635,
5964,
326,
460,
307,
198,
2,
1043,
287,
262,
38559,
24290,
2393,
13,
198,
37811,
16... | 2.779988 | 1,609 |
# wordle.py - Play Wordle in the command line
# Usage: wordle.py [-h] [--hard] [--answer ANSWER] [--show-answer]
#
# options:
# -h, --help show this help message and exit
# --hard Enable hard mode
# -a ANSWER, --answer ANSWER
# Provide the answer
# --show-answer Show the answer (for testing purposes)
# -w ALLOWED_WORDS, --allowed-words ALLOWED_WORDS
# Path to text file containing list of allowed words (one word per line)
# Output key:
# Turn : guess | symbolic result | alphabet result
# - : letter not in word in any spot
# 0 : letter in word, but in the wrong spot (shown as lower case letter)
# 1 : letter in the word, and in the correct spot (shown as upper case letter)
import argparse
import random
import re
if __name__ == "__main__":
main()
| [
2,
1573,
293,
13,
9078,
532,
3811,
9678,
293,
287,
262,
3141,
1627,
198,
198,
2,
29566,
25,
1573,
293,
13,
9078,
25915,
71,
60,
685,
438,
10424,
60,
685,
438,
41484,
3537,
17887,
1137,
60,
685,
438,
12860,
12,
41484,
60,
198,
2,
... | 2.587349 | 332 |
from functools import partial
from typing import List, Callable
import albumentations as A
import numpy as np
import torch
from sklearn.externals._pilutil import bytescale
from torchvision.ops import nms
def normalize_01(inp: np.ndarray):
"""Squash image input to the value range [0, 1] (no clipping)"""
inp_out = (inp - np.min(inp)) / np.ptp(inp)
return inp_out
def normalize(inp: np.ndarray, mean: float, std: float):
"""Normalize based on mean and standard deviation."""
inp_out = (inp - mean) / std
return inp_out
def re_normalize(inp: np.ndarray,
low: int = 0,
high: int = 255
):
"""Normalize the data to a certain range. Default: [0-255]"""
inp_out = bytescale(inp, low=low, high=high)
return inp_out
def clip_bbs(inp: np.ndarray,
bbs: np.ndarray):
"""
If the bounding boxes exceed one dimension, they are clipped to the dim's maximum.
Bounding boxes are expected to be in xyxy format.
Example: x_value=224 but x_shape=200 -> x1=199
"""
output = []
for bb in bbs:
x1, y1, x2, y2 = tuple(bb)
x_shape = inp.shape[1]
y_shape = inp.shape[0]
x1 = clip(x1, x_shape)
y1 = clip(y1, y_shape)
x2 = clip(x2, x_shape)
y2 = clip(y2, y_shape)
output.append([x1, y1, x2, y2])
return np.array(output)
def map_class_to_int(labels: List[str], mapping: dict):
"""Maps a string to an integer."""
labels = np.array(labels)
dummy = np.empty_like(labels)
for key, value in mapping.items():
dummy[labels == key] = value
return dummy.astype(np.uint8)
def apply_nms(target: dict, iou_threshold):
"""Non-maximum Suppression"""
boxes = torch.tensor(target['boxes'])
labels = torch.tensor(target['labels'])
scores = torch.tensor(target['scores'])
if boxes.size()[0] > 0:
mask = nms(boxes, scores, iou_threshold=iou_threshold)
mask = (np.array(mask),)
target['boxes'] = np.asarray(boxes)[mask]
target['labels'] = np.asarray(labels)[mask]
target['scores'] = np.asarray(scores)[mask]
return target
def apply_score_threshold(target: dict, score_threshold):
"""Removes bounding box predictions with low scores."""
boxes = target['boxes']
labels = target['labels']
scores = target['scores']
mask = np.where(scores > score_threshold)
target['boxes'] = boxes[mask]
target['labels'] = labels[mask]
target['scores'] = scores[mask]
return target
class Repr:
"""Evaluatable string representation of an object"""
class FunctionWrapperSingle(Repr):
"""A function wrapper that returns a partial for input only."""
class FunctionWrapperDouble(Repr):
"""A function wrapper that returns a partial for an input-target pair."""
class Compose:
"""Baseclass - composes several transforms together."""
class ComposeDouble(Compose):
"""Composes transforms for input-target pairs."""
class ComposeSingle(Compose):
"""Composes transforms for input only."""
class AlbumentationWrapper(Repr):
"""
A wrapper for the albumentation package.
Bounding boxes are expected to be in xyxy format (pascal_voc).
Bounding boxes cannot be larger than the spatial image's dimensions.
Use Clip() if your bounding boxes are outside of the image, before using this wrapper.
"""
class Clip(Repr):
"""
If the bounding boxes exceed one dimension, they are clipped to the dim's maximum.
Bounding boxes are expected to be in xyxy format.
Example: x_value=224 but x_shape=200 -> x1=199
"""
| [
6738,
1257,
310,
10141,
1330,
13027,
198,
6738,
19720,
1330,
7343,
11,
4889,
540,
198,
198,
11748,
435,
65,
1713,
602,
355,
317,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
28034,
198,
6738,
1341,
35720,
13,
1069,
759,
874,
13557,
... | 2.569718 | 1,420 |
from actuator.register import fm;
from .task import *
import data.db as database
import copy
this = self_handlers()
@fm.route("szse.com","stock_run")
@this.route("stock_run")
@fm.route("szse.com","stocks_all")
@this.route("stocks_all")
@fm.route("szse.com","stock_list")
@this.route("stock_list")
@fm.route("szse.com","stock_data")
@this.route("stock_data")
@fm.route("szse.com","minuts_data")
@this.route("minuts_data")
@fm.route("szse.com","company_data")
@this.route("company_data") | [
6738,
43840,
1352,
13,
30238,
1330,
277,
76,
26,
220,
198,
6738,
764,
35943,
1330,
1635,
198,
11748,
1366,
13,
9945,
355,
6831,
198,
11748,
4866,
198,
198,
5661,
796,
2116,
62,
4993,
8116,
3419,
198,
198,
31,
38353,
13,
38629,
7203,
... | 2.477387 | 199 |
"""Python Implementation of Multi-Layer Perceptron"""
import numpy as np
from numpy.random import seed
# =================
# Utility functions
# =================
import random
random.seed(123)
# calculate a random number where: a <= rand < b
# Make a matrix
# our sigmoid function
# derivative of our sigmoid function, in terms of the output (i.e. y)
# ==================
class MLP:
"""Multi Layer Perceptron
Parameters
------------
ni : int
Number of Input neurons
n_h : int
Number of Hidden neurons
n_o : int
Number of Output neurons
Attributes
-----------
ni : int
Number of Input neurons
n_h : int
Number of Hidden neurons
n_o : int
Number of Output neurons
ai : 1d-array (size: n_i)
Activations for Input layer
ah : 1d-array (size: n_h)
Activations for Hidden layer
ao : 1d-array (size: n_o)
Activations for Output layer
wi : 2d-array (shape n_i x n_h_)
Weight matrix between Input and Hidden Layer.
wo : 2d-array (shape n_h x n_o)
Weight matrix between Hidden and Output Layer.
"""
class Perceptron(object):
"""Perceptron classifier.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
errors_ : list
Number of misclassifications in every epoch.
"""
def fit(self, X, y):
"""Fit training data.
Parameters
----------
X : {array-like}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
"""
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
"""Return class label after unit step"""
return np.where(self.net_input(X) >= 0.0, 1, -1)
class AdalineGD:
"""ADAptive LInear NEuron classifier.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
errors_ : list
Number of misclassifications in every epoch.
"""
def fit(self, X, y):
""" Fit training data.
Parameters
----------
X : {array-like}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
"""
self.w_ = np.zeros(1 + X.shape[1])
self.cost_ = []
for i in range(self.n_iter):
output = self.net_input(X)
errors = (y - output)
self.w_[1:] += self.eta * X.T.dot(errors)
self.w_[0] += self.eta * errors.sum()
cost = (errors**2).sum() / 2.0
self.cost_.append(cost)
return self
def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def activation(self, X):
"""Compute linear activation"""
return self.net_input(X)
def predict(self, X):
"""Return class label after unit step"""
return np.where(self.activation(X) >= 0.0, 1, -1)
class AdalineSGD(object):
"""ADAptive LInear NEuron classifier.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
errors_ : list
Number of misclassifications in every epoch.
shuffle : bool (default: True)
Shuffles training data every epoch if True to prevent cycles.
random_state : int (default: None)
Set random state for shuffling and initializing the weights.
"""
def fit(self, X, y):
""" Fit training data.
Parameters
----------
X : {array-like}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
"""
self._initialize_weights(X.shape[1])
self.cost_ = []
for i in range(self.n_iter):
if self.shuffle:
X, y = self._shuffle(X, y)
cost = []
for xi, target in zip(X, y):
cost.append(self._update_weights(xi, target))
avg_cost = sum(cost)/len(y)
self.cost_.append(avg_cost)
return self
def partial_fit(self, X, y):
"""Fit training data without reinitializing the weights"""
if not self.w_initialized:
self._initialize_weights(X.shape[1])
if y.ravel().shape[0] > 1:
for xi, target in zip(X, y):
self._update_weights(xi, target)
else:
self._update_weights(X, y)
return self
def _shuffle(self, X, y):
"""Shuffle training data"""
r = np.random.permutation(len(y))
return X[r], y[r]
def _initialize_weights(self, m):
"""Initialize weights to zeros"""
self.w_ = np.zeros(1 + m)
self.w_initialized = True
def _update_weights(self, xi, target):
"""Apply Adaline learning rule to update the weights"""
output = self.net_input(xi)
error = (target - output)
self.w_[1:] += self.eta * xi.dot(error)
self.w_[0] += self.eta * error
cost = 0.5 * error**2
return cost
def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def activation(self, X):
"""Compute linear activation"""
return self.net_input(X)
def predict(self, X):
"""Return class label after unit step"""
return np.where(self.activation(X) >= 0.0, 1, -1)
| [
37811,
37906,
46333,
286,
15237,
12,
49925,
2448,
984,
1313,
37811,
198,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
299,
32152,
13,
25120,
1330,
9403,
198,
198,
2,
36658,
198,
2,
34030,
5499,
198,
2,
36658,
198,
198,
11748,
4738,
... | 2.212452 | 3,116 |
#!/usr/bin/env python3
"""
Common constants
"""
# put constants here
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
37811,
198,
17227,
38491,
198,
37811,
198,
198,
2,
1234,
38491,
994,
198
] | 3.043478 | 23 |
#!/usr/bin/python
# Copyright (c) 2020, Sine Nomine Associates
# BSD 2-Clause License
ANSIBLE_METADATA = {
'metadata_version': '1.1.',
'status': ['preview'],
'supported_by': 'community',
}
DOCUMENTATION = r'''
---
module: openafs_store_facts
short_description: Store OpenAFS facts in a json file
description:
- Store facts in the json formatted c(openafs.fact) file on the remote
host. This file is located in the c(/etc/ansible/facts.d) directory or the
path specified by the c(factsdir) parameter. The c(openafs.fact) file is
read by Ansible when facts are gathered on subsequent plays.
- The c(openafs.fact) contains a dictionary of facts which can be accessed
from c(ansible_local.openafs).
options:
state:
description:
- c(update) update the facts
choices:
- update
factsdir:
description: Path to the c(openafs.fact) file
type: path
default: /etc/ansible/facts.d
author:
- Michael Meffie
'''
EXAMPLES = r'''
'''
import json # noqa: E402
import logging # noqa: E402
import logging.handlers # noqa: E402
import os # noqa: E402
import pprint # noqa: E402
from ansible.module_utils.basic import AnsibleModule # noqa: E402
log = logging.getLogger('openafs_store_facts')
if __name__ == '__main__':
main()
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
15069,
357,
66,
8,
12131,
11,
311,
500,
21198,
500,
29306,
198,
2,
347,
10305,
362,
12,
2601,
682,
13789,
198,
198,
15037,
34563,
62,
47123,
2885,
13563,
796,
1391,
198,
220,
220,
220,
... | 2.477558 | 557 |
from collections import defaultdict
import datetime
import json
import logging
import os
import sys
import time
from urllib.parse import urlparse
import boto3
from botocore.exceptions import ClientError
import click
logging.basicConfig(format="%(message)s", level=logging.INFO)
def read_json(json_file):
""" (file) -> dict
Read in json_file, which is in json format, and
output a dict with its contents
"""
with open(json_file) as f:
data = json.load(f)
return data
def chunker(seq, size):
""" https://stackoverflow.com/a/434328 """
return (seq[pos : pos + size] for pos in range(0, len(seq), size))
CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"], "max_content_width": 160}
@click.command(context_settings=CONTEXT_SETTINGS)
@click.version_option()
@click.option(
"--submission_log",
"-l",
type=click.Path(),
default=os.path.join(os.getcwd(), "submission.json"),
help=(
"File path of where to save CSV of job submission details "
"Default is $PWD/submission.json."
),
)
@click.option(
"--status_file",
"-s",
type=click.Path(),
default=os.path.join(os.getcwd(), "status.json"),
help=(
"Status of submitted jobs, in JSON format. "
"Will write to this file if used with --poll, "
"otherwise this file is used to collect outputs (with the --get_* flags). "
"Default is $PWD/status.json."
),
)
@click.option(
"--poll",
is_flag=True,
default=False,
help=(
"Poll AWS Batch for information about submitted jobs. "
"Will write to the value of --status_file/-s "
"Default will not poll."
),
)
@click.option(
"--continuous",
is_flag=True,
default=False,
help=(
"Poll AWS Batch until all jobs have status 'SUCCEEDED' or 'FAILED'. "
"Has no effect unless --poll is also used. "
"Default will not continuously poll."
),
)
@click.option(
"--summary/--no_summary",
default=True,
help=(
"Summarize status info of submitted jobs, by printing number of jobs in each state. "
"Has no effect unless --poll is also used. "
"Default is to produce a summary."
),
)
@click.option(
"--output_list",
"-f",
default=None,
help=(
"File containing locations of THINQ/reTHINQ output, one AWS S3 path per line. "
"Used in specifying which subjects to get data from with one or more of the --get-* flags. "
"Not compatible with --poll (will only poll and ignore this option). "
"Not compatible with --output_status "
"(will only output results from subjects with the specified status). "
"Cannot use with --output_path/-o or --output_bucket/-O"
),
)
@click.option(
"--output_bucket",
"-O",
default=None,
help=(
"AWS S3 path pointing to the output of a group of THINQ/reTHINQ subjects. "
"Used in specifying which subjects to get data from with one or more of the --get-* flags. "
"Not compatible with --poll (will only poll and ignore this option). "
"Not compatible with --output_status "
"(will only output results from subjects with the specified status). "
"Cannot use with --output_list/-f or ----output_path/-o"
),
)
@click.option(
"--output_path",
"-o",
multiple=True,
help=(
"AWS S3 path for locations of THINQ/reTHINQ output. "
"Can use multiple times "
"(such as `-o s3://bucket/output_path -o s3://bucket/output_path2). "
"Used in specifying which subjects to get data from with one or more of the --get-* flags. "
"Not compatible with --poll (will only poll and ignore this option). "
"Not compatible with --output_status "
"(will only output results from subjects with the specified status). "
"Cannot use with --output_list/-f or --output_bucket/-O"
),
)
@click.option(
"--output_status",
type=click.Choice(["SUCCEEDED", "FAILED", "both"]),
help=(
"Use output_paths from all subjects with the specified status. "
"'both' will get outputs from 'SUCCEEDED' and 'FAILED' subjects. "
"Requires a status_file (specifed with --status_file/-s). "
),
)
@click.option(
"--save_location",
default=None,
help=(
"Location of where to save outputs of --get-* commands. "
"Not compatible with --poll (will only poll and ignore this option). "
),
)
@click.option(
"--get_log",
is_flag=True,
default=False,
help=(
"Download log file from the specified subject(s). "
"Not compatible with --get-all (if that is used, it will override this option."
"Not compatible with --poll (will only poll and ignore this option). "
),
)
@click.option(
"--get_report",
is_flag=True,
default=False,
help=(
"Download report pdf from the specified subject(s). "
"Not compatible with --get-all (if that is used, it will override this option."
"Not compatible with --poll (will only poll and ignore this option). "
),
)
@click.option(
"--get_artifact",
is_flag=True,
default=False,
help=(
"Download the artifact.tar.gz from the specified subject(s). "
"Not compatible with --get-all (if that is used, it will override this option."
"Not compatible with --poll (will only poll and ignore this option). "
),
)
@click.option(
"--get_subject_info",
is_flag=True,
default=False,
help=(
"Download the subject_info.json from the specified subject(s). "
"Not compatible with --get-all (if that is used, it will override this option."
"Not compatible with --poll (will only poll and ignore this option). "
),
)
@click.option(
"--get_all",
is_flag=True,
default=False,
help=(
"Download the log file, report and artifact.tar.gz from the specified subject(s). "
"Not compatible with other --get-* flags (those will be ignored)."
"Not compatible with --poll (will only poll and ignore this option). "
),
)
@click.option(
"--ignore_nonexistant",
is_flag=True,
default=False,
help=(
"If a file that should be be downloaded doesn't exist, "
"ignore instead of exiting with an error. "
"Not compatible with --poll (will only poll and ignore this option). "
),
)
| [
6738,
17268,
1330,
4277,
11600,
198,
11748,
4818,
8079,
198,
11748,
33918,
198,
11748,
18931,
198,
11748,
28686,
198,
11748,
25064,
198,
11748,
640,
198,
6738,
2956,
297,
571,
13,
29572,
1330,
19016,
29572,
198,
198,
11748,
275,
2069,
18,... | 2.623064 | 2,454 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'AutomationRunbookReceiverResponse',
'AzureAppPushReceiverResponse',
'AzureFunctionReceiverResponse',
'DynamicMetricCriteriaResponse',
'DynamicThresholdFailingPeriodsResponse',
'EmailReceiverResponse',
'ItsmReceiverResponse',
'LogicAppReceiverResponse',
'MetricAlertActionResponse',
'MetricAlertMultipleResourceMultipleMetricCriteriaResponse',
'MetricAlertSingleResourceMultipleMetricCriteriaResponse',
'MetricCriteriaResponse',
'MetricDimensionResponse',
'SmsReceiverResponse',
'VoiceReceiverResponse',
'WebhookReceiverResponse',
'WebtestLocationAvailabilityCriteriaResponse',
]
@pulumi.output_type
class AutomationRunbookReceiverResponse(dict):
"""
The Azure Automation Runbook notification receiver.
"""
def __init__(__self__, *,
automation_account_id: str,
is_global_runbook: bool,
runbook_name: str,
webhook_resource_id: str,
name: Optional[str] = None,
service_uri: Optional[str] = None):
"""
The Azure Automation Runbook notification receiver.
:param str automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource.
:param bool is_global_runbook: Indicates whether this instance is global runbook.
:param str runbook_name: The name for this runbook.
:param str webhook_resource_id: The resource id for webhook linked to this runbook.
:param str name: Indicates name of the webhook.
:param str service_uri: The URI where webhooks should be sent.
"""
pulumi.set(__self__, "automation_account_id", automation_account_id)
pulumi.set(__self__, "is_global_runbook", is_global_runbook)
pulumi.set(__self__, "runbook_name", runbook_name)
pulumi.set(__self__, "webhook_resource_id", webhook_resource_id)
if name is not None:
pulumi.set(__self__, "name", name)
if service_uri is not None:
pulumi.set(__self__, "service_uri", service_uri)
@property
@pulumi.getter(name="automationAccountId")
def automation_account_id(self) -> str:
"""
The Azure automation account Id which holds this runbook and authenticate to Azure resource.
"""
return pulumi.get(self, "automation_account_id")
@property
@pulumi.getter(name="isGlobalRunbook")
def is_global_runbook(self) -> bool:
"""
Indicates whether this instance is global runbook.
"""
return pulumi.get(self, "is_global_runbook")
@property
@pulumi.getter(name="runbookName")
def runbook_name(self) -> str:
"""
The name for this runbook.
"""
return pulumi.get(self, "runbook_name")
@property
@pulumi.getter(name="webhookResourceId")
def webhook_resource_id(self) -> str:
"""
The resource id for webhook linked to this runbook.
"""
return pulumi.get(self, "webhook_resource_id")
@property
@pulumi.getter
def name(self) -> Optional[str]:
"""
Indicates name of the webhook.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="serviceUri")
def service_uri(self) -> Optional[str]:
"""
The URI where webhooks should be sent.
"""
return pulumi.get(self, "service_uri")
@pulumi.output_type
class AzureAppPushReceiverResponse(dict):
"""
The Azure mobile App push notification receiver.
"""
def __init__(__self__, *,
email_address: str,
name: str):
"""
The Azure mobile App push notification receiver.
:param str email_address: The email address registered for the Azure mobile app.
:param str name: The name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group.
"""
pulumi.set(__self__, "email_address", email_address)
pulumi.set(__self__, "name", name)
@property
@pulumi.getter(name="emailAddress")
def email_address(self) -> str:
"""
The email address registered for the Azure mobile app.
"""
return pulumi.get(self, "email_address")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group.
"""
return pulumi.get(self, "name")
@pulumi.output_type
class AzureFunctionReceiverResponse(dict):
"""
An azure function receiver.
"""
def __init__(__self__, *,
function_app_resource_id: str,
function_name: str,
http_trigger_url: str,
name: str):
"""
An azure function receiver.
:param str function_app_resource_id: The azure resource id of the function app.
:param str function_name: The function name in the function app.
:param str http_trigger_url: The http trigger url where http request sent to.
:param str name: The name of the azure function receiver. Names must be unique across all receivers within an action group.
"""
pulumi.set(__self__, "function_app_resource_id", function_app_resource_id)
pulumi.set(__self__, "function_name", function_name)
pulumi.set(__self__, "http_trigger_url", http_trigger_url)
pulumi.set(__self__, "name", name)
@property
@pulumi.getter(name="functionAppResourceId")
def function_app_resource_id(self) -> str:
"""
The azure resource id of the function app.
"""
return pulumi.get(self, "function_app_resource_id")
@property
@pulumi.getter(name="functionName")
def function_name(self) -> str:
"""
The function name in the function app.
"""
return pulumi.get(self, "function_name")
@property
@pulumi.getter(name="httpTriggerUrl")
def http_trigger_url(self) -> str:
"""
The http trigger url where http request sent to.
"""
return pulumi.get(self, "http_trigger_url")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the azure function receiver. Names must be unique across all receivers within an action group.
"""
return pulumi.get(self, "name")
@pulumi.output_type
class DynamicMetricCriteriaResponse(dict):
"""
Criterion for dynamic threshold.
"""
def __init__(__self__, *,
alert_sensitivity: str,
criterion_type: str,
failing_periods: 'outputs.DynamicThresholdFailingPeriodsResponse',
metric_name: str,
name: str,
operator: str,
time_aggregation: str,
dimensions: Optional[Sequence['outputs.MetricDimensionResponse']] = None,
ignore_data_before: Optional[str] = None,
metric_namespace: Optional[str] = None,
skip_metric_validation: Optional[bool] = None):
"""
Criterion for dynamic threshold.
:param str alert_sensitivity: The extent of deviation required to trigger an alert. This will affect how tight the threshold is to the metric series pattern.
:param str criterion_type: Specifies the type of threshold criteria
:param 'DynamicThresholdFailingPeriodsResponseArgs' failing_periods: The minimum number of violations required within the selected lookback time window required to raise an alert.
:param str metric_name: Name of the metric.
:param str name: Name of the criteria.
:param str operator: The operator used to compare the metric value against the threshold.
:param str time_aggregation: the criteria time aggregation types.
:param Sequence['MetricDimensionResponseArgs'] dimensions: List of dimension conditions.
:param str ignore_data_before: Use this option to set the date from which to start learning the metric historical data and calculate the dynamic thresholds (in ISO8601 format)
:param str metric_namespace: Namespace of the metric.
:param bool skip_metric_validation: Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric validation to be skipped.
"""
pulumi.set(__self__, "alert_sensitivity", alert_sensitivity)
pulumi.set(__self__, "criterion_type", 'DynamicThresholdCriterion')
pulumi.set(__self__, "failing_periods", failing_periods)
pulumi.set(__self__, "metric_name", metric_name)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "operator", operator)
pulumi.set(__self__, "time_aggregation", time_aggregation)
if dimensions is not None:
pulumi.set(__self__, "dimensions", dimensions)
if ignore_data_before is not None:
pulumi.set(__self__, "ignore_data_before", ignore_data_before)
if metric_namespace is not None:
pulumi.set(__self__, "metric_namespace", metric_namespace)
if skip_metric_validation is not None:
pulumi.set(__self__, "skip_metric_validation", skip_metric_validation)
@property
@pulumi.getter(name="alertSensitivity")
def alert_sensitivity(self) -> str:
"""
The extent of deviation required to trigger an alert. This will affect how tight the threshold is to the metric series pattern.
"""
return pulumi.get(self, "alert_sensitivity")
@property
@pulumi.getter(name="criterionType")
def criterion_type(self) -> str:
"""
Specifies the type of threshold criteria
"""
return pulumi.get(self, "criterion_type")
@property
@pulumi.getter(name="failingPeriods")
def failing_periods(self) -> 'outputs.DynamicThresholdFailingPeriodsResponse':
"""
The minimum number of violations required within the selected lookback time window required to raise an alert.
"""
return pulumi.get(self, "failing_periods")
@property
@pulumi.getter(name="metricName")
def metric_name(self) -> str:
"""
Name of the metric.
"""
return pulumi.get(self, "metric_name")
@property
@pulumi.getter
def name(self) -> str:
"""
Name of the criteria.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def operator(self) -> str:
"""
The operator used to compare the metric value against the threshold.
"""
return pulumi.get(self, "operator")
@property
@pulumi.getter(name="timeAggregation")
def time_aggregation(self) -> str:
"""
the criteria time aggregation types.
"""
return pulumi.get(self, "time_aggregation")
@property
@pulumi.getter
def dimensions(self) -> Optional[Sequence['outputs.MetricDimensionResponse']]:
"""
List of dimension conditions.
"""
return pulumi.get(self, "dimensions")
@property
@pulumi.getter(name="ignoreDataBefore")
def ignore_data_before(self) -> Optional[str]:
"""
Use this option to set the date from which to start learning the metric historical data and calculate the dynamic thresholds (in ISO8601 format)
"""
return pulumi.get(self, "ignore_data_before")
@property
@pulumi.getter(name="metricNamespace")
def metric_namespace(self) -> Optional[str]:
"""
Namespace of the metric.
"""
return pulumi.get(self, "metric_namespace")
@property
@pulumi.getter(name="skipMetricValidation")
def skip_metric_validation(self) -> Optional[bool]:
"""
Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric validation to be skipped.
"""
return pulumi.get(self, "skip_metric_validation")
@pulumi.output_type
class DynamicThresholdFailingPeriodsResponse(dict):
"""
The minimum number of violations required within the selected lookback time window required to raise an alert.
"""
def __init__(__self__, *,
min_failing_periods_to_alert: float,
number_of_evaluation_periods: float):
"""
The minimum number of violations required within the selected lookback time window required to raise an alert.
:param float min_failing_periods_to_alert: The number of violations to trigger an alert. Should be smaller or equal to numberOfEvaluationPeriods.
:param float number_of_evaluation_periods: The number of aggregated lookback points. The lookback time window is calculated based on the aggregation granularity (windowSize) and the selected number of aggregated points.
"""
pulumi.set(__self__, "min_failing_periods_to_alert", min_failing_periods_to_alert)
pulumi.set(__self__, "number_of_evaluation_periods", number_of_evaluation_periods)
@property
@pulumi.getter(name="minFailingPeriodsToAlert")
def min_failing_periods_to_alert(self) -> float:
"""
The number of violations to trigger an alert. Should be smaller or equal to numberOfEvaluationPeriods.
"""
return pulumi.get(self, "min_failing_periods_to_alert")
@property
@pulumi.getter(name="numberOfEvaluationPeriods")
def number_of_evaluation_periods(self) -> float:
"""
The number of aggregated lookback points. The lookback time window is calculated based on the aggregation granularity (windowSize) and the selected number of aggregated points.
"""
return pulumi.get(self, "number_of_evaluation_periods")
@pulumi.output_type
class EmailReceiverResponse(dict):
"""
An email receiver.
"""
def __init__(__self__, *,
email_address: str,
name: str,
status: str):
"""
An email receiver.
:param str email_address: The email address of this receiver.
:param str name: The name of the email receiver. Names must be unique across all receivers within an action group.
:param str status: The receiver status of the e-mail.
"""
pulumi.set(__self__, "email_address", email_address)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "status", status)
@property
@pulumi.getter(name="emailAddress")
def email_address(self) -> str:
"""
The email address of this receiver.
"""
return pulumi.get(self, "email_address")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the email receiver. Names must be unique across all receivers within an action group.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def status(self) -> str:
"""
The receiver status of the e-mail.
"""
return pulumi.get(self, "status")
@pulumi.output_type
class ItsmReceiverResponse(dict):
"""
An Itsm receiver.
"""
def __init__(__self__, *,
connection_id: str,
name: str,
region: str,
ticket_configuration: str,
workspace_id: str):
"""
An Itsm receiver.
:param str connection_id: Unique identification of ITSM connection among multiple defined in above workspace.
:param str name: The name of the Itsm receiver. Names must be unique across all receivers within an action group.
:param str region: Region in which workspace resides. Supported values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'
:param str ticket_configuration: JSON blob for the configurations of the ITSM action. CreateMultipleWorkItems option will be part of this blob as well.
:param str workspace_id: OMS LA instance identifier.
"""
pulumi.set(__self__, "connection_id", connection_id)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "region", region)
pulumi.set(__self__, "ticket_configuration", ticket_configuration)
pulumi.set(__self__, "workspace_id", workspace_id)
@property
@pulumi.getter(name="connectionId")
def connection_id(self) -> str:
"""
Unique identification of ITSM connection among multiple defined in above workspace.
"""
return pulumi.get(self, "connection_id")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the Itsm receiver. Names must be unique across all receivers within an action group.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def region(self) -> str:
"""
Region in which workspace resides. Supported values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'
"""
return pulumi.get(self, "region")
@property
@pulumi.getter(name="ticketConfiguration")
def ticket_configuration(self) -> str:
"""
JSON blob for the configurations of the ITSM action. CreateMultipleWorkItems option will be part of this blob as well.
"""
return pulumi.get(self, "ticket_configuration")
@property
@pulumi.getter(name="workspaceId")
def workspace_id(self) -> str:
"""
OMS LA instance identifier.
"""
return pulumi.get(self, "workspace_id")
@pulumi.output_type
class LogicAppReceiverResponse(dict):
"""
A logic app receiver.
"""
def __init__(__self__, *,
callback_url: str,
name: str,
resource_id: str):
"""
A logic app receiver.
:param str callback_url: The callback url where http request sent to.
:param str name: The name of the logic app receiver. Names must be unique across all receivers within an action group.
:param str resource_id: The azure resource id of the logic app receiver.
"""
pulumi.set(__self__, "callback_url", callback_url)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "resource_id", resource_id)
@property
@pulumi.getter(name="callbackUrl")
def callback_url(self) -> str:
"""
The callback url where http request sent to.
"""
return pulumi.get(self, "callback_url")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the logic app receiver. Names must be unique across all receivers within an action group.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="resourceId")
def resource_id(self) -> str:
"""
The azure resource id of the logic app receiver.
"""
return pulumi.get(self, "resource_id")
@pulumi.output_type
class MetricAlertActionResponse(dict):
"""
An alert action.
"""
def __init__(__self__, *,
action_group_id: Optional[str] = None,
web_hook_properties: Optional[Mapping[str, str]] = None):
"""
An alert action.
:param str action_group_id: the id of the action group to use.
:param Mapping[str, str] web_hook_properties: The properties of a webhook object.
"""
if action_group_id is not None:
pulumi.set(__self__, "action_group_id", action_group_id)
if web_hook_properties is not None:
pulumi.set(__self__, "web_hook_properties", web_hook_properties)
@property
@pulumi.getter(name="actionGroupId")
def action_group_id(self) -> Optional[str]:
"""
the id of the action group to use.
"""
return pulumi.get(self, "action_group_id")
@property
@pulumi.getter(name="webHookProperties")
def web_hook_properties(self) -> Optional[Mapping[str, str]]:
"""
The properties of a webhook object.
"""
return pulumi.get(self, "web_hook_properties")
@pulumi.output_type
class MetricAlertMultipleResourceMultipleMetricCriteriaResponse(dict):
"""
Specifies the metric alert criteria for multiple resource that has multiple metric criteria.
"""
def __init__(__self__, *,
odata_type: str,
all_of: Optional[Sequence[Any]] = None):
"""
Specifies the metric alert criteria for multiple resource that has multiple metric criteria.
:param str odata_type: specifies the type of the alert criteria.
:param Sequence[Union['DynamicMetricCriteriaResponseArgs', 'MetricCriteriaResponseArgs']] all_of: the list of multiple metric criteria for this 'all of' operation.
"""
pulumi.set(__self__, "odata_type", 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria')
if all_of is not None:
pulumi.set(__self__, "all_of", all_of)
@property
@pulumi.getter(name="odataType")
def odata_type(self) -> str:
"""
specifies the type of the alert criteria.
"""
return pulumi.get(self, "odata_type")
@property
@pulumi.getter(name="allOf")
def all_of(self) -> Optional[Sequence[Any]]:
"""
the list of multiple metric criteria for this 'all of' operation.
"""
return pulumi.get(self, "all_of")
@pulumi.output_type
class MetricAlertSingleResourceMultipleMetricCriteriaResponse(dict):
"""
Specifies the metric alert criteria for a single resource that has multiple metric criteria.
"""
def __init__(__self__, *,
odata_type: str,
all_of: Optional[Sequence['outputs.MetricCriteriaResponse']] = None):
"""
Specifies the metric alert criteria for a single resource that has multiple metric criteria.
:param str odata_type: specifies the type of the alert criteria.
:param Sequence['MetricCriteriaResponseArgs'] all_of: The list of metric criteria for this 'all of' operation.
"""
pulumi.set(__self__, "odata_type", 'Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria')
if all_of is not None:
pulumi.set(__self__, "all_of", all_of)
@property
@pulumi.getter(name="odataType")
def odata_type(self) -> str:
"""
specifies the type of the alert criteria.
"""
return pulumi.get(self, "odata_type")
@property
@pulumi.getter(name="allOf")
def all_of(self) -> Optional[Sequence['outputs.MetricCriteriaResponse']]:
"""
The list of metric criteria for this 'all of' operation.
"""
return pulumi.get(self, "all_of")
@pulumi.output_type
class MetricCriteriaResponse(dict):
"""
Criterion to filter metrics.
"""
def __init__(__self__, *,
criterion_type: str,
metric_name: str,
name: str,
operator: str,
threshold: float,
time_aggregation: str,
dimensions: Optional[Sequence['outputs.MetricDimensionResponse']] = None,
metric_namespace: Optional[str] = None,
skip_metric_validation: Optional[bool] = None):
"""
Criterion to filter metrics.
:param str criterion_type: Specifies the type of threshold criteria
:param str metric_name: Name of the metric.
:param str name: Name of the criteria.
:param str operator: the criteria operator.
:param float threshold: the criteria threshold value that activates the alert.
:param str time_aggregation: the criteria time aggregation types.
:param Sequence['MetricDimensionResponseArgs'] dimensions: List of dimension conditions.
:param str metric_namespace: Namespace of the metric.
:param bool skip_metric_validation: Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric validation to be skipped.
"""
pulumi.set(__self__, "criterion_type", 'StaticThresholdCriterion')
pulumi.set(__self__, "metric_name", metric_name)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "operator", operator)
pulumi.set(__self__, "threshold", threshold)
pulumi.set(__self__, "time_aggregation", time_aggregation)
if dimensions is not None:
pulumi.set(__self__, "dimensions", dimensions)
if metric_namespace is not None:
pulumi.set(__self__, "metric_namespace", metric_namespace)
if skip_metric_validation is not None:
pulumi.set(__self__, "skip_metric_validation", skip_metric_validation)
@property
@pulumi.getter(name="criterionType")
def criterion_type(self) -> str:
"""
Specifies the type of threshold criteria
"""
return pulumi.get(self, "criterion_type")
@property
@pulumi.getter(name="metricName")
def metric_name(self) -> str:
"""
Name of the metric.
"""
return pulumi.get(self, "metric_name")
@property
@pulumi.getter
def name(self) -> str:
"""
Name of the criteria.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def operator(self) -> str:
"""
the criteria operator.
"""
return pulumi.get(self, "operator")
@property
@pulumi.getter
def threshold(self) -> float:
"""
the criteria threshold value that activates the alert.
"""
return pulumi.get(self, "threshold")
@property
@pulumi.getter(name="timeAggregation")
def time_aggregation(self) -> str:
"""
the criteria time aggregation types.
"""
return pulumi.get(self, "time_aggregation")
@property
@pulumi.getter
def dimensions(self) -> Optional[Sequence['outputs.MetricDimensionResponse']]:
"""
List of dimension conditions.
"""
return pulumi.get(self, "dimensions")
@property
@pulumi.getter(name="metricNamespace")
def metric_namespace(self) -> Optional[str]:
"""
Namespace of the metric.
"""
return pulumi.get(self, "metric_namespace")
@property
@pulumi.getter(name="skipMetricValidation")
def skip_metric_validation(self) -> Optional[bool]:
"""
Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric validation to be skipped.
"""
return pulumi.get(self, "skip_metric_validation")
@pulumi.output_type
class MetricDimensionResponse(dict):
"""
Specifies a metric dimension.
"""
def __init__(__self__, *,
name: str,
operator: str,
values: Sequence[str]):
"""
Specifies a metric dimension.
:param str name: Name of the dimension.
:param str operator: the dimension operator. Only 'Include' and 'Exclude' are supported
:param Sequence[str] values: list of dimension values.
"""
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "operator", operator)
pulumi.set(__self__, "values", values)
@property
@pulumi.getter
def name(self) -> str:
"""
Name of the dimension.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def operator(self) -> str:
"""
the dimension operator. Only 'Include' and 'Exclude' are supported
"""
return pulumi.get(self, "operator")
@property
@pulumi.getter
def values(self) -> Sequence[str]:
"""
list of dimension values.
"""
return pulumi.get(self, "values")
@pulumi.output_type
class SmsReceiverResponse(dict):
"""
An SMS receiver.
"""
def __init__(__self__, *,
country_code: str,
name: str,
phone_number: str,
status: str):
"""
An SMS receiver.
:param str country_code: The country code of the SMS receiver.
:param str name: The name of the SMS receiver. Names must be unique across all receivers within an action group.
:param str phone_number: The phone number of the SMS receiver.
:param str status: The status of the receiver.
"""
pulumi.set(__self__, "country_code", country_code)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "phone_number", phone_number)
pulumi.set(__self__, "status", status)
@property
@pulumi.getter(name="countryCode")
def country_code(self) -> str:
"""
The country code of the SMS receiver.
"""
return pulumi.get(self, "country_code")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the SMS receiver. Names must be unique across all receivers within an action group.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="phoneNumber")
def phone_number(self) -> str:
"""
The phone number of the SMS receiver.
"""
return pulumi.get(self, "phone_number")
@property
@pulumi.getter
def status(self) -> str:
"""
The status of the receiver.
"""
return pulumi.get(self, "status")
@pulumi.output_type
class VoiceReceiverResponse(dict):
"""
A voice receiver.
"""
def __init__(__self__, *,
country_code: str,
name: str,
phone_number: str):
"""
A voice receiver.
:param str country_code: The country code of the voice receiver.
:param str name: The name of the voice receiver. Names must be unique across all receivers within an action group.
:param str phone_number: The phone number of the voice receiver.
"""
pulumi.set(__self__, "country_code", country_code)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "phone_number", phone_number)
@property
@pulumi.getter(name="countryCode")
def country_code(self) -> str:
"""
The country code of the voice receiver.
"""
return pulumi.get(self, "country_code")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the voice receiver. Names must be unique across all receivers within an action group.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="phoneNumber")
def phone_number(self) -> str:
"""
The phone number of the voice receiver.
"""
return pulumi.get(self, "phone_number")
@pulumi.output_type
class WebhookReceiverResponse(dict):
"""
A webhook receiver.
"""
def __init__(__self__, *,
name: str,
service_uri: str):
"""
A webhook receiver.
:param str name: The name of the webhook receiver. Names must be unique across all receivers within an action group.
:param str service_uri: The URI where webhooks should be sent.
"""
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "service_uri", service_uri)
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the webhook receiver. Names must be unique across all receivers within an action group.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="serviceUri")
def service_uri(self) -> str:
"""
The URI where webhooks should be sent.
"""
return pulumi.get(self, "service_uri")
@pulumi.output_type
class WebtestLocationAvailabilityCriteriaResponse(dict):
"""
Specifies the metric alert rule criteria for a web test resource.
"""
def __init__(__self__, *,
component_id: str,
failed_location_count: float,
odata_type: str,
web_test_id: str):
"""
Specifies the metric alert rule criteria for a web test resource.
:param str component_id: The Application Insights resource Id.
:param float failed_location_count: The number of failed locations.
:param str odata_type: specifies the type of the alert criteria.
:param str web_test_id: The Application Insights web test Id.
"""
pulumi.set(__self__, "component_id", component_id)
pulumi.set(__self__, "failed_location_count", failed_location_count)
pulumi.set(__self__, "odata_type", 'Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria')
pulumi.set(__self__, "web_test_id", web_test_id)
@property
@pulumi.getter(name="componentId")
def component_id(self) -> str:
"""
The Application Insights resource Id.
"""
return pulumi.get(self, "component_id")
@property
@pulumi.getter(name="failedLocationCount")
def failed_location_count(self) -> float:
"""
The number of failed locations.
"""
return pulumi.get(self, "failed_location_count")
@property
@pulumi.getter(name="odataType")
def odata_type(self) -> str:
"""
specifies the type of the alert criteria.
"""
return pulumi.get(self, "odata_type")
@property
@pulumi.getter(name="webTestId")
def web_test_id(self) -> str:
"""
The Application Insights web test Id.
"""
return pulumi.get(self, "web_test_id")
| [
2,
19617,
28,
40477,
12,
23,
198,
2,
17202,
39410,
25,
428,
2393,
373,
7560,
416,
262,
21624,
12994,
26144,
35986,
13,
17202,
198,
2,
17202,
2141,
407,
4370,
416,
1021,
4556,
345,
821,
1728,
345,
760,
644,
345,
389,
1804,
0,
17202,
... | 2.443788 | 14,045 |
# Distributed under the MIT License.
# See LICENSE.txt for details.
from spectre.Domain import ElementId1D, ElementId2D, ElementId3D, SegmentId
import unittest
if __name__ == '__main__':
unittest.main(verbosity=2)
| [
2,
4307,
6169,
739,
262,
17168,
13789,
13,
198,
2,
4091,
38559,
24290,
13,
14116,
329,
3307,
13,
198,
198,
6738,
5444,
260,
13,
43961,
1330,
11703,
7390,
16,
35,
11,
11703,
7390,
17,
35,
11,
11703,
7390,
18,
35,
11,
1001,
5154,
73... | 2.846154 | 78 |
from spira.core.parameters.variables import DictParameter
from spira.core.parameters.initializer import ParameterInitializer
from spira.core.parameters.descriptor import Parameter
from spira.yevon.process.all import *
from spira.yevon.process import get_rule_deck
RDD = get_rule_deck()
__all__ = ['MapGdsiiToPhysical', 'MapPhysicalToGdsii']
class MapGdsiiToPhysical(ParameterInitializer):
""" Map the GDSII Layers onto ProcessLayers, and the Datatypes onto PurposeLayers. """
process_layer_map = DictParameter()
purpose_datatype_map = DictParameter()
@property
@property
class MapPhysicalToGdsii(ParameterInitializer):
""" """
process_layer_map = DictParameter()
purpose_datatype_map = DictParameter()
| [
6738,
599,
8704,
13,
7295,
13,
17143,
7307,
13,
25641,
2977,
1330,
360,
713,
36301,
198,
6738,
599,
8704,
13,
7295,
13,
17143,
7307,
13,
36733,
7509,
1330,
25139,
2357,
24243,
7509,
198,
6738,
599,
8704,
13,
7295,
13,
17143,
7307,
13,... | 3.016129 | 248 |
"""Defines exceptions that can occur when interacting with Scan configuration"""
from util.exceptions import ValidationException
class InvalidScanConfiguration(ValidationException):
"""Exception indicating that the provided Scan configuration was invalid"""
def __init__(self, description):
"""Constructor
:param description: The description of the validation error
:type description: string
"""
super(InvalidScanConfiguration, self).__init__('INVALID_SCAN_CONFIGURATION', description) | [
37811,
7469,
1127,
13269,
326,
460,
3051,
618,
24986,
351,
20937,
8398,
37811,
198,
6738,
7736,
13,
1069,
11755,
1330,
3254,
24765,
16922,
198,
198,
4871,
17665,
33351,
38149,
7,
7762,
24765,
16922,
2599,
198,
220,
220,
220,
37227,
16922,... | 3.653061 | 147 |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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.
#
''' Transforms for ONNX graph '''
import numpy as np
import onnx
from onnx import helper, numpy_helper, shape_inference, mapping
from onnx import AttributeProto, TensorProto, GraphProto
from dlpy.model_conversion.onnx_graph import OnnxNode
class OpTypePattern(object):
'''
A tree pattern of operators to match in an ONNX graph
Parameters
----------
op_type : str
Specifies the op type.
name : str, optional
Specifies a name for the node.
outputs : list of :class:`OpTypePattern` objects, optional
Specifies the output nodes.
Returns
-------
:class:`OpTypePattern` object
'''
@property
@property
@property
class Transformer(object):
'''
Transforms an OnnxGraph
Parameters
----------
pattern : :class:`OpTypePattern` object, optional
The pattern to match.
Returns
-------
:class:`Transformer` object
'''
def match(self, node, pattern=None):
'''
Checks if a subgraph rooted at `node` matches pattern.
If there is a match, returns True. If not, returns False.
Parameters
----------
node : :class:`OnnxNode` object
The root node to be checked.
pattern : :class:`OpTypePattern` object, optional
The pattern to match. If None, defaults to self.pattern.
Returns
-------
boolean
'''
if pattern is None:
if self.pattern is None:
raise ValueError('No pattern to match.')
pattern = self.pattern
if node.op_type != pattern.op_type:
return False
elif pattern.outputs and len(node.children) != len(pattern.outputs):
return False
else:
ret = []
for child, child_pattern in zip(node.children, pattern.outputs):
r = self.match(child, child_pattern)
ret.append(r)
return all(ret)
def get_mapping(self, node, pattern=None):
'''
Given that `node` is the root of a matched subgraph, returns a dict
mapping names of the OpTypePatterns to their matched OnnxNodes
Parameters
----------
node : :class:`OnnxNode` object
The root node of a matching subgraph.
pattern : :class:`OpTypePattern` object, optional
The matching pattern. If None, defaults to self.pattern.
Returns
-------
dict
key, value of OpTypePattern name and OnnxNode
'''
if pattern is None:
if self.pattern is None:
raise ValueError('No pattern to match.')
pattern = self.pattern
mapping_dict = {}
return _mapping(node, pattern, mapping_dict)
def is_eligible(self, graph, node):
'''
Checks whether subgraph rooted at node is eligible for the transform.
Each subclass should implement this.
Parameters
----------
graph : :class:`OnnxGraph` object
The graph to be transformed.
node : :class:`OnnxNode` object
The root node of the subgraph to be transformed.
Returns
-------
boolean
'''
return True
def run_transform(self, graph, node):
'''
Define the transform for a single subgraph. Implemented by subclass.
Parameters
----------
graph : :class:`OnnxGraph` object
The graph to be transformed.
node : :class:`OnnxNode` object
The root node of the subgraph to be transformed.
Returns
-------
:class:`OnnxGraph` object
The transformed graph
'''
return graph
def __call__(self, graph):
'''
Call on `graph` to execute the transform on all eligible subgraphs
Parameters
----------
graph : :class:`OnnxGraph` object
The graph to be transformed.
Returns
-------
:class:`OnnxGraph` object
The transformed graph
'''
matches = filter(lambda x: self.match(x), graph.node)
ops = filter(lambda x: self.is_eligible(graph, x), matches)
for op in ops:
self.run_transform(graph, op)
graph.connect_nodes()
return graph
class ConstToInitializer(Transformer):
''' Remove constant ops and add tensor to initializer'''
class InitReshape(Transformer):
''' Remove reshape ops and add reshaped tensor to initializer'''
def _get_shape(self, graph, node):
''' Get reshape op's shape '''
name = node.input[1]
shape = [int(x) for x in graph.tensor_dict[name].flatten()]
return tuple(shape)
class InitUnsqueeze(Transformer):
''' Remove unsqueeze ops and add unsqueezed tensor to initializer'''
def _unsqueeze(self, tensor, axes):
''' unsqueeze tensor by specifying axes to be inserted '''
_shape = list(tensor.shape)
new_dim = len(tensor.shape) + len(axes)
unsqueezed_shape = [1] * new_dim
for i in range(new_dim):
if i not in axes:
unsqueezed_shape[i] = _shape.pop(0)
return tensor.reshape(tuple(unsqueezed_shape))
class FuseMulAddBN(Transformer):
''' Fuse Mul + Add into BN '''
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
21004,
25,
3384,
69,
12,
23,
198,
2,
198,
2,
15069,
35516,
5136,
198,
2,
198,
2,
220,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
13789,
1776,
198,
2,
22... | 2.367659 | 2,554 |
import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
@pytest.fixture
| [
11748,
12972,
9288,
201,
198,
6738,
384,
11925,
1505,
1330,
3992,
26230,
201,
198,
6738,
384,
11925,
1505,
13,
12384,
26230,
13,
11284,
13,
17077,
1330,
5313,
32103,
21321,
201,
198,
6738,
384,
11925,
1505,
13,
12384,
26230,
13,
11284,
... | 3.223404 | 94 |
OntCversion = '2.0.0'
import ontology.builtins
import ontology.libont
| [
45984,
34,
9641,
796,
705,
17,
13,
15,
13,
15,
6,
198,
11748,
39585,
1435,
13,
18780,
1040,
198,
11748,
39585,
1435,
13,
8019,
756,
198
] | 2.692308 | 26 |