content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def findDecision(obj): #obj[0]: Passanger, obj[1]: Coupon, obj[2]: Education, obj[3]: Occupation, obj[4]: Bar, obj[5]: Restaurant20to50, obj[6]: Direction_same, obj[7]: Distance
# {"feature": "Passanger", "instances": 51, "metric_value": 0.9526, "depth": 1}
if obj[0]>0:
# {"feature": "Education", "instances": 47, "metric_value": 0.9734, "depth": 2}
if obj[2]<=2:
# {"feature": "Occupation", "instances": 34, "metric_value": 0.9082, "depth": 3}
if obj[3]<=12:
# {"feature": "Bar", "instances": 30, "metric_value": 0.9481, "depth": 4}
if obj[4]<=2.0:
# {"feature": "Restaurant20to50", "instances": 27, "metric_value": 0.8767, "depth": 5}
if obj[5]<=1.0:
# {"feature": "Distance", "instances": 20, "metric_value": 0.971, "depth": 6}
if obj[7]<=2:
# {"feature": "Direction_same", "instances": 18, "metric_value": 0.9911, "depth": 7}
if obj[6]<=0:
# {"feature": "Coupon", "instances": 17, "metric_value": 0.9975, "depth": 8}
if obj[1]>1:
return 'True'
elif obj[1]<=1:
return 'False'
else: return 'False'
elif obj[6]>0:
return 'True'
else: return 'True'
elif obj[7]>2:
return 'True'
else: return 'True'
elif obj[5]>1.0:
return 'True'
else: return 'True'
elif obj[4]>2.0:
return 'False'
else: return 'False'
elif obj[3]>12:
return 'True'
else: return 'True'
elif obj[2]>2:
# {"feature": "Coupon", "instances": 13, "metric_value": 0.9612, "depth": 3}
if obj[1]>1:
# {"feature": "Occupation", "instances": 9, "metric_value": 0.9911, "depth": 4}
if obj[3]<=11:
# {"feature": "Bar", "instances": 7, "metric_value": 0.9852, "depth": 5}
if obj[4]>1.0:
# {"feature": "Restaurant20to50", "instances": 4, "metric_value": 0.8113, "depth": 6}
if obj[5]>3.0:
# {"feature": "Distance", "instances": 2, "metric_value": 1.0, "depth": 7}
if obj[7]>1:
return 'True'
elif obj[7]<=1:
return 'False'
else: return 'False'
elif obj[5]<=3.0:
return 'True'
else: return 'True'
elif obj[4]<=1.0:
return 'False'
else: return 'False'
elif obj[3]>11:
return 'True'
else: return 'True'
elif obj[1]<=1:
return 'False'
else: return 'False'
else: return 'False'
elif obj[0]<=0:
return 'True'
else: return 'True'
| def find_decision(obj):
if obj[0] > 0:
if obj[2] <= 2:
if obj[3] <= 12:
if obj[4] <= 2.0:
if obj[5] <= 1.0:
if obj[7] <= 2:
if obj[6] <= 0:
if obj[1] > 1:
return 'True'
elif obj[1] <= 1:
return 'False'
else:
return 'False'
elif obj[6] > 0:
return 'True'
else:
return 'True'
elif obj[7] > 2:
return 'True'
else:
return 'True'
elif obj[5] > 1.0:
return 'True'
else:
return 'True'
elif obj[4] > 2.0:
return 'False'
else:
return 'False'
elif obj[3] > 12:
return 'True'
else:
return 'True'
elif obj[2] > 2:
if obj[1] > 1:
if obj[3] <= 11:
if obj[4] > 1.0:
if obj[5] > 3.0:
if obj[7] > 1:
return 'True'
elif obj[7] <= 1:
return 'False'
else:
return 'False'
elif obj[5] <= 3.0:
return 'True'
else:
return 'True'
elif obj[4] <= 1.0:
return 'False'
else:
return 'False'
elif obj[3] > 11:
return 'True'
else:
return 'True'
elif obj[1] <= 1:
return 'False'
else:
return 'False'
else:
return 'False'
elif obj[0] <= 0:
return 'True'
else:
return 'True' |
# Copyright 2020 Chen Bainian
# Licensed under the Apache License, Version 2.0
__version__ = '0.2.2'
| __version__ = '0.2.2' |
# NUCLEOTIDES
BASES = ['A' 'C', 'G', 'T']
dna_letters = "GATC"
dna_extended_letters = "GATCRYWSMKHBVDN"
rna_letters = "GAUC"
rna_extended_letters = "GAUCRYWSMKHBVDN"
dna_ambiguity = {
"A": "A",
"C": "C",
"G": "G",
"T": "T",
"M": "AC",
"R": "AG",
"W": "AT",
"S": "CG",
"Y": "CT",
"K": "GT",
"V": "ACG",
"H": "ACT",
"D": "AGT",
"B": "CGT",
"X": "GATC",
"N": "GATC",
}
rna_ambiguity = {
"A": "A",
"C": "C",
"G": "G",
"U": "U",
"M": "AC",
"R": "AG",
"W": "AU",
"S": "CG",
"Y": "CU",
"K": "GU",
"V": "ACG",
"H": "ACU",
"D": "AGU",
"B": "CGU",
"X": "GAUC",
"N": "GAUC",
}
nucleotide_names = {
'A': 'Adenosine',
'C': 'Cytidine',
'G': 'Guanine',
'T': 'Thymidine',
'U': 'Uracil',
'R': 'G A (puRine)',
'Y': 'T C (pYrimidine)',
'K': 'G T (Ketone)',
'M': 'A C (aMino group)',
'S': 'G C (Strong interaction)',
'W': 'A T (Weak interaction)',
'B': 'G T C (not A) (B comes after A)',
'D': 'G A T (not C) (D comes after C)',
'H': 'A C T (not G) (H comes after G)',
'V': 'G C A (not T, not U) (V comes after U)',
'N': 'A G C T (aNy)',
'-': 'gap',
}
# AMINOACIDS
AMINOACIDS = ["R", "H", "K", "D", "E", "S", "T", "N", "Q", "C",
"G", "P", "A", "V", "I", "L", "M", "F", "Y", "W", ]
THREE_LETTERS = {"ARG":"R", "HIS":"H",
"LYS":"K", "ASP": "D",
"GLU": "E","SER": "S",
"THR": "T", "ASN": "N",
"GLN" :"Q", "CYS" :"C",
"GLY": "G", "PRO" : "P",
"ALA": "A", "VAL": "V",
"ILE": "I", "LEU": "L",
"MET": "M", "PHE": "F",
"TYR" :"Y", "TRP": "W" }
amino_acid_letters = "ACDEFGHIKLMNPQRSTVWY"
amino_acid_alternative_letters = "ARNDCQEGHILKMFPSTWYV"
amino_acid_extended_letters = "ACDEFGHIKLMNOPQRSTUVWYBJZX*-"
amino_acid_ambiguity = {
"A": "A",
"B": "ND",
"C": "C",
"D": "D",
"E": "E",
"F": "F",
"G": "G",
"H": "H",
"I": "I",
"K": "K",
"L": "L",
"M": "M",
"N": "N",
"P": "P",
"Q": "Q",
"R": "R",
"S": "S",
"T": "T",
"V": "V",
"W": "W",
"X": "ACDEFGHIKLMNPQRSTVWY",
"Y": "Y",
"Z": "QE",
"J": "IL",
'U': 'U',
'O': 'O',
}
extended_three_to_one = {
'2as': 'D', '3ah': 'H', '5hp': 'E', 'Acl': 'R', 'Agm': 'R', 'Aib': 'A', 'Ala': 'A', 'Alm': 'A',
'Alo': 'T', 'Aly': 'K', 'Arg': 'R', 'Arm': 'R', 'Asa': 'D', 'Asb': 'D', 'Ask': 'D', 'Asl': 'D',
'Asn': 'N', 'Asp': 'D', 'Asq': 'D', 'Asx': 'B', 'Aya': 'A', 'Bcs': 'C', 'Bhd': 'D', 'Bmt': 'T',
'Bnn': 'A', 'Buc': 'C', 'Bug': 'L', 'C5c': 'C', 'C6c': 'C', 'Ccs': 'C', 'Cea': 'C', 'Cgu': 'E',
'Chg': 'A', 'Cle': 'L', 'Cme': 'C', 'Csd': 'A', 'Cso': 'C', 'Csp': 'C', 'Css': 'C', 'Csw': 'C',
'Csx': 'C', 'Cxm': 'M', 'Cy1': 'C', 'Cy3': 'C', 'Cyg': 'C', 'Cym': 'C', 'Cyq': 'C', 'Cys': 'C',
'Dah': 'F', 'Dal': 'A', 'Dar': 'R', 'Das': 'D', 'Dcy': 'C', 'Dgl': 'E', 'Dgn': 'Q', 'Dha': 'A',
'Dhi': 'H', 'Dil': 'I', 'Div': 'V', 'Dle': 'L', 'Dly': 'K', 'Dnp': 'A', 'Dpn': 'F', 'Dpr': 'P',
'Dsn': 'S', 'Dsp': 'D', 'Dth': 'T', 'Dtr': 'W', 'Dty': 'Y', 'Dva': 'V', 'Efc': 'C', 'Fla': 'A',
'Fme': 'M', 'Ggl': 'E', 'Gl3': 'G', 'Gln': 'Q', 'Glu': 'E', 'Glx': 'Z', 'Gly': 'G', 'Glz': 'G',
'Gma': 'E', 'Gsc': 'G', 'Hac': 'A', 'Har': 'R', 'Hic': 'H', 'Hip': 'H', 'His': 'H', 'Hmr': 'R',
'Hpq': 'F', 'Htr': 'W', 'Hyp': 'P', 'Iil': 'I', 'Ile': 'I', 'Iyr': 'Y', 'Kcx': 'K', 'Leu': 'L',
'Llp': 'K', 'Lly': 'K', 'Ltr': 'W', 'Lym': 'K', 'Lys': 'K', 'Lyz': 'K', 'Maa': 'A', 'Men': 'N',
'Met': 'M', 'Mhs': 'H', 'Mis': 'S', 'Mle': 'L', 'Mpq': 'G', 'Msa': 'G', 'Mse': 'M', 'Mva': 'V',
'Nem': 'H', 'Nep': 'H', 'Nle': 'L', 'Nln': 'L', 'Nlp': 'L', 'Nmc': 'G', 'Oas': 'S', 'Ocs': 'C',
'Omt': 'M', 'Paq': 'Y', 'Pca': 'E', 'Pec': 'C', 'Phe': 'F', 'Phi': 'F', 'Phl': 'F', 'Pr3': 'C',
'Pro': 'P', 'Prr': 'A', 'Ptr': 'Y', 'Pyl': 'O', 'Sac': 'S', 'Sar': 'G', 'Sch': 'C', 'Scs': 'C',
'Scy': 'C', 'Sec': 'U', 'Sel': 'U', 'Sep': 'S', 'Ser': 'S', 'Set': 'S', 'Shc': 'C', 'Shr': 'K',
'Smc': 'C', 'Soc': 'C', 'Sty': 'Y', 'Sva': 'S', 'Ter': '*', 'Thr': 'T', 'Tih': 'A', 'Tpl': 'W',
'Tpo': 'T', 'Tpq': 'A', 'Trg': 'K', 'Tro': 'W', 'Trp': 'W', 'Tyb': 'Y', 'Tyq': 'Y', 'Tyr': 'Y',
'Tys': 'Y', 'Tyy': 'Y', 'Unk': 'X', 'Val': 'V', 'Xaa': 'X', 'Xer': 'X', 'Xle': 'J'}
amino_acid_names = {
'A': 'alanine',
'M': 'methionine',
'C': 'cysteine',
'N': 'asparagine',
'D': 'aspartic acid',
'P': 'proline',
'E': 'glutamic acid',
'Q': 'glutamine',
'F': 'phenylalanine',
'R': 'arginine',
'G': 'glycine',
'S': 'serine',
'H': 'histidine',
'T': 'threonine',
'I': 'isoleucine',
'V': 'valine',
'K': 'lysine',
'W': 'tryptophan',
'L': 'leucine',
'Y': 'tyrosine',
'B': 'aspartic acid or asparagine',
'J': 'leucine or isoleucine',
'X': 'unknown',
'Z': 'glutamic acid or glutamine',
'U': 'selenocysteine',
'O': 'pyrrolysine',
'*': 'translation stop',
'-': 'gap'
}
| bases = ['AC', 'G', 'T']
dna_letters = 'GATC'
dna_extended_letters = 'GATCRYWSMKHBVDN'
rna_letters = 'GAUC'
rna_extended_letters = 'GAUCRYWSMKHBVDN'
dna_ambiguity = {'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', 'M': 'AC', 'R': 'AG', 'W': 'AT', 'S': 'CG', 'Y': 'CT', 'K': 'GT', 'V': 'ACG', 'H': 'ACT', 'D': 'AGT', 'B': 'CGT', 'X': 'GATC', 'N': 'GATC'}
rna_ambiguity = {'A': 'A', 'C': 'C', 'G': 'G', 'U': 'U', 'M': 'AC', 'R': 'AG', 'W': 'AU', 'S': 'CG', 'Y': 'CU', 'K': 'GU', 'V': 'ACG', 'H': 'ACU', 'D': 'AGU', 'B': 'CGU', 'X': 'GAUC', 'N': 'GAUC'}
nucleotide_names = {'A': 'Adenosine', 'C': 'Cytidine', 'G': 'Guanine', 'T': 'Thymidine', 'U': 'Uracil', 'R': 'G A (puRine)', 'Y': 'T C (pYrimidine)', 'K': 'G T (Ketone)', 'M': 'A C (aMino group)', 'S': 'G C (Strong interaction)', 'W': 'A T (Weak interaction)', 'B': 'G T C (not A) (B comes after A)', 'D': 'G A T (not C) (D comes after C)', 'H': 'A C T (not G) (H comes after G)', 'V': 'G C A (not T, not U) (V comes after U)', 'N': 'A G C T (aNy)', '-': 'gap'}
aminoacids = ['R', 'H', 'K', 'D', 'E', 'S', 'T', 'N', 'Q', 'C', 'G', 'P', 'A', 'V', 'I', 'L', 'M', 'F', 'Y', 'W']
three_letters = {'ARG': 'R', 'HIS': 'H', 'LYS': 'K', 'ASP': 'D', 'GLU': 'E', 'SER': 'S', 'THR': 'T', 'ASN': 'N', 'GLN': 'Q', 'CYS': 'C', 'GLY': 'G', 'PRO': 'P', 'ALA': 'A', 'VAL': 'V', 'ILE': 'I', 'LEU': 'L', 'MET': 'M', 'PHE': 'F', 'TYR': 'Y', 'TRP': 'W'}
amino_acid_letters = 'ACDEFGHIKLMNPQRSTVWY'
amino_acid_alternative_letters = 'ARNDCQEGHILKMFPSTWYV'
amino_acid_extended_letters = 'ACDEFGHIKLMNOPQRSTUVWYBJZX*-'
amino_acid_ambiguity = {'A': 'A', 'B': 'ND', 'C': 'C', 'D': 'D', 'E': 'E', 'F': 'F', 'G': 'G', 'H': 'H', 'I': 'I', 'K': 'K', 'L': 'L', 'M': 'M', 'N': 'N', 'P': 'P', 'Q': 'Q', 'R': 'R', 'S': 'S', 'T': 'T', 'V': 'V', 'W': 'W', 'X': 'ACDEFGHIKLMNPQRSTVWY', 'Y': 'Y', 'Z': 'QE', 'J': 'IL', 'U': 'U', 'O': 'O'}
extended_three_to_one = {'2as': 'D', '3ah': 'H', '5hp': 'E', 'Acl': 'R', 'Agm': 'R', 'Aib': 'A', 'Ala': 'A', 'Alm': 'A', 'Alo': 'T', 'Aly': 'K', 'Arg': 'R', 'Arm': 'R', 'Asa': 'D', 'Asb': 'D', 'Ask': 'D', 'Asl': 'D', 'Asn': 'N', 'Asp': 'D', 'Asq': 'D', 'Asx': 'B', 'Aya': 'A', 'Bcs': 'C', 'Bhd': 'D', 'Bmt': 'T', 'Bnn': 'A', 'Buc': 'C', 'Bug': 'L', 'C5c': 'C', 'C6c': 'C', 'Ccs': 'C', 'Cea': 'C', 'Cgu': 'E', 'Chg': 'A', 'Cle': 'L', 'Cme': 'C', 'Csd': 'A', 'Cso': 'C', 'Csp': 'C', 'Css': 'C', 'Csw': 'C', 'Csx': 'C', 'Cxm': 'M', 'Cy1': 'C', 'Cy3': 'C', 'Cyg': 'C', 'Cym': 'C', 'Cyq': 'C', 'Cys': 'C', 'Dah': 'F', 'Dal': 'A', 'Dar': 'R', 'Das': 'D', 'Dcy': 'C', 'Dgl': 'E', 'Dgn': 'Q', 'Dha': 'A', 'Dhi': 'H', 'Dil': 'I', 'Div': 'V', 'Dle': 'L', 'Dly': 'K', 'Dnp': 'A', 'Dpn': 'F', 'Dpr': 'P', 'Dsn': 'S', 'Dsp': 'D', 'Dth': 'T', 'Dtr': 'W', 'Dty': 'Y', 'Dva': 'V', 'Efc': 'C', 'Fla': 'A', 'Fme': 'M', 'Ggl': 'E', 'Gl3': 'G', 'Gln': 'Q', 'Glu': 'E', 'Glx': 'Z', 'Gly': 'G', 'Glz': 'G', 'Gma': 'E', 'Gsc': 'G', 'Hac': 'A', 'Har': 'R', 'Hic': 'H', 'Hip': 'H', 'His': 'H', 'Hmr': 'R', 'Hpq': 'F', 'Htr': 'W', 'Hyp': 'P', 'Iil': 'I', 'Ile': 'I', 'Iyr': 'Y', 'Kcx': 'K', 'Leu': 'L', 'Llp': 'K', 'Lly': 'K', 'Ltr': 'W', 'Lym': 'K', 'Lys': 'K', 'Lyz': 'K', 'Maa': 'A', 'Men': 'N', 'Met': 'M', 'Mhs': 'H', 'Mis': 'S', 'Mle': 'L', 'Mpq': 'G', 'Msa': 'G', 'Mse': 'M', 'Mva': 'V', 'Nem': 'H', 'Nep': 'H', 'Nle': 'L', 'Nln': 'L', 'Nlp': 'L', 'Nmc': 'G', 'Oas': 'S', 'Ocs': 'C', 'Omt': 'M', 'Paq': 'Y', 'Pca': 'E', 'Pec': 'C', 'Phe': 'F', 'Phi': 'F', 'Phl': 'F', 'Pr3': 'C', 'Pro': 'P', 'Prr': 'A', 'Ptr': 'Y', 'Pyl': 'O', 'Sac': 'S', 'Sar': 'G', 'Sch': 'C', 'Scs': 'C', 'Scy': 'C', 'Sec': 'U', 'Sel': 'U', 'Sep': 'S', 'Ser': 'S', 'Set': 'S', 'Shc': 'C', 'Shr': 'K', 'Smc': 'C', 'Soc': 'C', 'Sty': 'Y', 'Sva': 'S', 'Ter': '*', 'Thr': 'T', 'Tih': 'A', 'Tpl': 'W', 'Tpo': 'T', 'Tpq': 'A', 'Trg': 'K', 'Tro': 'W', 'Trp': 'W', 'Tyb': 'Y', 'Tyq': 'Y', 'Tyr': 'Y', 'Tys': 'Y', 'Tyy': 'Y', 'Unk': 'X', 'Val': 'V', 'Xaa': 'X', 'Xer': 'X', 'Xle': 'J'}
amino_acid_names = {'A': 'alanine', 'M': 'methionine', 'C': 'cysteine', 'N': 'asparagine', 'D': 'aspartic acid', 'P': 'proline', 'E': 'glutamic acid', 'Q': 'glutamine', 'F': 'phenylalanine', 'R': 'arginine', 'G': 'glycine', 'S': 'serine', 'H': 'histidine', 'T': 'threonine', 'I': 'isoleucine', 'V': 'valine', 'K': 'lysine', 'W': 'tryptophan', 'L': 'leucine', 'Y': 'tyrosine', 'B': 'aspartic acid or asparagine', 'J': 'leucine or isoleucine', 'X': 'unknown', 'Z': 'glutamic acid or glutamine', 'U': 'selenocysteine', 'O': 'pyrrolysine', '*': 'translation stop', '-': 'gap'} |
""" Assignment 1
Write a short script that will get some information from the user, reformat
the information and print it back to the terminal. """
name = input("What is your name? ")
favorite_color = input("What is your favorite color? ")
print(f"{name}'s favorite color is {favorite_color}.")
| """ Assignment 1
Write a short script that will get some information from the user, reformat
the information and print it back to the terminal. """
name = input('What is your name? ')
favorite_color = input('What is your favorite color? ')
print(f"{name}'s favorite color is {favorite_color}.") |
expected_output = {
"bgp_id": 5918,
"vrf": {
"default": {
"neighbor": {
"192.168.10.253": {
"address_family": {
"vpnv4 unicast": {
"activity_paths": "23637710/17596802",
"activity_prefixes": "11724891/9708585",
"as": 65555,
"attribute_entries": "5101/4700",
"bgp_table_version": 33086714,
"cache_entries": {
"filter-list": {"memory_usage": 0, "total_entries": 0},
"route-map": {"memory_usage": 0, "total_entries": 0},
},
"community_entries": {
"memory_usage": 60120,
"total_entries": 2303,
},
"entries": {
"AS-PATH": {"memory_usage": 4824, "total_entries": 201},
"rrinfo": {"memory_usage": 20080, "total_entries": 502},
},
"input_queue": 0,
"local_as": 5918,
"msg_rcvd": 619,
"msg_sent": 695,
"output_queue": 0,
"path": {"memory_usage": 900480, "total_entries": 7504},
"prefixes": {"memory_usage": 973568, "total_entries": 3803},
"route_identifier": "192.168.10.254",
"routing_table_version": 33086714,
"scan_interval": 60,
"state_pfxrcd": "100",
"tbl_ver": 33086714,
"total_memory": 3305736,
"up_down": "05:07:45",
"version": 4,
}
}
}
}
}
},
}
| expected_output = {'bgp_id': 5918, 'vrf': {'default': {'neighbor': {'192.168.10.253': {'address_family': {'vpnv4 unicast': {'activity_paths': '23637710/17596802', 'activity_prefixes': '11724891/9708585', 'as': 65555, 'attribute_entries': '5101/4700', 'bgp_table_version': 33086714, 'cache_entries': {'filter-list': {'memory_usage': 0, 'total_entries': 0}, 'route-map': {'memory_usage': 0, 'total_entries': 0}}, 'community_entries': {'memory_usage': 60120, 'total_entries': 2303}, 'entries': {'AS-PATH': {'memory_usage': 4824, 'total_entries': 201}, 'rrinfo': {'memory_usage': 20080, 'total_entries': 502}}, 'input_queue': 0, 'local_as': 5918, 'msg_rcvd': 619, 'msg_sent': 695, 'output_queue': 0, 'path': {'memory_usage': 900480, 'total_entries': 7504}, 'prefixes': {'memory_usage': 973568, 'total_entries': 3803}, 'route_identifier': '192.168.10.254', 'routing_table_version': 33086714, 'scan_interval': 60, 'state_pfxrcd': '100', 'tbl_ver': 33086714, 'total_memory': 3305736, 'up_down': '05:07:45', 'version': 4}}}}}}} |
# File: proofpoint_consts.py
# Copyright (c) 2017-2020 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
#
PP_API_BASE_URL = "https://tap-api-v2.proofpoint.com"
PP_API_PATH_CLICKS_BLOCKED = "/v2/siem/clicks/blocked"
PP_API_PATH_CLICKS_PERMITTED = "/v2/siem/clicks/permitted"
PP_API_PATH_MESSAGES_BLOCKED = "/v2/siem/messages/blocked"
PP_API_PATH_MESSAGES_DELIVERED = "/v2/siem/messages/delivered"
PP_API_PATH_ISSUES = "/v2/siem/issues"
PP_API_PATH_ALL = "/v2/siem/all"
PP_API_PATH_CAMPAIGN = "/v2/campaign/{}"
PP_API_PATH_FORENSICS = "/v2/forensics"
PP_API_PATH_DECODE = "/v2/url/decode"
# Constants relating to 'get_error_message_from_exception'
ERR_CODE_MSG = "Error code unavailable"
ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action parameters"
PARSE_ERR_MSG = "Unable to parse the error message. Please check the asset configuration and|or action parameters"
TYPE_ERR_MSG = "Error occurred while connecting to the Proofpoint TAP Server. Please check the asset configuration and|or action parameters."
ERR_MSG_FORMAT_WITH_CODE = "Error Code: {}. Error Message: {}"
ERR_MSG_FORMAT_WITHOUT_CODE = "Error Message: {}"
# Constants relating to 'validate_integer'
INVALID_INTEGER_ERR_MSG = "Please provide a valid integer value in the {}"
INVALID_NON_NEGATIVE_INTEGER_ERR_MSG = "Please provide a valid non-negative integer value in the {}"
INITIAL_INGESTION_WINDOW_KEY = "'initial_ingestion_window' configuration parameter"
# Constant relating to 'handle_py_ver_compat_for_input_str'
PY_2TO3_ERR_MSG = "Error occurred while handling python 2to3 compatibility for the input string"
# Constant relating to fetching the python major version
ERR_FETCHING_PYTHON_VERSION = "Error occurred while fetching the Phantom server's Python major version"
# Constants relating to error messages while processing response from server
EMPTY_RESPONSE_MSG = "Status code: {}. Empty response and no information in the header"
HTML_RESPONSE_PARSE_ERR_MSG = "Cannot parse error details"
JSON_PARSE_ERR_MSG = 'Unable to parse JSON response. Error: {}'
SERVER_ERR_MSG = 'Error from server. Status Code: {} Data from server: {}'
SERVER_ERR_CANT_PROCESS_RESPONSE_MSG = "Can't process response from server. Status Code: {} Data from server: {}"
CONNECTION_REFUSED_ERR_MSG = "Error Details: Connection Refused from the Server"
SERVER_CONNECTION_ERR_MSG = "Error Connecting to server. Details: {}"
| pp_api_base_url = 'https://tap-api-v2.proofpoint.com'
pp_api_path_clicks_blocked = '/v2/siem/clicks/blocked'
pp_api_path_clicks_permitted = '/v2/siem/clicks/permitted'
pp_api_path_messages_blocked = '/v2/siem/messages/blocked'
pp_api_path_messages_delivered = '/v2/siem/messages/delivered'
pp_api_path_issues = '/v2/siem/issues'
pp_api_path_all = '/v2/siem/all'
pp_api_path_campaign = '/v2/campaign/{}'
pp_api_path_forensics = '/v2/forensics'
pp_api_path_decode = '/v2/url/decode'
err_code_msg = 'Error code unavailable'
err_msg_unavailable = 'Error message unavailable. Please check the asset configuration and|or action parameters'
parse_err_msg = 'Unable to parse the error message. Please check the asset configuration and|or action parameters'
type_err_msg = 'Error occurred while connecting to the Proofpoint TAP Server. Please check the asset configuration and|or action parameters.'
err_msg_format_with_code = 'Error Code: {}. Error Message: {}'
err_msg_format_without_code = 'Error Message: {}'
invalid_integer_err_msg = 'Please provide a valid integer value in the {}'
invalid_non_negative_integer_err_msg = 'Please provide a valid non-negative integer value in the {}'
initial_ingestion_window_key = "'initial_ingestion_window' configuration parameter"
py_2_to3_err_msg = 'Error occurred while handling python 2to3 compatibility for the input string'
err_fetching_python_version = "Error occurred while fetching the Phantom server's Python major version"
empty_response_msg = 'Status code: {}. Empty response and no information in the header'
html_response_parse_err_msg = 'Cannot parse error details'
json_parse_err_msg = 'Unable to parse JSON response. Error: {}'
server_err_msg = 'Error from server. Status Code: {} Data from server: {}'
server_err_cant_process_response_msg = "Can't process response from server. Status Code: {} Data from server: {}"
connection_refused_err_msg = 'Error Details: Connection Refused from the Server'
server_connection_err_msg = 'Error Connecting to server. Details: {}' |
def caeser(message, key):
x = list((map(ord,message)))
def foo(a):
if 96 < a < 123:
if a + key < 123:
return chr(a + key)
else:
return chr(a + key - 123 + 97)
else:
return chr(a)
return ''.join(map(foo,x)).upper() | def caeser(message, key):
x = list(map(ord, message))
def foo(a):
if 96 < a < 123:
if a + key < 123:
return chr(a + key)
else:
return chr(a + key - 123 + 97)
else:
return chr(a)
return ''.join(map(foo, x)).upper() |
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
#
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
#
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
if not root:
return True
def helper(node1, node2):
if not node1 and not node2:
return True
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
return helper(node1.left, node2.right) and helper(node1.right, node2.left)
return helper(root.left, root.right)
def isSymmetricIterative(self, root):
if not root:
return True
stack = []
stack.append([root.left, root.right])
while len(stack):
node1, node2 = stack.pop()
if not node1 and not node2:
continue
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
stack.append([node1.left, node2.right])
stack.append([node1.right, node2.left])
return True
| class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_symmetric(self, root):
if not root:
return True
def helper(node1, node2):
if not node1 and (not node2):
return True
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
return helper(node1.left, node2.right) and helper(node1.right, node2.left)
return helper(root.left, root.right)
def is_symmetric_iterative(self, root):
if not root:
return True
stack = []
stack.append([root.left, root.right])
while len(stack):
(node1, node2) = stack.pop()
if not node1 and (not node2):
continue
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
stack.append([node1.left, node2.right])
stack.append([node1.right, node2.left])
return True |
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
>>> sln = Solution()
>>> sln.combinationSum2([1, 1, 2, 3], 3)
[[3], [1, 2]]
>>> sln.combinationSum2([1, 2, 1, 5, 6, 7, 10], 8)
[[1, 7], [2, 6], [1, 1, 6], [1, 2, 5]]
"""
candidates = sorted(candidates, reverse=True)
return self.combSum2(candidates, target)
def combSum2(self, cand, target):
"""
Divide two cases:
- include cand[0]
- not include any equal to cand[0]
Then recursive
"""
if len(cand) == 0 or target < 0:
return []
lst = []
if cand[0] < target:
lst += self.combSum2(cand[1:], target - cand[0])
elif cand[0] == target:
lst += [[]]
[i.append(cand[0]) for i in lst]
rmFirst = [i for i in cand if i != cand[0]]
others = self.combSum2(rmFirst, target)
return lst + others
| class Solution(object):
def combination_sum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
>>> sln = Solution()
>>> sln.combinationSum2([1, 1, 2, 3], 3)
[[3], [1, 2]]
>>> sln.combinationSum2([1, 2, 1, 5, 6, 7, 10], 8)
[[1, 7], [2, 6], [1, 1, 6], [1, 2, 5]]
"""
candidates = sorted(candidates, reverse=True)
return self.combSum2(candidates, target)
def comb_sum2(self, cand, target):
"""
Divide two cases:
- include cand[0]
- not include any equal to cand[0]
Then recursive
"""
if len(cand) == 0 or target < 0:
return []
lst = []
if cand[0] < target:
lst += self.combSum2(cand[1:], target - cand[0])
elif cand[0] == target:
lst += [[]]
[i.append(cand[0]) for i in lst]
rm_first = [i for i in cand if i != cand[0]]
others = self.combSum2(rmFirst, target)
return lst + others |
# Artifact management.
# Forensic artifacts are a way of semantically specifying various parts of
# information to collect from a system. They encode domain specific information
# into an easily sharable specification.
# For more information, see https://github.com/ForensicArtifacts
def index():
return dict()
TEMPLATE = """
# You can add comments anywhere in the artifact file.
name: ArtifactTemplate
doc: |
Here you describe the artifact for humans.
sources:
- type: REKALL_EFILTER
attributes:
# This is an EFilter query. Here "maps" is a plugin, and "proc_regex" is a
# plugin arg.
query: >
select task.name, task.pid, start, end, flags, file_path
from maps(proc_regex: "sshd") where flags.x and flags.w
# If you want more control over output columns you can specify the
# following list. If this is missing Rekall will deduce the columns
# from the query but it will typically include more information.
fields:
- name: name
type: unicode
- name: pid
type: int
- name: start
type: int
style: address
- name: end
type: int
style: address
- name: flags
type: unicode
- name: file_path
type: unicode
supported_os:
# This can be one or more of Windows, Linux, Darwin, WindowsAPI,
# LinuxAPI, DarwinAPI
- Linux
"""
def add():
return dict(artifact_text=TEMPLATE)
| def index():
return dict()
template = '\n# You can add comments anywhere in the artifact file.\nname: ArtifactTemplate\ndoc: |\n Here you describe the artifact for humans.\n\nsources:\n - type: REKALL_EFILTER\n attributes:\n\n # This is an EFilter query. Here "maps" is a plugin, and "proc_regex" is a\n # plugin arg.\n query: >\n select task.name, task.pid, start, end, flags, file_path\n from maps(proc_regex: "sshd") where flags.x and flags.w\n\n # If you want more control over output columns you can specify the\n # following list. If this is missing Rekall will deduce the columns\n # from the query but it will typically include more information.\n fields:\n - name: name\n type: unicode\n - name: pid\n type: int\n - name: start\n type: int\n style: address\n - name: end\n type: int\n style: address\n - name: flags\n type: unicode\n - name: file_path\n type: unicode\n\nsupported_os:\n # This can be one or more of Windows, Linux, Darwin, WindowsAPI,\n # LinuxAPI, DarwinAPI\n - Linux\n'
def add():
return dict(artifact_text=TEMPLATE) |
"""
The substrate.
"""
class Substrate(object):
"""
Represents a substrate: Input coordinates, output coordinates, hidden coordinates and a resolution defaulting to 10.0.
"""
def __init__(self, input_coordinates, output_coordinates, hidden_coordinates=(), res=10.0):
self.input_coordinates = input_coordinates
self.hidden_coordinates = hidden_coordinates
self.output_coordinates = output_coordinates
self.res = res
| """
The substrate.
"""
class Substrate(object):
"""
Represents a substrate: Input coordinates, output coordinates, hidden coordinates and a resolution defaulting to 10.0.
"""
def __init__(self, input_coordinates, output_coordinates, hidden_coordinates=(), res=10.0):
self.input_coordinates = input_coordinates
self.hidden_coordinates = hidden_coordinates
self.output_coordinates = output_coordinates
self.res = res |
def adder(good, bad, ugly, **kwargs):
tmp = good + bad + ugly
for k in kwargs.keys():
tmp += kwargs[k]
return tmp
| def adder(good, bad, ugly, **kwargs):
tmp = good + bad + ugly
for k in kwargs.keys():
tmp += kwargs[k]
return tmp |
#Solution1
def power_of_four(input_number):
if input_number==1 or input_number==4:
return True
if input_number<0 or input_number<4:
return False
while input_number>4:
input_number = input_number/4
remainder = input_number % 4
if remainder>0:
return False
return True
#Tests
def power_of_four_test():
input_num1 = 16
input_num2 = 0
input_num3 = 5
input_num4 = 1
input_num5 = -4
expected_output1 = True
expected_output2 = False
expected_output3 = False
expected_output4 = True
expected_output5 = False
return ( expected_output1 == power_of_four(input_num1), expected_output2 == power_of_four(input_num2), expected_output3 == power_of_four(input_num3), expected_output4 == power_of_four(input_num4), expected_output5 == power_of_four(input_num5) )
print(power_of_four_test())
#Leetcode
class Solution(object):
def isPowerOfFour(self, input_number):
"""
:type n: int
:rtype: bool
"""
if input_number==1 or input_number==4:
return True
if input_number<0 or input_number<4:
return False
while input_number>4:
input_number = float(input_number)/float(4)
remainder = input_number % 4
if remainder>0:
return False
return True
| def power_of_four(input_number):
if input_number == 1 or input_number == 4:
return True
if input_number < 0 or input_number < 4:
return False
while input_number > 4:
input_number = input_number / 4
remainder = input_number % 4
if remainder > 0:
return False
return True
def power_of_four_test():
input_num1 = 16
input_num2 = 0
input_num3 = 5
input_num4 = 1
input_num5 = -4
expected_output1 = True
expected_output2 = False
expected_output3 = False
expected_output4 = True
expected_output5 = False
return (expected_output1 == power_of_four(input_num1), expected_output2 == power_of_four(input_num2), expected_output3 == power_of_four(input_num3), expected_output4 == power_of_four(input_num4), expected_output5 == power_of_four(input_num5))
print(power_of_four_test())
class Solution(object):
def is_power_of_four(self, input_number):
"""
:type n: int
:rtype: bool
"""
if input_number == 1 or input_number == 4:
return True
if input_number < 0 or input_number < 4:
return False
while input_number > 4:
input_number = float(input_number) / float(4)
remainder = input_number % 4
if remainder > 0:
return False
return True |
"""
Junta todas las constantes del sistema y los metodos que involucran la salida al GUI
Esta por separado para evitar importes circulares.
"""
class Globals:
"""Proporciona la variable global que se utilizara para mandar al contexto de la GUI
y la manipulacion de la variable se definen mas abajo"""
resultado_ids = [
[['Copy 0'], ['all']],
[['Copy 1'], ['all']],
[['Copy 2'], ['all']]
]
def add_result(self, id_copy: int, contenido: str, color: str = "all"):
Globals.resultado_ids[id_copy][0].append(f'[Time: {self.clock} | Id: {self.id}]: {contenido}')
Globals.resultado_ids[id_copy][1].append(color)
# print(f'[{self.clock}]: {contenido}')
def add_all(self, contenido, color="all"):
for elemento in range(len(Globals.resultado_ids)):
Globals.resultado_ids[elemento][0].append(
f'[Time: {self.clock} | Id: {self.id}]:[ALL]: {contenido}'
)
Globals.resultado_ids[elemento][1].append(color)
# print(f'[{self.clock}]: {contenido}')
def clear():
Globals.resultado_ids = [
[['Copy 0'], ['all']],
[['Copy 1'], ['all']],
[['Copy 2'], ['all']]
]
return Globals.resultado_ids
def regresa():
return Globals.resultado_ids
| """
Junta todas las constantes del sistema y los metodos que involucran la salida al GUI
Esta por separado para evitar importes circulares.
"""
class Globals:
"""Proporciona la variable global que se utilizara para mandar al contexto de la GUI
y la manipulacion de la variable se definen mas abajo"""
resultado_ids = [[['Copy 0'], ['all']], [['Copy 1'], ['all']], [['Copy 2'], ['all']]]
def add_result(self, id_copy: int, contenido: str, color: str='all'):
Globals.resultado_ids[id_copy][0].append(f'[Time: {self.clock} | Id: {self.id}]: {contenido}')
Globals.resultado_ids[id_copy][1].append(color)
def add_all(self, contenido, color='all'):
for elemento in range(len(Globals.resultado_ids)):
Globals.resultado_ids[elemento][0].append(f'[Time: {self.clock} | Id: {self.id}]:[ALL]: {contenido}')
Globals.resultado_ids[elemento][1].append(color)
def clear():
Globals.resultado_ids = [[['Copy 0'], ['all']], [['Copy 1'], ['all']], [['Copy 2'], ['all']]]
return Globals.resultado_ids
def regresa():
return Globals.resultado_ids |
data = """
(7 * 5 * 6 + (9 * 8 + 3 * 3 + 5) + 7) * (6 + 3 * 9) + 6 + 7 + (7 * 5) * 4
(4 + 9 + (8 * 2) + 5) * 8 + (3 + 2 * 3 * 7 * (7 * 4 * 5) * 9) * 2
3 + 7 + (9 + 6 + 4 * 7 * 3 + 5) * 9
3 + 3 * (5 + (7 * 5 + 4 * 8 + 9 * 2) + 3) * 8 * 7
(8 + 3 + 7 * 7) + (3 + 8) * 4 + 2
2 + 9 * (7 + 3 * 3 * 8) + 9 + 3
2 * ((5 + 7 + 9 + 7 * 3 * 7) * 2 + 4 * 4 + (2 + 2 + 7) + 3) + 6
8 * 3 * (6 + (6 * 8 * 2)) + 9 + 9 * 3
(9 * 7 + 6) + 5 * (7 + 5 + 4) + 2
(9 + 4 * (5 + 5 + 4 * 2) * 7) * 7 * 9 * 5 * 3
7 * 6 * ((5 + 6 + 8 + 4 * 3) + 2 + 2 * (4 + 6 + 2 + 7) + 8) + 4
6 + 5 + 3 * (4 * (8 + 8 + 7 + 2 * 6) + 3 + (7 * 6 * 3) * (9 + 5)) + 4
9 +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 9 * 8 + 2 * 5)) + (3 + (3 + 5 + 6) + 8 + 9 * 4) + 8
9 * ((7 * 6) * 9 * 2) * ((8 * 9 * 3 + 8 * 2) * 6 + 8 + 9 * 5 + 3) + (5 * 4) * (7 + 4) * 7
(4 * 7 + 8 * 9) + (7 + (3 + 9 * 2 * 9 * 4) * 9 * 3 * 4 * 7) * 4 * 6 + 2
6 + 9 * 6 + (2 + 9 * 4) * 8
3 * (6 * 5 + (7 * 6 * 5 * 8) + 7 * 5 * 4) + (3 * (6 * 5 + 7 * 9) + (4 * 9 + 2 * 3) * 7 * 8 * 3) + 9 + 5 + 9
3 + (2 + (6 * 3 * 8 + 3) + 4) * (8 * 9) * 7 + 6
(2 * (7 * 9)) * 6 + 7 * 2 + 9 * 4
((5 + 4 * 2) + (3 * 2 * 6 + 3 + 5 * 5) * 4 + (2 + 5 * 9 * 8 + 3 * 5) * (7 * 2 * 8 * 2) + (5 * 4)) + 7 * 8 + 9
(8 + 4 + (5 * 4 * 6) * 2 * 8) * (6 + (9 * 4 * 5) * 7 * 5 * 4) + 3 + ((2 + 2) + 7 + 5 * 7 * 2 + 4) * 5 + (9 * 3 * (9 + 3 * 4 * 8 * 7 + 9))
6 * 7 * 3 * (7 * 2 + (6 * 4 * 5) * (5 * 3 * 8 + 8 + 3 + 9)) * (7 * 9 + 7 * 5)
4 + 2 + (3 * (9 + 7) * 6)
(8 + (8 * 4)) + (7 + 3 * 5) + 4 + 4 + 7
(7 + 7 * 4 * 4 * 4) * 4 + 3
""".strip()
| data = '\n(7 * 5 * 6 + (9 * 8 + 3 * 3 + 5) + 7) * (6 + 3 * 9) + 6 + 7 + (7 * 5) * 4\n(4 + 9 + (8 * 2) + 5) * 8 + (3 + 2 * 3 * 7 * (7 * 4 * 5) * 9) * 2\n3 + 7 + (9 + 6 + 4 * 7 * 3 + 5) * 9\n3 + 3 * (5 + (7 * 5 + 4 * 8 + 9 * 2) + 3) * 8 * 7\n(8 + 3 + 7 * 7) + (3 + 8) * 4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* 8 + 3) + 4) * (8 * 9) * 7 + 6\n(2 * (7 * 9)) * 6 + 7 * 2 + 9 * 4\n((5 + 4 * 2) + (3 * 2 * 6 + 3 + 5 * 5) * 4 + (2 + 5 * 9 * 8 + 3 * 5) * (7 * 2 * 8 * 2) + (5 * 4)) + 7 * 8 + 9\n(8 + 4 + (5 * 4 * 6) * 2 * 8) * (6 + (9 * 4 * 5) * 7 * 5 * 4) + 3 + ((2 + 2) + 7 + 5 * 7 * 2 + 4) * 5 + (9 * 3 * (9 + 3 * 4 * 8 * 7 + 9))\n6 * 7 * 3 * (7 * 2 + (6 * 4 * 5) * (5 * 3 * 8 + 8 + 3 + 9)) * (7 * 9 + 7 * 5)\n4 + 2 + (3 * (9 + 7) * 6)\n(8 + (8 * 4)) + (7 + 3 * 5) + 4 + 4 + 7\n(7 + 7 * 4 * 4 * 4) * 4 + 3\n'.strip() |
def somar():
a = float(input("digite um valor: "))
b = float(input("digite outro valor: "))
soma = a + b
print(soma)
'''import calculadora
ou
form calculadora import somar #se eu colocar * no somar, nao precisa "calculadora".somar
calculadora.somar()'''
somar()
| def somar():
a = float(input('digite um valor: '))
b = float(input('digite outro valor: '))
soma = a + b
print(soma)
'import calculadora\nou \nform calculadora import somar #se eu colocar * no somar, nao precisa "calculadora".somar\ncalculadora.somar()'
somar() |
def constrainToInterval(val, low, high):
return max(low, min(val, high))
def moveVectorTowardByAtMost(fromVec, toVec, maxDelta):
"""
Return the vector which is obtained by moving from fromVec toward toVec by
a total distance of maxDelta. If the distance from fromVec to toVec is less
than maxDelta, return toVec.
"""
assert maxDelta >= 0
if maxDelta == 0:
return fromVec
vecDelta = toVec - fromVec
if vecDelta.length() < maxDelta:
return toVec
else:
# Since maxDelta > 0 and vecDelta.length() !< maxDelta,
# vecDelta.length() can't be 0, so it's safe to divide by it.
vecDelta *= maxDelta / vecDelta.length()
return fromVec + vecDelta
| def constrain_to_interval(val, low, high):
return max(low, min(val, high))
def move_vector_toward_by_at_most(fromVec, toVec, maxDelta):
"""
Return the vector which is obtained by moving from fromVec toward toVec by
a total distance of maxDelta. If the distance from fromVec to toVec is less
than maxDelta, return toVec.
"""
assert maxDelta >= 0
if maxDelta == 0:
return fromVec
vec_delta = toVec - fromVec
if vecDelta.length() < maxDelta:
return toVec
else:
vec_delta *= maxDelta / vecDelta.length()
return fromVec + vecDelta |
class Trie:
def __init__(self):
self.root = Node()
def search(self, s):
node = self.root
for c in s:
node = node.next[ord(c) - ord('a')]
if not node:
return False
return node.next[26] != None
def insert(self, s):
node = self.root
for c in s:
i = ord(c) - ord('a')
if not node.next[i]:
node.next[i] = Node()
node = node.next[i]
node.next[26] = Node()
def startsWith(self, s):
node = self.root
for c in s:
node = node.next[ord(c) - ord('a')]
if not node:
return False
return True
class Node:
def __init__(self):
self.next = [ None for i in range(27) ]
s = Trie()
s.insert("apple")
s.insert("banana")
print(s.search("app"))
print(s.search("bananananana"))
print(s.search("banana"))
print(s.startsWith("ban"))
| class Trie:
def __init__(self):
self.root = node()
def search(self, s):
node = self.root
for c in s:
node = node.next[ord(c) - ord('a')]
if not node:
return False
return node.next[26] != None
def insert(self, s):
node = self.root
for c in s:
i = ord(c) - ord('a')
if not node.next[i]:
node.next[i] = node()
node = node.next[i]
node.next[26] = node()
def starts_with(self, s):
node = self.root
for c in s:
node = node.next[ord(c) - ord('a')]
if not node:
return False
return True
class Node:
def __init__(self):
self.next = [None for i in range(27)]
s = trie()
s.insert('apple')
s.insert('banana')
print(s.search('app'))
print(s.search('bananananana'))
print(s.search('banana'))
print(s.startsWith('ban')) |
# @TODO complete the point class
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distanceFrom(self, p2):
return ((self.x - p2.x)**2 + (self.y - p2.y)**2)**0.5
# @todo complete the Line class
class Line:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def getLength(self):
return self.p1.distanceFrom(self.p2)
# @TODO complete The triangle class
class Triangle:
def __init__(self, l1, l2, l3):
self.l1 = l1
self.l2 = l2
self.l3 = l3
def getPerimeter(self):
return self.l1.getLength() + self.l2.getLength() \
+ self.l3.getLength()
# @TODO Test classes
def main():
p1 = Point(0, 0)
p2 = Point(0, 4)
p3 = Point(3, 0)
print("distance p1 from p2")
print(p2.distanceFrom(p1))
# test class Line
l1 = Line(p1, p2)
l2 = Line(p2, p3)
l3 = Line(p3, p1)
print('Length of L1:', l1.getLength())
triangle = Triangle(l1, l2, l3)
print('Triangle:', triangle.getPerimeter())
if __name__ == "__main__":
# test class point
main()
| class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_from(self, p2):
return ((self.x - p2.x) ** 2 + (self.y - p2.y) ** 2) ** 0.5
class Line:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def get_length(self):
return self.p1.distanceFrom(self.p2)
class Triangle:
def __init__(self, l1, l2, l3):
self.l1 = l1
self.l2 = l2
self.l3 = l3
def get_perimeter(self):
return self.l1.getLength() + self.l2.getLength() + self.l3.getLength()
def main():
p1 = point(0, 0)
p2 = point(0, 4)
p3 = point(3, 0)
print('distance p1 from p2')
print(p2.distanceFrom(p1))
l1 = line(p1, p2)
l2 = line(p2, p3)
l3 = line(p3, p1)
print('Length of L1:', l1.getLength())
triangle = triangle(l1, l2, l3)
print('Triangle:', triangle.getPerimeter())
if __name__ == '__main__':
main() |
"""
the basic idea is that track every movement of the first player, if the other player can not make a movement, then movement
the first player made is a winning movement.
the optimization is to use memorization to memorize the string state that we have seen.
this is a backtracking problem with memorization optimization
"""
class Solution1:
mem = {}
def canWin(self, s):
if s not in self.mem:
self.mem[s] = any(s[i:i+2]=='++' and not self.canWin(s[:i]+'--'+s[i+2:]) for i in range(len(s)-1))
return self.mem[s]
class Solution2(object):
def canWin(self, s):
for i in range(len(s)-1):
if s[i]=='+' and s[i+1]=='+' and not self.canWin(s[:i]+'--'+s[i+2:]): return True
return False | """
the basic idea is that track every movement of the first player, if the other player can not make a movement, then movement
the first player made is a winning movement.
the optimization is to use memorization to memorize the string state that we have seen.
this is a backtracking problem with memorization optimization
"""
class Solution1:
mem = {}
def can_win(self, s):
if s not in self.mem:
self.mem[s] = any((s[i:i + 2] == '++' and (not self.canWin(s[:i] + '--' + s[i + 2:])) for i in range(len(s) - 1)))
return self.mem[s]
class Solution2(object):
def can_win(self, s):
for i in range(len(s) - 1):
if s[i] == '+' and s[i + 1] == '+' and (not self.canWin(s[:i] + '--' + s[i + 2:])):
return True
return False |
"""
lec9
class
"""
class car: #class name
maker = 'toyota' #attribute
def __init__(self,input_model):
self.model = input_model
def report(self):
#return the attribute of the instance
return self.maker,self.model
#my_car= car('corolla')
#print(my_car.report())
#my_car.maker='ford'
#print(my_car.report()) | """
lec9
class
"""
class Car:
maker = 'toyota'
def __init__(self, input_model):
self.model = input_model
def report(self):
return (self.maker, self.model) |
def qb_date_format(input_date):
"""
Converts date to quickbooks date format
:param input_date:
:return:
"""
return input_date.strftime("%Y-%m-%d")
def qb_datetime_format(input_date):
"""
Converts datetime to quickbooks datetime format
:param input_date:
:return:
"""
return input_date.strftime("%Y-%m-%dT%H:%M:%S")
def qb_datetime_utc_offset_format(input_date, utc_offset):
"""
Converts datetime to quickbooks datetime format including UTC offset
:param input_date:
:param utc_offset: Formatted +/-HH:MM example: -08:00
:return:
"""
return "{0}{1}".format(qb_datetime_format(input_date), utc_offset)
| def qb_date_format(input_date):
"""
Converts date to quickbooks date format
:param input_date:
:return:
"""
return input_date.strftime('%Y-%m-%d')
def qb_datetime_format(input_date):
"""
Converts datetime to quickbooks datetime format
:param input_date:
:return:
"""
return input_date.strftime('%Y-%m-%dT%H:%M:%S')
def qb_datetime_utc_offset_format(input_date, utc_offset):
"""
Converts datetime to quickbooks datetime format including UTC offset
:param input_date:
:param utc_offset: Formatted +/-HH:MM example: -08:00
:return:
"""
return '{0}{1}'.format(qb_datetime_format(input_date), utc_offset) |
class Solution:
def decodeString(self, s: str) -> str:
res, _ = self.dfs(s, 0)
return res
def dfs(self, s, i):
res = ''
while i < len(s) and s[i] != ']':
if s[i].isdigit():
times = 0
while i < len(s) and s[i].isdigit():
times = times*10 + int(s[i])
i += 1
i += 1
decodeString, i = self.dfs(s, i)
i += 1
res += times*decodeString
else:
res += s[i]
i += 1
return res, i
| class Solution:
def decode_string(self, s: str) -> str:
(res, _) = self.dfs(s, 0)
return res
def dfs(self, s, i):
res = ''
while i < len(s) and s[i] != ']':
if s[i].isdigit():
times = 0
while i < len(s) and s[i].isdigit():
times = times * 10 + int(s[i])
i += 1
i += 1
(decode_string, i) = self.dfs(s, i)
i += 1
res += times * decodeString
else:
res += s[i]
i += 1
return (res, i) |
class Node:
def __init__(self, dado=None) -> None:
self.__dado: object = dado
self.__prox = None
@property
def dado(self) -> object:
return self.__dado
@property
def prox(self) -> object:
return self.__prox
@dado.setter
def dado(self, novoDado) -> None:
self.__dado = novoDado
@prox.setter
def prox(self, novoProx) -> None:
self.__prox = novoProx
def __str__(self) -> str:
return str(self.__dado)
| class Node:
def __init__(self, dado=None) -> None:
self.__dado: object = dado
self.__prox = None
@property
def dado(self) -> object:
return self.__dado
@property
def prox(self) -> object:
return self.__prox
@dado.setter
def dado(self, novoDado) -> None:
self.__dado = novoDado
@prox.setter
def prox(self, novoProx) -> None:
self.__prox = novoProx
def __str__(self) -> str:
return str(self.__dado) |
def is_palindrome(x):
s = str(x)
return s == s[::-1]
def solve():
products = []
for i in range(100, 1000):
for j in range(i, 1000):
products.append(i * j)
products = sorted((i * j for i in range(100, 1000) for j in range(i, 1000)), reverse = True)
for p in products:
if is_palindrome(p):
return p
if __name__ == '__main__':
print(solve())
| def is_palindrome(x):
s = str(x)
return s == s[::-1]
def solve():
products = []
for i in range(100, 1000):
for j in range(i, 1000):
products.append(i * j)
products = sorted((i * j for i in range(100, 1000) for j in range(i, 1000)), reverse=True)
for p in products:
if is_palindrome(p):
return p
if __name__ == '__main__':
print(solve()) |
def format_metric(text: str):
return text.replace('.', '_')
def format_period(text: str):
return text.split(',', 1)[0]
def try_or_else(op, default):
try:
return op()
except:
return default
| def format_metric(text: str):
return text.replace('.', '_')
def format_period(text: str):
return text.split(',', 1)[0]
def try_or_else(op, default):
try:
return op()
except:
return default |
class QuestRedeemResponsePacket:
def __init__(self):
self.type = "QUESTREDEEMRESPONSE"
self.ok = False
self.message = ""
def read(self, reader):
self.ok = reader.readBool()
self.message = reader.readStr()
| class Questredeemresponsepacket:
def __init__(self):
self.type = 'QUESTREDEEMRESPONSE'
self.ok = False
self.message = ''
def read(self, reader):
self.ok = reader.readBool()
self.message = reader.readStr() |
list1 = ['abcd', 786, 2.33, 'baidu', 70.2]
tinylist = [123, 'baidu']
print(list1)
print(list1[0])
print(list1[1:3])
print(list1[2:])
print(tinylist * 2)
print(list1 + tinylist)
| list1 = ['abcd', 786, 2.33, 'baidu', 70.2]
tinylist = [123, 'baidu']
print(list1)
print(list1[0])
print(list1[1:3])
print(list1[2:])
print(tinylist * 2)
print(list1 + tinylist) |
'''
https://leetcode.com/problems/bulls-and-cows/
299. Bulls and Cows
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is.
When your friend makes a guess, you provide a hint with the following info:
The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position.
Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret
and guess may contain duplicate digits.
'''
class Solution:
def getHint(self, secret: str, guess: str) -> str:
bulls_count = 0
cows_count = 0
secret_digits_to_match = {}
# we first map each digit in secret to its count in secret
for digit in secret:
if digit in secret_digits_to_match:
secret_digits_to_match[digit] += 1
else:
secret_digits_to_match[digit] = 1
for i in range(0, len(secret)):
if secret[i] == guess[i]:
# matched secret[i] to guess[i] so we need
# reduce the count of digits in secret to match
secret_digits_to_match[secret[i]] -= 1
bulls_count += 1
# now that we matched all the digits in secrets to the matching ones (in terms of value and position)
# in guess, we need to check if there are characters in guess that are in secret but same index as anything
# in bulls_indices
for j in range(0, len(guess)):
if secret[j] != guess[j] and guess[j] in secret_digits_to_match and secret_digits_to_match[guess[j]] > 0:
secret_digits_to_match[guess[j]] -= 1
cows_count += 1
return str(bulls_count) + "A" + str(cows_count) + "B"
# secret = "1807"
# guess = "7810"
# secret = "1123"
# guess = "0111"
secret = "11"
guess = "10"
print(Solution().getHint(secret, guess))
| """
https://leetcode.com/problems/bulls-and-cows/
299. Bulls and Cows
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is.
When your friend makes a guess, you provide a hint with the following info:
The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position.
Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret
and guess may contain duplicate digits.
"""
class Solution:
def get_hint(self, secret: str, guess: str) -> str:
bulls_count = 0
cows_count = 0
secret_digits_to_match = {}
for digit in secret:
if digit in secret_digits_to_match:
secret_digits_to_match[digit] += 1
else:
secret_digits_to_match[digit] = 1
for i in range(0, len(secret)):
if secret[i] == guess[i]:
secret_digits_to_match[secret[i]] -= 1
bulls_count += 1
for j in range(0, len(guess)):
if secret[j] != guess[j] and guess[j] in secret_digits_to_match and (secret_digits_to_match[guess[j]] > 0):
secret_digits_to_match[guess[j]] -= 1
cows_count += 1
return str(bulls_count) + 'A' + str(cows_count) + 'B'
secret = '11'
guess = '10'
print(solution().getHint(secret, guess)) |
current = 0
def f():
global current
if current == 50:
return
print(current)
current += 1
f()
f()
| current = 0
def f():
global current
if current == 50:
return
print(current)
current += 1
f()
f() |
"""
Tema: Complejidad Algoritmica. Notacion asintotica - Recursividad multiple
Curso: Pensamiento Computacional, 2da entrega.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
def fibonacci(n):
'''
Recursividad multiple
O(2^n)
'''
if n == 0 or n == 1: return 1
return fibonacci(n-1) + fibonacci(n-2)
def main():
n = 5
print(fibonacci(n))
if __name__ == '__main__':
main()
| """
Tema: Complejidad Algoritmica. Notacion asintotica - Recursividad multiple
Curso: Pensamiento Computacional, 2da entrega.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
def fibonacci(n):
"""
Recursividad multiple
O(2^n)
"""
if n == 0 or n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
def main():
n = 5
print(fibonacci(n))
if __name__ == '__main__':
main() |
"""
Question Source:Leetcode
Level: Medium
Topic: Stack
Solver: Tayyrov
Date: 14.03.2022
"""
def simplifyPath(path: str) -> str:
path = path.split("/")
ans = []
for p in path:
if p == "." or p == "":
continue
elif p == "..":
if ans:
ans.pop()
else:
ans.append(p)
return "/" + "/".join(ans)
| """
Question Source:Leetcode
Level: Medium
Topic: Stack
Solver: Tayyrov
Date: 14.03.2022
"""
def simplify_path(path: str) -> str:
path = path.split('/')
ans = []
for p in path:
if p == '.' or p == '':
continue
elif p == '..':
if ans:
ans.pop()
else:
ans.append(p)
return '/' + '/'.join(ans) |
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
perms = set()
self.recursive(nums, [], perms)
return perms
def recursive(self, nums, perm, perms):
if len(nums) == 0:
perms.add(tuple(perm))
return None
for i in range(len(nums)):
self.recursive(nums[:i] + nums[i + 1:], perm + [nums[i]], perms)
return None | class Solution(object):
def permute_unique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
perms = set()
self.recursive(nums, [], perms)
return perms
def recursive(self, nums, perm, perms):
if len(nums) == 0:
perms.add(tuple(perm))
return None
for i in range(len(nums)):
self.recursive(nums[:i] + nums[i + 1:], perm + [nums[i]], perms)
return None |
#factorial.py
n=int(input("enter number.."))
#calculating factorial of n
f=1
for i in range(1,n+1):
f=f*i
print ('factorial of {} = {}'.format(n,f))
| n = int(input('enter number..'))
f = 1
for i in range(1, n + 1):
f = f * i
print('factorial of {} = {}'.format(n, f)) |
def hitung():
umur=int(input("masukan umur kamu:"))
jj = umur *369* 24 * 60 * 60
print(f"kamu sudah hidup selama{jj}.detik")
print("Selamat datang di program hitung detik umur")
hitung()
| def hitung():
umur = int(input('masukan umur kamu:'))
jj = umur * 369 * 24 * 60 * 60
print(f'kamu sudah hidup selama{jj}.detik')
print('Selamat datang di program hitung detik umur')
hitung() |
size(300, 300)
_total_w = 0
def flow(w, h):
global _total_w
if _total_w + w*2 >= WIDTH:
translate(-_total_w, h)
_total_w = 0
else:
translate(w, 0)
_total_w += w
x, y = 10, 10
rect(x, y, 50, 50)
flow(60, 60)
rect(x, y, 50, 50, 0.6)
flow(60, 60)
oval(x, y, 50, 50)
flow(60, 60)
star(x+25, y+25, 20, outer=25, inner=15)
flow(60, 60)
arrow(x+50, y+25, 50)
flow(60, 60)
arrow(x+50, y, 50, type=FORTYFIVE)
flow(60, 60)
oval(x, y, 50, 50)
| size(300, 300)
_total_w = 0
def flow(w, h):
global _total_w
if _total_w + w * 2 >= WIDTH:
translate(-_total_w, h)
_total_w = 0
else:
translate(w, 0)
_total_w += w
(x, y) = (10, 10)
rect(x, y, 50, 50)
flow(60, 60)
rect(x, y, 50, 50, 0.6)
flow(60, 60)
oval(x, y, 50, 50)
flow(60, 60)
star(x + 25, y + 25, 20, outer=25, inner=15)
flow(60, 60)
arrow(x + 50, y + 25, 50)
flow(60, 60)
arrow(x + 50, y, 50, type=FORTYFIVE)
flow(60, 60)
oval(x, y, 50, 50) |
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
if not S: return
l = S.split('-')
s, depth = [[TreeNode(l[0]), 0]], 1
for item in l[1:]:
if not item:
depth += 1
continue
node = TreeNode(item)
while s[-1][1] != depth - 1:
s.pop()
if not s[-1][0].left:
s[-1][0].left = node
else:
s[-1][0].right = node
s.append([node, depth])
depth = 1
return s[0][0] | class Solution:
def recover_from_preorder(self, S: str) -> TreeNode:
if not S:
return
l = S.split('-')
(s, depth) = ([[tree_node(l[0]), 0]], 1)
for item in l[1:]:
if not item:
depth += 1
continue
node = tree_node(item)
while s[-1][1] != depth - 1:
s.pop()
if not s[-1][0].left:
s[-1][0].left = node
else:
s[-1][0].right = node
s.append([node, depth])
depth = 1
return s[0][0] |
{
'targets': [
{
'include_dirs': ['/usr/include', '/usr/local/include'],
'libraries': ['-L/usr/lib', '-L/usr/local/lib'],
'target_name': 'gzbz2',
'sources': ['compress.cc'],
'link_settings': {
'libraries': [
'-lbz2'
]
},
'conditions': [
['OS=="linux"',
{
'cflags': [ '-Wall', '-O2', '-fexceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'defines': [
'_FILE_OFFSET_BITS=64',
'_LARGEFILE_SOURCE',
'WITH_GZIP',
'WITH_BZIP'
],
'configurations': {
'Debug': {
'cflags': ['-O0', '-g3'],
'cflags!': ['-O2']
}
}
}
],
['OS=="mac"',
{
'include_dirs': ['/opt/local/include'],
'libraries': ['-L/opt/local/lib'],
'cflags': [ '-Wall', '-O2', '-fexceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'GCC_ENABLE_CPP_RTTI': 'YES'
},
'defines': [
'_FILE_OFFSET_BITS=64',
'_LARGEFILE_SOURCE',
'WITH_GZIP',
'WITH_BZIP'
],
'configurations': {
'Debug': {
'cflags': ['-O0', '-g3'],
'cflags!': ['-O2']
}
}
}
]
]
},
{
'target_name': 'copy_binary',
'type': 'none',
'dependencies': [ 'gzbz2' ],
'copies': [
{
'files': [ '<(PRODUCT_DIR)/gzbz2.node' ],
'destination': '<(module_root_dir)'
}
],
}
]
}
| {'targets': [{'include_dirs': ['/usr/include', '/usr/local/include'], 'libraries': ['-L/usr/lib', '-L/usr/local/lib'], 'target_name': 'gzbz2', 'sources': ['compress.cc'], 'link_settings': {'libraries': ['-lbz2']}, 'conditions': [['OS=="linux"', {'cflags': ['-Wall', '-O2', '-fexceptions'], 'cflags_cc!': ['-fno-exceptions'], 'defines': ['_FILE_OFFSET_BITS=64', '_LARGEFILE_SOURCE', 'WITH_GZIP', 'WITH_BZIP'], 'configurations': {'Debug': {'cflags': ['-O0', '-g3'], 'cflags!': ['-O2']}}}], ['OS=="mac"', {'include_dirs': ['/opt/local/include'], 'libraries': ['-L/opt/local/lib'], 'cflags': ['-Wall', '-O2', '-fexceptions'], 'cflags_cc!': ['-fno-exceptions'], 'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'GCC_ENABLE_CPP_RTTI': 'YES'}, 'defines': ['_FILE_OFFSET_BITS=64', '_LARGEFILE_SOURCE', 'WITH_GZIP', 'WITH_BZIP'], 'configurations': {'Debug': {'cflags': ['-O0', '-g3'], 'cflags!': ['-O2']}}}]]}, {'target_name': 'copy_binary', 'type': 'none', 'dependencies': ['gzbz2'], 'copies': [{'files': ['<(PRODUCT_DIR)/gzbz2.node'], 'destination': '<(module_root_dir)'}]}]} |
# Uses python3
def get_fibonacci_huge_naive(n, m):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current % m
def get_fibonacci_period(m):
P = [0]
prv, cur = 0, 1
while (prv, cur) != (1, 0):
P.append(cur)
prv, cur = cur, (prv + cur) % m
return P
def get_fibonacci_huge(n, m):
P = get_fibonacci_period(m)
return P[n % len(P)]
if __name__ == '__main__':
n, m = map(int, input().split())
print(get_fibonacci_huge(n, m))
| def get_fibonacci_huge_naive(n, m):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
(previous, current) = (current, previous + current)
return current % m
def get_fibonacci_period(m):
p = [0]
(prv, cur) = (0, 1)
while (prv, cur) != (1, 0):
P.append(cur)
(prv, cur) = (cur, (prv + cur) % m)
return P
def get_fibonacci_huge(n, m):
p = get_fibonacci_period(m)
return P[n % len(P)]
if __name__ == '__main__':
(n, m) = map(int, input().split())
print(get_fibonacci_huge(n, m)) |
class DriverNotSet(EnvironmentError):
""" webdriver not initialized """
class NoSession(RuntimeError):
""" forgot to call new_session()"""
class ElementNotFound(ValueError):
""" no element to process """
class TabDiscarded(RuntimeError):
""" tab no longer exists"""
class FireFoxCrashed(EnvironmentError):
""" ouch, sounds like the browser itself crashed"""
class InvalidElement(ValueError):
""" not a valid element object """
class InvalidTabID(ValueError):
""" not a valid tab id """
class TorNotFound(EnvironmentError):
""" tor not found in xdg path or wrong binary path specified"""
class PreferencesFileNotFound(FileNotFoundError):
""" """
class PreferencesParseError(RuntimeError):
""" failed to parse prefs.js """
| class Drivernotset(EnvironmentError):
""" webdriver not initialized """
class Nosession(RuntimeError):
""" forgot to call new_session()"""
class Elementnotfound(ValueError):
""" no element to process """
class Tabdiscarded(RuntimeError):
""" tab no longer exists"""
class Firefoxcrashed(EnvironmentError):
""" ouch, sounds like the browser itself crashed"""
class Invalidelement(ValueError):
""" not a valid element object """
class Invalidtabid(ValueError):
""" not a valid tab id """
class Tornotfound(EnvironmentError):
""" tor not found in xdg path or wrong binary path specified"""
class Preferencesfilenotfound(FileNotFoundError):
""" """
class Preferencesparseerror(RuntimeError):
""" failed to parse prefs.js """ |
#-----------------------------------------------------------------------------
# Runtime: 44ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def intToRoman(self, num: int) -> str:
result = []
if num >= 1000:
result.append('M' * (num // 1000))
num %= 1000
if num >= 900:
result.append('CM')
num -= 900
if num >= 500:
result.append('D')
num -= 500
if num >= 400:
result.append('CD')
num -= 400
if num >= 100:
result.append('C' * (num // 100))
num %= 100
if num >= 90:
result.append('XC')
num -= 90
if num >= 50:
result.append('L')
num -= 50
if num >= 40:
result.append('XL')
num -= 40
if num >= 10:
result.append('X' * (num // 10))
num %= 10
if num >= 9:
result.append('IX')
num -= 9
if num >= 5:
result.append('V')
num -= 5
if num >= 4:
result.append('IV')
num -= 4
if num >= 1:
result.append('I' * num)
return ''.join(result)
| class Solution:
def int_to_roman(self, num: int) -> str:
result = []
if num >= 1000:
result.append('M' * (num // 1000))
num %= 1000
if num >= 900:
result.append('CM')
num -= 900
if num >= 500:
result.append('D')
num -= 500
if num >= 400:
result.append('CD')
num -= 400
if num >= 100:
result.append('C' * (num // 100))
num %= 100
if num >= 90:
result.append('XC')
num -= 90
if num >= 50:
result.append('L')
num -= 50
if num >= 40:
result.append('XL')
num -= 40
if num >= 10:
result.append('X' * (num // 10))
num %= 10
if num >= 9:
result.append('IX')
num -= 9
if num >= 5:
result.append('V')
num -= 5
if num >= 4:
result.append('IV')
num -= 4
if num >= 1:
result.append('I' * num)
return ''.join(result) |
"""
RCIR Module
Consits of representations for Candidate, Voter and Election
"""
print("This is the RCIR module")
| """
RCIR Module
Consits of representations for Candidate, Voter and Election
"""
print('This is the RCIR module') |
# is_hot = False
# is_clod = False
#
#
# if is_hot:
# print("it is hot day ")
# print("drink plentry of water ")
# elif is_clod:
# print("it is clod day ")
# print("Wear warm Clothes")
# else:
# print("it is a Lovely day ")
# print("Enjoy Your Day ")
# has_high_income = False
# has_good_credit = True
#
# if has_high_income or has_good_credit:
# print("Eligible for Loan")
# has_good_credit = True
# has_criminal_record = False
#
# if has_good_credit and not has_criminal_record:
# print("Eligible for Loan")
#
# temperature =35
# if temperature > 40:
# print("its a hot day ")
# else:
# print("its a not hot day ")
name = "shivam singh"
if len(name) < 3:
print("name must at least 3 charters")
elif len(name) > 50:
print("name must be a maximum 50 charters")
else:
print("name Looks Good ")
| name = 'shivam singh'
if len(name) < 3:
print('name must at least 3 charters')
elif len(name) > 50:
print('name must be a maximum 50 charters')
else:
print('name Looks Good ') |
class AnyObject(object):
"""
def get_address(self):
order_list = self.parentsDict.order_list
address = list()
for i in range(len(order_list))[::-1]:
if isinstance(self.parentsDict[order_list[i]], Collection):
continue
elif isinstance(self.parentsDict[order_list[i]], Part):
address.append(order_list[i])
break
address.append(order_list[i])
string_address = ""
for i in address[::-1]:
string_address += "{}\\".format(i)
return string_address[0:-1]
"""
@property
def name(self):
return self.cat_constructor.Name
@name.setter
def name(self, value):
self.cat_constructor.Name = value
| class Anyobject(object):
"""
def get_address(self):
order_list = self.parentsDict.order_list
address = list()
for i in range(len(order_list))[::-1]:
if isinstance(self.parentsDict[order_list[i]], Collection):
continue
elif isinstance(self.parentsDict[order_list[i]], Part):
address.append(order_list[i])
break
address.append(order_list[i])
string_address = ""
for i in address[::-1]:
string_address += "{}\\".format(i)
return string_address[0:-1]
"""
@property
def name(self):
return self.cat_constructor.Name
@name.setter
def name(self, value):
self.cat_constructor.Name = value |
"""
-----------
Discussion:
-----------
Paper:
------
NLP-based ontology learning from legal texts. A case study paper
Ontology
--------
Formally-defined vocabulary for a particular domain of interest used to capture
knowledge about that (restricted) domain of interest.
The ontology describes the concepts in the domain and the relationship hold
between those concepts which is necessary for knowledge representation(Field of AI, dedicated
to representing information about the world in form that a computer system use
to solve tasks. From wikipedia: https://en.wikipedia.org/wiki/Knowledge_representation_and_reasoning)
and knowledge exchange.
From : Juliao Braga, Joaquim L R Dias, and Francisco Regateiro. A MACHINE LEARNING ONTOLOGY, 2021
Legal ontology
--------------
Legal ontology aim to provide a structured representation of legal concepts
and their interconnections... They are used to model the domain of knowledge
for which a system is developed and the underlying concepts structure.
Ontology learning
-----------------
Ontology learning is the automatic or semi-automatic creation of ontologies, including
extracting the corresponding domain's terms and the relationships between the concepts
that these terms represent from a corpus of natural language text, and encoding them
with an ontology language for easy retrieval.
""" | """
-----------
Discussion:
-----------
Paper:
------
NLP-based ontology learning from legal texts. A case study paper
Ontology
--------
Formally-defined vocabulary for a particular domain of interest used to capture
knowledge about that (restricted) domain of interest.
The ontology describes the concepts in the domain and the relationship hold
between those concepts which is necessary for knowledge representation(Field of AI, dedicated
to representing information about the world in form that a computer system use
to solve tasks. From wikipedia: https://en.wikipedia.org/wiki/Knowledge_representation_and_reasoning)
and knowledge exchange.
From : Juliao Braga, Joaquim L R Dias, and Francisco Regateiro. A MACHINE LEARNING ONTOLOGY, 2021
Legal ontology
--------------
Legal ontology aim to provide a structured representation of legal concepts
and their interconnections... They are used to model the domain of knowledge
for which a system is developed and the underlying concepts structure.
Ontology learning
-----------------
Ontology learning is the automatic or semi-automatic creation of ontologies, including
extracting the corresponding domain's terms and the relationships between the concepts
that these terms represent from a corpus of natural language text, and encoding them
with an ontology language for easy retrieval.
""" |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright(c) 2020 Ericsson AB
name = "paf"
| name = 'paf' |
# -*- coding: utf-8 -*-
class Solution:
def bitwiseComplement(self, N: int) -> int:
return int(''.join('1' if c == '0' else '0' for c in format(N, 'b')), 2)
if __name__ == '__main__':
solution = Solution()
assert 2 == solution.bitwiseComplement(5)
assert 0 == solution.bitwiseComplement(7)
assert 5 == solution.bitwiseComplement(10)
| class Solution:
def bitwise_complement(self, N: int) -> int:
return int(''.join(('1' if c == '0' else '0' for c in format(N, 'b'))), 2)
if __name__ == '__main__':
solution = solution()
assert 2 == solution.bitwiseComplement(5)
assert 0 == solution.bitwiseComplement(7)
assert 5 == solution.bitwiseComplement(10) |
description = 'Placeholders for devices not yet present.'
group = 'lowlevel'
devices = dict(
xs = device('nicos.devices.generic.VirtualMotor',
description = 'Sample x position',
abslimits = (0, 730),
unit = 'mm',
curvalue = 2500
),
xd2 = device('nicos.devices.generic.VirtualMotor',
description = 'Diaphragm2 x position',
abslimits = (0, 3000),
unit = 'mm',
curvalue = 2000
),
xl = device('nicos.devices.generic.VirtualMotor',
description = 'Deflector x position',
abslimits = (-500, 2000),
unit = 'mm',
curvalue = 1500
),
mu_offset = device('nicos.devices.generic.VirtualMotor',
description = 'Offset on the angle of incidence (deflector mode)',
abslimits = (-1000, 1000),
unit = 'mm',
curvalue = 0
),
kappa = device('nicos.devices.generic.VirtualMotor',
description = 'Inclination of the beam after the Selene guide',
abslimits = (-.5, 0),
unit = '',
curvalue = -0.2
),
xd3 = device('nicos.devices.generic.VirtualMotor',
description = 'Diaphragm3 x position',
abslimits = (2000, 5000),
unit = 'mm',
curvalue = 3000
),
soz_ideal = device('nicos.devices.generic.VirtualMotor',
description = 'Ideal sample stage z (deflector mode)',
abslimits = (2000, 5000),
unit = 'mm',
curvalue = 3000
),
)
| description = 'Placeholders for devices not yet present.'
group = 'lowlevel'
devices = dict(xs=device('nicos.devices.generic.VirtualMotor', description='Sample x position', abslimits=(0, 730), unit='mm', curvalue=2500), xd2=device('nicos.devices.generic.VirtualMotor', description='Diaphragm2 x position', abslimits=(0, 3000), unit='mm', curvalue=2000), xl=device('nicos.devices.generic.VirtualMotor', description='Deflector x position', abslimits=(-500, 2000), unit='mm', curvalue=1500), mu_offset=device('nicos.devices.generic.VirtualMotor', description='Offset on the angle of incidence (deflector mode)', abslimits=(-1000, 1000), unit='mm', curvalue=0), kappa=device('nicos.devices.generic.VirtualMotor', description='Inclination of the beam after the Selene guide', abslimits=(-0.5, 0), unit='', curvalue=-0.2), xd3=device('nicos.devices.generic.VirtualMotor', description='Diaphragm3 x position', abslimits=(2000, 5000), unit='mm', curvalue=3000), soz_ideal=device('nicos.devices.generic.VirtualMotor', description='Ideal sample stage z (deflector mode)', abslimits=(2000, 5000), unit='mm', curvalue=3000)) |
# -*- coding: utf-8 -*-
# 2021/10/29
# create by: snower
class Parser(object):
def __init__(self, content):
self.content = content
def parse(self):
raise NotImplementedError | class Parser(object):
def __init__(self, content):
self.content = content
def parse(self):
raise NotImplementedError |
class GreatClass:
def __init__(self, x):
self.x = x
def do_stuff(self):
pass
class LilGreatClass:
def __init__(self, things, stuff):
self.things = things
self.stuff = stuff
| class Greatclass:
def __init__(self, x):
self.x = x
def do_stuff(self):
pass
class Lilgreatclass:
def __init__(self, things, stuff):
self.things = things
self.stuff = stuff |
"""
Loan Calculator
You take a loan from a friend and need to calculate how much you will
owe him after 3 months.
You are going to pay him back 10% of the remaining loan amount each month.
Create a program that takes the loan amount as input, calculates and
outputs the remaining amount after 3 months.
Sample Input:
20000
Sample Output:
10628
Here is the monthly payment schedule:
Month 1
Payment: 10% of 20000 = 2000
Remaining amount: 18000
Month 2
Payment: 10% of 18000 = 1800
Remaining amount: 16200
Month 3:
Payment: 10% of 16200 = 1620
Remaining amount: 14580
"""
amount = float(input("Enter amount: "))
i = 0
while i < 3:
amount -= (amount * 0.10)
i += 1
print(amount)
| """
Loan Calculator
You take a loan from a friend and need to calculate how much you will
owe him after 3 months.
You are going to pay him back 10% of the remaining loan amount each month.
Create a program that takes the loan amount as input, calculates and
outputs the remaining amount after 3 months.
Sample Input:
20000
Sample Output:
10628
Here is the monthly payment schedule:
Month 1
Payment: 10% of 20000 = 2000
Remaining amount: 18000
Month 2
Payment: 10% of 18000 = 1800
Remaining amount: 16200
Month 3:
Payment: 10% of 16200 = 1620
Remaining amount: 14580
"""
amount = float(input('Enter amount: '))
i = 0
while i < 3:
amount -= amount * 0.1
i += 1
print(amount) |
# Grid elements
STRUCT = 0
P1 = 1
P2 = 2
WALL = 3
HOLE = 4
# Timeout (in ms)
ROUND_TIMEOUT = 6000.0
GLOBAL_TIMEOUT = 60000.0
# Gauges state and speed
# Gauge state is in gauge units
GAUGE_STATE_INIT = 65535
# Gauges speed are in gauge units per milliseconds
ROUND_GAUGE_SPEED_INIT = GAUGE_STATE_INIT/ROUND_TIMEOUT
GLOBAL_GAUGE_SPEED = GAUGE_STATE_INIT/GLOBAL_TIMEOUT
# Grid dimensions
M = 15
N = 6
# Client events
TAP_LEFT = 2001
TAP_RIGHT = 2002
TWO_FINGER_SWIPE = 2003
HIDE_STRUCT = 2004
| struct = 0
p1 = 1
p2 = 2
wall = 3
hole = 4
round_timeout = 6000.0
global_timeout = 60000.0
gauge_state_init = 65535
round_gauge_speed_init = GAUGE_STATE_INIT / ROUND_TIMEOUT
global_gauge_speed = GAUGE_STATE_INIT / GLOBAL_TIMEOUT
m = 15
n = 6
tap_left = 2001
tap_right = 2002
two_finger_swipe = 2003
hide_struct = 2004 |
# A simple User model for logging in/registering
# Created by: Mark Mott
class User:
# A single underline denotes a private method/variable.
# Default is a Guest user
def __init__(self, username='Guest', password='guest', permission=0):
print(username)
self.username = username
self.password = password
self.permission = permission
def setusername(self,username):
self.username = username
def getusername(self):
return self.username
def setpassword(self,password):
self.password = password
def getpassword(self):
return self.password
def setpermission(self,permission):
self.permission = permission
def getpermission(self):
return self.permission
def toString(self):
out = {
"username": self.getusername(),
"password": self.getpassword(),
"permission": self.getpermission()
}
return out | class User:
def __init__(self, username='Guest', password='guest', permission=0):
print(username)
self.username = username
self.password = password
self.permission = permission
def setusername(self, username):
self.username = username
def getusername(self):
return self.username
def setpassword(self, password):
self.password = password
def getpassword(self):
return self.password
def setpermission(self, permission):
self.permission = permission
def getpermission(self):
return self.permission
def to_string(self):
out = {'username': self.getusername(), 'password': self.getpassword(), 'permission': self.getpermission()}
return out |
"""
topic_config
"""
def read_config():
"""
read JSON config file for topic options
"""
topic_data = {
"platform_type": ["buoy", "station", "glider"],
"ra": [
"aoos",
"caricoos",
"cencoos",
"gcoos",
"glos",
"maracoos",
"nanoos",
"neracoos",
"pacioos",
"secoora",
"sccoos",
],
"platform": ["a", "b", "c", "d", "e", "f", "g", "h"],
"sensor": ["met", "ctd", "adcp", "wave", "bio"],
"variable": [
"air_temperature",
"air_pressure_at_sea_level",
"sea_water_practical_salinity",
"sea_water_temperature",
"sea_surface_wave_significant_height",
"mass_concentration_of_chlorophyll_in_sea_water",
"eastward_sea_water_velocity",
"northward_sea_water_velocity",
"mass_concentration_of_chlorophyll_in_sea_water",
],
}
# json.dumps(topic_data, sort_keys=True, indent=4)
return topic_data
| """
topic_config
"""
def read_config():
"""
read JSON config file for topic options
"""
topic_data = {'platform_type': ['buoy', 'station', 'glider'], 'ra': ['aoos', 'caricoos', 'cencoos', 'gcoos', 'glos', 'maracoos', 'nanoos', 'neracoos', 'pacioos', 'secoora', 'sccoos'], 'platform': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 'sensor': ['met', 'ctd', 'adcp', 'wave', 'bio'], 'variable': ['air_temperature', 'air_pressure_at_sea_level', 'sea_water_practical_salinity', 'sea_water_temperature', 'sea_surface_wave_significant_height', 'mass_concentration_of_chlorophyll_in_sea_water', 'eastward_sea_water_velocity', 'northward_sea_water_velocity', 'mass_concentration_of_chlorophyll_in_sea_water']}
return topic_data |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# created: 2015-04-15
class WebConst(object):
ROUTER_PARAM_PATH = '_http_router_url'
ROUTER_PARAM_OPT = '_http_router_opt'
ROUTER_PARAM_VIEW_FUNC_PARAMS = '_http_router_view_params'
ROUTER_VIEW_FUNC_KWS_REQUEST = 'request'
ROUTER_VIEW_FUNC_KWS_METHOD = 'method'
REQUEST_METHOD_GET = 'GET'
REQUEST_METHOD_POST = 'POST'
REQUEST_METHOD_PUT = 'PUT'
REQUEST_METHOD_DELETE = 'DELETE'
REQUEST_HEADER_CONTENT_TYPE = 'Content-Type'
WEB_API_PARAM_QUERY = 'query'
WEB_API_PARAM_STATUS = 'status'
WEB_API_PARAM_ORDER = 'order'
PARAM_PAGE_SIZE = b'pageSize'
PARAM_CURRENT_PAGE = b'current'
DEFAULT_PAGE = 1
DEFAULT_PAGE_SIZE = 50
MIME_TYPE_JSON = 'application/json'
def set_options_methods(request, post=False, get=False, put=False, delete=False, allowed_methods=None):
methods = ['OPTIONS']
if post:
methods.append('POST')
if get:
methods.append('GET')
if put:
methods.append('PUT')
if delete:
methods.append('DEL')
if allowed_methods:
methods = list(set(methods).union(set(allowed_methods)))
request.setHeader('Access-Control-Allow-Origin', '*')
request.setHeader('Access-Control-Allow-Methods', ', '.join(methods))
request.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Content-Length")
| class Webconst(object):
router_param_path = '_http_router_url'
router_param_opt = '_http_router_opt'
router_param_view_func_params = '_http_router_view_params'
router_view_func_kws_request = 'request'
router_view_func_kws_method = 'method'
request_method_get = 'GET'
request_method_post = 'POST'
request_method_put = 'PUT'
request_method_delete = 'DELETE'
request_header_content_type = 'Content-Type'
web_api_param_query = 'query'
web_api_param_status = 'status'
web_api_param_order = 'order'
param_page_size = b'pageSize'
param_current_page = b'current'
default_page = 1
default_page_size = 50
mime_type_json = 'application/json'
def set_options_methods(request, post=False, get=False, put=False, delete=False, allowed_methods=None):
methods = ['OPTIONS']
if post:
methods.append('POST')
if get:
methods.append('GET')
if put:
methods.append('PUT')
if delete:
methods.append('DEL')
if allowed_methods:
methods = list(set(methods).union(set(allowed_methods)))
request.setHeader('Access-Control-Allow-Origin', '*')
request.setHeader('Access-Control-Allow-Methods', ', '.join(methods))
request.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization, Content-Length') |
def cgi_content(type="text/html"):
return('Content type: ' + type + '\n\n')
def webpage_start():
return('<html>')
def web_title(title):
return('<head><title>' + title + '</title></head>')
def body_start(h1_message):
return('<h1 align="center">' + h1_message + '</h1><p align="center">')
def body_end():
return("</p><br><p align='center'><a href='../index.html'>HOME</a></p></body>")
def webpage_end():
return('</html>') | def cgi_content(type='text/html'):
return 'Content type: ' + type + '\n\n'
def webpage_start():
return '<html>'
def web_title(title):
return '<head><title>' + title + '</title></head>'
def body_start(h1_message):
return '<h1 align="center">' + h1_message + '</h1><p align="center">'
def body_end():
return "</p><br><p align='center'><a href='../index.html'>HOME</a></p></body>"
def webpage_end():
return '</html>' |
class GTDException(Exception):
'''single parameter indicates exit code for the interpreter, because
this exception typically results in a return of control to the terminal'''
def __init__(self, errno):
self.errno = errno
| class Gtdexception(Exception):
"""single parameter indicates exit code for the interpreter, because
this exception typically results in a return of control to the terminal"""
def __init__(self, errno):
self.errno = errno |
class ExcalValueError(ValueError):
pass
class ExcalFileExistsError(FileExistsError):
pass
| class Excalvalueerror(ValueError):
pass
class Excalfileexistserror(FileExistsError):
pass |
my_family = { 'wife': { 'name': 'Julia', 'age': 32 },
'daughter': { 'name': 'Aurelia', 'age': 2 },
'son': { 'name': 'Lazarus', 'age': .5 },
'father': { 'name': 'Rodney', 'age': 62 } }
# use a dictionary comprehension to produce output that looks like this:
# Krista is my sister and is 42 years old
for relationship, information in my_family.items():
family_member = relationship
name = (information['name'])
age = (information['age'])
# comprehend_my_family = ['{0}'.format(name)]
# comprehend_my_family.append('is my')
# comprehend_my_family.append('{0}'.format(family_member))
# comprehend_my_family.append('and is')
# comprehend_my_family.append('{0}'.format(age))
# comprehend_my_family.append('years old.')
# print(' '.join(partial for partial in comprehend_my_family))
# also works as:
print(name + ' is my ' + family_member + ' and is ' + str(age) + ' years old.')
| my_family = {'wife': {'name': 'Julia', 'age': 32}, 'daughter': {'name': 'Aurelia', 'age': 2}, 'son': {'name': 'Lazarus', 'age': 0.5}, 'father': {'name': 'Rodney', 'age': 62}}
for (relationship, information) in my_family.items():
family_member = relationship
name = information['name']
age = information['age']
print(name + ' is my ' + family_member + ' and is ' + str(age) + ' years old.') |
fieldname_list = [
"file_name",
"file_path",
"v_format",
"v_info",
"v_profile",
"v_settings",
"v_settings_cabac",
"v_settings_reframes",
"v_format_settings_gop",
"v_codec_id",
"v_codec_id_info",
"v_duration",
"v_bit_rate_mode",
"v_bit_rate",
"v_max_bit_rate",
"v_frame_rate",
"v_frame_rate_mode",
"v_width",
"v_height",
"v_rotation",
"v_display_aspect_ratio",
"v_standard",
"v_color_space",
"v_chroma_sub",
"v_bit_depth",
"v_scan_type",
"v_encoded_date",
"a_format",
"a_format_info",
"a_format_profile",
"a_codec_id",
"a_duration",
"a_bit_rate_mode",
"a_bit_rate",
"a_max_bit_rate",
"a_channel_positions",
"a_sampling_rate",
"a_compression_mode",
]
| fieldname_list = ['file_name', 'file_path', 'v_format', 'v_info', 'v_profile', 'v_settings', 'v_settings_cabac', 'v_settings_reframes', 'v_format_settings_gop', 'v_codec_id', 'v_codec_id_info', 'v_duration', 'v_bit_rate_mode', 'v_bit_rate', 'v_max_bit_rate', 'v_frame_rate', 'v_frame_rate_mode', 'v_width', 'v_height', 'v_rotation', 'v_display_aspect_ratio', 'v_standard', 'v_color_space', 'v_chroma_sub', 'v_bit_depth', 'v_scan_type', 'v_encoded_date', 'a_format', 'a_format_info', 'a_format_profile', 'a_codec_id', 'a_duration', 'a_bit_rate_mode', 'a_bit_rate', 'a_max_bit_rate', 'a_channel_positions', 'a_sampling_rate', 'a_compression_mode'] |
#binary search
class BinarySearch:
def __init__(self):
self.elements = [10,12,15,18,19,22,27,32,38]
def SearchElm(self,elem):
start = 0
stop = len(self.elements)-1
while start <= stop:
mid_point = start + (stop - start)
if self.elements[mid_point] == elem:
return mid_point
elif elem > self.elements[mid_point]:
start = mid_point + 1
else:
stop = mid_point - 1
return -1
binary = BinarySearch()
element = int(input("Enter the element you want search :"))
res = binary.SearchElm(element)
if res != -1:
print("The position of the {x} is {y} ".format(x = element,y=res))
else:
print("The element is not presented in the array")
| class Binarysearch:
def __init__(self):
self.elements = [10, 12, 15, 18, 19, 22, 27, 32, 38]
def search_elm(self, elem):
start = 0
stop = len(self.elements) - 1
while start <= stop:
mid_point = start + (stop - start)
if self.elements[mid_point] == elem:
return mid_point
elif elem > self.elements[mid_point]:
start = mid_point + 1
else:
stop = mid_point - 1
return -1
binary = binary_search()
element = int(input('Enter the element you want search :'))
res = binary.SearchElm(element)
if res != -1:
print('The position of the {x} is {y} '.format(x=element, y=res))
else:
print('The element is not presented in the array') |
'''
This problem was asked by Facebook.
Given a string of round, curly, and square open and closing brackets,
return whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
'''
bracket_vocab = {'(': 1,
')': 2,
'[': 3,
']': 4,
'{': 5,
'}': 6}
# The ord() method returns an integer representing Unicode code point for the given Unicode character.
def balanced(string):
stack = []
for i in string:
if len(stack) ==0:
stack.append(i)
elif bracket_vocab[i]-1 == bracket_vocab[stack[-1]]:
# found matching bracket
stack.pop(-1)
else:
stack.append(i)
if len(stack) ==0:
# successfully matched all brackets
return True
else:
return False
if __name__ == '__main__':
# string = "([)]"
string = "([])[]({})"
# string = "((()"
print(balanced(string))
| """
This problem was asked by Facebook.
Given a string of round, curly, and square open and closing brackets,
return whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
"""
bracket_vocab = {'(': 1, ')': 2, '[': 3, ']': 4, '{': 5, '}': 6}
def balanced(string):
stack = []
for i in string:
if len(stack) == 0:
stack.append(i)
elif bracket_vocab[i] - 1 == bracket_vocab[stack[-1]]:
stack.pop(-1)
else:
stack.append(i)
if len(stack) == 0:
return True
else:
return False
if __name__ == '__main__':
string = '([])[]({})'
print(balanced(string)) |
# -*- encoding: utf-8 -*-
# Copyright (c) 2021 Stephen Bunn <stephen@bunn.io>
# ISC License <https://choosealicense.com/licenses/isc>
"""Contains module-wide constants."""
APP_NAME = "brut"
APP_VERSION = "0.1.0"
| """Contains module-wide constants."""
app_name = 'brut'
app_version = '0.1.0' |
# Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
# Once 'done' is entered, print out the largest and smallest of the numbers.
# If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
# Enter 7, 2, bob, 10, and 4 and match the output below.
ps=None
tss=None
while True:
new=input("Enter any number")
if new =="done":
break
try:
new=int(new)
except:
print("Invalid input")
continue
if (ps==None) or (ps>new):
ps=new
if (tss == None)or (tss < new):
tss=new
print("Maximum is",tss)
print("Minimum is",ps)
# IMPRORTANT sould enter "done" in the end.
| ps = None
tss = None
while True:
new = input('Enter any number')
if new == 'done':
break
try:
new = int(new)
except:
print('Invalid input')
continue
if ps == None or ps > new:
ps = new
if tss == None or tss < new:
tss = new
print('Maximum is', tss)
print('Minimum is', ps) |
# Can you find the needle in the haystack?
# Write a function findNeedle() that takes an array full of junk but containing one "needle"
# After your function finds the needle it should return a message (as a string) that says:
# "found the needle at position " plus the index it found the needle, so:
# Python, Ruby & Elixir
# find_needle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk'])
def find_needle(haystack):
for el in haystack:
if el == 'needle':
return 'found the needle at position ' + str(haystack.index(el))
print(find_needle([1,2,3,4,'needle']))
| def find_needle(haystack):
for el in haystack:
if el == 'needle':
return 'found the needle at position ' + str(haystack.index(el))
print(find_needle([1, 2, 3, 4, 'needle'])) |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict1, dict2 = {}, {}
for item in s:
dict1[item] = dict1.get(item, 0) + 1
for item in t:
dict2[item] = dict2.get(item, 0) + 1
return dict1 == dict2 | class Solution(object):
def is_anagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
(dict1, dict2) = ({}, {})
for item in s:
dict1[item] = dict1.get(item, 0) + 1
for item in t:
dict2[item] = dict2.get(item, 0) + 1
return dict1 == dict2 |
#
# @lc app=leetcode id=859 lang=python3
#
# [859] Buddy Strings
#
# @lc code=start
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) <= 1 or len(B) <= 1 or len(A) != len(B):
return False
if A == B:
return len(set(A)) < len(A)
i = 0
while A[i] == B[i]: i += 1
for j in range(i + 1, len(A)):
if A[j] == B[i] and A[i] == B[j]:
A = A[:i] + A[j] + A[i+1:j] + A[i] + A[j+1:]
return A == B
# @lc code=end
| class Solution:
def buddy_strings(self, A: str, B: str) -> bool:
if len(A) <= 1 or len(B) <= 1 or len(A) != len(B):
return False
if A == B:
return len(set(A)) < len(A)
i = 0
while A[i] == B[i]:
i += 1
for j in range(i + 1, len(A)):
if A[j] == B[i] and A[i] == B[j]:
a = A[:i] + A[j] + A[i + 1:j] + A[i] + A[j + 1:]
return A == B |
#
# @lc app=leetcode.cn id=114 lang=python3
#
# [114] flatten-binary-tree-to-linked-list
#
None
# @lc code=end | None |
def get_counter_and_increment(filename="counter.dat"):
with open(filename, "a+") as f:
f.seek(0)
val = int(f.read() or 0) + 1
f.seek(0)
f.truncate()
f.write(str(val))
return val
def get_counter(filename="counter.dat"):
with open(filename, "a+") as f:
f.seek(0)
return int(f.read() or 0)
| def get_counter_and_increment(filename='counter.dat'):
with open(filename, 'a+') as f:
f.seek(0)
val = int(f.read() or 0) + 1
f.seek(0)
f.truncate()
f.write(str(val))
return val
def get_counter(filename='counter.dat'):
with open(filename, 'a+') as f:
f.seek(0)
return int(f.read() or 0) |
#
# Keys under which options are stored.
OPTIONS_UNKNOWN = 0
OPTIONS_FILE_OUTPUT = 1
OPTIONS_CPU = 2
OPTIONS_STANDARD = 3
# General options that belong to no specific collection.
OPTION_UNKNOWN = 0
OPTION_DISABLE_OPTIMISATIONS = 1
OPTION_DEFAULT_FILE_NAME = 2
# CPU optons.
CPU_UNKNOWN = 0
CPU_MC60000 = 1
CPU_MC60010 = 2
CPU_MC60020 = 3
CPU_MC60030 = 4
CPU_MC60040 = 5
CPU_MC60060 = 7
def get_cpu_name_by_id(cpu_id):
for k, v in globals().items():
if k.startswith("CPU_") and v == cpu_id:
return k
ASM_SYNTAX_UNKNOWN = 0
ASM_SYNTAX_MOTOROLA = 1
def get_syntax_name_by_id(syntax_id):
for k, v in globals().items():
if k.startswith("ASM_SYNTAX_") and v == syntax_id:
return k
OUTPUT_FORMAT_UNKNOWN = 0
OUTPUT_FORMAT_BINARY = 1
OUTPUT_FORMAT_AMIGA_HUNK = 2
OUTPUT_FORMAT_ATARIST_TOS = 3
def get_output_format_name_by_id(output_format_id):
for k, v in globals().items():
if k.startswith("OUTPUT_FORMAT_") and v == output_format_id:
return k
| options_unknown = 0
options_file_output = 1
options_cpu = 2
options_standard = 3
option_unknown = 0
option_disable_optimisations = 1
option_default_file_name = 2
cpu_unknown = 0
cpu_mc60000 = 1
cpu_mc60010 = 2
cpu_mc60020 = 3
cpu_mc60030 = 4
cpu_mc60040 = 5
cpu_mc60060 = 7
def get_cpu_name_by_id(cpu_id):
for (k, v) in globals().items():
if k.startswith('CPU_') and v == cpu_id:
return k
asm_syntax_unknown = 0
asm_syntax_motorola = 1
def get_syntax_name_by_id(syntax_id):
for (k, v) in globals().items():
if k.startswith('ASM_SYNTAX_') and v == syntax_id:
return k
output_format_unknown = 0
output_format_binary = 1
output_format_amiga_hunk = 2
output_format_atarist_tos = 3
def get_output_format_name_by_id(output_format_id):
for (k, v) in globals().items():
if k.startswith('OUTPUT_FORMAT_') and v == output_format_id:
return k |
class seq:
def __init__(self, strbases):
self.strbases = strbases
def len(self):
return len(self.strbases)
def complement(self):
comp = ''
for e in self.strbases:
if e == 'A':
comp += 'T'
elif e == 'C':
comp += 'G'
elif e == 'G':
comp += 'C'
elif e == 'T':
comp += 'A'
return comp
def reverse(self):
return self.strbases[::-1]
def count(self, base):
n = 0
if base == 'A':
n += 1
elif base == 'G':
n += 1
elif base == 'T':
n += 1
elif base == 'C':
n += 1
return n
def perc(self, base):
(self.count(base) / self.len()) * 100 | class Seq:
def __init__(self, strbases):
self.strbases = strbases
def len(self):
return len(self.strbases)
def complement(self):
comp = ''
for e in self.strbases:
if e == 'A':
comp += 'T'
elif e == 'C':
comp += 'G'
elif e == 'G':
comp += 'C'
elif e == 'T':
comp += 'A'
return comp
def reverse(self):
return self.strbases[::-1]
def count(self, base):
n = 0
if base == 'A':
n += 1
elif base == 'G':
n += 1
elif base == 'T':
n += 1
elif base == 'C':
n += 1
return n
def perc(self, base):
self.count(base) / self.len() * 100 |
"""Change the config values."""
branches = ('master', 'dev') # Note: Single element requires a comma at end.
add_codeowners_file = True
signed_commit = False
branch_rules = {"required_approving_review_count": 1,
"require_code_owner_reviews": True,
"contexts": ["CodeQL"],
"strict": True
}
| """Change the config values."""
branches = ('master', 'dev')
add_codeowners_file = True
signed_commit = False
branch_rules = {'required_approving_review_count': 1, 'require_code_owner_reviews': True, 'contexts': ['CodeQL'], 'strict': True} |
"""
LC322 -- Coin Change
time complexity -- O(N*M)
space complexiy -- O(M)
M is len(coins), N is amount
Runtime: 1080 ms, faster than 85.13% of Python3 online submissions for Coin Change.
Memory Usage: 13.8 MB, less than 30.56% of Python3 online submissions for Coin Change.
normal dp
small trick is to build a n+1 length dp array
however, still pretty slow if no optimization is used
"""
# method1 -- no optimization
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
if not amount:
return 0
dp = [amount + 1] * (amount + 1)
for i in range(amount + 1):
if i in coins:
dp[i] = 1
continue
candidates = [dp[i - coin] + 1 for coin in coins if i - coin > 0]
if candidates:
dp[i] = min(candidates)
return -1 if dp[amount] > amount else dp[amount]
# method2 -- dfs, first sort the coins array
# this dfs is also smart
# should think more about his pruning trick
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
coins.sort(reverse=True)
MAX = amount + 1
self.ans = MAX
def dfs(coin_idx, tot_num, amount):
if amount == 0:
self.ans = tot_num
return
if coin_idx == len(coins):
return
coin = coins[coin_idx]
for k in range(amount//coin, -1, -1):
if tot_num + k >= self.ans:
break
dfs(coin_idx+1, tot_num+k, amount-k*coin)
dfs(0, 0, amount)
return -1 if self.ans==MAX else self.ans
| """
LC322 -- Coin Change
time complexity -- O(N*M)
space complexiy -- O(M)
M is len(coins), N is amount
Runtime: 1080 ms, faster than 85.13% of Python3 online submissions for Coin Change.
Memory Usage: 13.8 MB, less than 30.56% of Python3 online submissions for Coin Change.
normal dp
small trick is to build a n+1 length dp array
however, still pretty slow if no optimization is used
"""
class Solution:
def coin_change(self, coins: List[int], amount: int) -> int:
if not amount:
return 0
dp = [amount + 1] * (amount + 1)
for i in range(amount + 1):
if i in coins:
dp[i] = 1
continue
candidates = [dp[i - coin] + 1 for coin in coins if i - coin > 0]
if candidates:
dp[i] = min(candidates)
return -1 if dp[amount] > amount else dp[amount]
class Solution:
def coin_change(self, coins: List[int], amount: int) -> int:
coins.sort(reverse=True)
max = amount + 1
self.ans = MAX
def dfs(coin_idx, tot_num, amount):
if amount == 0:
self.ans = tot_num
return
if coin_idx == len(coins):
return
coin = coins[coin_idx]
for k in range(amount // coin, -1, -1):
if tot_num + k >= self.ans:
break
dfs(coin_idx + 1, tot_num + k, amount - k * coin)
dfs(0, 0, amount)
return -1 if self.ans == MAX else self.ans |
class TimeSlot:
"""A class to store time slot"""
minutes_in_hour = 60
def __init__(self, name='name'): # initialize an empty slot
self._h = 0
self._m = 0
self.name = name
# timeslot is an instance attribute
# (attribute of the object)
@property
def m(self):
return self._m
@property
def h(self):
return self._h
@m.setter
def m(self, m):
self._h = int(m / self.minutes_in_hour)
self._m = m % self.minutes_in_hour
def set_h_m(self, h, m):
# set_h_m() is an instance method #(method of the object)
self._h = h
self._m = m
def get_h_m(self):
return self._h, self._m
def __add__(self, ts):
new_ts = TimeSlot()
new_ts.m = (self._h + ts._h) * self.minutes_in_hour + self._m + ts._m
return new_ts
t1 = TimeSlot('Carbonara')
t1.m = 20
t2 = TimeSlot('Tiramisu')
t2.m = 30
t_menu = t1 + t2
print('t_menu-> ', t_menu.h, t_menu.m)
| class Timeslot:
"""A class to store time slot"""
minutes_in_hour = 60
def __init__(self, name='name'):
self._h = 0
self._m = 0
self.name = name
@property
def m(self):
return self._m
@property
def h(self):
return self._h
@m.setter
def m(self, m):
self._h = int(m / self.minutes_in_hour)
self._m = m % self.minutes_in_hour
def set_h_m(self, h, m):
self._h = h
self._m = m
def get_h_m(self):
return (self._h, self._m)
def __add__(self, ts):
new_ts = time_slot()
new_ts.m = (self._h + ts._h) * self.minutes_in_hour + self._m + ts._m
return new_ts
t1 = time_slot('Carbonara')
t1.m = 20
t2 = time_slot('Tiramisu')
t2.m = 30
t_menu = t1 + t2
print('t_menu-> ', t_menu.h, t_menu.m) |
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
max_num = max(nums)
for i in nums:
if i != max_num and max_num < 2*i:
return -1
return nums.index(max_num)
| class Solution:
def dominant_index(self, nums: List[int]) -> int:
max_num = max(nums)
for i in nums:
if i != max_num and max_num < 2 * i:
return -1
return nums.index(max_num) |
# Program to print first n tribonacci
# numbers Matrix Multiplication
# function for 3*3 matrix
def multiply(T, M):
a = (T[0][0] * M[0][0] + T[0][1] *
M[1][0] + T[0][2] * M[2][0])
b = (T[0][0] * M[0][1] + T[0][1] *
M[1][1] + T[0][2] * M[2][1])
c = (T[0][0] * M[0][2] + T[0][1] *
M[1][2] + T[0][2] * M[2][2])
d = (T[1][0] * M[0][0] + T[1][1] *
M[1][0] + T[1][2] * M[2][0])
e = (T[1][0] * M[0][1] + T[1][1] *
M[1][1] + T[1][2] * M[2][1])
f = (T[1][0] * M[0][2] + T[1][1] *
M[1][2] + T[1][2] * M[2][2])
g = (T[2][0] * M[0][0] + T[2][1] *
M[1][0] + T[2][2] * M[2][0])
h = (T[2][0] * M[0][1] + T[2][1] *
M[1][1] + T[2][2] * M[2][1])
i = (T[2][0] * M[0][2] + T[2][1] *
M[1][2] + T[2][2] * M[2][2])
T[0][0] = a
T[0][1] = b
T[0][2] = c
T[1][0] = d
T[1][1] = e
T[1][2] = f
T[2][0] = g
T[2][1] = h
T[2][2] = i
# Recursive function to raise
# the matrix T to the power n
def power(T, n):
# base condition.
if (n == 0 or n == 1):
return;
M = [[ 1, 1, 1 ],
[ 1, 0, 0 ],
[ 0, 1, 0 ]]
# recursively call to
# square the matrix
power(T, n // 2)
# calculating square
# of the matrix T
multiply(T, T)
# if n is odd multiply
# it one time with M
if (n % 2):
multiply(T, M)
def tribonacci(n):
T = [[ 1, 1, 1 ],
[1, 0, 0 ],
[0, 1, 0 ]]
# base condition
if (n == 0 or n == 1):
return 0
else:
power(T, n - 2)
# T[0][0] contains the
# tribonacci number so
# return it
return T[0][0]
# Driver Code
if __name__ == "__main__":
n = int(input())
for i in range(n):
print(tribonacci(i),end=" ")
print()
| def multiply(T, M):
a = T[0][0] * M[0][0] + T[0][1] * M[1][0] + T[0][2] * M[2][0]
b = T[0][0] * M[0][1] + T[0][1] * M[1][1] + T[0][2] * M[2][1]
c = T[0][0] * M[0][2] + T[0][1] * M[1][2] + T[0][2] * M[2][2]
d = T[1][0] * M[0][0] + T[1][1] * M[1][0] + T[1][2] * M[2][0]
e = T[1][0] * M[0][1] + T[1][1] * M[1][1] + T[1][2] * M[2][1]
f = T[1][0] * M[0][2] + T[1][1] * M[1][2] + T[1][2] * M[2][2]
g = T[2][0] * M[0][0] + T[2][1] * M[1][0] + T[2][2] * M[2][0]
h = T[2][0] * M[0][1] + T[2][1] * M[1][1] + T[2][2] * M[2][1]
i = T[2][0] * M[0][2] + T[2][1] * M[1][2] + T[2][2] * M[2][2]
T[0][0] = a
T[0][1] = b
T[0][2] = c
T[1][0] = d
T[1][1] = e
T[1][2] = f
T[2][0] = g
T[2][1] = h
T[2][2] = i
def power(T, n):
if n == 0 or n == 1:
return
m = [[1, 1, 1], [1, 0, 0], [0, 1, 0]]
power(T, n // 2)
multiply(T, T)
if n % 2:
multiply(T, M)
def tribonacci(n):
t = [[1, 1, 1], [1, 0, 0], [0, 1, 0]]
if n == 0 or n == 1:
return 0
else:
power(T, n - 2)
return T[0][0]
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(tribonacci(i), end=' ')
print() |
''' Problem 5. Write a program that finds out whether
a given name is present in a list or not.'''
# Name search genrator using the Python
names = ["Vasudev","Ridhi","hritik","Hanuman", "Gaurav"]
name = input("Enter the Name : ")
if name in names:
print("Your name is in the list")
else:
print("Your name is not in the list") | """ Problem 5. Write a program that finds out whether
a given name is present in a list or not."""
names = ['Vasudev', 'Ridhi', 'hritik', 'Hanuman', 'Gaurav']
name = input('Enter the Name : ')
if name in names:
print('Your name is in the list')
else:
print('Your name is not in the list') |
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sum = (10 ** 4) * -1
restart = True
tmp_sum = (10 ** 4) * -1
for n in nums:
if restart:
tmp_sum = n
restart = False
else:
tmp_sum += n
if tmp_sum > max_sum:
max_sum = tmp_sum
if tmp_sum < 0:
restart = True
tmp_sum = 10 ^ 4 * -1
return max_sum | class Solution(object):
def max_sub_array(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sum = 10 ** 4 * -1
restart = True
tmp_sum = 10 ** 4 * -1
for n in nums:
if restart:
tmp_sum = n
restart = False
else:
tmp_sum += n
if tmp_sum > max_sum:
max_sum = tmp_sum
if tmp_sum < 0:
restart = True
tmp_sum = 10 ^ 4 * -1
return max_sum |
FLAG_OK = 0
FLAG_WARNING = 1
FLAG_ERROR = 2
FLAG_UNKNOWN = 3
FLAG_OK_STR = "OK"
FLAG_WARNING_STR = "WARNING"
FLAG_ERROR_STR = "ERROR"
FLAG_UNKNOWN_STR = "UNKNOWN"
FLAG_MAP = {
FLAG_OK_STR: FLAG_OK,
FLAG_WARNING_STR: FLAG_WARNING,
FLAG_ERROR_STR: FLAG_ERROR,
FLAG_UNKNOWN_STR: FLAG_UNKNOWN,
}
| flag_ok = 0
flag_warning = 1
flag_error = 2
flag_unknown = 3
flag_ok_str = 'OK'
flag_warning_str = 'WARNING'
flag_error_str = 'ERROR'
flag_unknown_str = 'UNKNOWN'
flag_map = {FLAG_OK_STR: FLAG_OK, FLAG_WARNING_STR: FLAG_WARNING, FLAG_ERROR_STR: FLAG_ERROR, FLAG_UNKNOWN_STR: FLAG_UNKNOWN} |
kernel_weight = 0.03
bias_weight = 0.03
model_iris_l1 = models.Sequential([
layers.Input(shape = (4,)),
layers.Dense(32, activation='relu', kernel_regularizer=regularizers.l1(kernel_weight), bias_regularizer=regularizers.l2(bias_weight)),
layers.Dense(32, activation='relu', kernel_regularizer=regularizers.l1(kernel_weight), bias_regularizer=regularizers.l2(bias_weight)),
layers.Dense(3, activation = 'softmax')
])
model_iris_l1.compile(
loss='sparse_categorical_crossentropy',
optimizer=optimizers.Adam(0.005),
metrics=['accuracy'],
)
iris_trained_l1 = model_iris_l1.fit(
x = X_train_iris.to_numpy(), y = y_train_iris.to_numpy(), verbose=0,
epochs=1000, validation_data= (X_test_iris.to_numpy(), y_test_iris.to_numpy()),
)
plot_accuracy_loss_rolling(iris_trained_l1)
| kernel_weight = 0.03
bias_weight = 0.03
model_iris_l1 = models.Sequential([layers.Input(shape=(4,)), layers.Dense(32, activation='relu', kernel_regularizer=regularizers.l1(kernel_weight), bias_regularizer=regularizers.l2(bias_weight)), layers.Dense(32, activation='relu', kernel_regularizer=regularizers.l1(kernel_weight), bias_regularizer=regularizers.l2(bias_weight)), layers.Dense(3, activation='softmax')])
model_iris_l1.compile(loss='sparse_categorical_crossentropy', optimizer=optimizers.Adam(0.005), metrics=['accuracy'])
iris_trained_l1 = model_iris_l1.fit(x=X_train_iris.to_numpy(), y=y_train_iris.to_numpy(), verbose=0, epochs=1000, validation_data=(X_test_iris.to_numpy(), y_test_iris.to_numpy()))
plot_accuracy_loss_rolling(iris_trained_l1) |
DEBUG = False
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '{{ secret_key }}'
ALLOWED_HOSTS = ['{{ host }}']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '{{ database_name }}',
'USER': '{{ database_user }}',
'PASSWORD': '{{ database_password }}',
'HOST': '{{ database_host }}',
'PORT': '{{database_port }}',
'CONN_MAX_AGE': 600,
},
}
| debug = False
secret_key = '{{ secret_key }}'
allowed_hosts = ['{{ host }}']
databases = {'default': {'ENGINE': 'django.db.backends.postgresql', 'NAME': '{{ database_name }}', 'USER': '{{ database_user }}', 'PASSWORD': '{{ database_password }}', 'HOST': '{{ database_host }}', 'PORT': '{{database_port }}', 'CONN_MAX_AGE': 600}} |
"""Constants used in the openapi_builder package."""
EXTENSION_NAME = "__open_api_doc__" # Name of the extension in the Flask application.
HIDDEN_ATTR_NAME = "__option_api_attr" # Attribute name for adding options.
DOCUMENTATION_URL = "https://flyingbird95.github.io/openapi-builder"
| """Constants used in the openapi_builder package."""
extension_name = '__open_api_doc__'
hidden_attr_name = '__option_api_attr'
documentation_url = 'https://flyingbird95.github.io/openapi-builder' |
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.bigSize, self.bigCount, self.mediumSize, self.mediumCount, self.smallSize, self.smallCount = big, 0, medium, 0, small, 0
def addCar(self, carType: int) -> bool:
if carType == 1:
if self.bigCount < self.bigSize:
self.bigCount += 1
return True
return False
elif carType == 2:
if self.mediumCount < self.mediumSize:
self.mediumCount += 1
return True
return False
elif carType == 3:
if self.smallCount < self.smallSize:
self.smallCount += 1
return True
return False
return False
# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType) | class Parkingsystem:
def __init__(self, big: int, medium: int, small: int):
(self.bigSize, self.bigCount, self.mediumSize, self.mediumCount, self.smallSize, self.smallCount) = (big, 0, medium, 0, small, 0)
def add_car(self, carType: int) -> bool:
if carType == 1:
if self.bigCount < self.bigSize:
self.bigCount += 1
return True
return False
elif carType == 2:
if self.mediumCount < self.mediumSize:
self.mediumCount += 1
return True
return False
elif carType == 3:
if self.smallCount < self.smallSize:
self.smallCount += 1
return True
return False
return False |
#
# PySNMP MIB module CISCO-IMAGE-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IMAGE-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Bits, Gauge32, Unsigned32, ObjectIdentity, NotificationType, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, ModuleIdentity, TimeTicks, Integer32, Counter64, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Bits", "Gauge32", "Unsigned32", "ObjectIdentity", "NotificationType", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "ModuleIdentity", "TimeTicks", "Integer32", "Counter64", "IpAddress")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoImageTc = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 455))
ciscoImageTc.setRevisions(('2005-01-12 00:00',))
if mibBuilder.loadTexts: ciscoImageTc.setLastUpdated('200501120000Z')
if mibBuilder.loadTexts: ciscoImageTc.setOrganization('Cisco Systems, Inc.')
class CeImageInstallableStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))
namedValues = NamedValues(("active", 1), ("pendingInstall", 2), ("pendingRemoval", 3), ("installPendingReload", 4), ("removedPendingReload", 5), ("installPendingReloadPendingRemoval", 6), ("removedPendingReloadPendingInstall", 7), ("pruned", 8), ("inactive", 9))
class CeImageInstallableType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))
namedValues = NamedValues(("base", 1), ("patch", 2), ("script", 3), ("package", 4), ("compositePackage", 5), ("softwareMaintenanceUpgrade", 6))
mibBuilder.exportSymbols("CISCO-IMAGE-TC", CeImageInstallableStatus=CeImageInstallableStatus, CeImageInstallableType=CeImageInstallableType, ciscoImageTc=ciscoImageTc, PYSNMP_MODULE_ID=ciscoImageTc)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion')
(cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(iso, bits, gauge32, unsigned32, object_identity, notification_type, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, module_identity, time_ticks, integer32, counter64, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Bits', 'Gauge32', 'Unsigned32', 'ObjectIdentity', 'NotificationType', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'ModuleIdentity', 'TimeTicks', 'Integer32', 'Counter64', 'IpAddress')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
cisco_image_tc = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 455))
ciscoImageTc.setRevisions(('2005-01-12 00:00',))
if mibBuilder.loadTexts:
ciscoImageTc.setLastUpdated('200501120000Z')
if mibBuilder.loadTexts:
ciscoImageTc.setOrganization('Cisco Systems, Inc.')
class Ceimageinstallablestatus(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9))
named_values = named_values(('active', 1), ('pendingInstall', 2), ('pendingRemoval', 3), ('installPendingReload', 4), ('removedPendingReload', 5), ('installPendingReloadPendingRemoval', 6), ('removedPendingReloadPendingInstall', 7), ('pruned', 8), ('inactive', 9))
class Ceimageinstallabletype(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))
named_values = named_values(('base', 1), ('patch', 2), ('script', 3), ('package', 4), ('compositePackage', 5), ('softwareMaintenanceUpgrade', 6))
mibBuilder.exportSymbols('CISCO-IMAGE-TC', CeImageInstallableStatus=CeImageInstallableStatus, CeImageInstallableType=CeImageInstallableType, ciscoImageTc=ciscoImageTc, PYSNMP_MODULE_ID=ciscoImageTc) |
# Addresses
LOAD_R3_ADDR = 0x0C00C650
OSFATAL_ADDR = 0x01031618
class PayloadAddress:
pass
CHAIN_END = "#Execute ROP chain\nexit\n\n#Dunno why but I figured I might as well put it here, should never hit this though\nend"
def write_rop_chain(rop_chain, path):
with open('rop_setup.s', 'r') as f:
setup = f.read()
with open(path, 'w') as f:
print(setup, file=f)
for command in rop_chain:
if isinstance(command, PayloadAddress):
print("pushVar. globalVar,mscScriptAddress", file=f)
elif isinstance(command, int):
print(f"pushInt. {hex(command)}", file=f)
else:
raise Exception(f"Found invalid type {type(command)} in rop_chain")
print(CHAIN_END, file=f)
"""
Example payload (writeOSFatalPayload func)
pushInt. 0xC00C650
pushVar. globalVar,mscScriptAddress #r3 value (will be printed by OSFatal)
pushInt. 0xBEEF0001
pushInt. 0xBEEF0002
pushInt. 0xBEEF0003
pushInt. 0xBEEF0004
pushInt. 0xBEEF0005
pushInt. 0xBEEF0006
pushInt. 0xBEEF0007
pushInt. 0xBEEF0008
pushInt. 0xBEEF0009
pushInt. 0xBEEF000A
pushInt. 0xBEEF000B
pushInt. 0xBEEF000C
pushInt. 0xBEEF000D
pushInt. 0xBEEF000E
pushInt. 0xBEEF000F
pushInt. 0xBEEF0010
pushInt. 0xBEEF0011
pushInt. 0xBEEF0012
pushInt. 0xBEEF0013
pushInt. 0xBEEF0014
pushInt. 0xBEEF0015
pushInt. 0xBEEF0016
pushInt. 0xBEEF0017
pushInt. 0xBEEF0018
pushInt. 0xBEEF0019
pushInt. 0xBEEF001A
pushInt. 0x01031618 #return address (OSFatal)
"""
# Print out contents of payload as null terminated string
def generateOSFatalPayload():
return [
LOAD_R3_ADDR,
PayloadAddress()
] + [
0xBEEF0001 + i for i in range(0x1A)
] + [
OSFATAL_ADDR
]
writeEnd()
def main():
rop_chain = generateOSFatalPayload()
write_rop_chain(rop_chain, 'main.s')
if __name__ == "__main__":
main()
| load_r3_addr = 201377360
osfatal_addr = 16979480
class Payloadaddress:
pass
chain_end = '#Execute ROP chain\nexit\n\n#Dunno why but I figured I might as well put it here, should never hit this though\nend'
def write_rop_chain(rop_chain, path):
with open('rop_setup.s', 'r') as f:
setup = f.read()
with open(path, 'w') as f:
print(setup, file=f)
for command in rop_chain:
if isinstance(command, PayloadAddress):
print('pushVar. globalVar,mscScriptAddress', file=f)
elif isinstance(command, int):
print(f'pushInt. {hex(command)}', file=f)
else:
raise exception(f'Found invalid type {type(command)} in rop_chain')
print(CHAIN_END, file=f)
'\nExample payload (writeOSFatalPayload func)\n\npushInt. 0xC00C650\npushVar. globalVar,mscScriptAddress #r3 value (will be printed by OSFatal)\npushInt. 0xBEEF0001\npushInt. 0xBEEF0002\npushInt. 0xBEEF0003\npushInt. 0xBEEF0004\npushInt. 0xBEEF0005\npushInt. 0xBEEF0006\npushInt. 0xBEEF0007\npushInt. 0xBEEF0008\npushInt. 0xBEEF0009\npushInt. 0xBEEF000A\npushInt. 0xBEEF000B\npushInt. 0xBEEF000C\npushInt. 0xBEEF000D\npushInt. 0xBEEF000E\npushInt. 0xBEEF000F\npushInt. 0xBEEF0010\npushInt. 0xBEEF0011\npushInt. 0xBEEF0012\npushInt. 0xBEEF0013\npushInt. 0xBEEF0014\npushInt. 0xBEEF0015\npushInt. 0xBEEF0016\npushInt. 0xBEEF0017\npushInt. 0xBEEF0018\npushInt. 0xBEEF0019\npushInt. 0xBEEF001A\npushInt. 0x01031618 #return address (OSFatal)\n\n'
def generate_os_fatal_payload():
return [LOAD_R3_ADDR, payload_address()] + [3203334145 + i for i in range(26)] + [OSFATAL_ADDR]
write_end()
def main():
rop_chain = generate_os_fatal_payload()
write_rop_chain(rop_chain, 'main.s')
if __name__ == '__main__':
main() |
"""
Wriggler crawler module.
"""
class Error(Exception):
"""
All exceptions returned are subclass of this one.
"""
| """
Wriggler crawler module.
"""
class Error(Exception):
"""
All exceptions returned are subclass of this one.
""" |
class DisjointSet:
def __init__(self, n, data):
self.graph = data
self.n = n
self.parent = [i for i in range(self.n)]
self.rank = [1] * self.n
def find_parent(self, x):
if self.parent[x] != x:
self.parent[x] = self.find_parent(self.parent[x])
return self.parent[x]
def merge_sets(self, x, y):
p_x = self.find_parent(x)
p_y = self.find_parent(y)
if p_x == p_y:
return False
if self.rank[p_x] >= self.rank[p_y]:
self.rank[p_x] += self.rank[p_y]
self.parent[p_y] = p_x
self.rank[p_y] = 0
else:
self.rank[p_y] += self.rank[p_x]
self.parent[p_x] = p_y
self.rank[p_x] = 0
return True
class MST(DisjointSet):
def __init__(self, n, data):
super().__init__(n, data)
self.result = []
def kruskal(self):
self.graph = sorted(self.graph, key=lambda e: e[0])
for item in self.graph:
# w = item[0]
# u = item[1]
# v = item[2]
w, u, v = item
if not self.merge_sets(u, v):
self.result.append(w)
return self.result
if __name__ == '__main__':
while True:
try:
n, m = map(int, input().split())
if n + m:
g = []
for i in range(m):
u, v, w = map(int, input().split())
g.append((w, u, v))
ans = MST(n, g).kruskal()
sz = len(ans)
if sz:
print(*ans)
else:
print('forest')
else:
break
except Exception as e:
break
| class Disjointset:
def __init__(self, n, data):
self.graph = data
self.n = n
self.parent = [i for i in range(self.n)]
self.rank = [1] * self.n
def find_parent(self, x):
if self.parent[x] != x:
self.parent[x] = self.find_parent(self.parent[x])
return self.parent[x]
def merge_sets(self, x, y):
p_x = self.find_parent(x)
p_y = self.find_parent(y)
if p_x == p_y:
return False
if self.rank[p_x] >= self.rank[p_y]:
self.rank[p_x] += self.rank[p_y]
self.parent[p_y] = p_x
self.rank[p_y] = 0
else:
self.rank[p_y] += self.rank[p_x]
self.parent[p_x] = p_y
self.rank[p_x] = 0
return True
class Mst(DisjointSet):
def __init__(self, n, data):
super().__init__(n, data)
self.result = []
def kruskal(self):
self.graph = sorted(self.graph, key=lambda e: e[0])
for item in self.graph:
(w, u, v) = item
if not self.merge_sets(u, v):
self.result.append(w)
return self.result
if __name__ == '__main__':
while True:
try:
(n, m) = map(int, input().split())
if n + m:
g = []
for i in range(m):
(u, v, w) = map(int, input().split())
g.append((w, u, v))
ans = mst(n, g).kruskal()
sz = len(ans)
if sz:
print(*ans)
else:
print('forest')
else:
break
except Exception as e:
break |
# island count problem big hint (use a Stack)
# data structures (stack queue etc)
class OLDStack:
def __init__(self):
self.storage = []
"""
Push method
-----------
takes in a value and appends it to the storage
"""
def push(self, value):
self.storage.append(value)
"""
Pop Method
----------
checks if there is data left
and returns the top of the stack storage
"""
def pop(self):
# check if storage has any data
if self.size() > 0:
# return the top of the storage stack
return self.storage.pop()
# otherwise
else:
# return None
return None
"""
Size Method
-----------
Returns the length of the storage list
"""
def size(self):
return len(self.storage)
# you can also just copy a stack from the other code
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None
def size(self):
return len(self.stack)
# helper functions (traversal algorithm function bft, dft etc)
# (get neighbors, etc)
# example algorithm
def get_neighbors(x, y, matrix):
# create a neighbors list
neighbors = []
# check the north south east and west for any 1's
# (this would be a bunch of if conditions)
# and append any positive finds
# to the neighbors list as a tuple
if x > 0 and matrix[y][x - 1] == 1:
neighbors.append((x - 1, y))
if x < len(matrix[0]) - 1 and matrix[y][x + 1] == 1:
neighbors.append((x + 1, y))
if y > 0 and matrix[y - 1][x] == 1:
neighbors.append((x, y - 1))
if y < len(matrix) - 1 and matrix[y + 1][x] == 1:
neighbors.append((x, y + 1))
# return neighbors
return neighbors
# a simple dfs / sft to deal with the nested lists
def dft(x, y, matrix, visited):
# create a stack
s = Stack()
# push (x, y) tuple to the stack
s.push((x, y))
# while the stack has data
while s.size() > 0:
# pop a vert off the stack
v = s.pop()
# extract the x and y from the tuple
x = v[0]
y = v[1]
# if the tuple is not in the visited structure
if not visited[y][x]:
# add the tuple to the visited structure
visited[y][x] = True
# loop over each neighbor and run get_neighbor
# on vert[0] , vert[1] and the matrix
for neighbor in get_neighbors(x, y, matrix):
# push the neighbor on to the stack
s.push(neighbor)
# return visited
return visited
# main island counter function
def island_counter(matrix):
# create a visited matrix
visited = []
# loop over the matrix
for _ in range(len(matrix)):
# append False to the visited matrix
# times the length of the matrix[0]
visited.append([False] * len(matrix[0]))
# set an island counter
island_count = 0
# loop over the x
for x in range(len(matrix[0])):
# loop over the y
for y in range(len(matrix)):
# check if [y][x] are visited
if not visited[y][x]:
# if the matrix at [y][x] are equal to 1
if matrix[y][x] == 1:
# set the visited to the dfs
# passing in x, y, matrix and visited
visited = dft(x, y, matrix, visited)
# increment island count
island_count += 1
# otherwise
else:
# set visited at [y][x] to True
visited[y][x] = True
# return island count
return island_count
if __name__ == "__main__":
islands = [
[0, 1, 0, 1, 0],
[1, 1, 0, 1, 1],
[0, 0, 1, 0, 0],
[1, 0, 1, 0, 0],
[1, 1, 0, 0, 0],
]
print(island_counter(islands)) # 4
islands = [
[1, 0, 0, 1, 1, 0, 1, 1, 0, 1],
[0, 0, 1, 1, 0, 1, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 0, 0, 1, 1],
[0, 0, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 1, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 0, 0, 0],
[1, 0, 1, 1, 0, 0, 0, 1, 1, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 1, 0, 0, 1, 0],
]
print(island_counter(islands)) # 13
| class Oldstack:
def __init__(self):
self.storage = []
' \n Push method\n -----------\n takes in a value and appends it to the storage\n '
def push(self, value):
self.storage.append(value)
'\n Pop Method\n ----------\n checks if there is data left \n and returns the top of the stack storage\n '
def pop(self):
if self.size() > 0:
return self.storage.pop()
else:
return None
'\n Size Method\n -----------\n Returns the length of the storage list\n '
def size(self):
return len(self.storage)
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None
def size(self):
return len(self.stack)
def get_neighbors(x, y, matrix):
neighbors = []
if x > 0 and matrix[y][x - 1] == 1:
neighbors.append((x - 1, y))
if x < len(matrix[0]) - 1 and matrix[y][x + 1] == 1:
neighbors.append((x + 1, y))
if y > 0 and matrix[y - 1][x] == 1:
neighbors.append((x, y - 1))
if y < len(matrix) - 1 and matrix[y + 1][x] == 1:
neighbors.append((x, y + 1))
return neighbors
def dft(x, y, matrix, visited):
s = stack()
s.push((x, y))
while s.size() > 0:
v = s.pop()
x = v[0]
y = v[1]
if not visited[y][x]:
visited[y][x] = True
for neighbor in get_neighbors(x, y, matrix):
s.push(neighbor)
return visited
def island_counter(matrix):
visited = []
for _ in range(len(matrix)):
visited.append([False] * len(matrix[0]))
island_count = 0
for x in range(len(matrix[0])):
for y in range(len(matrix)):
if not visited[y][x]:
if matrix[y][x] == 1:
visited = dft(x, y, matrix, visited)
island_count += 1
else:
visited[y][x] = True
return island_count
if __name__ == '__main__':
islands = [[0, 1, 0, 1, 0], [1, 1, 0, 1, 1], [0, 0, 1, 0, 0], [1, 0, 1, 0, 0], [1, 1, 0, 0, 0]]
print(island_counter(islands))
islands = [[1, 0, 0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 1, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 1, 0, 0, 0], [1, 0, 1, 1, 0, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0, 0, 1, 0]]
print(island_counter(islands)) |
# coding: utf-8
DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/55.0.2883.95 Safari/537.36 '
DATA_FOLDER = "data"
| default_user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36 '
data_folder = 'data' |
def my_decorator(func):
def wrapper():
print("before the function is called.")
func()
print("after the function is called.")
return wrapper
@my_decorator
def say_hi_HTA_with_syntax():
print("Hi! HTA with_syntax")
def say_hi_HTA_without_syntax():
print('Hi! HTA without_syntax')
if __name__ == '__main__':
say_hi_HTA_with_syntax()
print('-----=-----')
say_hi_HTA_without_syntax = my_decorator(say_hi_HTA_without_syntax)
say_hi_HTA_without_syntax() | def my_decorator(func):
def wrapper():
print('before the function is called.')
func()
print('after the function is called.')
return wrapper
@my_decorator
def say_hi_hta_with_syntax():
print('Hi! HTA with_syntax')
def say_hi_hta_without_syntax():
print('Hi! HTA without_syntax')
if __name__ == '__main__':
say_hi_hta_with_syntax()
print('-----=-----')
say_hi_hta_without_syntax = my_decorator(say_hi_HTA_without_syntax)
say_hi_hta_without_syntax() |
N = int(input())
XL = [list(map(int, input().split())) for _ in range(N)]
t = [(x + l, x - l) for x, l in XL]
t.sort()
max_r = -float('inf')
result = 0
for i in range(N):
r, l = t[i]
if max_r <= l:
result += 1
max_r = r
print(result)
| n = int(input())
xl = [list(map(int, input().split())) for _ in range(N)]
t = [(x + l, x - l) for (x, l) in XL]
t.sort()
max_r = -float('inf')
result = 0
for i in range(N):
(r, l) = t[i]
if max_r <= l:
result += 1
max_r = r
print(result) |
def solution(xs):
maxp = 1
negs = []
for i in xs:
if i < 0:
negs.append(i)
elif i > 1:
maxp *= i
if len(negs) < 2 and max(xs) < 2:
return str(max(xs))
negs.sort()
while len(negs) > 1:
maxp *= negs.pop(0) * negs.pop(0)
return str(maxp)
| def solution(xs):
maxp = 1
negs = []
for i in xs:
if i < 0:
negs.append(i)
elif i > 1:
maxp *= i
if len(negs) < 2 and max(xs) < 2:
return str(max(xs))
negs.sort()
while len(negs) > 1:
maxp *= negs.pop(0) * negs.pop(0)
return str(maxp) |
# Stairs
# https://www.interviewbit.com/problems/stairs/
#
# You are climbing a stair case. It takes n steps to reach to the top.
#
# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
#
# Example :
#
# Input : 3
# Return : 3
#
# Steps : [1 1 1], [1 2], [2 1]
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Solution:
# @param A : integer
# @return an integer
def climbStairs(self, A):
result = [0] * A
if A < 2:
return A
result[0], result[1] = 1, 2
for i in range(2, A):
result[i] = result[i - 1] + result[i - 2]
return result[-1]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # | class Solution:
def climb_stairs(self, A):
result = [0] * A
if A < 2:
return A
(result[0], result[1]) = (1, 2)
for i in range(2, A):
result[i] = result[i - 1] + result[i - 2]
return result[-1] |
'''
A Python program to add two objects if both objects are an integer type.
'''
def areObjectsInteger (inputNum01, inputNum02):
if not (isinstance(inputNum01, int) and isinstance(inputNum02, int)):
return False
return inputNum01 + inputNum02
def main ():
a,b = [float(x) for x in input("Enter two values\n").split(',')]
print ("Given both objects are integer type? ", areObjectsInteger(a,b))
main () | """
A Python program to add two objects if both objects are an integer type.
"""
def are_objects_integer(inputNum01, inputNum02):
if not (isinstance(inputNum01, int) and isinstance(inputNum02, int)):
return False
return inputNum01 + inputNum02
def main():
(a, b) = [float(x) for x in input('Enter two values\n').split(',')]
print('Given both objects are integer type? ', are_objects_integer(a, b))
main() |
def next_line(line):
res = []
prev = 0
nb = 0
for i in range(len(line)):
if prev == 0:
prev = line[i]
nb = 1
else:
if prev == line[i]:
nb += 1
else:
res.append(nb)
res.append(prev)
prev = line[i]
nb = 1
if nb != 0:
res.append(nb)
res.append(prev)
else:
res.append(1)
return res
print(next_line([1, 2, 1, 1]))
print(next_line([1]))
print(next_line([])) | def next_line(line):
res = []
prev = 0
nb = 0
for i in range(len(line)):
if prev == 0:
prev = line[i]
nb = 1
elif prev == line[i]:
nb += 1
else:
res.append(nb)
res.append(prev)
prev = line[i]
nb = 1
if nb != 0:
res.append(nb)
res.append(prev)
else:
res.append(1)
return res
print(next_line([1, 2, 1, 1]))
print(next_line([1]))
print(next_line([])) |
"""
See statsmodels.tsa.arima.model.ARIMA and statsmodels.tsa.SARIMAX.
"""
ARIMA_DEPRECATION_ERROR = """
statsmodels.tsa.arima_model.ARMA and statsmodels.tsa.arima_model.ARIMA have
been removed in favor of statsmodels.tsa.arima.model.ARIMA (note the .
between arima and model) and statsmodels.tsa.SARIMAX.
statsmodels.tsa.arima.model.ARIMA makes use of the statespace framework and
is both well tested and maintained. It also offers alternative specialized
parameter estimators.
"""
class ARMA:
"""
ARMA has been deprecated in favor of the new implementation
See Also
--------
statsmodels.tsa.arima.model.ARIMA
ARIMA models with a variety of parameter estimators
statsmodels.tsa.statespace.SARIMAX
SARIMAX models estimated using MLE
"""
def __init__(self, *args, **kwargs):
raise NotImplementedError(ARIMA_DEPRECATION_ERROR)
class ARIMA(ARMA):
"""
ARIMA has been deprecated in favor of the new implementation
See Also
--------
statsmodels.tsa.arima.model.ARIMA
ARIMA models with a variety of parameter estimators
statsmodels.tsa.statespace.SARIMAX
SARIMAX models estimated using MLE
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class ARMAResults:
"""
ARMA has been deprecated in favor of the new implementation
See Also
--------
statsmodels.tsa.arima.model.ARIMA
ARIMA models with a variety of parameter estimators
statsmodels.tsa.statespace.SARIMAX
SARIMAX models estimated using MLE
"""
def __init__(self, *args, **kwargs):
raise NotImplementedError(ARIMA_DEPRECATION_ERROR)
class ARIMAResults(ARMAResults):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
| """
See statsmodels.tsa.arima.model.ARIMA and statsmodels.tsa.SARIMAX.
"""
arima_deprecation_error = '\nstatsmodels.tsa.arima_model.ARMA and statsmodels.tsa.arima_model.ARIMA have\nbeen removed in favor of statsmodels.tsa.arima.model.ARIMA (note the .\nbetween arima and model) and statsmodels.tsa.SARIMAX.\n\nstatsmodels.tsa.arima.model.ARIMA makes use of the statespace framework and\nis both well tested and maintained. It also offers alternative specialized\nparameter estimators.\n'
class Arma:
"""
ARMA has been deprecated in favor of the new implementation
See Also
--------
statsmodels.tsa.arima.model.ARIMA
ARIMA models with a variety of parameter estimators
statsmodels.tsa.statespace.SARIMAX
SARIMAX models estimated using MLE
"""
def __init__(self, *args, **kwargs):
raise not_implemented_error(ARIMA_DEPRECATION_ERROR)
class Arima(ARMA):
"""
ARIMA has been deprecated in favor of the new implementation
See Also
--------
statsmodels.tsa.arima.model.ARIMA
ARIMA models with a variety of parameter estimators
statsmodels.tsa.statespace.SARIMAX
SARIMAX models estimated using MLE
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Armaresults:
"""
ARMA has been deprecated in favor of the new implementation
See Also
--------
statsmodels.tsa.arima.model.ARIMA
ARIMA models with a variety of parameter estimators
statsmodels.tsa.statespace.SARIMAX
SARIMAX models estimated using MLE
"""
def __init__(self, *args, **kwargs):
raise not_implemented_error(ARIMA_DEPRECATION_ERROR)
class Arimaresults(ARMAResults):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) |
class UserPoolDeleteError(Exception):
""" User pool delete error handler
"""
pass
| class Userpooldeleteerror(Exception):
""" User pool delete error handler
"""
pass |
#!/usr/bin/env python
name = 'Bob'
age = 2002
if name == 'Alice':
print('Hi, Alice!')
elif age < 12:
print('You are not Alice, kiddo!')
elif age > 2000:
print('Unlike you, Alice is not undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')
| name = 'Bob'
age = 2002
if name == 'Alice':
print('Hi, Alice!')
elif age < 12:
print('You are not Alice, kiddo!')
elif age > 2000:
print('Unlike you, Alice is not undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.') |
# 1. CREATE A DICTIONARY
# Remember, dictionaries are essentially objects.
# Make a dictionary with five different keys relating to your favorite celebrity. You must include at least four different data types as values for those keys.
# ================ CODE HERE ================
# ================ END CODE ================
# 2. FOR LOOPS
# Loop through the array below. For each iteration of the loop, print: "A <ONE OF THE FRUITS IN THE ARRAY> is a fruit."
fruits = ["apple", "banana", "strawberry", "orange", "grape"]
# ================ CODE HERE ================
# ================ END CODE ================
# 3. WHILE LOOPS
# Create a while loop that prints the one number in each iteration. It should print the numbers 1 through 10, and then stop.
count = 1
# ================ CODE HERE ================
# ================ END CODE ================
# 4. CONDITIONALS
# Loop through the fruits array again. If the fruit starts with the letter b, print "vegetable", otherwise, simply print the fruit.
# ================ CODE HERE ================
# ================ END CODE ================ | fruits = ['apple', 'banana', 'strawberry', 'orange', 'grape']
count = 1 |
#!/usr/bin/python
with open('README.md', 'w') as README:
with open('docs/list_of__modules.rst', 'r') as index:
README.write('''
# Cisco ACI modules for Ansible
This project is working on upstreaming Cisco ACI support within the Ansible project.
We currently have 30+ modules available, and many more are being added.
## News
Ansible v2.4 will ship with **aci_rest** and tens of ACI modules ! We are working hard
with the Ansible Network Working Group to add more modules to ship with Ansible v2.5.
You can find more information related to this project at:
https://github.com/ansible/community/wiki/Network:-ACI
People interested in contributing to this project are welcome to join.
## Modules
''')
for line in index.readlines():
items = line.split()
if not items:
continue
module = items[0]
if module.startswith('aci_'):
description = ' '.join(items[2:-1])
README.write('- [%(mod)s](https://github.com/datacenter/aci-ansible/blob/master/docs/%(mod)s_module.rst) -\n' % dict(mod=module))
README.write(' %(desc)s\n' % dict(desc=description))
index.closed
README.closed
| with open('README.md', 'w') as readme:
with open('docs/list_of__modules.rst', 'r') as index:
README.write('\n# Cisco ACI modules for Ansible\n\nThis project is working on upstreaming Cisco ACI support within the Ansible project.\nWe currently have 30+ modules available, and many more are being added.\n\n\n## News\nAnsible v2.4 will ship with **aci_rest** and tens of ACI modules ! We are working hard\nwith the Ansible Network Working Group to add more modules to ship with Ansible v2.5.\n\nYou can find more information related to this project at:\nhttps://github.com/ansible/community/wiki/Network:-ACI\n\nPeople interested in contributing to this project are welcome to join.\n\n\n## Modules\n\n')
for line in index.readlines():
items = line.split()
if not items:
continue
module = items[0]
if module.startswith('aci_'):
description = ' '.join(items[2:-1])
README.write('- [%(mod)s](https://github.com/datacenter/aci-ansible/blob/master/docs/%(mod)s_module.rst) -\n' % dict(mod=module))
README.write(' %(desc)s\n' % dict(desc=description))
index.closed
README.closed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.