content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
lst = [8, 3, 9, 6, 4, 7, 5, 2, 1]
def main():
test(lst)
def test(lst):
line_one = []
reverse_line_two = lst
shifted_num = []
reverse_line_two = reverse_line_two[::-1]
limit = len(reverse_line_two)
for i in range(limit):
line_one.append(i + 1)
line_one.pop(0)
left = reverse_line_two[:i]
right = reverse_line_two[i:]
reverse_line_two1 = reverse_line_two[1:]
for i in range(len(reverse_line_two1)):
count = 0
if i == 0:
for j in left:
if j < reverse_line_two1[i]:
count+=1
shifted_num.append(count)
if i > 0:
if line_one[i] % 2 == 1:
if shifted_num[i-1]%2 ==0:
for j in reverse_line_two[:reverse_line_two.index(line_one[i])]:
if line_one[i] > j:
count+=1
shifted_num.append(count)
elif shifted_num[i-1]%2 ==1:
for j in reverse_line_two[reverse_line_two.index(line_one[i]):]:
if line_one[i] > j:
count+=1
shifted_num.append(count)
elif line_one[i] % 2 == 0:
if (shifted_num[i-1]+shifted_num[i-2])%2 ==0:
for j in reverse_line_two[:reverse_line_two.index(line_one[i])]:
if line_one[i] > j:
count+=1
shifted_num.append(count)
if (shifted_num[i-1]+shifted_num[i-2])%2 ==1:
for j in reverse_line_two[reverse_line_two.index(line_one[i]):]:
if line_one[i] > j:
count+=1
shifted_num.append(count)
print(shifted_num)
return shifted_num
#def order(lst):
if __name__ == '__main__':
main()
| lst = [8, 3, 9, 6, 4, 7, 5, 2, 1]
def main():
test(lst)
def test(lst):
line_one = []
reverse_line_two = lst
shifted_num = []
reverse_line_two = reverse_line_two[::-1]
limit = len(reverse_line_two)
for i in range(limit):
line_one.append(i + 1)
line_one.pop(0)
left = reverse_line_two[:i]
right = reverse_line_two[i:]
reverse_line_two1 = reverse_line_two[1:]
for i in range(len(reverse_line_two1)):
count = 0
if i == 0:
for j in left:
if j < reverse_line_two1[i]:
count += 1
shifted_num.append(count)
if i > 0:
if line_one[i] % 2 == 1:
if shifted_num[i - 1] % 2 == 0:
for j in reverse_line_two[:reverse_line_two.index(line_one[i])]:
if line_one[i] > j:
count += 1
shifted_num.append(count)
elif shifted_num[i - 1] % 2 == 1:
for j in reverse_line_two[reverse_line_two.index(line_one[i]):]:
if line_one[i] > j:
count += 1
shifted_num.append(count)
elif line_one[i] % 2 == 0:
if (shifted_num[i - 1] + shifted_num[i - 2]) % 2 == 0:
for j in reverse_line_two[:reverse_line_two.index(line_one[i])]:
if line_one[i] > j:
count += 1
shifted_num.append(count)
if (shifted_num[i - 1] + shifted_num[i - 2]) % 2 == 1:
for j in reverse_line_two[reverse_line_two.index(line_one[i]):]:
if line_one[i] > j:
count += 1
shifted_num.append(count)
print(shifted_num)
return shifted_num
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 3 23:45:39 2017
@author: ASUS
This code snippet takes the complement and reverse of a DNA string
"""
string = 'GTGGTTACGCTCCCGGGGGGGTTCTACGTGCAGATACTGTTCGGGAAGAAGGAGGCACGTCAGGGAGCGCACCCCCCGGTCTACTTGACGGTGGTGAACGTTATCGGCTGGGCCATGTCGTGGAGATAGGAAGCAGGGGAAGTGTGTAAGACAAGTGTACGTGTGTGCATATCTTTTCGTTTGTATAATGTATCGCCAGTGTTATGTCAACCCTAATCCCGGGTATTAAGGAGACAGTCGTGGATTCAGAGGGGTGTCGTCGTGAGCTAGGGGACATTCTTGTAGCGGAGATATGACAACGAGACCGTTGAACATCTTAGTTTTAAGTCTCGCCTCACCTTCCTGGCAAGCTAAACCGGTGGTTCAGCGGTGTTTTGCCCACTTAACCGCCCACCGATTAAGCCATCGACCTACCGAGGTCGGATATAGTGGACCATAGTTACCAAGAATCACCTCAGGTCTGGGCTCATGAAAGGATTAAGGGGTATACAAAAGGCACACAGCCCATCTTACGTTGATCGAGGCGGATGGTTTAAAGGTCCCAGCTTACCTTTTTCCCTTAGACGTAGACTACCGTCGAGGGAGCTGAGAGATTTCAGCCGTATTAAACAACTGAAACCGTCCAACGATACTCATATTCTACGGTGCTCAAGGTGACCGCTGACGGTGATTCTTGACCCCCCTCACTATAGAACACCTCCTATCGCACGACACATTGTCGACTTTTGACCACCCCCGGTTCCCGGGTTTACCTAGAGATCTAGGAATCACTCAAATCGTCTCTCGTGGCGGTGTGCAATGCCAAGAAGAGAAACACTACGGTCGACGAGGGGGCCTGTTATTCTAGGGACGGTCGTGCAACTGCTCCGC'
#Take the reverse
reversed_string = string[::-1]
#Create a dictionary
complement_dict = {'A':'T','T':'A','G':'C','C':'G'}
#Take the compelement of the reverse
complement_reversed_string = ""
for base in reversed_string:
complement_reversed_string += complement_dict[base]
print(complement_reversed_string)
| """
Created on Sun Sep 3 23:45:39 2017
@author: ASUS
This code snippet takes the complement and reverse of a DNA string
"""
string = 'GTGGTTACGCTCCCGGGGGGGTTCTACGTGCAGATACTGTTCGGGAAGAAGGAGGCACGTCAGGGAGCGCACCCCCCGGTCTACTTGACGGTGGTGAACGTTATCGGCTGGGCCATGTCGTGGAGATAGGAAGCAGGGGAAGTGTGTAAGACAAGTGTACGTGTGTGCATATCTTTTCGTTTGTATAATGTATCGCCAGTGTTATGTCAACCCTAATCCCGGGTATTAAGGAGACAGTCGTGGATTCAGAGGGGTGTCGTCGTGAGCTAGGGGACATTCTTGTAGCGGAGATATGACAACGAGACCGTTGAACATCTTAGTTTTAAGTCTCGCCTCACCTTCCTGGCAAGCTAAACCGGTGGTTCAGCGGTGTTTTGCCCACTTAACCGCCCACCGATTAAGCCATCGACCTACCGAGGTCGGATATAGTGGACCATAGTTACCAAGAATCACCTCAGGTCTGGGCTCATGAAAGGATTAAGGGGTATACAAAAGGCACACAGCCCATCTTACGTTGATCGAGGCGGATGGTTTAAAGGTCCCAGCTTACCTTTTTCCCTTAGACGTAGACTACCGTCGAGGGAGCTGAGAGATTTCAGCCGTATTAAACAACTGAAACCGTCCAACGATACTCATATTCTACGGTGCTCAAGGTGACCGCTGACGGTGATTCTTGACCCCCCTCACTATAGAACACCTCCTATCGCACGACACATTGTCGACTTTTGACCACCCCCGGTTCCCGGGTTTACCTAGAGATCTAGGAATCACTCAAATCGTCTCTCGTGGCGGTGTGCAATGCCAAGAAGAGAAACACTACGGTCGACGAGGGGGCCTGTTATTCTAGGGACGGTCGTGCAACTGCTCCGC'
reversed_string = string[::-1]
complement_dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
complement_reversed_string = ''
for base in reversed_string:
complement_reversed_string += complement_dict[base]
print(complement_reversed_string) |
def age_predict():
name = input("What is your name?\n")
print("Hello " + name + " it is nice to meet you!")
x = True
while x:
age = input("How old are you " + name + "?\n")
if age.isnumeric():
x = False
else:
print("Please try again.")
age_date = ((100 - (int(age))) + 2016)
print(name + " will turn 100 in the year " + str(age_date) + "!")
if ((int(age) % 2) == 0):
print(age + " is an even number!")
else:
print(age + " is an odd number :(")
if ((age_date % 3) == 0):
print("The year " + str(age_date) + " is divisible by three!")
else:
print("The year " + str(age_date) + " is not divisible by three :(")
print("The first letter of your name repeated " + age + " times is " + (
name[0] * int(age)))
age_predict()
| def age_predict():
name = input('What is your name?\n')
print('Hello ' + name + ' it is nice to meet you!')
x = True
while x:
age = input('How old are you ' + name + '?\n')
if age.isnumeric():
x = False
else:
print('Please try again.')
age_date = 100 - int(age) + 2016
print(name + ' will turn 100 in the year ' + str(age_date) + '!')
if int(age) % 2 == 0:
print(age + ' is an even number!')
else:
print(age + ' is an odd number :(')
if age_date % 3 == 0:
print('The year ' + str(age_date) + ' is divisible by three!')
else:
print('The year ' + str(age_date) + ' is not divisible by three :(')
print('The first letter of your name repeated ' + age + ' times is ' + name[0] * int(age))
age_predict() |
def get_eben(n: list):
if sum(n) % 2 == 0:
return int("".join(map(str, n)))
num = n
s = sum(num)
while s % 2 != 0:
s
def main():
t = int(input())
for _ in range(t):
length = int(input())
n = map(int, input().split())
print(get_eben(n))
if __name__=='__main__':
main()
| def get_eben(n: list):
if sum(n) % 2 == 0:
return int(''.join(map(str, n)))
num = n
s = sum(num)
while s % 2 != 0:
s
def main():
t = int(input())
for _ in range(t):
length = int(input())
n = map(int, input().split())
print(get_eben(n))
if __name__ == '__main__':
main() |
# encoding: utf-8
class Enum(object):
@classmethod
def get_keys(cls):
return filter(lambda x: not x.startswith('_'), cls.__dict__.keys())
@classmethod
def items(cls):
return map(lambda x: (x, getattr(cls, x)), cls.get_keys())
@classmethod
def get_values(cls):
return map(lambda x: getattr(cls, x), cls.get_keys())
@classmethod
def as_choices(cls):
_choices = cls.get_values()
choices = []
for choice in _choices:
choices.append((choice, cls.get_key_from_value(choice)))
return tuple(choices)
@classmethod
def inverted_choices(cls):
_choices = cls.get_keys()
choices = []
for choice in _choices:
choices.append((choice, getattr(cls, choice)))
return tuple(choices)
@classmethod
def get_key_from_value(cls, value):
for key, v in cls.__dict__.items():
if value == v:
return key
@classmethod
def get_value(cls, key):
return getattr(cls, key)
| class Enum(object):
@classmethod
def get_keys(cls):
return filter(lambda x: not x.startswith('_'), cls.__dict__.keys())
@classmethod
def items(cls):
return map(lambda x: (x, getattr(cls, x)), cls.get_keys())
@classmethod
def get_values(cls):
return map(lambda x: getattr(cls, x), cls.get_keys())
@classmethod
def as_choices(cls):
_choices = cls.get_values()
choices = []
for choice in _choices:
choices.append((choice, cls.get_key_from_value(choice)))
return tuple(choices)
@classmethod
def inverted_choices(cls):
_choices = cls.get_keys()
choices = []
for choice in _choices:
choices.append((choice, getattr(cls, choice)))
return tuple(choices)
@classmethod
def get_key_from_value(cls, value):
for (key, v) in cls.__dict__.items():
if value == v:
return key
@classmethod
def get_value(cls, key):
return getattr(cls, key) |
def euro(b, m, c):
czas = dict()
mecze = dict()
baza = dict()
wynik = ['', float('inf')]
for baz in b:
baza[baz[0]] = baz[1]
for mecz in m:
if mecz[0] not in mecze.keys():
mecze[mecz[0]] = [mecz[2]]
else:
mecze[mecz[0]].append(mecz[2])
if mecz[1] not in mecze.keys():
mecze[mecz[1]] = [mecz[2]]
else:
mecze[mecz[1]].append(mecz[2])
for polaczenie in c:
czas[repr(polaczenie[:2])] = int(polaczenie[2])
czas[repr(polaczenie[:2][::-1])] = int(polaczenie[2])
for druzyna, mlist in mecze.items():
podroze = 0
kwatera = baza[druzyna]
for me in mlist:
if me == kwatera:
continue
podroze += czas[repr([kwatera, me])]
if podroze < wynik[1]:
wynik[0] = druzyna
wynik[1] = podroze
return wynik[0]
#euro([['A', 'M1'],['B', 'M2'],['C', 'M1'],['D', 'M3']], [['A', 'B', 'M1'],['A', 'C', 'M1'],['A', 'D', 'M3'],['B', 'C', 'M1'],['B', 'D', 'M3'],['C', 'D', 'M3']], [['M1', 'M2', '1'],['M1', 'M3', '5'], ['M2', 'M3', '6']])
#euro([['D1', 'M1'],['D2', 'M2'],['D3', 'M3'],['D4', 'M4']], [['D1', 'D3', 'M5'],['D2', 'D4', 'M6'],['D1', 'D2', 'M5'],['D3', 'D4', 'M6'],['D1', 'D4', 'M5'],['D2', 'D3', 'M6']], [['M1', 'M5', '20'],['M1', 'M6', '5'],['M2', 'M5', '15'],['M2', 'M6', '10'],['M3', 'M5', '25'], ['M3', 'M6', '20'], ['M4', 'M5', '20'],['M4', 'M6', '20']])
| def euro(b, m, c):
czas = dict()
mecze = dict()
baza = dict()
wynik = ['', float('inf')]
for baz in b:
baza[baz[0]] = baz[1]
for mecz in m:
if mecz[0] not in mecze.keys():
mecze[mecz[0]] = [mecz[2]]
else:
mecze[mecz[0]].append(mecz[2])
if mecz[1] not in mecze.keys():
mecze[mecz[1]] = [mecz[2]]
else:
mecze[mecz[1]].append(mecz[2])
for polaczenie in c:
czas[repr(polaczenie[:2])] = int(polaczenie[2])
czas[repr(polaczenie[:2][::-1])] = int(polaczenie[2])
for (druzyna, mlist) in mecze.items():
podroze = 0
kwatera = baza[druzyna]
for me in mlist:
if me == kwatera:
continue
podroze += czas[repr([kwatera, me])]
if podroze < wynik[1]:
wynik[0] = druzyna
wynik[1] = podroze
return wynik[0] |
dataset_type = 'CocoDataset'
data_root = '/work/u5216579/ctr/data/PCB_v3/'#'/home/u5216579/vf/data/coco/' #'data/coco/'
img_norm_cfg = dict(
#mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
mean=[38.720, 51.155, 40.22], std=[53.275, 52.273, 46.819], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', img_scale=(512, 512), keep_ratio=True),
dict(type='Sharpness', prob=0.0, level=8),
dict(type='Rotate', prob=0.75, level=10, max_rotate_angle=360),
dict(type='Color', prob=0.6, level=6),
dict(type='ColorTransform', level=4.0, prob=0.5),
dict(type='BrightnessTransform', level=4.0, prob=0.5),
dict(type='ContrastTransform', level=4.0, prob=0.5),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(512, 512),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
#train=dict(
# type=dataset_type,
# ann_file=data_root + 'annotations/instances_train2017.json',
# img_prefix=data_root + 'train2017/',
# pipeline=train_pipeline),
#val=dict(
# type=dataset_type,
# ann_file=data_root + 'annotations/instances_val2017.json',
# img_prefix=data_root + 'val2017/',
# pipeline=test_pipeline),
#test=dict(
# type=dataset_type,
# ann_file=data_root + 'annotations/instances_val2017.json',
# img_prefix=data_root + 'val2017/',
# pipeline=test_pipeline))
train=dict(
type=dataset_type,
ann_file=data_root + 'annotations/train.json',
img_prefix=data_root + 'train/',
pipeline=train_pipeline,
filter_empty_gt=False),
val=dict(
type=dataset_type,
ann_file=data_root + 'annotations/val.json',
img_prefix=data_root + 'val/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'annotations/val.json',
img_prefix=data_root + 'val/',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='bbox')
| dataset_type = 'CocoDataset'
data_root = '/work/u5216579/ctr/data/PCB_v3/'
img_norm_cfg = dict(mean=[38.72, 51.155, 40.22], std=[53.275, 52.273, 46.819], to_rgb=True)
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(512, 512), keep_ratio=True), dict(type='Sharpness', prob=0.0, level=8), dict(type='Rotate', prob=0.75, level=10, max_rotate_angle=360), dict(type='Color', prob=0.6, level=6), dict(type='ColorTransform', level=4.0, prob=0.5), dict(type='BrightnessTransform', level=4.0, prob=0.5), dict(type='ContrastTransform', level=4.0, prob=0.5), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])]
test_pipeline = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=(512, 512), flip=False, transforms=[dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'])])]
data = dict(samples_per_gpu=2, workers_per_gpu=2, train=dict(type=dataset_type, ann_file=data_root + 'annotations/train.json', img_prefix=data_root + 'train/', pipeline=train_pipeline, filter_empty_gt=False), val=dict(type=dataset_type, ann_file=data_root + 'annotations/val.json', img_prefix=data_root + 'val/', pipeline=test_pipeline), test=dict(type=dataset_type, ann_file=data_root + 'annotations/val.json', img_prefix=data_root + 'val/', pipeline=test_pipeline))
evaluation = dict(interval=1, metric='bbox') |
def get_nd_par(ref_len, read_type, basecaller):
if read_type:
if read_type == "dRNA":
return drna_nd_par(ref_len, basecaller)
else:
return cdna_nd_par(ref_len, read_type)
else:
return dna_nd_par(ref_len, basecaller)
def seg_par(ref_len, changepoint):
if ref_len > changepoint:
xe2 = 0
xe3 = ref_len - changepoint
else:
xe2 = ref_len - changepoint
xe3 = 0
xe1 = ref_len - changepoint
return xe1, xe2, xe3
def dna_nd_par(ref_len, basecaller):
if basecaller == "albacore":
at_xe1, at_xe2, at_xe3 = seg_par(ref_len, 12)
at_mu = 9.32968110 + 0.75215056 * at_xe1 + 0.01234263 * at_xe2 ** 2 - 0.02699184 * at_xe3 ** 2
at_sigma = 0.2507 * ref_len - 0.1510
cg_xe1, cg_xe2, cg_xe3 = seg_par(ref_len, 7)
cg_mu = 4.76783156 + 0.21751512 * cg_xe1 - 0.10414613 * cg_xe2 ** 2 - 0.01647626 * cg_xe3 ** 2
cg_sigma = 0.1109 * ref_len + 0.8959
elif basecaller == "guppy":
at_xe1, at_xe2, at_xe3 = seg_par(ref_len, 16)
at_mu = 12.13283713 + 0.71843395 * at_xe1 + 0.00127124 * at_xe2 ** 2 - 0.01429113 * at_xe3 ** 2
at_sigma = 0.2138 * ref_len + 0.4799
cg_xe1, cg_xe2, cg_xe3 = seg_par(ref_len, 12)
cg_mu = 6.13526513 + 0.21219760 * cg_xe1 - 0.01249273 * cg_xe2 ** 2 - 0.04870821 * cg_xe3 ** 2
cg_sigma = 0.3021 * ref_len - 0.06803
else: # guppy-flipflop
at_xe1, at_xe2, at_xe3 = seg_par(ref_len, 12)
at_mu = 9.65577227 + 0.92524095 * at_xe1 + 0.02814258 * at_xe2 ** 2 - 0.01666699 * at_xe3 ** 2
at_sigma = 0.2013 * ref_len + 0.2159
cg_xe1, cg_xe2, cg_xe3 = seg_par(ref_len, 14)
cg_mu = 5.5402163422 - 0.0163232962 * cg_xe1 - 0.0205230566 * cg_xe2 ** 2 + 0.0009633945 * cg_xe3 ** 2
cg_sigma = 0.1514 * ref_len + 0.5611
return at_mu, at_sigma, at_mu, at_sigma, cg_mu, cg_sigma, cg_mu, cg_sigma
def drna_nd_par(ref_len, basecaller):
if basecaller == "albacore":
a_xe1, a_xe2, a_xe3 = seg_par(ref_len, 15)
a_mu = 7.920954923 + 0.060905864 * a_xe1 - 0.031587949 * a_xe2 ** 2 + 0.008346099 * a_xe3 ** 2
a_sigma = 0.21924 * ref_len + 0.08617
t_xe1, t_xe2, t_xe3 = seg_par(ref_len, 10)
t_mu = 5.57952387 + 0.11981070 * t_xe1 - 0.05381813 * t_xe2 ** 2 - 0.01851555 * t_xe3 ** 2
t_sigma = 0.1438 * ref_len + 0.9004
c_xe1, c_xe2, c_xe3 = seg_par(ref_len, 6)
c_mu = 4.34230221 + 0.23685824 * c_xe1 - 0.08072337 * c_xe2 ** 2 - 0.01720295 * c_xe3 ** 2
c_sigma = 0.06822 * ref_len + 0.87553
g_xe1, g_xe2, g_xe3 = seg_par(ref_len, 10)
g_mu = 4.5110033642 + 0.1757467623 * g_xe1 - 0.0009943928 * g_xe2 ** 2 - 0.0915431864 * g_xe3 ** 2
g_sigma = 0.1066 * ref_len + 0.8223
else: # guppy
a_xe1, a_xe2, a_xe3 = seg_par(ref_len, 16)
a_mu = 10.619825093 + 0.367474710 * a_xe1 - 0.018351943 * a_xe2 ** 2 - 0.001138652 * a_xe3 ** 2
a_sigma = 0.3128 * ref_len - 0.6731
t_xe1, t_xe2, t_xe3 = seg_par(ref_len, 18)
t_mu = 9.819245514 + 0.212176633 * t_xe1 - 0.016791683 * t_xe2 ** 2 - 0.001310379 * t_xe3 ** 2
t_sigma = 0.23963 * ref_len + 0.02851
c_xe1, c_xe2, c_xe3 = seg_par(ref_len, 9)
c_mu = 4.873485405 + 0.006877753 * c_xe1 - 0.043582044 * c_xe2 ** 2 + 0.018552245 * c_xe3 ** 2
c_sigma = 0.07976 * ref_len + 0.67479
g_xe1, g_xe2, g_xe3 = seg_par(ref_len, 7)
g_mu = 4.431945507 + 0.162662708 * g_xe1 - 0.070326449 * g_xe2 ** 2 + 0.004705819 * g_xe3 ** 2
g_sigma = 0.08815 * ref_len + 0.81112
return a_mu, a_sigma, t_mu, t_sigma, c_mu, c_sigma, g_mu, g_sigma
def cdna_nd_par(ref_len, read_type):
if read_type == "cDNA_1D":
a_xe1, a_xe2, a_xe3 = seg_par(ref_len, 17)
a_mu = 12.242619571 + 0.668226076 * a_xe1 + 0.001965846 * a_xe2 ** 2 - 0.026708831 * a_xe3 ** 2
a_sigma = 0.3703 * ref_len - 0.8779
t_xe1, t_xe2, t_xe3 = seg_par(ref_len, 14)
t_mu = 11.979887272 + 1.005918453 * t_xe1 + 0.018442004 * t_xe2 ** 2 - 0.001733806 * t_xe3 ** 2
t_sigma = 0.2374 * ref_len + 0.0647
c_xe1, c_xe2, c_xe3 = seg_par(ref_len, 7)
c_mu = 4.63015250 + 0.02288890 * c_xe1 - 0.13258183 * c_xe2 ** 2 + 0.01859354 * c_xe3 ** 2
c_sigma = 0.1805 * ref_len + 0.3770
g_xe1, g_xe2, g_xe3 = seg_par(ref_len, 6)
g_mu = 4.26732085 + 0.18475982 * g_xe1 - 0.14151564 * g_xe2 ** 2 - 0.03719026 * g_xe3 ** 2
g_sigma = 0.1065 * ref_len + 0.8318
else: # cDNA 1D2
a_xe1, a_xe2, a_xe3 = seg_par(ref_len, 16)
a_mu = 14.807216375 + 0.957883839 * a_xe1 + 0.003869761 * a_xe2 ** 2 - 0.027664685 * a_xe3 ** 2
a_sigma = 0.1842 * ref_len + 0.5642
t_xe1, t_xe2, at_xe3 = seg_par(ref_len, 12)
t_mu = 11.281353708 + 1.039742281 * t_xe1 + 0.015074972 * t_xe2 ** 2 - 0.004161978 * at_xe3 ** 2
t_sigma = 0.1842 * ref_len + 0.5642
c_xe1, c_xe2, c_xe3 = seg_par(ref_len, 11)
c_mu = 6.925880017 + 0.383403249 * c_xe1 - 0.003611025 * c_xe2 ** 2 - 0.038495472 * c_xe3 ** 2
c_sigma = 0.32113 * ref_len - 0.04017
g_xe1, g_xe2, g_xe3 = seg_par(ref_len, 14)
g_mu = 9.10846385 + 0.68454921 * g_xe1 + 0.01769293 * g_xe2 ** 2 - 0.07252329 * g_xe3 ** 2
g_sigma = 0.32113 * ref_len - 0.04017
return a_mu, a_sigma, t_mu, t_sigma, c_mu, c_sigma, g_mu, g_sigma
def get_hpmis_rate(read_type, basecaller):
if read_type:
if read_type == "dRNA":
if basecaller == "albacore":
return 0.041483
elif basecaller == "guppy":
return 0.027234
elif read_type == "cDNA_1D":
return 0.036122
else: # cDNA 1D2
return 0.040993
else: #DNA
if basecaller == "albacore":
return 0.02204
elif basecaller == "guppy":
return 0.02166
elif basecaller == "guppy-flipflop":
return 0.02215
| def get_nd_par(ref_len, read_type, basecaller):
if read_type:
if read_type == 'dRNA':
return drna_nd_par(ref_len, basecaller)
else:
return cdna_nd_par(ref_len, read_type)
else:
return dna_nd_par(ref_len, basecaller)
def seg_par(ref_len, changepoint):
if ref_len > changepoint:
xe2 = 0
xe3 = ref_len - changepoint
else:
xe2 = ref_len - changepoint
xe3 = 0
xe1 = ref_len - changepoint
return (xe1, xe2, xe3)
def dna_nd_par(ref_len, basecaller):
if basecaller == 'albacore':
(at_xe1, at_xe2, at_xe3) = seg_par(ref_len, 12)
at_mu = 9.3296811 + 0.75215056 * at_xe1 + 0.01234263 * at_xe2 ** 2 - 0.02699184 * at_xe3 ** 2
at_sigma = 0.2507 * ref_len - 0.151
(cg_xe1, cg_xe2, cg_xe3) = seg_par(ref_len, 7)
cg_mu = 4.76783156 + 0.21751512 * cg_xe1 - 0.10414613 * cg_xe2 ** 2 - 0.01647626 * cg_xe3 ** 2
cg_sigma = 0.1109 * ref_len + 0.8959
elif basecaller == 'guppy':
(at_xe1, at_xe2, at_xe3) = seg_par(ref_len, 16)
at_mu = 12.13283713 + 0.71843395 * at_xe1 + 0.00127124 * at_xe2 ** 2 - 0.01429113 * at_xe3 ** 2
at_sigma = 0.2138 * ref_len + 0.4799
(cg_xe1, cg_xe2, cg_xe3) = seg_par(ref_len, 12)
cg_mu = 6.13526513 + 0.2121976 * cg_xe1 - 0.01249273 * cg_xe2 ** 2 - 0.04870821 * cg_xe3 ** 2
cg_sigma = 0.3021 * ref_len - 0.06803
else:
(at_xe1, at_xe2, at_xe3) = seg_par(ref_len, 12)
at_mu = 9.65577227 + 0.92524095 * at_xe1 + 0.02814258 * at_xe2 ** 2 - 0.01666699 * at_xe3 ** 2
at_sigma = 0.2013 * ref_len + 0.2159
(cg_xe1, cg_xe2, cg_xe3) = seg_par(ref_len, 14)
cg_mu = 5.5402163422 - 0.0163232962 * cg_xe1 - 0.0205230566 * cg_xe2 ** 2 + 0.0009633945 * cg_xe3 ** 2
cg_sigma = 0.1514 * ref_len + 0.5611
return (at_mu, at_sigma, at_mu, at_sigma, cg_mu, cg_sigma, cg_mu, cg_sigma)
def drna_nd_par(ref_len, basecaller):
if basecaller == 'albacore':
(a_xe1, a_xe2, a_xe3) = seg_par(ref_len, 15)
a_mu = 7.920954923 + 0.060905864 * a_xe1 - 0.031587949 * a_xe2 ** 2 + 0.008346099 * a_xe3 ** 2
a_sigma = 0.21924 * ref_len + 0.08617
(t_xe1, t_xe2, t_xe3) = seg_par(ref_len, 10)
t_mu = 5.57952387 + 0.1198107 * t_xe1 - 0.05381813 * t_xe2 ** 2 - 0.01851555 * t_xe3 ** 2
t_sigma = 0.1438 * ref_len + 0.9004
(c_xe1, c_xe2, c_xe3) = seg_par(ref_len, 6)
c_mu = 4.34230221 + 0.23685824 * c_xe1 - 0.08072337 * c_xe2 ** 2 - 0.01720295 * c_xe3 ** 2
c_sigma = 0.06822 * ref_len + 0.87553
(g_xe1, g_xe2, g_xe3) = seg_par(ref_len, 10)
g_mu = 4.5110033642 + 0.1757467623 * g_xe1 - 0.0009943928 * g_xe2 ** 2 - 0.0915431864 * g_xe3 ** 2
g_sigma = 0.1066 * ref_len + 0.8223
else:
(a_xe1, a_xe2, a_xe3) = seg_par(ref_len, 16)
a_mu = 10.619825093 + 0.36747471 * a_xe1 - 0.018351943 * a_xe2 ** 2 - 0.001138652 * a_xe3 ** 2
a_sigma = 0.3128 * ref_len - 0.6731
(t_xe1, t_xe2, t_xe3) = seg_par(ref_len, 18)
t_mu = 9.819245514 + 0.212176633 * t_xe1 - 0.016791683 * t_xe2 ** 2 - 0.001310379 * t_xe3 ** 2
t_sigma = 0.23963 * ref_len + 0.02851
(c_xe1, c_xe2, c_xe3) = seg_par(ref_len, 9)
c_mu = 4.873485405 + 0.006877753 * c_xe1 - 0.043582044 * c_xe2 ** 2 + 0.018552245 * c_xe3 ** 2
c_sigma = 0.07976 * ref_len + 0.67479
(g_xe1, g_xe2, g_xe3) = seg_par(ref_len, 7)
g_mu = 4.431945507 + 0.162662708 * g_xe1 - 0.070326449 * g_xe2 ** 2 + 0.004705819 * g_xe3 ** 2
g_sigma = 0.08815 * ref_len + 0.81112
return (a_mu, a_sigma, t_mu, t_sigma, c_mu, c_sigma, g_mu, g_sigma)
def cdna_nd_par(ref_len, read_type):
if read_type == 'cDNA_1D':
(a_xe1, a_xe2, a_xe3) = seg_par(ref_len, 17)
a_mu = 12.242619571 + 0.668226076 * a_xe1 + 0.001965846 * a_xe2 ** 2 - 0.026708831 * a_xe3 ** 2
a_sigma = 0.3703 * ref_len - 0.8779
(t_xe1, t_xe2, t_xe3) = seg_par(ref_len, 14)
t_mu = 11.979887272 + 1.005918453 * t_xe1 + 0.018442004 * t_xe2 ** 2 - 0.001733806 * t_xe3 ** 2
t_sigma = 0.2374 * ref_len + 0.0647
(c_xe1, c_xe2, c_xe3) = seg_par(ref_len, 7)
c_mu = 4.6301525 + 0.0228889 * c_xe1 - 0.13258183 * c_xe2 ** 2 + 0.01859354 * c_xe3 ** 2
c_sigma = 0.1805 * ref_len + 0.377
(g_xe1, g_xe2, g_xe3) = seg_par(ref_len, 6)
g_mu = 4.26732085 + 0.18475982 * g_xe1 - 0.14151564 * g_xe2 ** 2 - 0.03719026 * g_xe3 ** 2
g_sigma = 0.1065 * ref_len + 0.8318
else:
(a_xe1, a_xe2, a_xe3) = seg_par(ref_len, 16)
a_mu = 14.807216375 + 0.957883839 * a_xe1 + 0.003869761 * a_xe2 ** 2 - 0.027664685 * a_xe3 ** 2
a_sigma = 0.1842 * ref_len + 0.5642
(t_xe1, t_xe2, at_xe3) = seg_par(ref_len, 12)
t_mu = 11.281353708 + 1.039742281 * t_xe1 + 0.015074972 * t_xe2 ** 2 - 0.004161978 * at_xe3 ** 2
t_sigma = 0.1842 * ref_len + 0.5642
(c_xe1, c_xe2, c_xe3) = seg_par(ref_len, 11)
c_mu = 6.925880017 + 0.383403249 * c_xe1 - 0.003611025 * c_xe2 ** 2 - 0.038495472 * c_xe3 ** 2
c_sigma = 0.32113 * ref_len - 0.04017
(g_xe1, g_xe2, g_xe3) = seg_par(ref_len, 14)
g_mu = 9.10846385 + 0.68454921 * g_xe1 + 0.01769293 * g_xe2 ** 2 - 0.07252329 * g_xe3 ** 2
g_sigma = 0.32113 * ref_len - 0.04017
return (a_mu, a_sigma, t_mu, t_sigma, c_mu, c_sigma, g_mu, g_sigma)
def get_hpmis_rate(read_type, basecaller):
if read_type:
if read_type == 'dRNA':
if basecaller == 'albacore':
return 0.041483
elif basecaller == 'guppy':
return 0.027234
elif read_type == 'cDNA_1D':
return 0.036122
else:
return 0.040993
elif basecaller == 'albacore':
return 0.02204
elif basecaller == 'guppy':
return 0.02166
elif basecaller == 'guppy-flipflop':
return 0.02215 |
if __name__ == "__main__":
T = int(input().strip())
correct = 1 << 32
for _ in range(T):
num = int(input().strip())
print(~num + correct)
| if __name__ == '__main__':
t = int(input().strip())
correct = 1 << 32
for _ in range(T):
num = int(input().strip())
print(~num + correct) |
def format_user(userdata, format):
result = ""
u = userdata["name"]
if format == "greeting":
result = "{}, {} {}".format(u["title"], u["first"], u["last"])
elif format == "short":
result = "{}{}".format(u["title"], u["last"])
elif format == "country":
result = userdata["nat"]
elif format == "table":
result = "{} | {} | {} | {}".format(u["first"], u["last"], u["title"], userdata["nat"])
else:
result = "{} {}".format(u["first"], u["last"])
return result
| def format_user(userdata, format):
result = ''
u = userdata['name']
if format == 'greeting':
result = '{}, {} {}'.format(u['title'], u['first'], u['last'])
elif format == 'short':
result = '{}{}'.format(u['title'], u['last'])
elif format == 'country':
result = userdata['nat']
elif format == 'table':
result = '{} | {} | {} | {}'.format(u['first'], u['last'], u['title'], userdata['nat'])
else:
result = '{} {}'.format(u['first'], u['last'])
return result |
"""
DEVA AI Oversight Tool.
Copyright 2021-2022 Gradient Institute Ltd. <info@gradientinstitute.org>
"""
| """
DEVA AI Oversight Tool.
Copyright 2021-2022 Gradient Institute Ltd. <info@gradientinstitute.org>
""" |
t = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(t[3])
print(t[-99:-7])
print(t[-99:-5])
print(t[::])
| t = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(t[3])
print(t[-99:-7])
print(t[-99:-5])
print(t[:]) |
SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {
"DEB_REPO_SCHEMA": {
"type": "object",
"required": [
"name",
"uri",
"suite",
"section"
],
"properties": {
"name": {
"type": "string"
},
"type": {
"type": "string",
"enum": ["deb"]
},
"uri": {
"type": "string"
},
"priority": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
]
},
"suite": {
"type": "string"
},
"section": {
"type": "array",
"items": {"type": "string"}
},
}
},
"RPM_REPO_SCHEMA": {
"type": "object",
"required": [
"name",
"uri",
],
"properties": {
"name": {
"type": "string"
},
"type": {
"type": "string",
"enum": ["rpm"]
},
"uri": {
"type": "string"
},
"priority": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
]
},
}
},
"REPO_SCHEMA": {
"anyOf":
[
{"$ref": "#/definitions/DEB_REPO_SCHEMA"},
{"$ref": "#/definitions/RPM_REPO_SCHEMA"}
]
},
"REPOS_SCHEMA": {
"type": "array", "items": {"$ref": "#/definitions/REPO_SCHEMA"}
}
},
"type": "object",
"required": [
"groups",
],
"properties": {
"fuel_release_match": {
"type": "object",
"properties": {
"operating_system": {
"type": "string"
}
},
"required": [
"operating_system"
]
},
"requirements": {
"type": "object",
"patternProperties": {
"^[0-9a-z_-]+$": {
"type": "object",
"anyOf": [
{"required": ["packages"]},
{"required": ["repositories"]},
{"required": ["mandatory"]}
],
"properties": {
"repositories": {
"type": "array",
"items": {
"type": "object",
"required": ["name"],
"properties": {
"name": {
"type": "string"
},
"excludes": {
"type": "array",
"items": {
"type": "object",
"patternProperties": {
r"[a-z][\w_]*": {
"type": "string"
}
}
}
}
}
}
},
"packages": {
"type": "array",
"items": {
"type": "object",
"required": ["name"],
"properties": {
"name": {
"type": "string"
},
"versions": {
"type": "array",
"items": {
"type": "string",
"pattern": "^([<>]=?|=)\s+.+$"
}
}
}
}
},
"mandatory": {
"enum": ["exact", "newest"]
}
}
}
},
"additionalProperties": False,
},
"groups": {
"type": "object",
"patternProperties": {
"^[0-9a-z_-]+$": {"$ref": "#/definitions/REPOS_SCHEMA"}
},
"additionalProperties": False,
},
"inheritance": {
"type": "object",
"patternProperties": {
"^[0-9a-z_-]+$": {"type": "string"}
},
"additionalProperties": False,
}
}
}
| schema = {'$schema': 'http://json-schema.org/draft-04/schema#', 'definitions': {'DEB_REPO_SCHEMA': {'type': 'object', 'required': ['name', 'uri', 'suite', 'section'], 'properties': {'name': {'type': 'string'}, 'type': {'type': 'string', 'enum': ['deb']}, 'uri': {'type': 'string'}, 'priority': {'anyOf': [{'type': 'integer'}, {'type': 'null'}]}, 'suite': {'type': 'string'}, 'section': {'type': 'array', 'items': {'type': 'string'}}}}, 'RPM_REPO_SCHEMA': {'type': 'object', 'required': ['name', 'uri'], 'properties': {'name': {'type': 'string'}, 'type': {'type': 'string', 'enum': ['rpm']}, 'uri': {'type': 'string'}, 'priority': {'anyOf': [{'type': 'integer'}, {'type': 'null'}]}}}, 'REPO_SCHEMA': {'anyOf': [{'$ref': '#/definitions/DEB_REPO_SCHEMA'}, {'$ref': '#/definitions/RPM_REPO_SCHEMA'}]}, 'REPOS_SCHEMA': {'type': 'array', 'items': {'$ref': '#/definitions/REPO_SCHEMA'}}}, 'type': 'object', 'required': ['groups'], 'properties': {'fuel_release_match': {'type': 'object', 'properties': {'operating_system': {'type': 'string'}}, 'required': ['operating_system']}, 'requirements': {'type': 'object', 'patternProperties': {'^[0-9a-z_-]+$': {'type': 'object', 'anyOf': [{'required': ['packages']}, {'required': ['repositories']}, {'required': ['mandatory']}], 'properties': {'repositories': {'type': 'array', 'items': {'type': 'object', 'required': ['name'], 'properties': {'name': {'type': 'string'}, 'excludes': {'type': 'array', 'items': {'type': 'object', 'patternProperties': {'[a-z][\\w_]*': {'type': 'string'}}}}}}}, 'packages': {'type': 'array', 'items': {'type': 'object', 'required': ['name'], 'properties': {'name': {'type': 'string'}, 'versions': {'type': 'array', 'items': {'type': 'string', 'pattern': '^([<>]=?|=)\\s+.+$'}}}}}, 'mandatory': {'enum': ['exact', 'newest']}}}}, 'additionalProperties': False}, 'groups': {'type': 'object', 'patternProperties': {'^[0-9a-z_-]+$': {'$ref': '#/definitions/REPOS_SCHEMA'}}, 'additionalProperties': False}, 'inheritance': {'type': 'object', 'patternProperties': {'^[0-9a-z_-]+$': {'type': 'string'}}, 'additionalProperties': False}}} |
# -*- coding: utf-8 -*-
# Author: Rodrigo E. Principe
# Email: fitoprincipe82 at gmail
# Make a prediction with weights
# one vector has n elements
# p = (element1*weight1) + (element2*weight2) + (elementn*weightn) + bias
# if p >= 0; 1; 0
def predict(vector, bias, weights):
pairs = zip(vector, weights) # [[element1, weight1], [..]]
for (element, weight) in pairs:
bias += element * weight
return 1.0 if bias >= 0.0 else 0.0
# Estimate Perceptron weights using stochastic gradient descent
def train_weights(train, l_rate, n_epoch, bias=0):
first_vector = train[0][0]
# weights = [0.0 for i in range(len(first_vector))]
weights = [random() for i in range(len(first_vector))]
# iterate over the epochs
for epoch in range(n_epoch):
# each epoch has a sum_error, starting at 0
sum_error = 0.0
for row in train:
vector = row[0]
expected = row[1]
prediction = predict(vector, bias, weights)
error = expected - prediction
sum_error += error**2
# update activation (weights[0]))
bias = bias + (l_rate * error)
# update weights
for i in range(len(vector)):
# for each element of the vector
weights[i] = weights[i] + (l_rate * error * vector[i])
# print('>epoch={}, lrate={}, error={}'.format(epoch, l_rate, sum_error))
return bias, weights
# Perceptron Algorithm With Stochastic Gradient Descent
def perceptron(train, test, l_rate, n_epoch):
predictions = list()
weights = train_weights(train, l_rate, n_epoch)
for row in test:
prediction = predict(row, weights)
predictions.append(prediction)
return(predictions)
| def predict(vector, bias, weights):
pairs = zip(vector, weights)
for (element, weight) in pairs:
bias += element * weight
return 1.0 if bias >= 0.0 else 0.0
def train_weights(train, l_rate, n_epoch, bias=0):
first_vector = train[0][0]
weights = [random() for i in range(len(first_vector))]
for epoch in range(n_epoch):
sum_error = 0.0
for row in train:
vector = row[0]
expected = row[1]
prediction = predict(vector, bias, weights)
error = expected - prediction
sum_error += error ** 2
bias = bias + l_rate * error
for i in range(len(vector)):
weights[i] = weights[i] + l_rate * error * vector[i]
return (bias, weights)
def perceptron(train, test, l_rate, n_epoch):
predictions = list()
weights = train_weights(train, l_rate, n_epoch)
for row in test:
prediction = predict(row, weights)
predictions.append(prediction)
return predictions |
{
"variables": {
"buffer_impl" : "<!(node -pe 'v=process.versions.node.split(\".\");v[0] > 0 || v[0] == 0 && v[1] >= 11 ? \"POS_0_11\" : \"PRE_0_11\"')",
"callback_style" : "<!(node -pe 'v=process.versions.v8.split(\".\");v[0] > 3 || v[0] == 3 && v[1] >= 20 ? \"POS_3_20\" : \"PRE_3_20\"')"
},
"targets": [
{
"target_name": "openvg",
"sources": [
"src/openvg.cc",
"src/egl.cc"
],
"defines": [
"NODE_BUFFER_TYPE_<(buffer_impl)",
"TYPED_ARRAY_TYPE_<(buffer_impl)",
"V8_CALLBACK_STYLE_<(callback_style)"
],
"ldflags": [
"-lGLESv2 -lEGL -lOpenVG -lSDL2",
],
"cflags": [
"-DENABLE_GDB_JIT_INTERFACE",
"-Wall",
"-I/usr/include/SDL2 -D_REENTRANT"
],
},
{
"target_name": "init-egl",
"sources": [
"src/init-egl.cc"
],
"ldflags": [
"-lGLESv2 -lEGL -lOpenVG -lSDL2",
],
"cflags": [
"-DENABLE_GDB_JIT_INTERFACE",
"-Wall",
"-I/usr/include/SDL2 -D_REENTRANT"
],
},
]
}
| {'variables': {'buffer_impl': '<!(node -pe \'v=process.versions.node.split(".");v[0] > 0 || v[0] == 0 && v[1] >= 11 ? "POS_0_11" : "PRE_0_11"\')', 'callback_style': '<!(node -pe \'v=process.versions.v8.split(".");v[0] > 3 || v[0] == 3 && v[1] >= 20 ? "POS_3_20" : "PRE_3_20"\')'}, 'targets': [{'target_name': 'openvg', 'sources': ['src/openvg.cc', 'src/egl.cc'], 'defines': ['NODE_BUFFER_TYPE_<(buffer_impl)', 'TYPED_ARRAY_TYPE_<(buffer_impl)', 'V8_CALLBACK_STYLE_<(callback_style)'], 'ldflags': ['-lGLESv2 -lEGL -lOpenVG -lSDL2'], 'cflags': ['-DENABLE_GDB_JIT_INTERFACE', '-Wall', '-I/usr/include/SDL2 -D_REENTRANT']}, {'target_name': 'init-egl', 'sources': ['src/init-egl.cc'], 'ldflags': ['-lGLESv2 -lEGL -lOpenVG -lSDL2'], 'cflags': ['-DENABLE_GDB_JIT_INTERFACE', '-Wall', '-I/usr/include/SDL2 -D_REENTRANT']}]} |
#method 'find' finds index positon of specified string
#index position starts with 0
my_fruit = "My favorite fruit is apple".find('apple')
print(my_fruit) | my_fruit = 'My favorite fruit is apple'.find('apple')
print(my_fruit) |
"""Constants for Seat Connect library."""
BASE_SESSION = 'https://msg.volkswagen.de'
BASE_AUTH = 'https://identity.vwgroup.io'
CLIENT_ID = '7f045eee-7003-4379-9968-9355ed2adb06%40apps_vw-dilab_com'
XCLIENT_ID = '28cd30c6-dee7-4529-a0e6-b1e07ff90b79'
XAPPVERSION = '3.2.6'
XAPPNAME = 'es.seatauto.connect'
USER_AGENT = 'okhttp/3.7.0'
APP_URI = 'seatconnect://oidc.login/'
HEADERS_SESSION = {
'Connection': 'keep-alive',
'Content-Type': 'application/json',
'Accept-charset': 'UTF-8',
'Accept': 'application/json',
'X-Client-Id': XCLIENT_ID,
'X-App-Version': XAPPVERSION,
'X-App-Name': XAPPNAME,
'User-Agent': USER_AGENT
}
HEADERS_AUTH = {
'Connection': 'keep-alive',
'Accept': 'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,\
image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': USER_AGENT
}
| """Constants for Seat Connect library."""
base_session = 'https://msg.volkswagen.de'
base_auth = 'https://identity.vwgroup.io'
client_id = '7f045eee-7003-4379-9968-9355ed2adb06%40apps_vw-dilab_com'
xclient_id = '28cd30c6-dee7-4529-a0e6-b1e07ff90b79'
xappversion = '3.2.6'
xappname = 'es.seatauto.connect'
user_agent = 'okhttp/3.7.0'
app_uri = 'seatconnect://oidc.login/'
headers_session = {'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Accept-charset': 'UTF-8', 'Accept': 'application/json', 'X-Client-Id': XCLIENT_ID, 'X-App-Version': XAPPVERSION, 'X-App-Name': XAPPNAME, 'User-Agent': USER_AGENT}
headers_auth = {'Connection': 'keep-alive', 'Accept': 'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp, image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': USER_AGENT} |
# File: Slicing_in_Python.py
# Description: How to slice strings in Python
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
#
# Reference to:
# [1] Valentyn N Sichkar. Slicing in Python // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Slicing_in_Python (date of access: XX.XX.XXXX)
# Initial string
dna = 'ATTCGGAGCT'
# = '0123456789'
# = 'A T T C G G A G C T'
# = '(-10)(-9)(-8)(-7)(-6)(-5)(-4)(-3)(-2)(-1)'
print(dna[1]) # Showing the 1 element - T
print(dna[1:4]) # Showing the elements from 1 to 4 - TTC
print(dna[:4]) # Showing the elements from 0 (beginning) to 4 - ATTC
print(dna[4:]) # Showing the elements from 4th to the end - GGAGCT
print(dna[-4:]) # Showing the elements from -4th counting from the end to the end - AGCT
print(dna[1:-1]) # Showing the elements from 1 to -1th - TTCGGAGC
print(dna[1:-1:2]) # Showing the elements from 1 to -1th with step 2 - TCGAG
print(dna[::-1]) # Showing the elements from the beginning to the end in revers direction with step 1 - TCGAGGCTTA
| dna = 'ATTCGGAGCT'
print(dna[1])
print(dna[1:4])
print(dna[:4])
print(dna[4:])
print(dna[-4:])
print(dna[1:-1])
print(dna[1:-1:2])
print(dna[::-1]) |
class Hund:
def __init__(self, alder, vekt):
self._alder = alder
self._vekt = vekt
self._metthet = 10
def hentAlder(self):
return self._alder
def hentVekt(self):
return self._vekt
def spring(self):
self._metthet -= 1
if self._metthet < 5:
self._vekt -= 1
def spis(self):
self._metthet += 1
if self._metthet > 7:
self._vekt += 1
| class Hund:
def __init__(self, alder, vekt):
self._alder = alder
self._vekt = vekt
self._metthet = 10
def hent_alder(self):
return self._alder
def hent_vekt(self):
return self._vekt
def spring(self):
self._metthet -= 1
if self._metthet < 5:
self._vekt -= 1
def spis(self):
self._metthet += 1
if self._metthet > 7:
self._vekt += 1 |
#
# PySNMP MIB module LLDP-EXT-DOT1-PE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LLDP-EXT-DOT1-PE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:57:50 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)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint")
ifGeneralInformationGroup, = mibBuilder.importSymbols("IF-MIB", "ifGeneralInformationGroup")
lldpXdot1StandAloneExtensions, = mibBuilder.importSymbols("LLDP-EXT-DOT1-EVB-EXTENSIONS-MIB", "lldpXdot1StandAloneExtensions")
lldpV2RemLocalDestMACAddress, lldpV2RemLocalIfIndex, lldpV2RemTimeMark, lldpV2RemIndex, lldpV2LocPortIfIndex, lldpV2Extensions, lldpV2PortConfigEntry = mibBuilder.importSymbols("LLDP-V2-MIB", "lldpV2RemLocalDestMACAddress", "lldpV2RemLocalIfIndex", "lldpV2RemTimeMark", "lldpV2RemIndex", "lldpV2LocPortIfIndex", "lldpV2Extensions", "lldpV2PortConfigEntry")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
iso, NotificationType, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, MibIdentifier, ModuleIdentity, Integer32, Counter64, Counter32, IpAddress, Bits, TimeTicks, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "MibIdentifier", "ModuleIdentity", "Integer32", "Counter64", "Counter32", "IpAddress", "Bits", "TimeTicks", "Gauge32")
DisplayString, MacAddress, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "MacAddress", "TextualConvention", "TruthValue")
lldpXDot1PEExtensions = ModuleIdentity((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2))
lldpXDot1PEExtensions.setRevisions(('2012-01-23 00:00',))
if mibBuilder.loadTexts: lldpXDot1PEExtensions.setLastUpdated('201201230000Z')
if mibBuilder.loadTexts: lldpXDot1PEExtensions.setOrganization('IEEE 802.1 Working Group')
lldpXdot1PeMIB = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1))
lldpXdot1PeObjects = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1))
lldpXdot1PeConfig = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 1))
lldpXdot1PeLocalData = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2))
lldpXdot1PeRemoteData = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3))
lldpXdot1PeConfigPortExtensionTable = MibTable((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 1, 1), )
if mibBuilder.loadTexts: lldpXdot1PeConfigPortExtensionTable.setStatus('current')
lldpXdot1PeConfigPortExtensionEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 1, 1, 1), )
lldpV2PortConfigEntry.registerAugmentions(("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeConfigPortExtensionEntry"))
lldpXdot1PeConfigPortExtensionEntry.setIndexNames(*lldpV2PortConfigEntry.getIndexNames())
if mibBuilder.loadTexts: lldpXdot1PeConfigPortExtensionEntry.setStatus('current')
lldpXdot1PeConfigPortExtensionTxEnable = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 1, 1, 1, 1), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: lldpXdot1PeConfigPortExtensionTxEnable.setStatus('current')
lldpXdot1PeLocPortExtensionTable = MibTable((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1), )
if mibBuilder.loadTexts: lldpXdot1PeLocPortExtensionTable.setStatus('current')
lldpXdot1PeLocPortExtensionEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1, 1), ).setIndexNames((0, "LLDP-V2-MIB", "lldpV2LocPortIfIndex"))
if mibBuilder.loadTexts: lldpXdot1PeLocPortExtensionEntry.setStatus('current')
lldpXdot1PeLocPECascadePortPriority = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: lldpXdot1PeLocPECascadePortPriority.setStatus('current')
lldpXdot1PeLocPEAddress = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1, 1, 2), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: lldpXdot1PeLocPEAddress.setStatus('current')
lldpXdot1PeLocPECSPAddress = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1, 1, 3), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: lldpXdot1PeLocPECSPAddress.setStatus('current')
lldpXdot1PeRemPortExtensionTable = MibTable((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1), )
if mibBuilder.loadTexts: lldpXdot1PeRemPortExtensionTable.setStatus('current')
lldpXdot1PeRemPortExtensionEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1, 1), ).setIndexNames((0, "LLDP-V2-MIB", "lldpV2RemTimeMark"), (0, "LLDP-V2-MIB", "lldpV2RemLocalIfIndex"), (0, "LLDP-V2-MIB", "lldpV2RemLocalDestMACAddress"), (0, "LLDP-V2-MIB", "lldpV2RemIndex"))
if mibBuilder.loadTexts: lldpXdot1PeRemPortExtensionEntry.setStatus('current')
lldpXdot1PeRemPECascadePortPriority = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: lldpXdot1PeRemPECascadePortPriority.setStatus('current')
lldpXdot1PeRemPEAddress = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1, 1, 2), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: lldpXdot1PeRemPEAddress.setStatus('current')
lldpXdot1PeRemPECSPAddress = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1, 1, 3), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: lldpXdot1PeRemPECSPAddress.setStatus('current')
lldpXdot1PeConformance = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2))
lldpXdot1PeCompliances = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2, 1))
lldpXdot1PeGroups = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2, 2))
lldpXdot1PeCompliance = ModuleCompliance((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2, 1, 1)).setObjects(("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeGroup"), ("LLDP-EXT-DOT1-PE-MIB", "ifGeneralInformationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
lldpXdot1PeCompliance = lldpXdot1PeCompliance.setStatus('current')
lldpXdot1PeGroup = ObjectGroup((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2, 2, 1)).setObjects(("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeConfigPortExtensionTxEnable"), ("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeLocPECascadePortPriority"), ("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeLocPEAddress"), ("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeLocPECSPAddress"), ("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeRemPECascadePortPriority"), ("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeRemPEAddress"), ("LLDP-EXT-DOT1-PE-MIB", "lldpXdot1PeRemPECSPAddress"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
lldpXdot1PeGroup = lldpXdot1PeGroup.setStatus('current')
mibBuilder.exportSymbols("LLDP-EXT-DOT1-PE-MIB", lldpXdot1PeGroup=lldpXdot1PeGroup, lldpXdot1PeLocalData=lldpXdot1PeLocalData, lldpXdot1PeLocPECSPAddress=lldpXdot1PeLocPECSPAddress, lldpXdot1PeLocPortExtensionTable=lldpXdot1PeLocPortExtensionTable, lldpXdot1PeLocPEAddress=lldpXdot1PeLocPEAddress, lldpXdot1PeGroups=lldpXdot1PeGroups, lldpXdot1PeRemPEAddress=lldpXdot1PeRemPEAddress, lldpXdot1PeCompliance=lldpXdot1PeCompliance, lldpXDot1PEExtensions=lldpXDot1PEExtensions, lldpXdot1PeRemPortExtensionTable=lldpXdot1PeRemPortExtensionTable, lldpXdot1PeObjects=lldpXdot1PeObjects, lldpXdot1PeRemPECascadePortPriority=lldpXdot1PeRemPECascadePortPriority, lldpXdot1PeRemPortExtensionEntry=lldpXdot1PeRemPortExtensionEntry, lldpXdot1PeConfigPortExtensionTxEnable=lldpXdot1PeConfigPortExtensionTxEnable, PYSNMP_MODULE_ID=lldpXDot1PEExtensions, lldpXdot1PeConfigPortExtensionEntry=lldpXdot1PeConfigPortExtensionEntry, lldpXdot1PeMIB=lldpXdot1PeMIB, lldpXdot1PeCompliances=lldpXdot1PeCompliances, lldpXdot1PeRemoteData=lldpXdot1PeRemoteData, lldpXdot1PeConfigPortExtensionTable=lldpXdot1PeConfigPortExtensionTable, lldpXdot1PeLocPECascadePortPriority=lldpXdot1PeLocPECascadePortPriority, lldpXdot1PeLocPortExtensionEntry=lldpXdot1PeLocPortExtensionEntry, lldpXdot1PeRemPECSPAddress=lldpXdot1PeRemPECSPAddress, lldpXdot1PeConformance=lldpXdot1PeConformance, lldpXdot1PeConfig=lldpXdot1PeConfig)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint')
(if_general_information_group,) = mibBuilder.importSymbols('IF-MIB', 'ifGeneralInformationGroup')
(lldp_xdot1_stand_alone_extensions,) = mibBuilder.importSymbols('LLDP-EXT-DOT1-EVB-EXTENSIONS-MIB', 'lldpXdot1StandAloneExtensions')
(lldp_v2_rem_local_dest_mac_address, lldp_v2_rem_local_if_index, lldp_v2_rem_time_mark, lldp_v2_rem_index, lldp_v2_loc_port_if_index, lldp_v2_extensions, lldp_v2_port_config_entry) = mibBuilder.importSymbols('LLDP-V2-MIB', 'lldpV2RemLocalDestMACAddress', 'lldpV2RemLocalIfIndex', 'lldpV2RemTimeMark', 'lldpV2RemIndex', 'lldpV2LocPortIfIndex', 'lldpV2Extensions', 'lldpV2PortConfigEntry')
(object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance')
(iso, notification_type, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, mib_identifier, module_identity, integer32, counter64, counter32, ip_address, bits, time_ticks, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'NotificationType', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'MibIdentifier', 'ModuleIdentity', 'Integer32', 'Counter64', 'Counter32', 'IpAddress', 'Bits', 'TimeTicks', 'Gauge32')
(display_string, mac_address, textual_convention, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'MacAddress', 'TextualConvention', 'TruthValue')
lldp_x_dot1_pe_extensions = module_identity((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2))
lldpXDot1PEExtensions.setRevisions(('2012-01-23 00:00',))
if mibBuilder.loadTexts:
lldpXDot1PEExtensions.setLastUpdated('201201230000Z')
if mibBuilder.loadTexts:
lldpXDot1PEExtensions.setOrganization('IEEE 802.1 Working Group')
lldp_xdot1_pe_mib = mib_identifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1))
lldp_xdot1_pe_objects = mib_identifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1))
lldp_xdot1_pe_config = mib_identifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 1))
lldp_xdot1_pe_local_data = mib_identifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2))
lldp_xdot1_pe_remote_data = mib_identifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3))
lldp_xdot1_pe_config_port_extension_table = mib_table((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 1, 1))
if mibBuilder.loadTexts:
lldpXdot1PeConfigPortExtensionTable.setStatus('current')
lldp_xdot1_pe_config_port_extension_entry = mib_table_row((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 1, 1, 1))
lldpV2PortConfigEntry.registerAugmentions(('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeConfigPortExtensionEntry'))
lldpXdot1PeConfigPortExtensionEntry.setIndexNames(*lldpV2PortConfigEntry.getIndexNames())
if mibBuilder.loadTexts:
lldpXdot1PeConfigPortExtensionEntry.setStatus('current')
lldp_xdot1_pe_config_port_extension_tx_enable = mib_table_column((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 1, 1, 1, 1), truth_value().clone('true')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
lldpXdot1PeConfigPortExtensionTxEnable.setStatus('current')
lldp_xdot1_pe_loc_port_extension_table = mib_table((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1))
if mibBuilder.loadTexts:
lldpXdot1PeLocPortExtensionTable.setStatus('current')
lldp_xdot1_pe_loc_port_extension_entry = mib_table_row((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1, 1)).setIndexNames((0, 'LLDP-V2-MIB', 'lldpV2LocPortIfIndex'))
if mibBuilder.loadTexts:
lldpXdot1PeLocPortExtensionEntry.setStatus('current')
lldp_xdot1_pe_loc_pe_cascade_port_priority = mib_table_column((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
lldpXdot1PeLocPECascadePortPriority.setStatus('current')
lldp_xdot1_pe_loc_pe_address = mib_table_column((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1, 1, 2), mac_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lldpXdot1PeLocPEAddress.setStatus('current')
lldp_xdot1_pe_loc_pecsp_address = mib_table_column((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 2, 1, 1, 3), mac_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lldpXdot1PeLocPECSPAddress.setStatus('current')
lldp_xdot1_pe_rem_port_extension_table = mib_table((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1))
if mibBuilder.loadTexts:
lldpXdot1PeRemPortExtensionTable.setStatus('current')
lldp_xdot1_pe_rem_port_extension_entry = mib_table_row((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1, 1)).setIndexNames((0, 'LLDP-V2-MIB', 'lldpV2RemTimeMark'), (0, 'LLDP-V2-MIB', 'lldpV2RemLocalIfIndex'), (0, 'LLDP-V2-MIB', 'lldpV2RemLocalDestMACAddress'), (0, 'LLDP-V2-MIB', 'lldpV2RemIndex'))
if mibBuilder.loadTexts:
lldpXdot1PeRemPortExtensionEntry.setStatus('current')
lldp_xdot1_pe_rem_pe_cascade_port_priority = mib_table_column((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lldpXdot1PeRemPECascadePortPriority.setStatus('current')
lldp_xdot1_pe_rem_pe_address = mib_table_column((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1, 1, 2), mac_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lldpXdot1PeRemPEAddress.setStatus('current')
lldp_xdot1_pe_rem_pecsp_address = mib_table_column((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 1, 1, 3, 1, 1, 3), mac_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lldpXdot1PeRemPECSPAddress.setStatus('current')
lldp_xdot1_pe_conformance = mib_identifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2))
lldp_xdot1_pe_compliances = mib_identifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2, 1))
lldp_xdot1_pe_groups = mib_identifier((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2, 2))
lldp_xdot1_pe_compliance = module_compliance((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2, 1, 1)).setObjects(('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeGroup'), ('LLDP-EXT-DOT1-PE-MIB', 'ifGeneralInformationGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
lldp_xdot1_pe_compliance = lldpXdot1PeCompliance.setStatus('current')
lldp_xdot1_pe_group = object_group((1, 3, 111, 2, 802, 1, 1, 13, 1, 5, 32962, 7, 2, 2, 2, 1)).setObjects(('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeConfigPortExtensionTxEnable'), ('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeLocPECascadePortPriority'), ('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeLocPEAddress'), ('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeLocPECSPAddress'), ('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeRemPECascadePortPriority'), ('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeRemPEAddress'), ('LLDP-EXT-DOT1-PE-MIB', 'lldpXdot1PeRemPECSPAddress'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
lldp_xdot1_pe_group = lldpXdot1PeGroup.setStatus('current')
mibBuilder.exportSymbols('LLDP-EXT-DOT1-PE-MIB', lldpXdot1PeGroup=lldpXdot1PeGroup, lldpXdot1PeLocalData=lldpXdot1PeLocalData, lldpXdot1PeLocPECSPAddress=lldpXdot1PeLocPECSPAddress, lldpXdot1PeLocPortExtensionTable=lldpXdot1PeLocPortExtensionTable, lldpXdot1PeLocPEAddress=lldpXdot1PeLocPEAddress, lldpXdot1PeGroups=lldpXdot1PeGroups, lldpXdot1PeRemPEAddress=lldpXdot1PeRemPEAddress, lldpXdot1PeCompliance=lldpXdot1PeCompliance, lldpXDot1PEExtensions=lldpXDot1PEExtensions, lldpXdot1PeRemPortExtensionTable=lldpXdot1PeRemPortExtensionTable, lldpXdot1PeObjects=lldpXdot1PeObjects, lldpXdot1PeRemPECascadePortPriority=lldpXdot1PeRemPECascadePortPriority, lldpXdot1PeRemPortExtensionEntry=lldpXdot1PeRemPortExtensionEntry, lldpXdot1PeConfigPortExtensionTxEnable=lldpXdot1PeConfigPortExtensionTxEnable, PYSNMP_MODULE_ID=lldpXDot1PEExtensions, lldpXdot1PeConfigPortExtensionEntry=lldpXdot1PeConfigPortExtensionEntry, lldpXdot1PeMIB=lldpXdot1PeMIB, lldpXdot1PeCompliances=lldpXdot1PeCompliances, lldpXdot1PeRemoteData=lldpXdot1PeRemoteData, lldpXdot1PeConfigPortExtensionTable=lldpXdot1PeConfigPortExtensionTable, lldpXdot1PeLocPECascadePortPriority=lldpXdot1PeLocPECascadePortPriority, lldpXdot1PeLocPortExtensionEntry=lldpXdot1PeLocPortExtensionEntry, lldpXdot1PeRemPECSPAddress=lldpXdot1PeRemPECSPAddress, lldpXdot1PeConformance=lldpXdot1PeConformance, lldpXdot1PeConfig=lldpXdot1PeConfig) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
output = ListNode(None)
outputPointer = output
carry = 0
pointer1, pointer2 = l1, l2
while pointer1 or pointer2:
if pointer1 and pointer2:
new = pointer1.val + pointer2.val
elif pointer1:
new = pointer1.val
elif pointer2:
new = pointer2.val
new += carry
if new >= 10:
carry = int(new / 10)
new -= 10
else:
carry = 0
outputPointer.next = ListNode(new)
outputPointer = outputPointer.next
pointer1 = pointer1.next if pointer1 else None
pointer2 = pointer2.next if pointer2 else None
if carry > 0:
outputPointer.next = ListNode(carry)
return output.next | class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
output = list_node(None)
output_pointer = output
carry = 0
(pointer1, pointer2) = (l1, l2)
while pointer1 or pointer2:
if pointer1 and pointer2:
new = pointer1.val + pointer2.val
elif pointer1:
new = pointer1.val
elif pointer2:
new = pointer2.val
new += carry
if new >= 10:
carry = int(new / 10)
new -= 10
else:
carry = 0
outputPointer.next = list_node(new)
output_pointer = outputPointer.next
pointer1 = pointer1.next if pointer1 else None
pointer2 = pointer2.next if pointer2 else None
if carry > 0:
outputPointer.next = list_node(carry)
return output.next |
class Trackable(object):
def __init__(self, name):
self.name = name
print('CREATE {}'.format(name))
def __del__(self):
print('DELETE {}'.format(self.name))
| class Trackable(object):
def __init__(self, name):
self.name = name
print('CREATE {}'.format(name))
def __del__(self):
print('DELETE {}'.format(self.name)) |
CURRENCY_ALGO = "ALGO"
EXCHANGE_ALGORAND_BLOCKCHAIN = "algorand_blockchain"
TRANSACTION_TYPE_PAYMENT = "pay"
TRANSACTION_TYPE_ASSET_TRANSFER = "axfer"
TRANSACTION_TYPE_APP_CALL = "appl"
APPLICATION_ID_TINYMAN_v10 = 350338509
APPLICATION_ID_TINYMAN_v11 = 552635992
APPLICATION_ID_YIELDLY = 233725848
APPLICATION_ID_YIELDLY_NLL = 233725844
APPLICATION_ID_YIELDLY_YLDY_ALGO_POOL = 233725850
APPLICATION_ID_YIELDLY_YLDY_OPUL_POOL = 348079765
APPLICATION_ID_YIELDLY_OPUL_OPUL_POOL = 367431051
APPLICATION_ID_YIELDLY_YLDY_SMILE_POOL = 352116819
APPLICATION_ID_YIELDLY_SMILE_SMILE_POOL = 373819681
APPLICATION_ID_YIELDLY_YLDY_ARCC_POOL = 385089192
APPLICATION_ID_YIELDLY_ARRC_ARCC_POOL = 498747685
APPLICATION_ID_YIELDLY_YLDY_GEMS_POOL = 393388133
APPLICATION_ID_YIELDLY_GEMS_GEMS_POOL = 419301793
APPLICATION_ID_YIELDLY_YLDY_XET_POOL = 424101057
APPLICATION_ID_YIELDLY_XET_XET_POOL = 470390215
APPLICATION_ID_YIELDLY_YLDY_CHOICE_POOL = 447336112
APPLICATION_ID_YIELDLY_CHOICE_CHOICE_POOL = 464365150
APPLICATION_ID_YIELDLY_YLDY_AKITA_POOL = 511597182
APPLICATION_ID_YIELDLY_AKITA_LP_POOL = 511593477
YIELDLY_APPLICATIONS = [
APPLICATION_ID_YIELDLY,
APPLICATION_ID_YIELDLY_NLL,
APPLICATION_ID_YIELDLY_YLDY_ALGO_POOL,
APPLICATION_ID_YIELDLY_YLDY_OPUL_POOL,
APPLICATION_ID_YIELDLY_OPUL_OPUL_POOL,
APPLICATION_ID_YIELDLY_YLDY_SMILE_POOL,
APPLICATION_ID_YIELDLY_SMILE_SMILE_POOL,
APPLICATION_ID_YIELDLY_YLDY_ARCC_POOL,
APPLICATION_ID_YIELDLY_ARRC_ARCC_POOL,
APPLICATION_ID_YIELDLY_YLDY_GEMS_POOL,
APPLICATION_ID_YIELDLY_GEMS_GEMS_POOL,
APPLICATION_ID_YIELDLY_YLDY_XET_POOL,
APPLICATION_ID_YIELDLY_XET_XET_POOL,
APPLICATION_ID_YIELDLY_YLDY_CHOICE_POOL,
APPLICATION_ID_YIELDLY_CHOICE_CHOICE_POOL,
APPLICATION_ID_YIELDLY_YLDY_AKITA_POOL,
APPLICATION_ID_YIELDLY_AKITA_LP_POOL,
]
TINYMAN_TRANSACTION_SWAP = "c3dhcA=="
TINYMAN_TRANSACTION_LP_ADD = "bWludA=="
TINYMAN_TRANSACTION_LP_REMOVE = "YnVybg=="
YIELDLY_TRANSACTION_POOL_CLAIM = "Q0E="
YIELDLY_TRANSACTION_POOL_CLOSE = "Q0FX"
| currency_algo = 'ALGO'
exchange_algorand_blockchain = 'algorand_blockchain'
transaction_type_payment = 'pay'
transaction_type_asset_transfer = 'axfer'
transaction_type_app_call = 'appl'
application_id_tinyman_v10 = 350338509
application_id_tinyman_v11 = 552635992
application_id_yieldly = 233725848
application_id_yieldly_nll = 233725844
application_id_yieldly_yldy_algo_pool = 233725850
application_id_yieldly_yldy_opul_pool = 348079765
application_id_yieldly_opul_opul_pool = 367431051
application_id_yieldly_yldy_smile_pool = 352116819
application_id_yieldly_smile_smile_pool = 373819681
application_id_yieldly_yldy_arcc_pool = 385089192
application_id_yieldly_arrc_arcc_pool = 498747685
application_id_yieldly_yldy_gems_pool = 393388133
application_id_yieldly_gems_gems_pool = 419301793
application_id_yieldly_yldy_xet_pool = 424101057
application_id_yieldly_xet_xet_pool = 470390215
application_id_yieldly_yldy_choice_pool = 447336112
application_id_yieldly_choice_choice_pool = 464365150
application_id_yieldly_yldy_akita_pool = 511597182
application_id_yieldly_akita_lp_pool = 511593477
yieldly_applications = [APPLICATION_ID_YIELDLY, APPLICATION_ID_YIELDLY_NLL, APPLICATION_ID_YIELDLY_YLDY_ALGO_POOL, APPLICATION_ID_YIELDLY_YLDY_OPUL_POOL, APPLICATION_ID_YIELDLY_OPUL_OPUL_POOL, APPLICATION_ID_YIELDLY_YLDY_SMILE_POOL, APPLICATION_ID_YIELDLY_SMILE_SMILE_POOL, APPLICATION_ID_YIELDLY_YLDY_ARCC_POOL, APPLICATION_ID_YIELDLY_ARRC_ARCC_POOL, APPLICATION_ID_YIELDLY_YLDY_GEMS_POOL, APPLICATION_ID_YIELDLY_GEMS_GEMS_POOL, APPLICATION_ID_YIELDLY_YLDY_XET_POOL, APPLICATION_ID_YIELDLY_XET_XET_POOL, APPLICATION_ID_YIELDLY_YLDY_CHOICE_POOL, APPLICATION_ID_YIELDLY_CHOICE_CHOICE_POOL, APPLICATION_ID_YIELDLY_YLDY_AKITA_POOL, APPLICATION_ID_YIELDLY_AKITA_LP_POOL]
tinyman_transaction_swap = 'c3dhcA=='
tinyman_transaction_lp_add = 'bWludA=='
tinyman_transaction_lp_remove = 'YnVybg=='
yieldly_transaction_pool_claim = 'Q0E='
yieldly_transaction_pool_close = 'Q0FX' |
XK_emspace = 0xaa1
XK_enspace = 0xaa2
XK_em3space = 0xaa3
XK_em4space = 0xaa4
XK_digitspace = 0xaa5
XK_punctspace = 0xaa6
XK_thinspace = 0xaa7
XK_hairspace = 0xaa8
XK_emdash = 0xaa9
XK_endash = 0xaaa
XK_signifblank = 0xaac
XK_ellipsis = 0xaae
XK_doubbaselinedot = 0xaaf
XK_onethird = 0xab0
XK_twothirds = 0xab1
XK_onefifth = 0xab2
XK_twofifths = 0xab3
XK_threefifths = 0xab4
XK_fourfifths = 0xab5
XK_onesixth = 0xab6
XK_fivesixths = 0xab7
XK_careof = 0xab8
XK_figdash = 0xabb
XK_leftanglebracket = 0xabc
XK_decimalpoint = 0xabd
XK_rightanglebracket = 0xabe
XK_marker = 0xabf
XK_oneeighth = 0xac3
XK_threeeighths = 0xac4
XK_fiveeighths = 0xac5
XK_seveneighths = 0xac6
XK_trademark = 0xac9
XK_signaturemark = 0xaca
XK_trademarkincircle = 0xacb
XK_leftopentriangle = 0xacc
XK_rightopentriangle = 0xacd
XK_emopencircle = 0xace
XK_emopenrectangle = 0xacf
XK_leftsinglequotemark = 0xad0
XK_rightsinglequotemark = 0xad1
XK_leftdoublequotemark = 0xad2
XK_rightdoublequotemark = 0xad3
XK_prescription = 0xad4
XK_minutes = 0xad6
XK_seconds = 0xad7
XK_latincross = 0xad9
XK_hexagram = 0xada
XK_filledrectbullet = 0xadb
XK_filledlefttribullet = 0xadc
XK_filledrighttribullet = 0xadd
XK_emfilledcircle = 0xade
XK_emfilledrect = 0xadf
XK_enopencircbullet = 0xae0
XK_enopensquarebullet = 0xae1
XK_openrectbullet = 0xae2
XK_opentribulletup = 0xae3
XK_opentribulletdown = 0xae4
XK_openstar = 0xae5
XK_enfilledcircbullet = 0xae6
XK_enfilledsqbullet = 0xae7
XK_filledtribulletup = 0xae8
XK_filledtribulletdown = 0xae9
XK_leftpointer = 0xaea
XK_rightpointer = 0xaeb
XK_club = 0xaec
XK_diamond = 0xaed
XK_heart = 0xaee
XK_maltesecross = 0xaf0
XK_dagger = 0xaf1
XK_doubledagger = 0xaf2
XK_checkmark = 0xaf3
XK_ballotcross = 0xaf4
XK_musicalsharp = 0xaf5
XK_musicalflat = 0xaf6
XK_malesymbol = 0xaf7
XK_femalesymbol = 0xaf8
XK_telephone = 0xaf9
XK_telephonerecorder = 0xafa
XK_phonographcopyright = 0xafb
XK_caret = 0xafc
XK_singlelowquotemark = 0xafd
XK_doublelowquotemark = 0xafe
XK_cursor = 0xaff
| xk_emspace = 2721
xk_enspace = 2722
xk_em3space = 2723
xk_em4space = 2724
xk_digitspace = 2725
xk_punctspace = 2726
xk_thinspace = 2727
xk_hairspace = 2728
xk_emdash = 2729
xk_endash = 2730
xk_signifblank = 2732
xk_ellipsis = 2734
xk_doubbaselinedot = 2735
xk_onethird = 2736
xk_twothirds = 2737
xk_onefifth = 2738
xk_twofifths = 2739
xk_threefifths = 2740
xk_fourfifths = 2741
xk_onesixth = 2742
xk_fivesixths = 2743
xk_careof = 2744
xk_figdash = 2747
xk_leftanglebracket = 2748
xk_decimalpoint = 2749
xk_rightanglebracket = 2750
xk_marker = 2751
xk_oneeighth = 2755
xk_threeeighths = 2756
xk_fiveeighths = 2757
xk_seveneighths = 2758
xk_trademark = 2761
xk_signaturemark = 2762
xk_trademarkincircle = 2763
xk_leftopentriangle = 2764
xk_rightopentriangle = 2765
xk_emopencircle = 2766
xk_emopenrectangle = 2767
xk_leftsinglequotemark = 2768
xk_rightsinglequotemark = 2769
xk_leftdoublequotemark = 2770
xk_rightdoublequotemark = 2771
xk_prescription = 2772
xk_minutes = 2774
xk_seconds = 2775
xk_latincross = 2777
xk_hexagram = 2778
xk_filledrectbullet = 2779
xk_filledlefttribullet = 2780
xk_filledrighttribullet = 2781
xk_emfilledcircle = 2782
xk_emfilledrect = 2783
xk_enopencircbullet = 2784
xk_enopensquarebullet = 2785
xk_openrectbullet = 2786
xk_opentribulletup = 2787
xk_opentribulletdown = 2788
xk_openstar = 2789
xk_enfilledcircbullet = 2790
xk_enfilledsqbullet = 2791
xk_filledtribulletup = 2792
xk_filledtribulletdown = 2793
xk_leftpointer = 2794
xk_rightpointer = 2795
xk_club = 2796
xk_diamond = 2797
xk_heart = 2798
xk_maltesecross = 2800
xk_dagger = 2801
xk_doubledagger = 2802
xk_checkmark = 2803
xk_ballotcross = 2804
xk_musicalsharp = 2805
xk_musicalflat = 2806
xk_malesymbol = 2807
xk_femalesymbol = 2808
xk_telephone = 2809
xk_telephonerecorder = 2810
xk_phonographcopyright = 2811
xk_caret = 2812
xk_singlelowquotemark = 2813
xk_doublelowquotemark = 2814
xk_cursor = 2815 |
firstname = str(input("Enter your first name: "))
lastname = str(input("Enter your last name: "))
print("Initials: " + firstname[0] + "." + lastname[0] + ".")
| firstname = str(input('Enter your first name: '))
lastname = str(input('Enter your last name: '))
print('Initials: ' + firstname[0] + '.' + lastname[0] + '.') |
"""
The module for training the SVM classifer.
"""
def train(database_num=3):
"""
use SVM provided by sklearn with databases to train the classifier and
dump it into a pickle.
:param database_num: 3 means NUAA, CASIA, REPLAY-ATTACK;
2 means CASIA, REPLAY-ATTACK.
"""
| """
The module for training the SVM classifer.
"""
def train(database_num=3):
"""
use SVM provided by sklearn with databases to train the classifier and
dump it into a pickle.
:param database_num: 3 means NUAA, CASIA, REPLAY-ATTACK;
2 means CASIA, REPLAY-ATTACK.
""" |
POST_JSON_RESPONSES = {
'/auth/realms/test/protocol/openid-connect/token': {
'access_token': '54604e3b-4d6a-419d-9173-4b1af0530bfb',
'token_type': 'bearer',
'expires_in': 42695,
'scope': 'read write'},
'/v2/observations': {
'dimensionDeclarations': [
{
'name': 'study',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Object',
'fields': [
{
'name': 'name',
'type': 'String'
}
]
}, {
'name': 'concept',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Object',
'fields': [
{
'name': 'conceptPath',
'type': 'String'
},
{
'name': 'conceptCode',
'type': 'String'
},
{
'name': 'name',
'type': 'String'
}
]
}, {
'name': 'patient',
'dimensionType': 'subject',
'sortIndex': 1,
'valueType': 'Object',
'fields': [
{
'name': 'id',
'type': 'Int'
},
{
'name': 'trial',
'type': 'String'
},
{
'name': 'inTrialId',
'type': 'String'
},
{
'name': 'subjectIds',
'type': 'Object'
},
{
'name': 'birthDate',
'type': 'Timestamp'
},
{
'name': 'deathDate',
'type': 'Timestamp'
},
{
'name': 'age',
'type': 'Int'
},
{
'name': 'race',
'type': 'String'
},
{
'name': 'maritalStatus',
'type': 'String'
},
{
'name': 'religion',
'type': 'String'
},
{
'name': 'sexCd',
'type': 'String'
},
{
'name': 'sex',
'type': 'String'
}
]
}, {
'name': 'visit',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Object',
'fields': [
{
'name': 'id',
'type': 'Int'
},
{
'name': 'activeStatusCd',
'type': 'String'
},
{
'name': 'startDate',
'type': 'Timestamp'
},
{
'name': 'endDate',
'type': 'Timestamp'
},
{
'name': 'inoutCd',
'type': 'String'
},
{
'name': 'locationCd',
'type': 'String'
},
{
'name': 'encounterIds',
'type': 'Object'
}
]
}, {
'name': 'start time',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Timestamp',
'inline': 'true'
}, {
'name': 'end time',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Timestamp',
'inline': 'true'
}, {
'name': 'location',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'String',
'inline': 'true'
}, {
'name': 'trial visit',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Object',
'fields': [
{
'name': 'id',
'type': 'Int'
},
{
'name': 'studyId',
'type': 'String'
},
{
'name': 'relTimeLabel',
'type': 'String'
},
{
'name': 'relTimeUnit',
'type': 'String'
},
{
'name': 'relTime',
'type': 'Int'
}
]
}, {
'name': 'provider',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'String'
}, {
'name': 'sample_type',
'dimensionType': None,
'sortIndex': None,
'valueType': 'String'
}, {
'name': 'missing_value',
'dimensionType': None,
'sortIndex': None,
'valueType': 'String'
},
{
'name': 'Diagnosis ID',
'dimensionType': 'subject',
'sortIndex': 2,
'valueType': 'String',
'modifierCode': 'CSR_DIAGNOSIS_MOD'
}],
'sort': [{
'dimension': 'concept',
'sortOrder': 'asc'
}, {
'dimension': 'provider',
'sortOrder': 'asc'
}, {
'dimension': 'patient',
'sortOrder': 'asc'
}, {
'dimension': 'visit',
'sortOrder': 'asc'
}, {
'dimension': 'start time',
'sortOrder': 'asc'
}],
'cells': [{
'inlineDimensions': [
'2019-05-05 11:11:11',
'2019-07-05 11:11:11',
'@'
],
'dimensionIndexes': [
0,
0,
1,
0,
0,
None,
None,
None,
0
],
'numericValue': 20
},
{
'inlineDimensions': [
'2019-07-22 12:00:00',
None,
'@'
],
'dimensionIndexes': [
0,
1,
0,
None,
0,
None,
None,
None,
None
],
'stringValue': 'Caucasian'
},
{
'inlineDimensions': [
None,
None,
'@'
],
'dimensionIndexes': [
0,
2,
0,
None,
0,
None,
None,
None,
None
],
'stringValue': 'Female'
}
],
'dimensionElements': {
'study': [
{
'name': 'CATEGORICAL_VALUES'
}
],
'concept': [
{
'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Age\\',
'conceptCode': 'CV:DEM:AGE',
'name': 'Age'
},
{
'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Race\\',
'conceptCode': 'CV:DEM:RACE',
'name': 'Race'
},
{
'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Female\\',
'conceptCode': 'CV:DEM:SEX:F',
'name': 'Female'
}
],
'patient': [
{
'id': 1,
'trial': 'CATEGORICAL_VALUES',
'inTrialId': '3',
'subjectIds': {
'SUBJ_ID': 'CV:40'
},
'birthDate': None,
'deathDate': None,
'age': 20,
'race': 'Caucasian',
'maritalStatus': None,
'religion': None,
'sexCd': 'Female',
'sex': 'female'
},
{
'id': 2,
'trial': 'CATEGORICAL_VALUES',
'inTrialId': '3',
'subjectIds': {
'SUBJ_ID': 'CV:12'
},
'birthDate': None,
'deathDate': None,
'age': 28,
'race': 'Caucasian',
'maritalStatus': None,
'religion': None,
'sexCd': 'Female',
'sex': 'male'
}
],
'visit': [
{
'id': 1,
'patientId': 1,
'activeStatusCd': None,
'startDate': '2016-03-29T09:00:00Z',
'endDate': '2016-03-29T11:00:00Z',
'inoutCd': None,
'locationCd': None,
'lengthOfStay': None,
'encounterIds': {
'VISIT_ID': 'EHR:62:1'
}
}
],
'trial visit': [
{
'id': 1,
'studyId': 'CATEGORICAL_VALUES',
'relTimeLabel': '1',
'relTimeUnit': None,
'relTime': None,
}
],
'provider': [],
'sample_type': [],
'missing_value': [],
'Diagnosis ID': [
'D1'
]
}
}
}
GET_JSON_RESPONSES = {
'/v2/tree_nodes?depth=0&tags=True&counts=False&constraints=False': {
'tree_nodes': [
{
'name': 'CATEGORICAL_VALUES',
'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\',
'studyId': 'CATEGORICAL_VALUES',
'type': 'STUDY',
'visualAttributes': [
'FOLDER',
'ACTIVE',
'STUDY'
],
'constraint': {
'type': 'study_name',
'studyId': 'CATEGORICAL_VALUES'
},
'metadata': {
'upload date': '2019-07-31'
},
'children': [
{
'name': 'Demography',
'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\',
'studyId': 'CATEGORICAL_VALUES',
'type': 'UNKNOWN',
'visualAttributes': [
'FOLDER',
'ACTIVE'
],
'children': [
{
'name': 'Age',
'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Age\\',
'studyId': 'CATEGORICAL_VALUES',
'conceptCode': 'CV:DEM:AGE',
'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Age\\',
'type': 'NUMERIC',
'visualAttributes': [
'LEAF',
'ACTIVE',
'NUMERICAL'
],
'constraint': {
'type': 'and',
'args': [
{
'type': 'concept',
'conceptCode': 'CV:DEM:AGE'
},
{
'type': 'study_name',
'studyId': 'CATEGORICAL_VALUES'
}
]
}
},
{
'name': 'Gender',
'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\',
'studyId': 'CATEGORICAL_VALUES',
'type': 'CATEGORICAL',
'visualAttributes': [
'FOLDER',
'ACTIVE',
'CATEGORICAL'
],
'children': [
{
'name': 'Female',
'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Female\\',
'studyId': 'CATEGORICAL_VALUES',
'conceptCode': 'CV:DEM:SEX:F',
'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Female\\',
'type': 'CATEGORICAL_OPTION',
'visualAttributes': [
'LEAF',
'ACTIVE',
'CATEGORICAL_OPTION'
],
'constraint': {
'type': 'and',
'args': [
{
'type': 'concept',
'conceptCode': 'CV:DEM:SEX:F'
},
{
'type': 'study_name',
'studyId': 'CATEGORICAL_VALUES'
}
]
}
},
{
'name': 'Male',
'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Male\\',
'studyId': 'CATEGORICAL_VALUES',
'conceptCode': 'CV:DEM:SEX:M',
'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Male\\',
'type': 'CATEGORICAL_OPTION',
'visualAttributes': [
'LEAF',
'ACTIVE',
'CATEGORICAL_OPTION'
],
'constraint': {
'type': 'and',
'args': [
{
'type': 'concept',
'conceptCode': 'CV:DEM:SEX:M'
},
{
'type': 'study_name',
'studyId': 'CATEGORICAL_VALUES'
}
]
}
}
]
},
{
'name': 'Race',
'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Race\\',
'studyId': 'CATEGORICAL_VALUES',
'conceptCode': 'CV:DEM:RACE',
'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Race\\',
'type': 'CATEGORICAL',
'visualAttributes': [
'LEAF',
'ACTIVE',
'CATEGORICAL'
],
'constraint': {
'type': 'and',
'args': [
{
'type': 'concept',
'conceptCode': 'CV:DEM:RACE'
},
{
'type': 'study_name',
'studyId': 'CATEGORICAL_VALUES'
}
]
}
}
]
}
]
}
]
},
'/v2/dimensions': {
'dimensions': [
{
'name': 'study',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Object',
'fields': [{'name': 'name', 'type': 'String'}],
'inline': False
},
{
'name': 'patient',
'dimensionType': 'subject',
'sortIndex': 1,
'valueType': 'Object',
'fields': [
{'name': 'id', 'type': 'Int'},
{'name': 'subjectIds', 'type': 'Object'},
{'name': 'age', 'type': 'Int'},
{'name': 'sex', 'type': 'String'}
],
'inline': False
},
{
'name': 'concept',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Object',
'fields': [
{'name': 'conceptPath', 'type': 'String'},
{'name': 'conceptCode', 'type': 'String'},
{'name': 'name', 'type': 'String'}
],
'inline': False
},
{
'name': 'trial visit',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Object',
'fields': [
{'name': 'id', 'type': 'Int'},
{'name': 'relTimeLabel', 'type': 'String'},
{'name': 'relTimeUnit', 'type': 'String'},
{'name': 'relTime', 'type': 'Int'}
],
'inline': False
},
{
'name': 'start time',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Timestamp',
'inline': True
},
{
'name': 'visit',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Object',
'fields': [
{'name': 'id', 'type': 'Int'},
{'name': 'activeStatusCd', 'type': 'String'},
{'name': 'startDate', 'type': 'Timestamp'},
{'name': 'endDate', 'type': 'Timestamp'},
{'name': 'inoutCd', 'type': 'String'},
{'name': 'locationCd', 'type': 'String'},
{'name': 'encounterIds', 'type': 'Object'}
],
'inline': False
},
{
'name': 'end time',
'dimensionType': 'attribute',
'sortIndex': None,
'valueType': 'Timestamp',
'inline': True
},
{
'name': 'Diagnosis ID',
'modifierCode': 'CSR_DIAGNOSIS_MOD',
'dimensionType': 'subject',
'sortIndex': 2,
'valueType': 'String',
'inline': False
},
{
'name': 'Biomaterial ID',
'modifierCode': 'CSR_BIOMATERIAL_MOD',
'dimensionType': 'subject',
'sortIndex': 4,
'valueType': 'String',
'inline': False
},
{
'name': 'Biosource ID',
'modifierCode': 'CSR_BIOSOURCE_MOD',
'dimensionType': 'subject',
'sortIndex': 3,
'valueType': 'String',
'inline': False
}
]
},
'/v2/studies': {
'studies': [
{
'id': 1,
'studyId': 'CATEGORICAL_VALUES',
'bioExperimentId': None,
'secureObjectToken': 'PUBLIC',
'dimensions': [
'study',
'concept',
'patient'
],
'metadata': {
'conceptCodeToVariableMetadata': {
'gender': {
'columns': 14,
'decimals': None,
'description': 'Gender',
'measure': 'NOMINAL',
'missingValues': {
'lower': None,
'upper': None,
'values': [
-2
]
},
'name': 'gender1',
'type': 'NUMERIC',
'valueLabels': {
'1': 'Female',
'2': 'Male',
'-2': 'Not Specified'
},
'width': 12
},
'birthdate': {
'columns': 22,
'decimals': None,
'description': 'Birth Date',
'measure': 'SCALE',
'missingValues': None,
'name': 'birthdate1',
'type': 'DATE',
'valueLabels': {},
'width': 22
}
}
}
}
]
},
'/v2/pedigree/relation_types': {
'relationTypes': [
{
'id': 1, 'biological': False, 'description': 'Parent', 'label': 'PAR', 'symmetrical': False
},
{
'id': 2, 'biological': False, 'description': 'Spouse', 'label': 'SPO', 'symmetrical': True
},
{
'id': 3, 'biological': False, 'description': 'Sibling', 'label': 'SIB', 'symmetrical': True
},
{
'id': 4, 'biological': True, 'description': 'Monozygotic twin', 'label': 'MZ', 'symmetrical': True
},
{
'id': 5, 'biological': True, 'description': 'Dizygotic twin', 'label': 'DZ', 'symmetrical': True
},
{
'id': 6, 'biological': True, 'description': 'Twin with unknown zygosity', 'label': 'COT', 'symmetrical': True
},
{
'id': 7, 'biological': False, 'description': 'Child', 'label': 'CHI', 'symmetrical': False
}
]
},
'/v2/pedigree/relations': {
'relations': [
{
'leftSubjectId': 1,
'relationTypeLabel': 'SPO',
'rightSubjectId': 2,
'biological': False,
'shareHousehold': False
}
]
}
}
| post_json_responses = {'/auth/realms/test/protocol/openid-connect/token': {'access_token': '54604e3b-4d6a-419d-9173-4b1af0530bfb', 'token_type': 'bearer', 'expires_in': 42695, 'scope': 'read write'}, '/v2/observations': {'dimensionDeclarations': [{'name': 'study', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Object', 'fields': [{'name': 'name', 'type': 'String'}]}, {'name': 'concept', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Object', 'fields': [{'name': 'conceptPath', 'type': 'String'}, {'name': 'conceptCode', 'type': 'String'}, {'name': 'name', 'type': 'String'}]}, {'name': 'patient', 'dimensionType': 'subject', 'sortIndex': 1, 'valueType': 'Object', 'fields': [{'name': 'id', 'type': 'Int'}, {'name': 'trial', 'type': 'String'}, {'name': 'inTrialId', 'type': 'String'}, {'name': 'subjectIds', 'type': 'Object'}, {'name': 'birthDate', 'type': 'Timestamp'}, {'name': 'deathDate', 'type': 'Timestamp'}, {'name': 'age', 'type': 'Int'}, {'name': 'race', 'type': 'String'}, {'name': 'maritalStatus', 'type': 'String'}, {'name': 'religion', 'type': 'String'}, {'name': 'sexCd', 'type': 'String'}, {'name': 'sex', 'type': 'String'}]}, {'name': 'visit', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Object', 'fields': [{'name': 'id', 'type': 'Int'}, {'name': 'activeStatusCd', 'type': 'String'}, {'name': 'startDate', 'type': 'Timestamp'}, {'name': 'endDate', 'type': 'Timestamp'}, {'name': 'inoutCd', 'type': 'String'}, {'name': 'locationCd', 'type': 'String'}, {'name': 'encounterIds', 'type': 'Object'}]}, {'name': 'start time', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Timestamp', 'inline': 'true'}, {'name': 'end time', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Timestamp', 'inline': 'true'}, {'name': 'location', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'String', 'inline': 'true'}, {'name': 'trial visit', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Object', 'fields': [{'name': 'id', 'type': 'Int'}, {'name': 'studyId', 'type': 'String'}, {'name': 'relTimeLabel', 'type': 'String'}, {'name': 'relTimeUnit', 'type': 'String'}, {'name': 'relTime', 'type': 'Int'}]}, {'name': 'provider', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'String'}, {'name': 'sample_type', 'dimensionType': None, 'sortIndex': None, 'valueType': 'String'}, {'name': 'missing_value', 'dimensionType': None, 'sortIndex': None, 'valueType': 'String'}, {'name': 'Diagnosis ID', 'dimensionType': 'subject', 'sortIndex': 2, 'valueType': 'String', 'modifierCode': 'CSR_DIAGNOSIS_MOD'}], 'sort': [{'dimension': 'concept', 'sortOrder': 'asc'}, {'dimension': 'provider', 'sortOrder': 'asc'}, {'dimension': 'patient', 'sortOrder': 'asc'}, {'dimension': 'visit', 'sortOrder': 'asc'}, {'dimension': 'start time', 'sortOrder': 'asc'}], 'cells': [{'inlineDimensions': ['2019-05-05 11:11:11', '2019-07-05 11:11:11', '@'], 'dimensionIndexes': [0, 0, 1, 0, 0, None, None, None, 0], 'numericValue': 20}, {'inlineDimensions': ['2019-07-22 12:00:00', None, '@'], 'dimensionIndexes': [0, 1, 0, None, 0, None, None, None, None], 'stringValue': 'Caucasian'}, {'inlineDimensions': [None, None, '@'], 'dimensionIndexes': [0, 2, 0, None, 0, None, None, None, None], 'stringValue': 'Female'}], 'dimensionElements': {'study': [{'name': 'CATEGORICAL_VALUES'}], 'concept': [{'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Age\\', 'conceptCode': 'CV:DEM:AGE', 'name': 'Age'}, {'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Race\\', 'conceptCode': 'CV:DEM:RACE', 'name': 'Race'}, {'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Female\\', 'conceptCode': 'CV:DEM:SEX:F', 'name': 'Female'}], 'patient': [{'id': 1, 'trial': 'CATEGORICAL_VALUES', 'inTrialId': '3', 'subjectIds': {'SUBJ_ID': 'CV:40'}, 'birthDate': None, 'deathDate': None, 'age': 20, 'race': 'Caucasian', 'maritalStatus': None, 'religion': None, 'sexCd': 'Female', 'sex': 'female'}, {'id': 2, 'trial': 'CATEGORICAL_VALUES', 'inTrialId': '3', 'subjectIds': {'SUBJ_ID': 'CV:12'}, 'birthDate': None, 'deathDate': None, 'age': 28, 'race': 'Caucasian', 'maritalStatus': None, 'religion': None, 'sexCd': 'Female', 'sex': 'male'}], 'visit': [{'id': 1, 'patientId': 1, 'activeStatusCd': None, 'startDate': '2016-03-29T09:00:00Z', 'endDate': '2016-03-29T11:00:00Z', 'inoutCd': None, 'locationCd': None, 'lengthOfStay': None, 'encounterIds': {'VISIT_ID': 'EHR:62:1'}}], 'trial visit': [{'id': 1, 'studyId': 'CATEGORICAL_VALUES', 'relTimeLabel': '1', 'relTimeUnit': None, 'relTime': None}], 'provider': [], 'sample_type': [], 'missing_value': [], 'Diagnosis ID': ['D1']}}}
get_json_responses = {'/v2/tree_nodes?depth=0&tags=True&counts=False&constraints=False': {'tree_nodes': [{'name': 'CATEGORICAL_VALUES', 'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\', 'studyId': 'CATEGORICAL_VALUES', 'type': 'STUDY', 'visualAttributes': ['FOLDER', 'ACTIVE', 'STUDY'], 'constraint': {'type': 'study_name', 'studyId': 'CATEGORICAL_VALUES'}, 'metadata': {'upload date': '2019-07-31'}, 'children': [{'name': 'Demography', 'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\', 'studyId': 'CATEGORICAL_VALUES', 'type': 'UNKNOWN', 'visualAttributes': ['FOLDER', 'ACTIVE'], 'children': [{'name': 'Age', 'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Age\\', 'studyId': 'CATEGORICAL_VALUES', 'conceptCode': 'CV:DEM:AGE', 'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Age\\', 'type': 'NUMERIC', 'visualAttributes': ['LEAF', 'ACTIVE', 'NUMERICAL'], 'constraint': {'type': 'and', 'args': [{'type': 'concept', 'conceptCode': 'CV:DEM:AGE'}, {'type': 'study_name', 'studyId': 'CATEGORICAL_VALUES'}]}}, {'name': 'Gender', 'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\', 'studyId': 'CATEGORICAL_VALUES', 'type': 'CATEGORICAL', 'visualAttributes': ['FOLDER', 'ACTIVE', 'CATEGORICAL'], 'children': [{'name': 'Female', 'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Female\\', 'studyId': 'CATEGORICAL_VALUES', 'conceptCode': 'CV:DEM:SEX:F', 'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Female\\', 'type': 'CATEGORICAL_OPTION', 'visualAttributes': ['LEAF', 'ACTIVE', 'CATEGORICAL_OPTION'], 'constraint': {'type': 'and', 'args': [{'type': 'concept', 'conceptCode': 'CV:DEM:SEX:F'}, {'type': 'study_name', 'studyId': 'CATEGORICAL_VALUES'}]}}, {'name': 'Male', 'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Male\\', 'studyId': 'CATEGORICAL_VALUES', 'conceptCode': 'CV:DEM:SEX:M', 'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Gender\\Male\\', 'type': 'CATEGORICAL_OPTION', 'visualAttributes': ['LEAF', 'ACTIVE', 'CATEGORICAL_OPTION'], 'constraint': {'type': 'and', 'args': [{'type': 'concept', 'conceptCode': 'CV:DEM:SEX:M'}, {'type': 'study_name', 'studyId': 'CATEGORICAL_VALUES'}]}}]}, {'name': 'Race', 'fullName': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Race\\', 'studyId': 'CATEGORICAL_VALUES', 'conceptCode': 'CV:DEM:RACE', 'conceptPath': '\\Public Studies\\CATEGORICAL_VALUES\\Demography\\Race\\', 'type': 'CATEGORICAL', 'visualAttributes': ['LEAF', 'ACTIVE', 'CATEGORICAL'], 'constraint': {'type': 'and', 'args': [{'type': 'concept', 'conceptCode': 'CV:DEM:RACE'}, {'type': 'study_name', 'studyId': 'CATEGORICAL_VALUES'}]}}]}]}]}, '/v2/dimensions': {'dimensions': [{'name': 'study', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Object', 'fields': [{'name': 'name', 'type': 'String'}], 'inline': False}, {'name': 'patient', 'dimensionType': 'subject', 'sortIndex': 1, 'valueType': 'Object', 'fields': [{'name': 'id', 'type': 'Int'}, {'name': 'subjectIds', 'type': 'Object'}, {'name': 'age', 'type': 'Int'}, {'name': 'sex', 'type': 'String'}], 'inline': False}, {'name': 'concept', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Object', 'fields': [{'name': 'conceptPath', 'type': 'String'}, {'name': 'conceptCode', 'type': 'String'}, {'name': 'name', 'type': 'String'}], 'inline': False}, {'name': 'trial visit', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Object', 'fields': [{'name': 'id', 'type': 'Int'}, {'name': 'relTimeLabel', 'type': 'String'}, {'name': 'relTimeUnit', 'type': 'String'}, {'name': 'relTime', 'type': 'Int'}], 'inline': False}, {'name': 'start time', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Timestamp', 'inline': True}, {'name': 'visit', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Object', 'fields': [{'name': 'id', 'type': 'Int'}, {'name': 'activeStatusCd', 'type': 'String'}, {'name': 'startDate', 'type': 'Timestamp'}, {'name': 'endDate', 'type': 'Timestamp'}, {'name': 'inoutCd', 'type': 'String'}, {'name': 'locationCd', 'type': 'String'}, {'name': 'encounterIds', 'type': 'Object'}], 'inline': False}, {'name': 'end time', 'dimensionType': 'attribute', 'sortIndex': None, 'valueType': 'Timestamp', 'inline': True}, {'name': 'Diagnosis ID', 'modifierCode': 'CSR_DIAGNOSIS_MOD', 'dimensionType': 'subject', 'sortIndex': 2, 'valueType': 'String', 'inline': False}, {'name': 'Biomaterial ID', 'modifierCode': 'CSR_BIOMATERIAL_MOD', 'dimensionType': 'subject', 'sortIndex': 4, 'valueType': 'String', 'inline': False}, {'name': 'Biosource ID', 'modifierCode': 'CSR_BIOSOURCE_MOD', 'dimensionType': 'subject', 'sortIndex': 3, 'valueType': 'String', 'inline': False}]}, '/v2/studies': {'studies': [{'id': 1, 'studyId': 'CATEGORICAL_VALUES', 'bioExperimentId': None, 'secureObjectToken': 'PUBLIC', 'dimensions': ['study', 'concept', 'patient'], 'metadata': {'conceptCodeToVariableMetadata': {'gender': {'columns': 14, 'decimals': None, 'description': 'Gender', 'measure': 'NOMINAL', 'missingValues': {'lower': None, 'upper': None, 'values': [-2]}, 'name': 'gender1', 'type': 'NUMERIC', 'valueLabels': {'1': 'Female', '2': 'Male', '-2': 'Not Specified'}, 'width': 12}, 'birthdate': {'columns': 22, 'decimals': None, 'description': 'Birth Date', 'measure': 'SCALE', 'missingValues': None, 'name': 'birthdate1', 'type': 'DATE', 'valueLabels': {}, 'width': 22}}}}]}, '/v2/pedigree/relation_types': {'relationTypes': [{'id': 1, 'biological': False, 'description': 'Parent', 'label': 'PAR', 'symmetrical': False}, {'id': 2, 'biological': False, 'description': 'Spouse', 'label': 'SPO', 'symmetrical': True}, {'id': 3, 'biological': False, 'description': 'Sibling', 'label': 'SIB', 'symmetrical': True}, {'id': 4, 'biological': True, 'description': 'Monozygotic twin', 'label': 'MZ', 'symmetrical': True}, {'id': 5, 'biological': True, 'description': 'Dizygotic twin', 'label': 'DZ', 'symmetrical': True}, {'id': 6, 'biological': True, 'description': 'Twin with unknown zygosity', 'label': 'COT', 'symmetrical': True}, {'id': 7, 'biological': False, 'description': 'Child', 'label': 'CHI', 'symmetrical': False}]}, '/v2/pedigree/relations': {'relations': [{'leftSubjectId': 1, 'relationTypeLabel': 'SPO', 'rightSubjectId': 2, 'biological': False, 'shareHousehold': False}]}} |
def ends_with_punctuation(string):
if string is None:
return False
for punctuation in ['.', '!', '?']:
if string.rstrip().endswith(punctuation):
return True
return False
| def ends_with_punctuation(string):
if string is None:
return False
for punctuation in ['.', '!', '?']:
if string.rstrip().endswith(punctuation):
return True
return False |
# PREDSTORM L1 input parameters file
# ----------------------------------
# If True, show interpolated data points on the DSCOVR input plot
showinterpolated = True
# Time interval for both the observed and predicted windDelta T (hours), start with 24 hours here (covers 1 night of aurora)
deltat = 24
# Time range of training data (in example 4 solar minimum years as training data for 2018)
trainstart = '2006-01-01 00:00'
trainend = '2010-01-01 00:00'
| showinterpolated = True
deltat = 24
trainstart = '2006-01-01 00:00'
trainend = '2010-01-01 00:00' |
size = int(input())
matrix = []
for _ in range(size):
matrix.append([int(x) for x in input().split()])
primary_diagonal_sum = 0
secondary_diagonal_sum = 0
for i in range(len(matrix)):
primary_diagonal_sum += matrix[i][i]
secondary_diagonal_sum += matrix[i][size - i - 1]
total = abs(primary_diagonal_sum - secondary_diagonal_sum)
print(total)
| size = int(input())
matrix = []
for _ in range(size):
matrix.append([int(x) for x in input().split()])
primary_diagonal_sum = 0
secondary_diagonal_sum = 0
for i in range(len(matrix)):
primary_diagonal_sum += matrix[i][i]
secondary_diagonal_sum += matrix[i][size - i - 1]
total = abs(primary_diagonal_sum - secondary_diagonal_sum)
print(total) |
class BlockLinkedList:
def __init__(self):
self.size = 0
self.header = None
self.trailer = None
def addbh(self, block):
if self.size == 0:
self.trailer = block
else:
block.set_next(self.header)
self.header.set_previous(block)
self.header = block
self.size += 1
def addbt(self, block):
if self.size == 0:
self.header = block
else:
block.set_previous(self.trailer)
self.trailer.set_next(block)
self.trailer = block
self.size += 1
def rembh(self):
if self.size == 0:
return None
else:
self.size -= 1
b = self.header
self.header = self.header.get_next()
def rembt(self):
if self.size == 0:
return None
else:
self.size -= 1
b = self.trailer
self.trailer = self.trailer.get_previous() | class Blocklinkedlist:
def __init__(self):
self.size = 0
self.header = None
self.trailer = None
def addbh(self, block):
if self.size == 0:
self.trailer = block
else:
block.set_next(self.header)
self.header.set_previous(block)
self.header = block
self.size += 1
def addbt(self, block):
if self.size == 0:
self.header = block
else:
block.set_previous(self.trailer)
self.trailer.set_next(block)
self.trailer = block
self.size += 1
def rembh(self):
if self.size == 0:
return None
else:
self.size -= 1
b = self.header
self.header = self.header.get_next()
def rembt(self):
if self.size == 0:
return None
else:
self.size -= 1
b = self.trailer
self.trailer = self.trailer.get_previous() |
# -*- coding:utf-8 -*-
# package information.
INFO = dict(
name = "exputils",
description = "Utilities for experiment analysis",
author = "Yohsuke T. Fukai",
author_email = "ysk@yfukai.net",
license = "MIT License",
url = "",
classifiers = [
"Programming Language :: Python :: 3.6",
"License :: OSI Approved :: MIT License"
]
)
| info = dict(name='exputils', description='Utilities for experiment analysis', author='Yohsuke T. Fukai', author_email='ysk@yfukai.net', license='MIT License', url='', classifiers=['Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License']) |
"""
from rest_framework.serializers import ModelSerializer
from netbox_newplugin.models import MyModel1
class MyModel1Serializer(ModelSerializer):
class Meta:
model = MyModel1
fields = '__all__'
"""
| """
from rest_framework.serializers import ModelSerializer
from netbox_newplugin.models import MyModel1
class MyModel1Serializer(ModelSerializer):
class Meta:
model = MyModel1
fields = '__all__'
""" |
# Given a linked list, determine if it has a cycle in it.
#
# To represent a cycle in the given linked list, we use an integer pos which
# represents the position (0-indexed) in the linked list where tail connects to.
# If pos is -1, then there is no cycle in the linked list.
#
# Input: head = [3,2,0,-4], pos = 1
# Output: true
# Explanation: There is a cycle in the linked list, where tail connects to the second node.
#
# Input: head = [1], pos = -1
# Output: false
# Explanation: There is no cycle in the linked list.
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def isCycle(self, head):
pointer1 = head
pointer2 = head.next
while pointer1 != pointer2:
if pointer2 is None or pointer2.next is None:
return False
pointer1 = pointer1.next
pointer2 = pointer2.next.next
return True
if __name__ == "__main__":
arr = [3, 2, 0, -4]
node = ListNode(arr[0])
n = node
for i in arr[1:]:
n.next = ListNode(i)
n = n.next
ans = Solution().isCycle(node)
print(ans)
| class Listnode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def is_cycle(self, head):
pointer1 = head
pointer2 = head.next
while pointer1 != pointer2:
if pointer2 is None or pointer2.next is None:
return False
pointer1 = pointer1.next
pointer2 = pointer2.next.next
return True
if __name__ == '__main__':
arr = [3, 2, 0, -4]
node = list_node(arr[0])
n = node
for i in arr[1:]:
n.next = list_node(i)
n = n.next
ans = solution().isCycle(node)
print(ans) |
def print_table(n):
""" (int) -> NoneType
Print the multiplication table for numbers 1 through n inclusive.
>>> print_table(5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
"""
# The numbers to include in the table.
numbers = list(range(1, n + 1))
# Print the header row.
for i in numbers:
print('\t' + str(i), end='')
# End the header row.
print()
# Print each row number and the contents of each row.
for i in numbers:
print (i, end='')
for j in numbers:
print('\t' + str(i * j), end='')
# End the current row.
print()
| def print_table(n):
""" (int) -> NoneType
Print the multiplication table for numbers 1 through n inclusive.
>>> print_table(5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
"""
numbers = list(range(1, n + 1))
for i in numbers:
print('\t' + str(i), end='')
print()
for i in numbers:
print(i, end='')
for j in numbers:
print('\t' + str(i * j), end='')
print() |
# %% [492. Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle/)
class Solution:
def constructRectangle(self, area: int) -> List[int]:
w = int(area ** 0.5)
while area % w:
w -= 1
return area // w, w
| class Solution:
def construct_rectangle(self, area: int) -> List[int]:
w = int(area ** 0.5)
while area % w:
w -= 1
return (area // w, w) |
"""Empty test.
Empty so that tox can be used for CI in Github actions
"""
# def test_sum():
# assert sum([1, 2, 3]) == 6, "Should be 6"
def test():
assert True is True | """Empty test.
Empty so that tox can be used for CI in Github actions
"""
def test():
assert True is True |
def generateMatrix(n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = [[0 for i in range(n)] for j in range(n)]
# i = j = 0
# blow = 0
# bhigh = n-1
# for num in range(1, n ** 2 +1):
# ans[i][j] = num
# if j < bhigh and i == blow:
# j += 1
# continue
# if i < bhigh and j == bhigh:
# i += 1
# continue
# if j > blow and i == bhigh:
# j -= 1
# if j == blow:
# blow += 1
# continue
# if i > blow and j == blow-1:
# i -= 1
# if i == blow:
# bhigh -= 1
# continue
row = list(range(n))
col = list(range(n))
num = 1
while row or col:
for j in col:
ans[row[0]][j] = num
num += 1
row.pop(0)
for i in row:
ans[i][col[-1]] = num
num += 1
col.pop(-1)
col.reverse()
row.reverse()
return ans
print(generateMatrix(10))
print() | def generate_matrix(n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = [[0 for i in range(n)] for j in range(n)]
row = list(range(n))
col = list(range(n))
num = 1
while row or col:
for j in col:
ans[row[0]][j] = num
num += 1
row.pop(0)
for i in row:
ans[i][col[-1]] = num
num += 1
col.pop(-1)
col.reverse()
row.reverse()
return ans
print(generate_matrix(10))
print() |
# config.py
class Config(object):
embed_size = 300
in_channels = 1
num_channels = 100
kernel_size = [3,4,5]
output_size = 4
max_epochs = 10
lr = 0.25
batch_size = 64
max_sen_len = 20
dropout_keep = 0.6 | class Config(object):
embed_size = 300
in_channels = 1
num_channels = 100
kernel_size = [3, 4, 5]
output_size = 4
max_epochs = 10
lr = 0.25
batch_size = 64
max_sen_len = 20
dropout_keep = 0.6 |
# Byte code returned from flask-http in the case of auth failure.
NOT_AUTHORIZED_BYTE_STRING = b'Unauthorized Access'
def check_for_unauthorized_response(res):
"""
Raise an Unauthorized exception only if the response object contains the Not Authorized
byte string.
:param res: Response object to check.
:raise Unauthorized: If the response object contains the Not Authorized byte string.
"""
if not isinstance(res, dict):
if res.response and len(res.response) > 0 and isinstance(res.response[0], bytes):
if res.response[0] == NOT_AUTHORIZED_BYTE_STRING:
raise Unauthorized("Not Authorized")
| not_authorized_byte_string = b'Unauthorized Access'
def check_for_unauthorized_response(res):
"""
Raise an Unauthorized exception only if the response object contains the Not Authorized
byte string.
:param res: Response object to check.
:raise Unauthorized: If the response object contains the Not Authorized byte string.
"""
if not isinstance(res, dict):
if res.response and len(res.response) > 0 and isinstance(res.response[0], bytes):
if res.response[0] == NOT_AUTHORIZED_BYTE_STRING:
raise unauthorized('Not Authorized') |
class Color:
def __init__(self, r, g, b, alpha=255):
self.r = r
self.g = g
self.b = b
self.alpha = alpha
if self.r < 0 or self.g < 0 or self.b < 0 or self.alpha < 0:
raise ValueError("color values can't be below 0")
if self.r > 255 or self.g > 255 or self.b > 255 or self.alpha > 255:
raise ValueError("color values can't be above 255")
# Get the floating point representation between 0 and 1
def scale_down(self):
return Color(self.r / 255, self.g / 255, self.b / 255, self.alpha / 255) | class Color:
def __init__(self, r, g, b, alpha=255):
self.r = r
self.g = g
self.b = b
self.alpha = alpha
if self.r < 0 or self.g < 0 or self.b < 0 or (self.alpha < 0):
raise value_error("color values can't be below 0")
if self.r > 255 or self.g > 255 or self.b > 255 or (self.alpha > 255):
raise value_error("color values can't be above 255")
def scale_down(self):
return color(self.r / 255, self.g / 255, self.b / 255, self.alpha / 255) |
def ConverterTempo(tempo, unidade):
if unidade == "m":
return tempo*60
if unidade == "s":
return tempo
def ConverteMetros(quantidade, unidade):
if unidade == "M":
return quantidade*100
if unidade == "m":
return quantidade | def converter_tempo(tempo, unidade):
if unidade == 'm':
return tempo * 60
if unidade == 's':
return tempo
def converte_metros(quantidade, unidade):
if unidade == 'M':
return quantidade * 100
if unidade == 'm':
return quantidade |
class TokenType(object):
END = ""
ILLEGAL = "ILLEGAL"
# Operators
PLUS = "+"
MINUS = "-"
SLASH = "/"
AT = "@"
# Identifiers
NUMBER = "NUMBER"
MODIFIER = "MODIFIER"
# keywords
NOW = "NOW"
class Token(object):
def __init__(self, tok_type, tok_literal):
self.token_type = tok_type
self.token_literal = tok_literal
| class Tokentype(object):
end = ''
illegal = 'ILLEGAL'
plus = '+'
minus = '-'
slash = '/'
at = '@'
number = 'NUMBER'
modifier = 'MODIFIER'
now = 'NOW'
class Token(object):
def __init__(self, tok_type, tok_literal):
self.token_type = tok_type
self.token_literal = tok_literal |
def sort(L):
n = len(L)
# Build Heap
for i in range(n-1, -1, -1):
L = heapify(L, i, n)
for i in range(n-1, 0, -1):
L[i], L[0] = L[0], L[i]
n -= 1
heapify(L, 0, n)
return L
def heapify(L, _v, n): # v is index to be passed
v = _v + 1
largest = v
if 2*v <= n:
if L[2*v - 1] > L[v - 1]:
largest = 2*v
if 2*v + 1 <= n:
if L[2*v] > L[largest - 1]:
largest = 2*v + 1
if not largest == v:
L[_v], L[largest - 1] = L[largest - 1], L[_v]
return heapify(L, largest - 1, n)
return L
| def sort(L):
n = len(L)
for i in range(n - 1, -1, -1):
l = heapify(L, i, n)
for i in range(n - 1, 0, -1):
(L[i], L[0]) = (L[0], L[i])
n -= 1
heapify(L, 0, n)
return L
def heapify(L, _v, n):
v = _v + 1
largest = v
if 2 * v <= n:
if L[2 * v - 1] > L[v - 1]:
largest = 2 * v
if 2 * v + 1 <= n:
if L[2 * v] > L[largest - 1]:
largest = 2 * v + 1
if not largest == v:
(L[_v], L[largest - 1]) = (L[largest - 1], L[_v])
return heapify(L, largest - 1, n)
return L |
####################################################
#
# Components applicable to all types of items
#
####################################################
# what type of item is this entity
# this is primarily used in iterable statements as a filter
class TypeOfItem:
def __init__(self, label=''):
self.label = label
# defines the available actions based on the type of item
class Actionlist:
def __init__(self, action_list=''):
self.actions = action_list
class Name:
def __init__(self, label=''):
self.label = label
class Description:
def __init__(self, label=''):
self.label = label
class ItemGlyph:
def __init__(self, glyph=''):
self.glyph = glyph
class ItemForeColour:
def __init__(self, fg=0):
self.fg = fg
class ItemBackColour:
def __init__(self, bg=0):
self.bg = bg
class ItemDisplayName:
def __init__(self, label=''):
self.label = label
# physical location on the game map
# obviously no location means the item is not on the game map
class Location:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# what is the item made of
# this might not be used as a game mechanic, but it will at least add some flavour
class Material:
def __init__(self, texture='cloth', component1='', component2='', component3=''):
self.texture = texture
self.component1 = component1
self.component2 = component2
self.component3 = component3
# is this item visible on the game map
# YES means it can be seen by the player and any mobiles (unless they're blind)
# NO means: (1) it's invisible or (2) it's inside a container
class RenderItem:
def __init__(self, istrue=True):
self.is_true = istrue
# what is the quality of this item
# this may be a game mechanic or not but it will at least be flavour
class Quality:
def __init__(self, level='basic'):
self.level = level
####################################################
#
# BAGS
#
####################################################
# how many slots does this bag have
# populated indicates how many different slots contain at least one item
class SlotSize:
def __init__(self, maxsize=26, populated=0):
self.maxsize = maxsize
self.populated = populated
####################################################
#
# WEAPONS
#
####################################################
class Experience:
def __init__(self, current_level=10):
self.current_level = current_level
self.max_level = 10
class WeaponType:
def __init__(self, label=''):
self.label = label
# hallmarks are a way to add a different bonus to an existing weapon
class Hallmarks:
def __init__(self, hallmark_slot_one=0, hallmark_slot_two=0):
self.hallmark_slot_one = hallmark_slot_one
self.hallmark_slot_two = hallmark_slot_two
# can this item be held in the hands
# the true_or_false parameter drives this
class Wielded:
def __init__(self, hands='both', true_or_false=True):
self.hands = hands
self.true_or_false = true_or_false
# which spells are loaded into the weapon
class Spells:
def __init__(self, slot_one=0, slot_two=0, slot_three=0, slot_four=0, slot_five=0):
self.slot_one = slot_one
self.slot_two = slot_two
self.slot_three = slot_three
self.slot_four = slot_four
self.slot_five = slot_five
self.slot_one_disabled = False
self.slot_two_disabled = False
self.slot_three_disabled = False
self.slot_four_disabled = False
self.slot_five_disabled = False
# weapon damage range
class DamageRange:
def __init__(self, ranges=''):
self.ranges = ranges
####################################################
#
# ARMOUR
#
####################################################
# how heavy is this piece of armour
class Weight:
def __init__(self, label=''):
self.label = label
# what is the calculated defense value for this piece of armour
class Defense:
def __init__(self, value=0):
self.value = value
# where on the body can this piece of armour be placed
class ArmourBodyLocation:
def __init__(self, chest=False, head=False, hands=False, feet=False, legs=False):
self.chest = chest
self.head = head
self.hands = hands
self.feet = feet
self.legs = legs
# what bonus does this piece of armour add and to which attribute
class AttributeBonus:
def __init__(self, majorname='', majorbonus=0, minoronename='', minoronebonus=0):
self.major_name = majorname
self.major_bonus = majorbonus
self.minor_one_name = minoronename
self.minor_one_bonus = minoronebonus
# If this piece of armour belongs to an armour set it, the set name will
# be found here
class ArmourSet:
def __init__(self, label='', prefix='', level=0):
self.name = label
self.prefix = prefix
self.level = level
# Is the armour being worn
class ArmourBeingWorn:
def __init__(self, status=False):
self.status = status
# armour spell information
class ArmourSpell:
def __init__(self, entity=0, on_cool_down=False):
self.entity = entity
self.on_cool_down = on_cool_down
####################################################
#
# JEWELLERY
#
####################################################
# this defines the stat(s) the piece of jewellery improves
# the dictionary is in the format:{stat_name, bonus_value}
class JewelleryStatBonus:
def __init__(self, statname='', statbonus=0):
self.stat_name = statname
self.stat_bonus = statbonus
# defines the gemstone embedded in the piece of jewllery
class JewelleryGemstone:
def __init__(self, name=''):
self.name = name
# where on the body can this piece of jewellery be worn
# neck = Amulets, fingers = Rings, ears=Earrings
class JewelleryBodyLocation:
def __init__(self, fingers=False, neck=False, ears=False):
self.fingers = fingers
self.neck = neck
self.ears = ears
# Is the piece of jewellery already equipped
class JewelleryEquipped:
def __init__(self, istrue=False):
self.istrue = istrue
class JewelleryComponents:
def __init__(self, setting='', hook='', activator=''):
self.setting = setting
self.hook = hook
self.activator = activator
class JewellerySpell:
def __init__(self, entity=0, on_cool_down=False):
self.entity = entity
self.on_cool_down = on_cool_down | class Typeofitem:
def __init__(self, label=''):
self.label = label
class Actionlist:
def __init__(self, action_list=''):
self.actions = action_list
class Name:
def __init__(self, label=''):
self.label = label
class Description:
def __init__(self, label=''):
self.label = label
class Itemglyph:
def __init__(self, glyph=''):
self.glyph = glyph
class Itemforecolour:
def __init__(self, fg=0):
self.fg = fg
class Itembackcolour:
def __init__(self, bg=0):
self.bg = bg
class Itemdisplayname:
def __init__(self, label=''):
self.label = label
class Location:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class Material:
def __init__(self, texture='cloth', component1='', component2='', component3=''):
self.texture = texture
self.component1 = component1
self.component2 = component2
self.component3 = component3
class Renderitem:
def __init__(self, istrue=True):
self.is_true = istrue
class Quality:
def __init__(self, level='basic'):
self.level = level
class Slotsize:
def __init__(self, maxsize=26, populated=0):
self.maxsize = maxsize
self.populated = populated
class Experience:
def __init__(self, current_level=10):
self.current_level = current_level
self.max_level = 10
class Weapontype:
def __init__(self, label=''):
self.label = label
class Hallmarks:
def __init__(self, hallmark_slot_one=0, hallmark_slot_two=0):
self.hallmark_slot_one = hallmark_slot_one
self.hallmark_slot_two = hallmark_slot_two
class Wielded:
def __init__(self, hands='both', true_or_false=True):
self.hands = hands
self.true_or_false = true_or_false
class Spells:
def __init__(self, slot_one=0, slot_two=0, slot_three=0, slot_four=0, slot_five=0):
self.slot_one = slot_one
self.slot_two = slot_two
self.slot_three = slot_three
self.slot_four = slot_four
self.slot_five = slot_five
self.slot_one_disabled = False
self.slot_two_disabled = False
self.slot_three_disabled = False
self.slot_four_disabled = False
self.slot_five_disabled = False
class Damagerange:
def __init__(self, ranges=''):
self.ranges = ranges
class Weight:
def __init__(self, label=''):
self.label = label
class Defense:
def __init__(self, value=0):
self.value = value
class Armourbodylocation:
def __init__(self, chest=False, head=False, hands=False, feet=False, legs=False):
self.chest = chest
self.head = head
self.hands = hands
self.feet = feet
self.legs = legs
class Attributebonus:
def __init__(self, majorname='', majorbonus=0, minoronename='', minoronebonus=0):
self.major_name = majorname
self.major_bonus = majorbonus
self.minor_one_name = minoronename
self.minor_one_bonus = minoronebonus
class Armourset:
def __init__(self, label='', prefix='', level=0):
self.name = label
self.prefix = prefix
self.level = level
class Armourbeingworn:
def __init__(self, status=False):
self.status = status
class Armourspell:
def __init__(self, entity=0, on_cool_down=False):
self.entity = entity
self.on_cool_down = on_cool_down
class Jewellerystatbonus:
def __init__(self, statname='', statbonus=0):
self.stat_name = statname
self.stat_bonus = statbonus
class Jewellerygemstone:
def __init__(self, name=''):
self.name = name
class Jewellerybodylocation:
def __init__(self, fingers=False, neck=False, ears=False):
self.fingers = fingers
self.neck = neck
self.ears = ears
class Jewelleryequipped:
def __init__(self, istrue=False):
self.istrue = istrue
class Jewellerycomponents:
def __init__(self, setting='', hook='', activator=''):
self.setting = setting
self.hook = hook
self.activator = activator
class Jewelleryspell:
def __init__(self, entity=0, on_cool_down=False):
self.entity = entity
self.on_cool_down = on_cool_down |
def get_ages() -> list[int]:
with open('input.txt') as f:
line, = f.readlines()
return list(map(int, line.split(',')))
def step_day(ages: list[int]):
for i, age in enumerate(ages[:]):
age, *newborn = tick(age)
ages[i] = age
ages.extend(newborn)
def tick(age: int) -> list[int]:
if not age:
return [6, 8]
return [age - 1]
if __name__ == '__main__':
ages: list[int] = get_ages()
for day in range(18):
step_day(ages)
answer = len(ages)
print(f'Answer: {answer}')
| def get_ages() -> list[int]:
with open('input.txt') as f:
(line,) = f.readlines()
return list(map(int, line.split(',')))
def step_day(ages: list[int]):
for (i, age) in enumerate(ages[:]):
(age, *newborn) = tick(age)
ages[i] = age
ages.extend(newborn)
def tick(age: int) -> list[int]:
if not age:
return [6, 8]
return [age - 1]
if __name__ == '__main__':
ages: list[int] = get_ages()
for day in range(18):
step_day(ages)
answer = len(ages)
print(f'Answer: {answer}') |
'''
Given an array of integers A sorted in non-decreasing order,
return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
'''
def sortedSquares(A):
for i in range(len(A)):
A[i] = A[i]*A[i]
A.sort()
return A
def sortedSquares2(A):
N = len(A)
# i, j: negative, positive parts
j = 0
while j < N and A[j] < 0:
j += 1
i = j - 1
ans = []
while 0 <= i and j < N:
if A[i]**2 < A[j]**2:
ans.append(A[i]**2)
i -= 1
else:
ans.append(A[j]**2)
j += 1
while i >= 0:
ans.append(A[i]**2)
i -= 1
while j < N:
ans.append(A[j]**2)
j += 1
return ans
| """
Given an array of integers A sorted in non-decreasing order,
return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
"""
def sorted_squares(A):
for i in range(len(A)):
A[i] = A[i] * A[i]
A.sort()
return A
def sorted_squares2(A):
n = len(A)
j = 0
while j < N and A[j] < 0:
j += 1
i = j - 1
ans = []
while 0 <= i and j < N:
if A[i] ** 2 < A[j] ** 2:
ans.append(A[i] ** 2)
i -= 1
else:
ans.append(A[j] ** 2)
j += 1
while i >= 0:
ans.append(A[i] ** 2)
i -= 1
while j < N:
ans.append(A[j] ** 2)
j += 1
return ans |
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
| tuple1 = ('apple', 'banana', 'cherry')
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3) |
class Node:
def __init__(self,data):
self.data = data
self.previous = None
self.next = None
class removeDuplicates:
def __init__(self):
self.head = None
self.tail = None
def remove_duplicates(self):
if (self.head == None):
return
else:
current = self.head
while (current!= None):
index = current.next
while (index != None):
if (current.data == index.data):
temp = index
index.previous.next = index.next
if (index.next != None):
index.next.previous = index.previous
temp = None
index = index.next
current = current.next
| class Node:
def __init__(self, data):
self.data = data
self.previous = None
self.next = None
class Removeduplicates:
def __init__(self):
self.head = None
self.tail = None
def remove_duplicates(self):
if self.head == None:
return
else:
current = self.head
while current != None:
index = current.next
while index != None:
if current.data == index.data:
temp = index
index.previous.next = index.next
if index.next != None:
index.next.previous = index.previous
temp = None
index = index.next
current = current.next |
class Parameter:
def __init__(self, name: str, klass: str, data_member, required=True, array=False):
self._name = name
self._klass = klass
self._data_member = data_member
self._required = required
self._array = array
def __eq__(self, other):
return True if \
self.name == other.name and \
self.json == other.json \
else False
@property
def name(self):
return self._name
@property
def klass(self):
return self._klass
@property
def required(self):
return self._required
@property
def data_member(self):
return self._data_member
@property
def array(self):
return self._array
@required.setter
def required(self, value):
self._required = value
@property
def json(self):
return {
'name': self.name,
'class': self.klass,
'array': self.array,
'data_member': self.data_member.name if self.data_member else None
}
| class Parameter:
def __init__(self, name: str, klass: str, data_member, required=True, array=False):
self._name = name
self._klass = klass
self._data_member = data_member
self._required = required
self._array = array
def __eq__(self, other):
return True if self.name == other.name and self.json == other.json else False
@property
def name(self):
return self._name
@property
def klass(self):
return self._klass
@property
def required(self):
return self._required
@property
def data_member(self):
return self._data_member
@property
def array(self):
return self._array
@required.setter
def required(self, value):
self._required = value
@property
def json(self):
return {'name': self.name, 'class': self.klass, 'array': self.array, 'data_member': self.data_member.name if self.data_member else None} |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Const Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.view
class DuplexMode(object):
"""
Const Class
These constants specify available duplex modes.
See Also:
`API DuplexMode <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1view_1_1DuplexMode.html>`_
"""
__ooo_ns__: str = 'com.sun.star.view'
__ooo_full_ns__: str = 'com.sun.star.view.DuplexMode'
__ooo_type_name__: str = 'const'
UNKNOWN = 0
"""
specifies an unknown duplex mode.
"""
OFF = 1
"""
specifies that there is no duplex mode enabled
"""
LONGEDGE = 2
"""
specifies a long edge duplex mode
"""
SHORTEDGE = 3
"""
specifies a short edge duplex mode
"""
__all__ = ['DuplexMode']
| class Duplexmode(object):
"""
Const Class
These constants specify available duplex modes.
See Also:
`API DuplexMode <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1view_1_1DuplexMode.html>`_
"""
__ooo_ns__: str = 'com.sun.star.view'
__ooo_full_ns__: str = 'com.sun.star.view.DuplexMode'
__ooo_type_name__: str = 'const'
unknown = 0
'\n specifies an unknown duplex mode.\n '
off = 1
'\n specifies that there is no duplex mode enabled\n '
longedge = 2
'\n specifies a long edge duplex mode\n '
shortedge = 3
'\n specifies a short edge duplex mode\n '
__all__ = ['DuplexMode'] |
"""Calculation history Class"""
class Calculations:
"""Calculation history Class"""
history = []
@staticmethod
def clear_history():
""" clear the history items"""
Calculations.history.clear()
return True
@staticmethod
def count_history():
""" get the length of history items"""
return len(Calculations.history)
@staticmethod
def get_last_calculation_object():
""" get the last calculation from history"""
return Calculations.history[-1]
@staticmethod
def get_last_calculation_result():
""" get the last calculation from history"""
return Calculations.get_last_calculation_object().get_result()
@staticmethod
def get_first_calculation():
""" get the first calculation from history"""
return Calculations.history[0]
@staticmethod
def get_calculation_from_history(num):
""" get a specific calculation from history"""
return Calculations.history[num]
@staticmethod
def add_calculation_to_history(calculation):
""" get a specific calculation from history"""
Calculations.history.append(calculation)
return Calculations.history
| """Calculation history Class"""
class Calculations:
"""Calculation history Class"""
history = []
@staticmethod
def clear_history():
""" clear the history items"""
Calculations.history.clear()
return True
@staticmethod
def count_history():
""" get the length of history items"""
return len(Calculations.history)
@staticmethod
def get_last_calculation_object():
""" get the last calculation from history"""
return Calculations.history[-1]
@staticmethod
def get_last_calculation_result():
""" get the last calculation from history"""
return Calculations.get_last_calculation_object().get_result()
@staticmethod
def get_first_calculation():
""" get the first calculation from history"""
return Calculations.history[0]
@staticmethod
def get_calculation_from_history(num):
""" get a specific calculation from history"""
return Calculations.history[num]
@staticmethod
def add_calculation_to_history(calculation):
""" get a specific calculation from history"""
Calculations.history.append(calculation)
return Calculations.history |
fname = input('Enter the name of the file: ')
if(len(fname) < 1) : fname = 'clown.txt'
hand = open(fname)
di = dict()
for line in hand:
line = line.rstrip()
wds = line.split()
for w in wds:
##if not there, the count is zero
##if it is there, just add + 1
di[w] = di.get(w, 0) + 1
##All the code below in a single line in the code above
'''
if w in di:
di[w] = di[w] + 1
print('***EXISTING***')
else:
di[w] = 1
print('***NEW***')
'''
print(di)
#Finding the most common word:
bigCount = None
bigWord = None
for k, v in di.items():
if(bigCount == None or v > bigCount):
bigCount = v
bigWord = k
print('bigCount: ', bigCount)
print('bigWord: ', bigWord)
| fname = input('Enter the name of the file: ')
if len(fname) < 1:
fname = 'clown.txt'
hand = open(fname)
di = dict()
for line in hand:
line = line.rstrip()
wds = line.split()
for w in wds:
di[w] = di.get(w, 0) + 1
"\n if w in di:\n di[w] = di[w] + 1\n print('***EXISTING***')\n else:\n di[w] = 1\n print('***NEW***')\n "
print(di)
big_count = None
big_word = None
for (k, v) in di.items():
if bigCount == None or v > bigCount:
big_count = v
big_word = k
print('bigCount: ', bigCount)
print('bigWord: ', bigWord) |
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
rows_to_zero = set()
cols_to_zero = set()
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] == 0:
rows_to_zero.add(row)
cols_to_zero.add(col)
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if row in rows_to_zero or col in cols_to_zero:
matrix[row][col] = 0
| class Solution(object):
def set_zeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
rows_to_zero = set()
cols_to_zero = set()
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] == 0:
rows_to_zero.add(row)
cols_to_zero.add(col)
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if row in rows_to_zero or col in cols_to_zero:
matrix[row][col] = 0 |
def distinct(iterable, keyfunc=None):
seen = set()
for item in iterable:
key = item if keyfunc is None else keyfunc(item)
if key not in seen:
seen.add(key)
yield item | def distinct(iterable, keyfunc=None):
seen = set()
for item in iterable:
key = item if keyfunc is None else keyfunc(item)
if key not in seen:
seen.add(key)
yield item |
'''
URL: https://leetcode.com/problems/binary-tree-level-order-traversal/
Difficulty: Medium
Description: Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root):
result = []
# Empty tree
if root == None:
return result
# queue for tracking next node to process
queue = [root]
# last node in current level
lastInCurrLevel = root
# all the nodes in current level we have visited
nodesInCurrLevel = []
while len(queue):
node = queue.pop(0)
nodesInCurrLevel.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# if we reach last node in current level
if node == lastInCurrLevel:
# add the level (list of nodes) to result
result.append(nodesInCurrLevel)
# reset the list
nodesInCurrLevel = []
if len(queue):
# last node in the queue will be the last node in next level
lastInCurrLevel = queue[-1]
return result
| """
URL: https://leetcode.com/problems/binary-tree-level-order-traversal/
Difficulty: Medium
Description: Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ 9 20
/ 15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
"""
class Solution:
def level_order(self, root):
result = []
if root == None:
return result
queue = [root]
last_in_curr_level = root
nodes_in_curr_level = []
while len(queue):
node = queue.pop(0)
nodesInCurrLevel.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if node == lastInCurrLevel:
result.append(nodesInCurrLevel)
nodes_in_curr_level = []
if len(queue):
last_in_curr_level = queue[-1]
return result |
def read_file():
content = open("C:/Users/DIPANSH KHANDELWAL/Desktop/Python Codes/PythonFiles/read_file/read_file.txt")
text = content.read()
print (text)
content.close()
read_file()
| def read_file():
content = open('C:/Users/DIPANSH KHANDELWAL/Desktop/Python Codes/PythonFiles/read_file/read_file.txt')
text = content.read()
print(text)
content.close()
read_file() |
NAME='syslog'
CFLAGS = []
LDFLAGS = []
LIBS = []
GCC_LIST = ['syslog_plugin']
| name = 'syslog'
cflags = []
ldflags = []
libs = []
gcc_list = ['syslog_plugin'] |
class DisjointSets(object):
"""A simple implementation of the Disjoint Sets data structure.
Implements path compression but not union-by-rank.
"""
def __init__(self, elements):
self.num_elements = len(elements)
self.num_sets = len(elements)
self.parents = {element: element for element in elements}
def is_connected(self):
return self.num_sets == 1
def get_num_elements(self):
return self.num_elements
def contains(self, element):
return element in self.parents
def add_singleton(self, element):
assert not self.contains(element)
self.num_elements += 1
self.num_sets += 1
self.parents[element] = element
def find(self, element):
parent = self.parents[element]
if element == parent:
return parent
result = self.find(parent)
self.parents[element] = result
return result
def union(self, e1, e2):
p1, p2 = map(self.find, (e1, e2))
if p1 != p2:
self.num_sets -= 1
self.parents[p1] = p2
| class Disjointsets(object):
"""A simple implementation of the Disjoint Sets data structure.
Implements path compression but not union-by-rank.
"""
def __init__(self, elements):
self.num_elements = len(elements)
self.num_sets = len(elements)
self.parents = {element: element for element in elements}
def is_connected(self):
return self.num_sets == 1
def get_num_elements(self):
return self.num_elements
def contains(self, element):
return element in self.parents
def add_singleton(self, element):
assert not self.contains(element)
self.num_elements += 1
self.num_sets += 1
self.parents[element] = element
def find(self, element):
parent = self.parents[element]
if element == parent:
return parent
result = self.find(parent)
self.parents[element] = result
return result
def union(self, e1, e2):
(p1, p2) = map(self.find, (e1, e2))
if p1 != p2:
self.num_sets -= 1
self.parents[p1] = p2 |
"""This module provides the client to make the connection with the given database."""
class DatabaseClient:
"""Initializes the connector with the DatabaseFactory object and provides a connector."""
def __init__(self, factory_obj) -> None:
"""
Initializes the factory object.
:factory_obj : object of type DatabaseFactory.
"""
self.__connector = factory_obj
def connect(self, database_value, app_config):
"""Selectes the database system and returns its connection object."""
try:
database = self.__connector.get_database(database_value)
return database.connect(app_config)
except Exception as err:
raise err
def get_row_query( # pylint: disable=too-many-arguments
self,
database_value: int,
cols_to_query: str,
table_name: str,
output_col: str,
limit: int = 100,
) -> str:
"""
Selects the database and returns its row query.
: database_value: database representation value.
: cols_to_query: comma seperated column names to select from the table.
example: "id, input_text"
: table_name: name of the database table.
: output_col: name of the output column.
: limit: number of rows to return, default is 100
"""
if (
cols_to_query is None or
table_name is None or
output_col is None or
database_value is None
):
raise Exception("Missing parameters")
database = self.__connector.get_database(database_value)
return database.get_row_query(cols_to_query, table_name, output_col, limit)
| """This module provides the client to make the connection with the given database."""
class Databaseclient:
"""Initializes the connector with the DatabaseFactory object and provides a connector."""
def __init__(self, factory_obj) -> None:
"""
Initializes the factory object.
:factory_obj : object of type DatabaseFactory.
"""
self.__connector = factory_obj
def connect(self, database_value, app_config):
"""Selectes the database system and returns its connection object."""
try:
database = self.__connector.get_database(database_value)
return database.connect(app_config)
except Exception as err:
raise err
def get_row_query(self, database_value: int, cols_to_query: str, table_name: str, output_col: str, limit: int=100) -> str:
"""
Selects the database and returns its row query.
: database_value: database representation value.
: cols_to_query: comma seperated column names to select from the table.
example: "id, input_text"
: table_name: name of the database table.
: output_col: name of the output column.
: limit: number of rows to return, default is 100
"""
if cols_to_query is None or table_name is None or output_col is None or (database_value is None):
raise exception('Missing parameters')
database = self.__connector.get_database(database_value)
return database.get_row_query(cols_to_query, table_name, output_col, limit) |
#lambda is used to create an anonymous function (function with no name)
# It is an inline function that does not contain a return statement
a = lambda x: x*2
for i in range(1,6):
print(a(i)) | a = lambda x: x * 2
for i in range(1, 6):
print(a(i)) |
def solve(a, b):
return a + b
def driver():
a, b = list(map(int, input().split(' ')))
result = solve(a, b)
print(solve(a, b))
return result
def main():
return driver()
if __name__ == '__main__':
main()
| def solve(a, b):
return a + b
def driver():
(a, b) = list(map(int, input().split(' ')))
result = solve(a, b)
print(solve(a, b))
return result
def main():
return driver()
if __name__ == '__main__':
main() |
# Program to convert Miles to Kilometers
# Taking miles input from the user
miles = float(input("Enter value in miles: "))
# conversion factor
convFac = 0.621371
# calculate kilometers
kilometers = miles / convFac
print("%0.2f miles is equal to %0.2f kilometers" % (miles, kilometers))
| miles = float(input('Enter value in miles: '))
conv_fac = 0.621371
kilometers = miles / convFac
print('%0.2f miles is equal to %0.2f kilometers' % (miles, kilometers)) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright © 2014-2016 NetApp, Inc. All Rights Reserved.
#
# CONFIDENTIALITY NOTICE: THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION OF
# NETAPP, INC. USE, DISCLOSURE OR REPRODUCTION IS PROHIBITED WITHOUT THE PRIOR
# EXPRESS WRITTEN PERMISSION OF NETAPP, INC.
"""API Utilities"""
def ascii_art(version):
"""
Used to build SolidFire ASCII art.
:return: a string with the SolidFire ASCII art.
"""
art = "\n"
art += "\n"
art += " 77 \n"
art += " 7777 \n"
art += " 77 \n"
art += " == \n"
art += " 77IIIIIIIIIIIIIIIIII777 \n"
art += " =7 7= \n"
art += " 7 7 \n"
art += " =7 7= \n"
art += " =7 7= \n"
art += " =77 7777777777777777777 77= \n"
art += " 7777 777777777777777777777 7777 \n"
art += " 7777 7777777777777777777 7777 \n"
art += " =77 77= \n"
art += " =7 7= \n"
art += " 7 7 \n"
art += " 7= =7 \n"
art += " 77= =77 \n"
art += " =7777777777777777777= \n"
art += " \n"
art += " ====IIIIIIIIII===== \n"
art += " =77777= =77777= \n"
art += " =777= =777= \n"
art += " =777= =777=\n"
art += " \n"
art += " NetApp SolidFire Version {0} " \
"\n".format(version)
art += " \n"
return art
| """API Utilities"""
def ascii_art(version):
"""
Used to build SolidFire ASCII art.
:return: a string with the SolidFire ASCII art.
"""
art = '\n'
art += '\n'
art += ' 77 \n'
art += ' 7777 \n'
art += ' 77 \n'
art += ' == \n'
art += ' 77IIIIIIIIIIIIIIIIII777 \n'
art += ' =7 7= \n'
art += ' 7 7 \n'
art += ' =7 7= \n'
art += ' =7 7= \n'
art += ' =77 7777777777777777777 77= \n'
art += ' 7777 777777777777777777777 7777 \n'
art += ' 7777 7777777777777777777 7777 \n'
art += ' =77 77= \n'
art += ' =7 7= \n'
art += ' 7 7 \n'
art += ' 7= =7 \n'
art += ' 77= =77 \n'
art += ' =7777777777777777777= \n'
art += ' \n'
art += ' ====IIIIIIIIII===== \n'
art += ' =77777= =77777= \n'
art += ' =777= =777= \n'
art += ' =777= =777=\n'
art += ' \n'
art += ' NetApp SolidFire Version {0} \n'.format(version)
art += ' \n'
return art |
def venda_mensal(*args):
telaCaixa = args[0]
telaMensal = args[1]
cursor = args[2]
QtWidgets = args[3]
data1 = telaMensal.data_mensal.text()
cursor.execute("select sum(qt_pizzas), sum(qt_esfihas), sum(qt_bebidas), sum(qt_outros), sum(total) from caixa where extract(year_month from data2) = %s " % data1)
dados = cursor.fetchall()
if dados == ((None, None, None, None, None),):
dados = (('', '', '', '', ''),)
telaCaixa.tableWidget.setRowCount(len(dados))
telaCaixa.tableWidget.setColumnCount(5)
for i in range(0, len(dados)):
for j in range(5):
telaCaixa.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(str(dados[i][j])))
telaMensal.hide() | def venda_mensal(*args):
tela_caixa = args[0]
tela_mensal = args[1]
cursor = args[2]
qt_widgets = args[3]
data1 = telaMensal.data_mensal.text()
cursor.execute('select sum(qt_pizzas), sum(qt_esfihas), sum(qt_bebidas), sum(qt_outros), sum(total) from caixa where extract(year_month from data2) = %s ' % data1)
dados = cursor.fetchall()
if dados == ((None, None, None, None, None),):
dados = (('', '', '', '', ''),)
telaCaixa.tableWidget.setRowCount(len(dados))
telaCaixa.tableWidget.setColumnCount(5)
for i in range(0, len(dados)):
for j in range(5):
telaCaixa.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(str(dados[i][j])))
telaMensal.hide() |
class ApiException(Exception):
pass
class ResourceNotFound(ApiException):
pass
class InternalServerException(ApiException):
pass
class UserNotFound(ApiException):
pass
class Ratelimited(ApiException):
pass
class InvalidMetric(ApiException):
pass
class AuthenticationException(ApiException):
pass
| class Apiexception(Exception):
pass
class Resourcenotfound(ApiException):
pass
class Internalserverexception(ApiException):
pass
class Usernotfound(ApiException):
pass
class Ratelimited(ApiException):
pass
class Invalidmetric(ApiException):
pass
class Authenticationexception(ApiException):
pass |
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
arr = [0 for _ in range(len(nums))]
for num in nums:
arr[num - 1] += 1
ans = []
for i in range(len(arr)):
if arr[i] == 0:
ans.append(i + 1)
return ans
| class Solution:
def find_disappeared_numbers(self, nums: List[int]) -> List[int]:
arr = [0 for _ in range(len(nums))]
for num in nums:
arr[num - 1] += 1
ans = []
for i in range(len(arr)):
if arr[i] == 0:
ans.append(i + 1)
return ans |
s = "abdcd"
count = 0
for vowelsItem in s:
if vowelsItem in "aeiou":
count += 1
print("Number of vowels: " + str(count)) | s = 'abdcd'
count = 0
for vowels_item in s:
if vowelsItem in 'aeiou':
count += 1
print('Number of vowels: ' + str(count)) |
# Python3 implementation to
# find first element
# occurring k times
# function to find the
# first element occurring
# k number of times
def firstElement(arr, n, k):
# dictionary to count
# occurrences of
# each element
count_map = {};
for i in range(0, n):
if(arr[i] in count_map.keys()):
count_map[arr[i]] += 1
else:
count_map[arr[i]] = 1
i += 1
for i in range(0, n):
# if count of element == k ,
# then it is the required
# first element
if (count_map[arr[i]] == k):
return arr[i]
i += 1
# Driver Code
if __name__=="__main__":
arr = input().split(" ")
n = len(arr)
k = int(input())
print(firstElement(arr, n, k)) | def first_element(arr, n, k):
count_map = {}
for i in range(0, n):
if arr[i] in count_map.keys():
count_map[arr[i]] += 1
else:
count_map[arr[i]] = 1
i += 1
for i in range(0, n):
if count_map[arr[i]] == k:
return arr[i]
i += 1
if __name__ == '__main__':
arr = input().split(' ')
n = len(arr)
k = int(input())
print(first_element(arr, n, k)) |
rooms = int(input())
free_chairs = 0
game_on = True
for current_room in range(1, rooms + 1):
command = input().split()
chairs = len(command[0])
visitors = int(command[1])
if chairs > visitors:
free_chairs += chairs - visitors
elif chairs < visitors:
needed_chairs_in_room = visitors - chairs
print(f"{needed_chairs_in_room} more chairs needed in room {current_room}")
game_on = False
if game_on:
print(f"Game On, {free_chairs} free chairs left")
| rooms = int(input())
free_chairs = 0
game_on = True
for current_room in range(1, rooms + 1):
command = input().split()
chairs = len(command[0])
visitors = int(command[1])
if chairs > visitors:
free_chairs += chairs - visitors
elif chairs < visitors:
needed_chairs_in_room = visitors - chairs
print(f'{needed_chairs_in_room} more chairs needed in room {current_room}')
game_on = False
if game_on:
print(f'Game On, {free_chairs} free chairs left') |
def main():
students = []
number_students = int(input())
while number_students > 0:
student = input()
students.append(student)
number_students -= 1
number_days = int(input())
all_missing_students = []
while number_days > 0:
curr_num_students = int(input())
curr_students = []
while curr_num_students > 0:
curr_student = input()
curr_students.append(curr_student)
curr_num_students -= 1
curr_missing = []
for i in students:
if i not in curr_students:
curr_missing.append(i)
all_missing_students.append(curr_missing)
number_days -= 1
print(all_missing_students)
if __name__ == '__main__':
main()
| def main():
students = []
number_students = int(input())
while number_students > 0:
student = input()
students.append(student)
number_students -= 1
number_days = int(input())
all_missing_students = []
while number_days > 0:
curr_num_students = int(input())
curr_students = []
while curr_num_students > 0:
curr_student = input()
curr_students.append(curr_student)
curr_num_students -= 1
curr_missing = []
for i in students:
if i not in curr_students:
curr_missing.append(i)
all_missing_students.append(curr_missing)
number_days -= 1
print(all_missing_students)
if __name__ == '__main__':
main() |
"""
Input Options
-------------
model_path : Input path to generated models - hdf5 file
input_catalog : Input catalog path
input_format : Input catalog format, see astropy.Table
documentation for available formats
z_col : Column name for source redshifts
ID_col : Column name for source IDs
flux_col_end : Suffix corresponding to flux columns
fluxerr_col_end : Suffix corresponding to flux error columns
filts_used : Indices of filters in model file to be used for fitting.
If 'None', assumes all filters to be used.
"""
model_path = 'candels.goodss.models.savetest.hdf'
output_name = 'candels_test.cat'
input_catalog = 'data/CANDELS.GOODSS.example.cat'
input_format = 'ascii.commented_header'
z_col = 'Photo_z'
ID_col = 'ID'
flux_col_end = '_FLUX'
fluxerr_col_end = '_FLUXERR'
filts_used = None
"""
Fitting Options
---------------
fitting_mode :
Desired option for fitting mode/outputs,
'simple' - Simple single best-fit model
'hist' - Additional mass and sfr pdf outputs
include_rest : Calculate rest-frame magnitudes for best-fit model (True/False)
ncpus : Number of parallel processes to use when fitting
flux_corr : Correction to convert input fluxes to total
flux_err : Additional fractional flux error added to all bands in quadrature
"""
fitting_mode = 'hist'
include_rest = True
ncpus = 4
zp_offsets = 'test_offsets.txt'
temp_err = None #'TEMPLATE_ERROR.v2.0.zfourge.txt'
flux_corr = 1
flux_err = 0.
nmin_bands = 14.
"""
Output Options
--------------
output_catalog : Path for output catalog
output_format : Output catalog format, see astropy.Table
documentation for available formats
output_hdf : Path for output hdf5 file ('hist' mode only)
"""
output_hdf_path = 'candels_test.hdf'
output_catalog_path = 'candels_test.cat'
output_format = 'ascii.commented_header'
| """
Input Options
-------------
model_path : Input path to generated models - hdf5 file
input_catalog : Input catalog path
input_format : Input catalog format, see astropy.Table
documentation for available formats
z_col : Column name for source redshifts
ID_col : Column name for source IDs
flux_col_end : Suffix corresponding to flux columns
fluxerr_col_end : Suffix corresponding to flux error columns
filts_used : Indices of filters in model file to be used for fitting.
If 'None', assumes all filters to be used.
"""
model_path = 'candels.goodss.models.savetest.hdf'
output_name = 'candels_test.cat'
input_catalog = 'data/CANDELS.GOODSS.example.cat'
input_format = 'ascii.commented_header'
z_col = 'Photo_z'
id_col = 'ID'
flux_col_end = '_FLUX'
fluxerr_col_end = '_FLUXERR'
filts_used = None
"\nFitting Options\n---------------\n\nfitting_mode :\n Desired option for fitting mode/outputs,\n 'simple' - Simple single best-fit model\n 'hist' - Additional mass and sfr pdf outputs\ninclude_rest : Calculate rest-frame magnitudes for best-fit model (True/False)\nncpus : Number of parallel processes to use when fitting\nflux_corr : Correction to convert input fluxes to total\nflux_err : Additional fractional flux error added to all bands in quadrature\n\n"
fitting_mode = 'hist'
include_rest = True
ncpus = 4
zp_offsets = 'test_offsets.txt'
temp_err = None
flux_corr = 1
flux_err = 0.0
nmin_bands = 14.0
"\nOutput Options\n--------------\n\noutput_catalog : Path for output catalog\noutput_format : Output catalog format, see astropy.Table\n documentation for available formats\noutput_hdf : Path for output hdf5 file ('hist' mode only)\n"
output_hdf_path = 'candels_test.hdf'
output_catalog_path = 'candels_test.cat'
output_format = 'ascii.commented_header' |
def AAsInPeptideListCount(PeptidesListFileLocation):
PeptidesListFile = open(PeptidesListFileLocation, 'r')
Lines = PeptidesListFile.readlines()
PeptidesListFile.close
AminoAcidsCount = {'A':0, 'C':0, 'D':0, 'E':0,
'F':0, 'G':0, 'H':0, 'I':0,
'K':0, 'L':0, 'M':0, 'N':0,
'P':0, 'Q':0, 'R':0, 'S':0,
'T':0, 'V':0, 'W':0, 'Y':0,
'y':0, 'X':0, 'Z':0
}
# populate the dictionary, so that Peptides are the keys and
for Line in Lines:
Line = Line.strip('\n')
for i in range(len(Line)):
AminoAcidsCount[Line[i]] += 1
return AminoAcidsCount
def AAQuantitiesForSYRO(AAQuantitiesForSYROFileName, PeptidesListFileLocation):
AAData = {'A':('Ala','Fmoc-Ala-OH H2O', 311.34),
'C':('Cys','Fmoc-Cys(Trt)-OH', 585.72),
'D':('Asp','Fmoc-Asp(OtBu)-OH',411.46),
'E':('Glu','Fmoc-Glu(OtBu)-OH',425.49),
'F':('Phe','Fmoc-Phe-OH',387.40),
'G':('Gly','Fmoc-Gly-OH',297.31),
'H':('His','Fmoc-His(Trt)-OH',619.72),
'I':('Ile','Fmoc-Ile-OH',353.42),
'K':('Lys','Fmoc-Lys(Boc)-OH',468.55),
'L':('Leu','Fmoc-Leu-OH',353.42),
'M':('Met','Fmoc-Met-OH',371.45),
'N':('Asn','Fmoc-Asn(Trt)-OH',596.68),
'P':('Pro','Fmoc-Pro-OH',337.38),
'Q':('Gln','Fmoc-Gln(Trt)-OH',610.72),
'R':('Arg','Fmoc-Arg(Pbf)-OH',648.77),
'S':('Ser','Fmoc-Ser(tBu)-OH',383.45),
'T':('Thr','Fmoc-Thr(tBu)-OH',397.48),
'V':('Val','Fmoc-Val-OH',339.39),
'W':('Trp','Fmoc-Trp(Boc)-OH',526.59),
'Y':('Tyr','Fmoc-Tyr(tBu)-OH',459.54),
'y':('D-Tyr','Fmoc-D-Tyr(tBu)-OH',459.54),
'X':('HONH-Glu','Fmoc-(tBu)ONH-Glu-OH',440.50),
'Z':('HONH-ASub','Fmoc-(tBu)ONH-ASub-OH',482.50)
}
AAQuantitiesForSYRO = open(AAQuantitiesForSYROFileName, 'w')
AAQuantitiesForSYRO.write('AA' + ',' +
'Name' + ',' +
'Formula' + ',' +
'#' + ',' +
'MW(g/mol)' + ',' +
'Q(mol)' + ',' +
'Q(g)' + ',' +
'V (mL)' + '\n')
AAList = AAsInPeptideListCount(PeptidesListFileLocation)
TotalNumberOfSteps = sum(AAList.values())
for AminoAcid in AAList:
AAName = AAData[AminoAcid][0]
AAFormula = AAData[AminoAcid][1]
AACount = AAList[AminoAcid]
if AACount > 0:
AADilutionVolume = 1.1 * (2 * (0.0006 + (AACount - 1) * 0.0003))
else:
AADilutionVolume = 0
AAMolecularWeight = AAData[AminoAcid][2]
AAMoleQuantity = AADilutionVolume * 0.5
AAGrQuantity = AAMoleQuantity * AAMolecularWeight
AAQuantitiesForSYRO.write(AminoAcid + ',' +
AAName + ',' +
AAFormula + ',' +
str(AACount) + ',' +
'{:.2f}'.format(AAMolecularWeight) + ',' +
'{:.3f}'.format(AAMoleQuantity) + ',' +
'{:.3f}'.format(AAGrQuantity) + ',' +
'{:.3f}'.format(AADilutionVolume * 1000) + ',' + '\n')
MWofHBTU = 379.25
MWofHOBt = 171.134
MWofDIPEA = 129.25
DofDIPEA = 0.742
HBTUinDMFvolume = 2.2 * TotalNumberOfSteps * 0.000345
QofHBTU = 0.43 * HBTUinDMFvolume * MWofHBTU
QofHOBt = 0.43 * HBTUinDMFvolume * MWofHOBt
DIPEAinNMPvolume = 2.2 * TotalNumberOfSteps * 0.000150
QofDIPEA = 2.2 * DIPEAinNMPvolume * MWofDIPEA
VofDIPEA = QofDIPEA/DofDIPEA
VofPiperidineInDMF = 2.2 * TotalNumberOfSteps * 0.000900
AAQuantitiesForSYRO.write('HBTU quantity (g)' + ',' + '{:.2f}'.format(QofHBTU) + '\n' +
'HOBt.H2O quantity (g)' + ',' + '{:.2f}'.format(QofHOBt) + '\n' +
'HBTU & HOBt.H2O in DMF (mL)' + ',' + '{:.2f}'.format(1000 * HBTUinDMFvolume) + '\n' +
'DIPEA quantity (g)' + ',' + '{:.2f}'.format(QofDIPEA) + '\n' +
'DIPEA volume (mL)' + ',' + '{:.2f}'.format(VofDIPEA) + '\n' +
'DIPEA in NMP (mL)' + ',' + '{:.2f}'.format(1000 * DIPEAinNMPvolume) + '\n' +
'40% piperidine in DMF (mL)' + ',' + '{:.2f}'.format(1000 * VofPiperidineInDMF) + '\n')
AAQuantitiesForSYRO.close
#_____________________________RUNNING THE FUNCTION_____________________________#
#___AAQuantitiesForSYROFileName, PeptidesListFileLocation___
AAQuantitiesForSYRO('CloneSynthesis Test.csv', '/Volumes/NIKITA 2GB/CloneSynthesis.txt')
| def a_as_in_peptide_list_count(PeptidesListFileLocation):
peptides_list_file = open(PeptidesListFileLocation, 'r')
lines = PeptidesListFile.readlines()
PeptidesListFile.close
amino_acids_count = {'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0, 'y': 0, 'X': 0, 'Z': 0}
for line in Lines:
line = Line.strip('\n')
for i in range(len(Line)):
AminoAcidsCount[Line[i]] += 1
return AminoAcidsCount
def aa_quantities_for_syro(AAQuantitiesForSYROFileName, PeptidesListFileLocation):
aa_data = {'A': ('Ala', 'Fmoc-Ala-OH H2O', 311.34), 'C': ('Cys', 'Fmoc-Cys(Trt)-OH', 585.72), 'D': ('Asp', 'Fmoc-Asp(OtBu)-OH', 411.46), 'E': ('Glu', 'Fmoc-Glu(OtBu)-OH', 425.49), 'F': ('Phe', 'Fmoc-Phe-OH', 387.4), 'G': ('Gly', 'Fmoc-Gly-OH', 297.31), 'H': ('His', 'Fmoc-His(Trt)-OH', 619.72), 'I': ('Ile', 'Fmoc-Ile-OH', 353.42), 'K': ('Lys', 'Fmoc-Lys(Boc)-OH', 468.55), 'L': ('Leu', 'Fmoc-Leu-OH', 353.42), 'M': ('Met', 'Fmoc-Met-OH', 371.45), 'N': ('Asn', 'Fmoc-Asn(Trt)-OH', 596.68), 'P': ('Pro', 'Fmoc-Pro-OH', 337.38), 'Q': ('Gln', 'Fmoc-Gln(Trt)-OH', 610.72), 'R': ('Arg', 'Fmoc-Arg(Pbf)-OH', 648.77), 'S': ('Ser', 'Fmoc-Ser(tBu)-OH', 383.45), 'T': ('Thr', 'Fmoc-Thr(tBu)-OH', 397.48), 'V': ('Val', 'Fmoc-Val-OH', 339.39), 'W': ('Trp', 'Fmoc-Trp(Boc)-OH', 526.59), 'Y': ('Tyr', 'Fmoc-Tyr(tBu)-OH', 459.54), 'y': ('D-Tyr', 'Fmoc-D-Tyr(tBu)-OH', 459.54), 'X': ('HONH-Glu', 'Fmoc-(tBu)ONH-Glu-OH', 440.5), 'Z': ('HONH-ASub', 'Fmoc-(tBu)ONH-ASub-OH', 482.5)}
aa_quantities_for_syro = open(AAQuantitiesForSYROFileName, 'w')
AAQuantitiesForSYRO.write('AA' + ',' + 'Name' + ',' + 'Formula' + ',' + '#' + ',' + 'MW(g/mol)' + ',' + 'Q(mol)' + ',' + 'Q(g)' + ',' + 'V (mL)' + '\n')
aa_list = a_as_in_peptide_list_count(PeptidesListFileLocation)
total_number_of_steps = sum(AAList.values())
for amino_acid in AAList:
aa_name = AAData[AminoAcid][0]
aa_formula = AAData[AminoAcid][1]
aa_count = AAList[AminoAcid]
if AACount > 0:
aa_dilution_volume = 1.1 * (2 * (0.0006 + (AACount - 1) * 0.0003))
else:
aa_dilution_volume = 0
aa_molecular_weight = AAData[AminoAcid][2]
aa_mole_quantity = AADilutionVolume * 0.5
aa_gr_quantity = AAMoleQuantity * AAMolecularWeight
AAQuantitiesForSYRO.write(AminoAcid + ',' + AAName + ',' + AAFormula + ',' + str(AACount) + ',' + '{:.2f}'.format(AAMolecularWeight) + ',' + '{:.3f}'.format(AAMoleQuantity) + ',' + '{:.3f}'.format(AAGrQuantity) + ',' + '{:.3f}'.format(AADilutionVolume * 1000) + ',' + '\n')
m_wof_hbtu = 379.25
m_wof_ho_bt = 171.134
m_wof_dipea = 129.25
dof_dipea = 0.742
hbt_uin_dm_fvolume = 2.2 * TotalNumberOfSteps * 0.000345
qof_hbtu = 0.43 * HBTUinDMFvolume * MWofHBTU
qof_ho_bt = 0.43 * HBTUinDMFvolume * MWofHOBt
dipe_ain_nm_pvolume = 2.2 * TotalNumberOfSteps * 0.00015
qof_dipea = 2.2 * DIPEAinNMPvolume * MWofDIPEA
vof_dipea = QofDIPEA / DofDIPEA
vof_piperidine_in_dmf = 2.2 * TotalNumberOfSteps * 0.0009
AAQuantitiesForSYRO.write('HBTU quantity (g)' + ',' + '{:.2f}'.format(QofHBTU) + '\n' + 'HOBt.H2O quantity (g)' + ',' + '{:.2f}'.format(QofHOBt) + '\n' + 'HBTU & HOBt.H2O in DMF (mL)' + ',' + '{:.2f}'.format(1000 * HBTUinDMFvolume) + '\n' + 'DIPEA quantity (g)' + ',' + '{:.2f}'.format(QofDIPEA) + '\n' + 'DIPEA volume (mL)' + ',' + '{:.2f}'.format(VofDIPEA) + '\n' + 'DIPEA in NMP (mL)' + ',' + '{:.2f}'.format(1000 * DIPEAinNMPvolume) + '\n' + '40% piperidine in DMF (mL)' + ',' + '{:.2f}'.format(1000 * VofPiperidineInDMF) + '\n')
AAQuantitiesForSYRO.close
aa_quantities_for_syro('CloneSynthesis Test.csv', '/Volumes/NIKITA 2GB/CloneSynthesis.txt') |
a = 25
b = 0o31
c = 0x19
print(a)
print(b)
print(c)
| a = 25
b = 25
c = 25
print(a)
print(b)
print(c) |
class MaxSparseList:
def __init__(self, firstMember, limit: int,
weight: callable = lambda x: x[0],
value: callable = lambda x: x[1]):
self.weight = weight
self.value = value
self.data = [firstMember]
self.limit = limit
return
def append(self, newMember):
w = self.weight(newMember)
if w > self.limit:
return 1
if self.value(self.data[-1]) >= self.value(newMember):
return 2
if self.weight(self.data[-1]) == w:
_ = self.data.pop()
self.data.append(newMember)
return 0
| class Maxsparselist:
def __init__(self, firstMember, limit: int, weight: callable=lambda x: x[0], value: callable=lambda x: x[1]):
self.weight = weight
self.value = value
self.data = [firstMember]
self.limit = limit
return
def append(self, newMember):
w = self.weight(newMember)
if w > self.limit:
return 1
if self.value(self.data[-1]) >= self.value(newMember):
return 2
if self.weight(self.data[-1]) == w:
_ = self.data.pop()
self.data.append(newMember)
return 0 |
""" Python implementation of Paradox HD7X cameras (and future other modules)."""
class ParadoxModuleError(Exception):
"""Generic exception for Paradox modules."""
class ParadoxCameraError(ParadoxModuleError):
"""Generic exception for Camera modules."""
| """ Python implementation of Paradox HD7X cameras (and future other modules)."""
class Paradoxmoduleerror(Exception):
"""Generic exception for Paradox modules."""
class Paradoxcameraerror(ParadoxModuleError):
"""Generic exception for Camera modules.""" |
## Editing same list and then separating at the end
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head==None: return head
# Add new nodes in old list
c = head
while (c!=None):
_next = c.next
c.next = Node(c.val)
c.next.next = _next
c = _next
# Assign random pointers to new nodes
c = head
while (c!=None):
if c.random!=None:
c.next.random = c.random.next
c = c.next.next
# Separate both linked lists
c = head
copyHead = head.next
copy = copyHead
while (copy.next!=None):
c.next = c.next.next
c = c.next
copy.next = copy.next.next
copy = copy.next
c.next = c.next.next
return copyHead
| """
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copy_random_list(self, head: 'Node') -> 'Node':
if head == None:
return head
c = head
while c != None:
_next = c.next
c.next = node(c.val)
c.next.next = _next
c = _next
c = head
while c != None:
if c.random != None:
c.next.random = c.random.next
c = c.next.next
c = head
copy_head = head.next
copy = copyHead
while copy.next != None:
c.next = c.next.next
c = c.next
copy.next = copy.next.next
copy = copy.next
c.next = c.next.next
return copyHead |
class RGBColor:
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __str__(self):
return "rgb({},{},{})".format(self.r, self.g, self.b)
def as_hex(self):
return HexColor("#%02x%02x%02x" % (self.r, self.g, self.b))
def as_cmyk(self):
k = min(1-self.r, 1-self.g, 1-self.b)
c = (1-self.r-k)/(1-k)
m = (1-self.g-k)/(1-k)
y = (1-self.b-k)/(1-k)
return CMYKColor(c, m, y, k)
def as_hsl(self):
r_scaled = self.r/255
g_scaled = self.g/255
b_scaled = self.b/255
c_max = max(r_scaled, g_scaled, b_scaled)
c_min = min(r_scaled, g_scaled, b_scaled)
lightness = (c_max + c_min) / 2
if c_max == c_min:
hue = 0
saturation = 0
else:
delta = c_max - c_min
hue = {
r_scaled: 60*((g_scaled-b_scaled)/delta % 6),
g_scaled: 60*((b_scaled-r_scaled)/delta+2),
b_scaled: 60*((r_scaled-g_scaled)/delta+4),
}[c_max]
saturation = delta/(1-abs(2*lightness-1))
return HSLColor(hue, saturation, lightness)
def as_rgb(self):
return self
def as_rgba(self):
return [self.r, self.g, self.b, self.a]
def complementary(self):
hsl = self.as_hsl(self.r, self.g, self.b)
comp_hue = hsl.h + 180
if comp_hue > 360:
comp_hue = comp_hue - 360
hsl.h = comp_hue
return hsl
def analogous(self):
pass
class RGBAColor:
def __init__(self, r, g, b, a=255):
self.r = r
self.g = g
self.b = b
self.a = a
def __str__(self):
return "rgba({},{},{},{})".format(self.r, self.g, self.b, self.a)
class HexColor:
def __init__(self, hexcode):
self.code =hexcode
def __str__(self):
return self.code
class CMYKColor:
def __init__(self, c, m, y, k):
self.c = c
self.m = m
self.y = y
self.k = k
def __str__(self):
return "cmyk({},{},{},{})".format(self.c, self.m, self.y, self.k)
class HSLColor:
def __init__(self, h, s, l):
self.h = h
self.s = s
self.l = l
def __str__(self):
return "hsl({},{},{})".format(self.h, self.s, self.l)
if __name__ == "__main__":
color = RGBColor(10, 10, 13)
print(color)
print(color.as_cmyk())
print(color.as_hsl())
print(color.as_hex())
| class Rgbcolor:
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __str__(self):
return 'rgb({},{},{})'.format(self.r, self.g, self.b)
def as_hex(self):
return hex_color('#%02x%02x%02x' % (self.r, self.g, self.b))
def as_cmyk(self):
k = min(1 - self.r, 1 - self.g, 1 - self.b)
c = (1 - self.r - k) / (1 - k)
m = (1 - self.g - k) / (1 - k)
y = (1 - self.b - k) / (1 - k)
return cmyk_color(c, m, y, k)
def as_hsl(self):
r_scaled = self.r / 255
g_scaled = self.g / 255
b_scaled = self.b / 255
c_max = max(r_scaled, g_scaled, b_scaled)
c_min = min(r_scaled, g_scaled, b_scaled)
lightness = (c_max + c_min) / 2
if c_max == c_min:
hue = 0
saturation = 0
else:
delta = c_max - c_min
hue = {r_scaled: 60 * ((g_scaled - b_scaled) / delta % 6), g_scaled: 60 * ((b_scaled - r_scaled) / delta + 2), b_scaled: 60 * ((r_scaled - g_scaled) / delta + 4)}[c_max]
saturation = delta / (1 - abs(2 * lightness - 1))
return hsl_color(hue, saturation, lightness)
def as_rgb(self):
return self
def as_rgba(self):
return [self.r, self.g, self.b, self.a]
def complementary(self):
hsl = self.as_hsl(self.r, self.g, self.b)
comp_hue = hsl.h + 180
if comp_hue > 360:
comp_hue = comp_hue - 360
hsl.h = comp_hue
return hsl
def analogous(self):
pass
class Rgbacolor:
def __init__(self, r, g, b, a=255):
self.r = r
self.g = g
self.b = b
self.a = a
def __str__(self):
return 'rgba({},{},{},{})'.format(self.r, self.g, self.b, self.a)
class Hexcolor:
def __init__(self, hexcode):
self.code = hexcode
def __str__(self):
return self.code
class Cmykcolor:
def __init__(self, c, m, y, k):
self.c = c
self.m = m
self.y = y
self.k = k
def __str__(self):
return 'cmyk({},{},{},{})'.format(self.c, self.m, self.y, self.k)
class Hslcolor:
def __init__(self, h, s, l):
self.h = h
self.s = s
self.l = l
def __str__(self):
return 'hsl({},{},{})'.format(self.h, self.s, self.l)
if __name__ == '__main__':
color = rgb_color(10, 10, 13)
print(color)
print(color.as_cmyk())
print(color.as_hsl())
print(color.as_hex()) |
class HightonConstants:
# is used for requests
GET = 'GET'
POST = 'POST'
PUT = 'PUT'
DELETE = 'DELETE'
HIGHRISE_URL = 'highrisehq.com'
# Company
COMPANIES = 'companies'
COMPANY = 'company'
COMPANY_NAME = 'company-name'
COMPANY_ID = 'company-id'
# Case
KASES = 'kases'
# Deal
DEALS = 'deals'
TASK = 'task'
TASKS = 'tasks'
# Person
PEOPLE = 'people'
PERSON = 'person'
EMAIL = 'email'
EMAILS = 'emails'
USER = 'user'
USERS = 'users'
GROUP = 'group'
GROUPS = 'groups'
NAME = 'name'
TITLE = 'title'
FIRST_NAME = 'first-name'
LAST_NAME = 'last-name'
CONTACT_DATA = 'contact-data'
PARENT_ID = 'parent-id'
EMAIL_ADDRESS = 'email-address'
EMAIL_ADDRESSES = 'email-addresses'
TOKEN = 'token'
DROPBOX = 'dropbox'
ADMIN = 'admin'
WEB_ADDRESS = 'web-address'
WEB_ADDRESSES = 'web-addresses'
PHONE_NUMBER = 'phone-number'
PHONE_NUMBERS = 'phone-numbers'
SUBJECT_DATA = 'subject_data'
SUBJECT_DATAS = 'subject_datas'
ADDRESS = 'address'
ADDRESSES = 'addresses'
DEAL_CATEGORIES = 'deal_categories'
DEAL_CATEGORY = 'deal-category'
TASK_CATEGORIES = 'task_categories'
TASK_CATEGORY = 'task-category'
NOTE = 'note'
NOTES = 'notes'
TAG = 'tag'
TAGS = 'tags'
SUBJECT_ID = 'subject-id'
SUBJECT_FIELD = 'subject-field'
SUBJECT_FIELDS = 'subject_fields'
SUBJECT_FIELD_ID = 'subject_field_id'
SUBJECT_FIELD_LABEL = 'subject_field_label'
URL = 'url'
ZIP = 'zip'
CITY = 'city'
STATE = 'state'
STREET = 'street'
NUMBER = 'number'
COUNTRY = 'country'
LOCATION = 'location'
ID = 'id'
BODY = 'body'
TYPE = 'type'
VALUE = 'value'
LABEL = 'label'
SEARCH = 'search'
COMMENT = 'comment'
COMMENTS = 'comments'
BACKGROUND = 'background'
RECORDING_ID = 'recording-id'
FRAME = 'frame'
ALERT_AT = 'alert-at'
PUBLIC = 'public'
RECURRING_PERIOD = 'recurring-period'
ANCHOR_TYPE = 'anchor-type'
DONE_AT = 'done-at'
AUTHOR_ID = 'author-id'
CLOSED_AT = 'closed-at'
CREATED_AT = 'created-at'
UPDATED_AT = 'updated-at'
VISIBLE_TO = 'visible-to'
GROUP_ID = 'group-id'
OWNER_ID = 'owner-id'
LINKEDIN_URL = 'linkedin-url'
AVATAR_URL = 'avatar_url'
ALL = 'all'
DEAL = 'deal'
PARTY = 'party'
PARTIES = 'parties'
CASE = 'kase'
CASES = 'kases'
TWITTER_ACCOUNTS = 'twitter-accounts'
TWITTER_ACCOUNT = 'twitter-account'
USERNAME = 'username'
PROTOCOL = 'protocol'
COLOR = 'color'
INSTANT_MESSENGERS = 'instant-messengers'
INSTANT_MESSENGER = 'instant-messenger'
ASSOCIATED_PARTIES = 'associated-parties'
ASSOCIATED_PARTY = 'associated-party'
ACCOUNT_ID = 'account-id'
CATEGORY_ID = 'category-id'
CURRENCY = 'currency'
DURATION = 'duration'
PARTY_ID = 'party-id'
PRICE = 'price'
PRICE_TYPE = 'price-type'
RESPONSIBLE_PARTY_ID = 'responsible-party-id'
STATUS = 'status'
STATUS_CHANGED_ON = 'status-changed-on'
CATEGORY = 'category'
SIZE = 'size'
DUE_AT = 'due-at'
ELEMENTS_COUNT = 'elements-count'
WON = 'won'
PENDING = 'pending'
LOST = 'lost'
COLLECTION_ID = 'collection-id'
COLLECTION_TYPE = 'collection-type'
ATTACHMENTS = 'attachments'
ATTACHMENT = 'attachment'
SUBJECT_NAME = 'subject-name'
SUBJECT_TYPE = 'subject-type'
SUBJECT_TYPES = [COMPANIES, KASES, DEALS, PEOPLE, ]
CUSTOM_FIELD_TYPES = [PARTY, DEAL, ALL, ]
| class Hightonconstants:
get = 'GET'
post = 'POST'
put = 'PUT'
delete = 'DELETE'
highrise_url = 'highrisehq.com'
companies = 'companies'
company = 'company'
company_name = 'company-name'
company_id = 'company-id'
kases = 'kases'
deals = 'deals'
task = 'task'
tasks = 'tasks'
people = 'people'
person = 'person'
email = 'email'
emails = 'emails'
user = 'user'
users = 'users'
group = 'group'
groups = 'groups'
name = 'name'
title = 'title'
first_name = 'first-name'
last_name = 'last-name'
contact_data = 'contact-data'
parent_id = 'parent-id'
email_address = 'email-address'
email_addresses = 'email-addresses'
token = 'token'
dropbox = 'dropbox'
admin = 'admin'
web_address = 'web-address'
web_addresses = 'web-addresses'
phone_number = 'phone-number'
phone_numbers = 'phone-numbers'
subject_data = 'subject_data'
subject_datas = 'subject_datas'
address = 'address'
addresses = 'addresses'
deal_categories = 'deal_categories'
deal_category = 'deal-category'
task_categories = 'task_categories'
task_category = 'task-category'
note = 'note'
notes = 'notes'
tag = 'tag'
tags = 'tags'
subject_id = 'subject-id'
subject_field = 'subject-field'
subject_fields = 'subject_fields'
subject_field_id = 'subject_field_id'
subject_field_label = 'subject_field_label'
url = 'url'
zip = 'zip'
city = 'city'
state = 'state'
street = 'street'
number = 'number'
country = 'country'
location = 'location'
id = 'id'
body = 'body'
type = 'type'
value = 'value'
label = 'label'
search = 'search'
comment = 'comment'
comments = 'comments'
background = 'background'
recording_id = 'recording-id'
frame = 'frame'
alert_at = 'alert-at'
public = 'public'
recurring_period = 'recurring-period'
anchor_type = 'anchor-type'
done_at = 'done-at'
author_id = 'author-id'
closed_at = 'closed-at'
created_at = 'created-at'
updated_at = 'updated-at'
visible_to = 'visible-to'
group_id = 'group-id'
owner_id = 'owner-id'
linkedin_url = 'linkedin-url'
avatar_url = 'avatar_url'
all = 'all'
deal = 'deal'
party = 'party'
parties = 'parties'
case = 'kase'
cases = 'kases'
twitter_accounts = 'twitter-accounts'
twitter_account = 'twitter-account'
username = 'username'
protocol = 'protocol'
color = 'color'
instant_messengers = 'instant-messengers'
instant_messenger = 'instant-messenger'
associated_parties = 'associated-parties'
associated_party = 'associated-party'
account_id = 'account-id'
category_id = 'category-id'
currency = 'currency'
duration = 'duration'
party_id = 'party-id'
price = 'price'
price_type = 'price-type'
responsible_party_id = 'responsible-party-id'
status = 'status'
status_changed_on = 'status-changed-on'
category = 'category'
size = 'size'
due_at = 'due-at'
elements_count = 'elements-count'
won = 'won'
pending = 'pending'
lost = 'lost'
collection_id = 'collection-id'
collection_type = 'collection-type'
attachments = 'attachments'
attachment = 'attachment'
subject_name = 'subject-name'
subject_type = 'subject-type'
subject_types = [COMPANIES, KASES, DEALS, PEOPLE]
custom_field_types = [PARTY, DEAL, ALL] |
"""
we define a video object to record video information.
"""
# coding: utf-8
class Video:
"""
obj
"""
def __init__(self, video_id):
self.video_id = video_id
self.user_id = ''
self.title = ''
self.upload_time = '' # timestamp
self.avatar_path = ''
self.avatar_url = ''
self.des = ''
def dump(self):
"""for insert a new video object to sqlite database."""
return (self.video_id, self.user_id,
self.title, self.upload_time,
self.avatar_path, self.avatar_url,
self.des)
| """
we define a video object to record video information.
"""
class Video:
"""
obj
"""
def __init__(self, video_id):
self.video_id = video_id
self.user_id = ''
self.title = ''
self.upload_time = ''
self.avatar_path = ''
self.avatar_url = ''
self.des = ''
def dump(self):
"""for insert a new video object to sqlite database."""
return (self.video_id, self.user_id, self.title, self.upload_time, self.avatar_path, self.avatar_url, self.des) |
""" GLSL shader code to render bitmap glyphs.\
:download:`[source] <../../../litGL/glsl_bitmap.py>`
Author:
2020-2021 Nicola Creati
Copyright:
2020-2021 Nicola Creati <ncreati@inogs.it>
License:
MIT/X11 License (see
:download:`license.txt <../../../license.txt>`)
"""
#:
VERTEX_SHADER = """
#version 330
layout(location=0) in vec2 position;
layout(location=1) in vec2 tex;
layout(location=2) in vec4 gp;
uniform mat4 T_MVP;
out vs_output
{
vec2 texCoord;
flat uvec4 glyphParam;
} vs_out;
void main()
{
gl_Position = T_MVP * vec4(position.x, position.y, 0.0f, 1.0f);
vs_out.texCoord = tex;
vs_out.glyphParam = uvec4(gp);
}
"""
#:
FRAGMENT_SHADER = """
#version 330
in vs_output
{
vec2 texCoord;
flat uvec4 glyphParam;
} fs_in;
out vec4 fragColor;
uniform sampler2D u_colorsTex;
uniform vec4 u_color;
void main()
{
vec4 sampled = texture(u_colorsTex, fs_in.texCoord);
fragColor = vec4(sampled.xyz, sampled.w * u_color.w);
}
"""
| """ GLSL shader code to render bitmap glyphs. :download:`[source] <../../../litGL/glsl_bitmap.py>`
Author:
2020-2021 Nicola Creati
Copyright:
2020-2021 Nicola Creati <ncreati@inogs.it>
License:
MIT/X11 License (see
:download:`license.txt <../../../license.txt>`)
"""
vertex_shader = '\n#version 330\n\nlayout(location=0) in vec2 position;\nlayout(location=1) in vec2 tex;\nlayout(location=2) in vec4 gp;\n\nuniform mat4 T_MVP;\n\nout vs_output\n{\n vec2 texCoord;\n flat uvec4 glyphParam;\n} vs_out;\n\nvoid main()\n{\n gl_Position = T_MVP * vec4(position.x, position.y, 0.0f, 1.0f);\n vs_out.texCoord = tex;\n vs_out.glyphParam = uvec4(gp);\n}\n\n'
fragment_shader = '\n#version 330\n\nin vs_output\n{\n vec2 texCoord;\n flat uvec4 glyphParam;\n} fs_in;\n\nout vec4 fragColor;\n\nuniform sampler2D u_colorsTex;\nuniform vec4 u_color;\n\nvoid main()\n{\n vec4 sampled = texture(u_colorsTex, fs_in.texCoord);\n fragColor = vec4(sampled.xyz, sampled.w * u_color.w);\n}\n' |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
odd = head
even = even_head = head.next
while even is not None and even.next is not None:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = even_head
return head
def test_odd_even_list_1():
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
r = Solution().oddEvenList(a)
assert r.val == 1
assert r.next.val == 3
assert r.next.next.val == 5
assert r.next.next.next.val == 2
assert r.next.next.next.next.val == 4
def test_odd_even_list_2():
a = ListNode(2)
b = ListNode(1)
c = ListNode(3)
d = ListNode(5)
e = ListNode(6)
f = ListNode(4)
g = ListNode(7)
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
f.next = g
r = Solution().oddEvenList(a)
assert r.val == 2
assert r.next.val == 3
assert r.next.next.val == 6
assert r.next.next.next.val == 7
assert r.next.next.next.next.val == 1
assert r.next.next.next.next.next.val == 5
assert r.next.next.next.next.next.next.val == 4
| class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def odd_even_list(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
odd = head
even = even_head = head.next
while even is not None and even.next is not None:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = even_head
return head
def test_odd_even_list_1():
a = list_node(1)
b = list_node(2)
c = list_node(3)
d = list_node(4)
e = list_node(5)
a.next = b
b.next = c
c.next = d
d.next = e
r = solution().oddEvenList(a)
assert r.val == 1
assert r.next.val == 3
assert r.next.next.val == 5
assert r.next.next.next.val == 2
assert r.next.next.next.next.val == 4
def test_odd_even_list_2():
a = list_node(2)
b = list_node(1)
c = list_node(3)
d = list_node(5)
e = list_node(6)
f = list_node(4)
g = list_node(7)
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
f.next = g
r = solution().oddEvenList(a)
assert r.val == 2
assert r.next.val == 3
assert r.next.next.val == 6
assert r.next.next.next.val == 7
assert r.next.next.next.next.val == 1
assert r.next.next.next.next.next.val == 5
assert r.next.next.next.next.next.next.val == 4 |
class BraviaProtocol:
# def __init__():
# def makeQuery(self, parameters):
# queries = [];
# while parameters:
# if parameters[0] in self.protocol.keys():
# queries.append(self.protocol[parameters[0]] + "?")
# parameters = parameters[1:]
# return queries
# def makeCommands(self, params):
# commands = []
# for c, p in params.items():
# if c in self.protocol.keys():
# commands.append(str(list(self.protocol.values())[list(self.protocol.keys()).index(c)] + p))
# return commands
def parseEvents(self, events):
has_changed = True
# while events:
# ev = events[0][0:2]
# if ev in self.protocol.values():
# val = ''
# ob = events[0][2:]
# key = list(self.protocol.keys())[list(self.protocol.values()).index(ev)]
# if key in self.state.keys():
# val = self.state[key]
# if ob != val:
# has_changed = True
# self.state[key] = ob
# events = events[1:]
return has_changed
# def getState(self):
# return self.state
| class Braviaprotocol:
def parse_events(self, events):
has_changed = True
return has_changed |
class Value():
def __init__(self):
self._value = None
def __set__(self, obj, value):
self._value = value
def __get__(self, obj, obj_type):
return self._value - obj.commission * self._value | class Value:
def __init__(self):
self._value = None
def __set__(self, obj, value):
self._value = value
def __get__(self, obj, obj_type):
return self._value - obj.commission * self._value |
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
# brute force - time complexity O(n^2)
def two_sum(list, target):
for f_index, f_value in enumerate(list):
for s_index, s_value in enumerate(list[f_index+1:]):
if (f_value + s_value) == target:
return [f_index, list.index(s_value)]
return None
| def two_sum(list, target):
for (f_index, f_value) in enumerate(list):
for (s_index, s_value) in enumerate(list[f_index + 1:]):
if f_value + s_value == target:
return [f_index, list.index(s_value)]
return None |
SECRET_KEY = 'XXX'
DEBUG=False
# API-specific
API_500PX_KEY = 'XXX'
API_500PX_SECRET = 'XXX'
API_RIJKS = 'XXX'
FLICKR_KEY = 'XXX'
FLICKR_SECRET = 'XXX'
# Database-specific
SQLALCHEMY_DATABASE_URI = 'postgresql://{}:{}@{}:{}/{}'.format('cctest',
'cctest',
'localhost',
'5432',
'openledgertest')
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG_TB_ENABLED = False
TESTING=True
| secret_key = 'XXX'
debug = False
api_500_px_key = 'XXX'
api_500_px_secret = 'XXX'
api_rijks = 'XXX'
flickr_key = 'XXX'
flickr_secret = 'XXX'
sqlalchemy_database_uri = 'postgresql://{}:{}@{}:{}/{}'.format('cctest', 'cctest', 'localhost', '5432', 'openledgertest')
sqlalchemy_track_modifications = False
debug_tb_enabled = False
testing = True |
#!/usr/bin/env python3
"""Project Euler - Problem 17 Module"""
def problem17(limit):
"""Problem 17 - Number letter counts"""
# store known results
result = 0
for x in range(1, limit+1):
wl = 0
# thousends
t = int(x/THOUSAND)
if t > 0:
wl += len(LANGUAGE_DICT[t]) + len(LANGUAGE_DICT[THOUSAND])
# hundreds
h = int( (x % THOUSAND) / HUNDRED)
if (h > 0):
wl += len(LANGUAGE_DICT[h]) + len(LANGUAGE_DICT[HUNDRED])
# < 100
h_remainder = int(x % HUNDRED)
if h_remainder > 0:
if (h > 0):
wl += 3 # "and"
if (h_remainder < 20):
wl += len(LANGUAGE_DICT[h_remainder])
else:
d = int( h_remainder / TEN)
if (d > 0):
wl += len(LANGUAGE_DICT[d*TEN])
s = h_remainder % TEN
if (s > 0):
wl += len(LANGUAGE_DICT[s])
result += wl
return result
TEN = 10
HUNDRED = 100
THOUSAND = 1000
# Dictionary
LANGUAGE_DICT = {}
LANGUAGE_DICT[1] = "one"
LANGUAGE_DICT[2] = "two"
LANGUAGE_DICT[3] = "three"
LANGUAGE_DICT[4] = "four"
LANGUAGE_DICT[5] = "five"
LANGUAGE_DICT[6] = "six"
LANGUAGE_DICT[7] = "seven"
LANGUAGE_DICT[8] = "eight"
LANGUAGE_DICT[9] = "nine"
LANGUAGE_DICT[TEN] = "ten"
LANGUAGE_DICT[11] = "eleven"
LANGUAGE_DICT[12] = "twelve"
LANGUAGE_DICT[13] = "thirteen"
LANGUAGE_DICT[14] = "fourteen"
LANGUAGE_DICT[15] = "fifteen"
LANGUAGE_DICT[16] = "sixteen"
LANGUAGE_DICT[17] = "seventeen"
LANGUAGE_DICT[18] = "eighteen"
LANGUAGE_DICT[19] = "nineteen"
LANGUAGE_DICT[20] = "twenty"
LANGUAGE_DICT[30] = "thirty"
LANGUAGE_DICT[40] = "forty"
LANGUAGE_DICT[50] = "fifty"
LANGUAGE_DICT[60] = "sixty"
LANGUAGE_DICT[70] = "seventy"
LANGUAGE_DICT[80] = "eighty"
LANGUAGE_DICT[90] = "ninety"
LANGUAGE_DICT[HUNDRED] = "hundred"
LANGUAGE_DICT[THOUSAND] = "thousand"
def run():
"""Default Run Method"""
return problem17(1000)
if __name__ == '__main__':
print("Result: ", run())
| """Project Euler - Problem 17 Module"""
def problem17(limit):
"""Problem 17 - Number letter counts"""
result = 0
for x in range(1, limit + 1):
wl = 0
t = int(x / THOUSAND)
if t > 0:
wl += len(LANGUAGE_DICT[t]) + len(LANGUAGE_DICT[THOUSAND])
h = int(x % THOUSAND / HUNDRED)
if h > 0:
wl += len(LANGUAGE_DICT[h]) + len(LANGUAGE_DICT[HUNDRED])
h_remainder = int(x % HUNDRED)
if h_remainder > 0:
if h > 0:
wl += 3
if h_remainder < 20:
wl += len(LANGUAGE_DICT[h_remainder])
else:
d = int(h_remainder / TEN)
if d > 0:
wl += len(LANGUAGE_DICT[d * TEN])
s = h_remainder % TEN
if s > 0:
wl += len(LANGUAGE_DICT[s])
result += wl
return result
ten = 10
hundred = 100
thousand = 1000
language_dict = {}
LANGUAGE_DICT[1] = 'one'
LANGUAGE_DICT[2] = 'two'
LANGUAGE_DICT[3] = 'three'
LANGUAGE_DICT[4] = 'four'
LANGUAGE_DICT[5] = 'five'
LANGUAGE_DICT[6] = 'six'
LANGUAGE_DICT[7] = 'seven'
LANGUAGE_DICT[8] = 'eight'
LANGUAGE_DICT[9] = 'nine'
LANGUAGE_DICT[TEN] = 'ten'
LANGUAGE_DICT[11] = 'eleven'
LANGUAGE_DICT[12] = 'twelve'
LANGUAGE_DICT[13] = 'thirteen'
LANGUAGE_DICT[14] = 'fourteen'
LANGUAGE_DICT[15] = 'fifteen'
LANGUAGE_DICT[16] = 'sixteen'
LANGUAGE_DICT[17] = 'seventeen'
LANGUAGE_DICT[18] = 'eighteen'
LANGUAGE_DICT[19] = 'nineteen'
LANGUAGE_DICT[20] = 'twenty'
LANGUAGE_DICT[30] = 'thirty'
LANGUAGE_DICT[40] = 'forty'
LANGUAGE_DICT[50] = 'fifty'
LANGUAGE_DICT[60] = 'sixty'
LANGUAGE_DICT[70] = 'seventy'
LANGUAGE_DICT[80] = 'eighty'
LANGUAGE_DICT[90] = 'ninety'
LANGUAGE_DICT[HUNDRED] = 'hundred'
LANGUAGE_DICT[THOUSAND] = 'thousand'
def run():
"""Default Run Method"""
return problem17(1000)
if __name__ == '__main__':
print('Result: ', run()) |
_runs_on_key = "runs-on"
def execute(obj: dict) -> None:
default_runner = obj.get(_runs_on_key)
if not default_runner:
return
for job in obj.get("jobs", {}).values():
if _runs_on_key not in job:
job[_runs_on_key] = default_runner
# Clean up the left-overs
obj.pop(_runs_on_key)
| _runs_on_key = 'runs-on'
def execute(obj: dict) -> None:
default_runner = obj.get(_runs_on_key)
if not default_runner:
return
for job in obj.get('jobs', {}).values():
if _runs_on_key not in job:
job[_runs_on_key] = default_runner
obj.pop(_runs_on_key) |
class SisCheckpointSubstage(basestring):
"""
sis checkpoint sub-stage
Possible values:
<ul>
<li> "Sort_pass2" - Sorting the fingerprints for deduplication
</ul>
"""
@staticmethod
def get_api_name():
return "sis-checkpoint-substage"
| class Sischeckpointsubstage(basestring):
"""
sis checkpoint sub-stage
Possible values:
<ul>
<li> "Sort_pass2" - Sorting the fingerprints for deduplication
</ul>
"""
@staticmethod
def get_api_name():
return 'sis-checkpoint-substage' |
# **args
def save_user(**user):
print(user['name'])
#**user retorna um dict
save_user(id=1, name='admin') | def save_user(**user):
print(user['name'])
save_user(id=1, name='admin') |
class Service(object):
class Version(object):
def __init__(self, number, created_at, updated_at, deleted_at):
self.number = number
self.created_at = created_at
self.updated_at = updated_at
self.deleted_at = deleted_at
def __init__(self, id, name, version, versions, **kwargs):
self.id = id
self.name = name
self.version = version
self.versions = versions
class Invoice(object):
class Region(object):
class Details(object):
class Tier(object):
def __init__(self, name, units, price, discounted_price, total, **kwargs):
self.name = name
self.units = units
self.price = price
self.discounted_price = discounted_price
self.total = total
def __init__(self, tiers, total, **kwargs):
self.tiers = tiers
self.total = total
@property
def total_units(self):
"""
:return: The number of Gigabytes if bandwidth or the number of requests
"""
return sum([t.units for t in self.tiers])
class Bandwidth(Details):
pass
class Requests(Details):
pass
def __init__(self, bandwidth, requests, cost, **kwargs):
self.bandwidth = bandwidth
self.requests = requests
self.cost = cost
def __init__(self, invoice_id, start_time, end_time, regions, **kwargs):
self.invoice_id = invoice_id
self.start_time = start_time
self.end_time = end_time
self.regions = regions
class Stats(object):
class DailyStats(object):
def __init__(self, service_id, start_time, bandwidth, requests, **kwargs):
self.service_id = service_id
self.start_time = start_time
self.bandwidth = bandwidth
self.requests = requests
def __init__(self, daily_stats, region, **kwargs):
self.daily_stats = daily_stats
self.region = region
@property
def total_bandwidth(self):
return sum([d.bandwidth for d in self.daily_stats])
@property
def total_requests(self):
return sum([d.requests for d in self.daily_stats])
@property
def days(self):
return len(self.daily_stats)
| class Service(object):
class Version(object):
def __init__(self, number, created_at, updated_at, deleted_at):
self.number = number
self.created_at = created_at
self.updated_at = updated_at
self.deleted_at = deleted_at
def __init__(self, id, name, version, versions, **kwargs):
self.id = id
self.name = name
self.version = version
self.versions = versions
class Invoice(object):
class Region(object):
class Details(object):
class Tier(object):
def __init__(self, name, units, price, discounted_price, total, **kwargs):
self.name = name
self.units = units
self.price = price
self.discounted_price = discounted_price
self.total = total
def __init__(self, tiers, total, **kwargs):
self.tiers = tiers
self.total = total
@property
def total_units(self):
"""
:return: The number of Gigabytes if bandwidth or the number of requests
"""
return sum([t.units for t in self.tiers])
class Bandwidth(Details):
pass
class Requests(Details):
pass
def __init__(self, bandwidth, requests, cost, **kwargs):
self.bandwidth = bandwidth
self.requests = requests
self.cost = cost
def __init__(self, invoice_id, start_time, end_time, regions, **kwargs):
self.invoice_id = invoice_id
self.start_time = start_time
self.end_time = end_time
self.regions = regions
class Stats(object):
class Dailystats(object):
def __init__(self, service_id, start_time, bandwidth, requests, **kwargs):
self.service_id = service_id
self.start_time = start_time
self.bandwidth = bandwidth
self.requests = requests
def __init__(self, daily_stats, region, **kwargs):
self.daily_stats = daily_stats
self.region = region
@property
def total_bandwidth(self):
return sum([d.bandwidth for d in self.daily_stats])
@property
def total_requests(self):
return sum([d.requests for d in self.daily_stats])
@property
def days(self):
return len(self.daily_stats) |
# keys TabbinPoint
OFFSET_DX = 'OFFSET_DX' # DOUBLE
OFFSET_DY = 'OFFSET_DY' # DOUBLE
OFFSET_DZ = 'OFFSET_DZ' # DOUBLE
OFFSET_DLENGTH = 'OFFSET_DLENGTH' # DOUBLE
OFFSET_LINTENSITY = 'OFFSET_LINTENSITY' # LONG
OFFSET_IFILTER_OBSOLETE = 'OFFSET_IFILTER_OBSOLETE' # SHORT
OFFSET_ISYMSETTING_OBSOLETE = 'OFFSET_ISYMSETTING_OBSOLETE' # SHORT
OFFSET_ISWSMODE_OBSOLETE = 'OFFSET_ISWSMODE_OBSOLETE' # SHORT
OFFSET_IPHTSCANTYPE = 'OFFSET_IPHTSCANTYPE' # SHORT
OFFSET_IXPIX = 'OFFSET_IXPIX' # SHORT
OFFSET_IYPIX = 'OFFSET_IYPIX' # SHORT
OFFSET_FCENTROIDX = 'OFFSET_FCENTROIDX' # FLOAT, starts from 0
OFFSET_FCENTROIDY = 'OFFSET_FCENTROIDY' # FLOAT, starts from 0
OFFSET_DAPHTSTARTANGLESRAD = 'OFFSET_DAPHTSTARTANGLESRAD' # 6x DOUBLE
OFFSET_DAPHTENDANGLESRAD = 'OFFSET_DAPHTENDANGLESRAD' # 6x DOUBLE
OFFSET_LCALCULATIONSTATUS = 'OFFSET_LCALCULATIONSTATUS' # LONG
OFFSET_UTWINGROUPFLAGS = 'OFFSET_UTWINGROUPFLAGS' # TWINGROUPFLAGS 4x BYTE
OFFSET_DWRUNFRAME1BASED = 'OFFSET_DWRUNFRAME1BASED' # DWORD
OFFSET_DWFRAMESTAMP_OR_LO_RINGNUMBER_HI_FRAMEID = 'OFFSET_DWFRAMESTAMP_OR_LO_RINGNUMBER_HI_FRAMEID' # DWORD
# keys CrysalisTabbinController
OFFSET_GROUPSTART = "OFFSET_GROUPSTART"
OFFSET_GROUPKEY = "OFFSET_GROUPKEY"
OFFSET_GROUPNEXT = "OFFSET_GROUPNEXT"
OFFSET_POINT_NUM = "OFFSET_POINT_NUM"
OFFSET_POINT_LIST = "OFFSET_POINT_LIST"
OFFSET_IVERSION_TABBIN_HEADER = "OFFSET_IVERSION_TABBIN_HEADER"
OFFSET_GROUP_LIST = "OFFSET_GROUP_LIST"
OFFSET_POINT_LISTNEXT = "OFFSET_POINT_LIST_INCREMENT"
| offset_dx = 'OFFSET_DX'
offset_dy = 'OFFSET_DY'
offset_dz = 'OFFSET_DZ'
offset_dlength = 'OFFSET_DLENGTH'
offset_lintensity = 'OFFSET_LINTENSITY'
offset_ifilter_obsolete = 'OFFSET_IFILTER_OBSOLETE'
offset_isymsetting_obsolete = 'OFFSET_ISYMSETTING_OBSOLETE'
offset_iswsmode_obsolete = 'OFFSET_ISWSMODE_OBSOLETE'
offset_iphtscantype = 'OFFSET_IPHTSCANTYPE'
offset_ixpix = 'OFFSET_IXPIX'
offset_iypix = 'OFFSET_IYPIX'
offset_fcentroidx = 'OFFSET_FCENTROIDX'
offset_fcentroidy = 'OFFSET_FCENTROIDY'
offset_daphtstartanglesrad = 'OFFSET_DAPHTSTARTANGLESRAD'
offset_daphtendanglesrad = 'OFFSET_DAPHTENDANGLESRAD'
offset_lcalculationstatus = 'OFFSET_LCALCULATIONSTATUS'
offset_utwingroupflags = 'OFFSET_UTWINGROUPFLAGS'
offset_dwrunframe1_based = 'OFFSET_DWRUNFRAME1BASED'
offset_dwframestamp_or_lo_ringnumber_hi_frameid = 'OFFSET_DWFRAMESTAMP_OR_LO_RINGNUMBER_HI_FRAMEID'
offset_groupstart = 'OFFSET_GROUPSTART'
offset_groupkey = 'OFFSET_GROUPKEY'
offset_groupnext = 'OFFSET_GROUPNEXT'
offset_point_num = 'OFFSET_POINT_NUM'
offset_point_list = 'OFFSET_POINT_LIST'
offset_iversion_tabbin_header = 'OFFSET_IVERSION_TABBIN_HEADER'
offset_group_list = 'OFFSET_GROUP_LIST'
offset_point_listnext = 'OFFSET_POINT_LIST_INCREMENT' |
# -*- coding: utf-8 -*-
"""
TSPL - TimScriptProgrammingLanguage
A simple programming language and interpreter in python
- more of a learning device than a practical use language
Created on Sat May 9 20:24:51 2020
@author: tim_s
"""
class Exp:
""" An expression to be evaluated
can put default behaviour here
"""
def __init__(self):
pass
def eval(self):
return None
def __str__(self):
return ""
def has_zero(self):
return False
class Nul(Exp):
""" Used to represent a null value """
def __init__(self):
super().__init__()
def __str__(self):
return "nul"
class Int(Exp):
""" A constant int """
def __init__(self, i):
super().__init__()
self.i = i
def eval(self):
return self.i
def __str__(self):
return str(self.i)
def has_zero(self):
return self.i == 0
class Negate(Exp):
""" Negated expression """
def __init__(self, e):
super().__init__()
self.e = e
def eval(self):
return Int(-(self.e.eval()))
def __str__(self):
return "-(" + str(self.e) + ")"
def has_zero(self):
return self.e.has_zero()
class Add(Exp):
""" Expression representing the result
of adding two expressions
"""
def __init__(self, e1, e2):
super().__init__()
self.e1 = e1
self.e2 = e2
def eval(self):
return Int(self.e1.eval() + self.e2.eval())
def __str__(self):
return "(" + str(self.e1) + " + " + str(self.e2) + ")"
def has_zero(self):
return self.e1.has_zero() or self.e2.has_zero()
class Multiply(Exp):
""" Expression representing the result
of multiplying two expressions
"""
def __init__(self, e1, e2):
super().__init__()
self.e1 = e1
self.e2 = e2
def eval(self):
return Int(self.e1.eval().i * self.e2.eval().i)
def __str__(self):
return "(" + str(self.e1) + " * " + str(self.e2) + ")"
def has_zero(self):
self.e1.has_zero() or self.e2.has_zero()
# TODO: change implementation to use pure OOP
# class Divide(Exp):
# """ Expression representing the result
# of dividing two expressions
# """
# def __init(self, exp1: Exp, exp2: Exp):
# super().__init__()
# self.exp1 = exp1
# self.exp2 = exp2
# class Variable(Exp):
# """ A variable mapping a string to an expression """
# def __init__(self, name: str, value: Exp):
# super().__init__()
# self.name = name
# self.value = value
# class Pair(Exp):
# """ A pair of expressions
# use Nul expression to end list
# ex: Pair(e1, Pair(e2, Nul)) == [e1, e2]
# """
# def __init__(self, exp1: Exp, exp2: Exp):
# super().__init__()
# self.exp1 = exp1
# self.exp2 = exp2
| """
TSPL - TimScriptProgrammingLanguage
A simple programming language and interpreter in python
- more of a learning device than a practical use language
Created on Sat May 9 20:24:51 2020
@author: tim_s
"""
class Exp:
""" An expression to be evaluated
can put default behaviour here
"""
def __init__(self):
pass
def eval(self):
return None
def __str__(self):
return ''
def has_zero(self):
return False
class Nul(Exp):
""" Used to represent a null value """
def __init__(self):
super().__init__()
def __str__(self):
return 'nul'
class Int(Exp):
""" A constant int """
def __init__(self, i):
super().__init__()
self.i = i
def eval(self):
return self.i
def __str__(self):
return str(self.i)
def has_zero(self):
return self.i == 0
class Negate(Exp):
""" Negated expression """
def __init__(self, e):
super().__init__()
self.e = e
def eval(self):
return int(-self.e.eval())
def __str__(self):
return '-(' + str(self.e) + ')'
def has_zero(self):
return self.e.has_zero()
class Add(Exp):
""" Expression representing the result
of adding two expressions
"""
def __init__(self, e1, e2):
super().__init__()
self.e1 = e1
self.e2 = e2
def eval(self):
return int(self.e1.eval() + self.e2.eval())
def __str__(self):
return '(' + str(self.e1) + ' + ' + str(self.e2) + ')'
def has_zero(self):
return self.e1.has_zero() or self.e2.has_zero()
class Multiply(Exp):
""" Expression representing the result
of multiplying two expressions
"""
def __init__(self, e1, e2):
super().__init__()
self.e1 = e1
self.e2 = e2
def eval(self):
return int(self.e1.eval().i * self.e2.eval().i)
def __str__(self):
return '(' + str(self.e1) + ' * ' + str(self.e2) + ')'
def has_zero(self):
self.e1.has_zero() or self.e2.has_zero() |
# Tests Python 3.5+'s ops
# BINARY_MATRIX_MULTIPLY and INPLACE_MATRIX_MULTIPLY
# code taken from pycdc tests/35_matrix_mult_oper.pyc.src
m = [1, 2] @ [3, 4]
m @= [5, 6]
| m = [1, 2] @ [3, 4]
m @= [5, 6] |
apple=map(int,input().split())
high=int(input())+30
sum=0
for i in apple:
if i<=high:sum+=1
print(sum) | apple = map(int, input().split())
high = int(input()) + 30
sum = 0
for i in apple:
if i <= high:
sum += 1
print(sum) |
TEST = """initial state: #..#.#..##......###...###
...## => #
..#.. => #
.#... => #
.#.#. => #
.#.## => #
.##.. => #
.#### => #
#.#.# => #
#.### => #
##.#. => #
##.## => #
###.. => #
###.# => #
####. => #
""".splitlines()
def read_lines():
with open('input.txt', 'r') as f:
return [l.strip() for l in f.readlines()]
def parse_lines(lines):
initial_state = lines[0][15:]
rules = {}
for line in lines[2:]:
pattern, _, result = line.partition(' => ')
rules[pattern] = result
return initial_state, rules
def step(state, rules):
result = '..'
for idx in range(len(state) - 4):
c = rules.get(state[idx:idx + 5], '.')
result += c
return result + '..'
def value(state, offset):
first = state.find('#')
result = 0
for i in range(first, len(state)):
if state[i] == '#':
result += (i + offset)
return result
def shift(state, offset):
idx = state.find('#')
if idx < 5:
state = ('.' * 10) + state
offset -= 10
elif idx > 15:
state = state[10:]
offset += 10
idx = state.rfind('#')
if idx > (len(state) - 5):
state = state + ('.' * 10)
elif idx < (len(state) - 15):
state = state[:-10]
return state, offset
def run(state, rules, steps):
offset = 0
for i in range(steps):
state, offset = shift(state, offset)
state = step(state, rules)
return value(state, offset)
if __name__ == '__main__':
# lines = TEST
lines = read_lines()
state, rules = parse_lines(lines)
result = run(state, rules, 20)
print("Part1: sum = %d" % result)
# somewhere below 1000 the values get regular and repeat ...
offset = run(state, rules, 1000)
delta = run(state, rules, 2000) - offset
steps = 50000000000
print("Part2: steps = %d, sum = %d" % (steps, (steps / 1000 - 1) * delta + offset))
| test = 'initial state: #..#.#..##......###...###\n\n...## => #\n..#.. => #\n.#... => #\n.#.#. => #\n.#.## => #\n.##.. => #\n.#### => #\n#.#.# => #\n#.### => #\n##.#. => #\n##.## => #\n###.. => #\n###.# => #\n####. => #\n'.splitlines()
def read_lines():
with open('input.txt', 'r') as f:
return [l.strip() for l in f.readlines()]
def parse_lines(lines):
initial_state = lines[0][15:]
rules = {}
for line in lines[2:]:
(pattern, _, result) = line.partition(' => ')
rules[pattern] = result
return (initial_state, rules)
def step(state, rules):
result = '..'
for idx in range(len(state) - 4):
c = rules.get(state[idx:idx + 5], '.')
result += c
return result + '..'
def value(state, offset):
first = state.find('#')
result = 0
for i in range(first, len(state)):
if state[i] == '#':
result += i + offset
return result
def shift(state, offset):
idx = state.find('#')
if idx < 5:
state = '.' * 10 + state
offset -= 10
elif idx > 15:
state = state[10:]
offset += 10
idx = state.rfind('#')
if idx > len(state) - 5:
state = state + '.' * 10
elif idx < len(state) - 15:
state = state[:-10]
return (state, offset)
def run(state, rules, steps):
offset = 0
for i in range(steps):
(state, offset) = shift(state, offset)
state = step(state, rules)
return value(state, offset)
if __name__ == '__main__':
lines = read_lines()
(state, rules) = parse_lines(lines)
result = run(state, rules, 20)
print('Part1: sum = %d' % result)
offset = run(state, rules, 1000)
delta = run(state, rules, 2000) - offset
steps = 50000000000
print('Part2: steps = %d, sum = %d' % (steps, (steps / 1000 - 1) * delta + offset)) |
# -*- coding: utf-8 -*-
SYSTEM = "O"
USER = "I"
TYPE_CHAT = (
(SYSTEM, u'Gozokia'),
(USER, u'User'),
)
| system = 'O'
user = 'I'
type_chat = ((SYSTEM, u'Gozokia'), (USER, u'User')) |
class FluidSettings:
type = None
| class Fluidsettings:
type = None |
class AtbashCipher:
def encrypt(self, string):
lst = []
for elem in string.lower():
if elem.isalpha():
lst+=chr(219-ord(elem))
else:
lst+=[elem]
return ''.join(lst).lower()
def decrypt(self, string):
return self.encrypt(string).lower() #same result for encryption | class Atbashcipher:
def encrypt(self, string):
lst = []
for elem in string.lower():
if elem.isalpha():
lst += chr(219 - ord(elem))
else:
lst += [elem]
return ''.join(lst).lower()
def decrypt(self, string):
return self.encrypt(string).lower() |
def forward(t):
t.penup()
t.forward(3)
def no_draw_forward(t):
t.pendown()
t.forward(3)
axiom = 'A'
n = 5
subs = {
'A': 'ABA',
'B': 'BBB'
}
graphics = {
'A': lambda t: forward(t),
'B': lambda t: no_draw_forward(t)
}
| def forward(t):
t.penup()
t.forward(3)
def no_draw_forward(t):
t.pendown()
t.forward(3)
axiom = 'A'
n = 5
subs = {'A': 'ABA', 'B': 'BBB'}
graphics = {'A': lambda t: forward(t), 'B': lambda t: no_draw_forward(t)} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.