content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
class Pattern(object):
"""
[summary]
"""
@staticmethod
def default() -> str:
"""[summary]
Returns:
pattern (str): [{level}][{datetime}] - {transaction} - {project_name}.{class_name}.{function_name} - _message: traceback
"""
_message = "{message}"
_title_pattern: str = "[{level}][{datetime}] - {transaction} - "
_name_pattern: str = "{project_name}.{class_name}.{function_name} - "
_loggger_pattern = f"{_title_pattern}{_name_pattern}{_message}"
pattern = _loggger_pattern
return pattern
|
class Pattern(object):
"""
[summary]
"""
@staticmethod
def default() -> str:
"""[summary]
Returns:
pattern (str): [{level}][{datetime}] - {transaction} - {project_name}.{class_name}.{function_name} - _message: traceback
"""
_message = '{message}'
_title_pattern: str = '[{level}][{datetime}] - {transaction} - '
_name_pattern: str = '{project_name}.{class_name}.{function_name} - '
_loggger_pattern = f'{_title_pattern}{_name_pattern}{_message}'
pattern = _loggger_pattern
return pattern
|
_first_index_in_every_row_list = list()
def _build_first_index_in_every_row_list():
global _first_index_in_every_row_list
_first_index_in_every_row_list.clear()
_first_index_in_every_row_list.append(0)
for delta in range(199, 1, -1):
_first_index_in_every_row_list.append(_first_index_in_every_row_list[-1] + delta)
_build_first_index_in_every_row_list()
def parse_index(index, step=1):
if not isinstance(index, int):
index = int(index)
date_seq_no = (index // 19900) * step
correlation_no = index % 19900
# Use binary search to get fund number:
# FIXME: Consider to compute fund number directly.
low = correlation_no // 199 # include
high = min(low * 2 + 1, len(_first_index_in_every_row_list)) # exclude
while low < high:
middle = (low + high) // 2
if _first_index_in_every_row_list[middle] < correlation_no:
low = middle + 1
elif _first_index_in_every_row_list[middle] > correlation_no:
high = middle
else:
low = middle
break
if _first_index_in_every_row_list[low] > correlation_no:
low -= 1
fund1_no = low
fund2_no = correlation_no - _first_index_in_every_row_list[fund1_no] + fund1_no + 1
return date_seq_no, fund1_no, fund2_no, correlation_no
def calculate_correlation_no(fund1_no, fund2_no):
if fund1_no == fund2_no:
return None
if fund1_no > fund2_no:
tmp = fund1_no
fund1_no = fund2_no
fund2_no = tmp
if fund1_no < 0:
raise ValueError('fund1_no should >= 0, got %d.' % fund1_no)
if fund2_no >= 200:
raise ValueError('fund2_no should < 200, got %d.' % fund2_no)
'''
input:
f1 in [0, 198]
f2 in [f1 + 1, 199]
output:
c = (199 + 198 + ... + (199 - f1 + 1)) + (f2 - (f1 + 1))
|----------- f1 terms -----------|
= (199 + (199 - f1 + 1)) * f1 / 2 + (f2 - f1 - 1)
= (399 - f1) * f1 / 2 + f2 - f1 - 1
'''
correlation_no = int(((399 - fund1_no) * fund1_no) // 2) + fund2_no - fund1_no - 1
return correlation_no
def parse_square_ex_index(index, step=1):
if not isinstance(index, int):
index = int(index)
date_seq_no = (index // 40000) * step
index_rem = index % 40000
fund1_no = index_rem // 200
fund2_no = index_rem % 200
correlation_no = calculate_correlation_no(fund1_no, fund2_no)
return date_seq_no, fund1_no, fund2_no, correlation_no
|
_first_index_in_every_row_list = list()
def _build_first_index_in_every_row_list():
global _first_index_in_every_row_list
_first_index_in_every_row_list.clear()
_first_index_in_every_row_list.append(0)
for delta in range(199, 1, -1):
_first_index_in_every_row_list.append(_first_index_in_every_row_list[-1] + delta)
_build_first_index_in_every_row_list()
def parse_index(index, step=1):
if not isinstance(index, int):
index = int(index)
date_seq_no = index // 19900 * step
correlation_no = index % 19900
low = correlation_no // 199
high = min(low * 2 + 1, len(_first_index_in_every_row_list))
while low < high:
middle = (low + high) // 2
if _first_index_in_every_row_list[middle] < correlation_no:
low = middle + 1
elif _first_index_in_every_row_list[middle] > correlation_no:
high = middle
else:
low = middle
break
if _first_index_in_every_row_list[low] > correlation_no:
low -= 1
fund1_no = low
fund2_no = correlation_no - _first_index_in_every_row_list[fund1_no] + fund1_no + 1
return (date_seq_no, fund1_no, fund2_no, correlation_no)
def calculate_correlation_no(fund1_no, fund2_no):
if fund1_no == fund2_no:
return None
if fund1_no > fund2_no:
tmp = fund1_no
fund1_no = fund2_no
fund2_no = tmp
if fund1_no < 0:
raise value_error('fund1_no should >= 0, got %d.' % fund1_no)
if fund2_no >= 200:
raise value_error('fund2_no should < 200, got %d.' % fund2_no)
'\n input:\n f1 in [0, 198]\n f2 in [f1 + 1, 199]\n\n output:\n c = (199 + 198 + ... + (199 - f1 + 1)) + (f2 - (f1 + 1))\n |----------- f1 terms -----------|\n = (199 + (199 - f1 + 1)) * f1 / 2 + (f2 - f1 - 1)\n = (399 - f1) * f1 / 2 + f2 - f1 - 1\n '
correlation_no = int((399 - fund1_no) * fund1_no // 2) + fund2_no - fund1_no - 1
return correlation_no
def parse_square_ex_index(index, step=1):
if not isinstance(index, int):
index = int(index)
date_seq_no = index // 40000 * step
index_rem = index % 40000
fund1_no = index_rem // 200
fund2_no = index_rem % 200
correlation_no = calculate_correlation_no(fund1_no, fund2_no)
return (date_seq_no, fund1_no, fund2_no, correlation_no)
|
# Function for finding if it possible
# to obtain sorted array or not
def fun(arr, n, k):
v = []
# Iterate over all elements until K
for i in range(k):
# Store elements as multiples of K
for j in range(i, n, k):
v.append(arr[j]);
# Sort the elements
v.sort();
x = 0
# Put elements in their required position
for j in range(i, n, k):
arr[j] = v[x];
x += 1
v = []
# Check if the array becomes sorted or not
for i in range(n - 1):
if (arr[i] > arr[i + 1]):
return False
return True
# Driver code
nk= input().split()
K = int(nk[1])
n = int(nk[0])
arr= list(map(int,input().split()))
if (fun(arr, n, K)):
print("True")
else:
print("False")
|
def fun(arr, n, k):
v = []
for i in range(k):
for j in range(i, n, k):
v.append(arr[j])
v.sort()
x = 0
for j in range(i, n, k):
arr[j] = v[x]
x += 1
v = []
for i in range(n - 1):
if arr[i] > arr[i + 1]:
return False
return True
nk = input().split()
k = int(nk[1])
n = int(nk[0])
arr = list(map(int, input().split()))
if fun(arr, n, K):
print('True')
else:
print('False')
|
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 20:59:13 2019
@author: sudar
"""
class url_feeder(object):
def __init__(self, section):
"""initialize the feeder"""
self.section = section
def feeder(self):
"""We going to get the URL through each section
over-view
company information
analysis
company management
financial
Set a Flag to check what section is the user input
The flag will check and trigger the specific section
Pseudocode
Set flag
if the flag equal section company overview
Then Scrape the data
if not then keep going
if the flag equal section analysis
.........
"""
##############################################################
"""
Build the URL for specific company section
"""
try:
flag = self.section
base_url = 'https://www.reuters.com'
base_url1 = 'https://csimarket.com'
path_1 = '/finance'
path_2 = '/stocks/'
section_list = ['overview', 'company-officers', 'financial-highlights', 'analyst', 'industry', 'segment']
company_list = ['/MSFT.OQ', '/MET.N', '/MS.N', '/FNMA.PK', '/GM', '/PROC.NS', '/APO.N', '/BA.N', '/BRKa.N']
company_list1 = ['MSFT', 'MET','MS', 'FNMA', 'GM', 'PG', 'APO', 'BA', 'BRKA']
url_list = []
if self.section.lower:
for company in company_list:
if flag == section_list[0]:
url = base_url + path_1 + path_2 + flag + company
url_list.append(url)
elif flag == section_list[1]:
url = base_url + path_1 + path_2 + flag + company
url_list.append(url)
elif flag == section_list[2]:
url = base_url + path_1 + path_2 + flag + company
url_list.append(url)
elif flag == section_list[3]:
url = base_url + path_1 + path_2 + flag + company
url_list.append(url)
for company in company_list1:
if flag == section_list[4]:
url = base_url1 + '/stocks/competition.php?code=' + company
url_list.append(url)
elif flag == section_list[5]:
url = base_url1 + '/stocks/segments.php?code=' + company
url_list.append(url)
return url_list
except:
return ("error")
#############Uncomment to test####################
#test = url_feeder("company-officers")
#print(test.feeder())
|
"""
Created on Tue Feb 19 20:59:13 2019
@author: sudar
"""
class Url_Feeder(object):
def __init__(self, section):
"""initialize the feeder"""
self.section = section
def feeder(self):
"""We going to get the URL through each section
over-view
company information
analysis
company management
financial
Set a Flag to check what section is the user input
The flag will check and trigger the specific section
Pseudocode
Set flag
if the flag equal section company overview
Then Scrape the data
if not then keep going
if the flag equal section analysis
.........
"""
'\n Build the URL for specific company section\n '
try:
flag = self.section
base_url = 'https://www.reuters.com'
base_url1 = 'https://csimarket.com'
path_1 = '/finance'
path_2 = '/stocks/'
section_list = ['overview', 'company-officers', 'financial-highlights', 'analyst', 'industry', 'segment']
company_list = ['/MSFT.OQ', '/MET.N', '/MS.N', '/FNMA.PK', '/GM', '/PROC.NS', '/APO.N', '/BA.N', '/BRKa.N']
company_list1 = ['MSFT', 'MET', 'MS', 'FNMA', 'GM', 'PG', 'APO', 'BA', 'BRKA']
url_list = []
if self.section.lower:
for company in company_list:
if flag == section_list[0]:
url = base_url + path_1 + path_2 + flag + company
url_list.append(url)
elif flag == section_list[1]:
url = base_url + path_1 + path_2 + flag + company
url_list.append(url)
elif flag == section_list[2]:
url = base_url + path_1 + path_2 + flag + company
url_list.append(url)
elif flag == section_list[3]:
url = base_url + path_1 + path_2 + flag + company
url_list.append(url)
for company in company_list1:
if flag == section_list[4]:
url = base_url1 + '/stocks/competition.php?code=' + company
url_list.append(url)
elif flag == section_list[5]:
url = base_url1 + '/stocks/segments.php?code=' + company
url_list.append(url)
return url_list
except:
return 'error'
|
# day_3/classes.py
"""
Classes are a way to encapsulate code. It is a way of keeping functions and data
that represent something together and is a core concept to understand for object
oreinted programing.
"""
class Person:
def __init__(self, name: str, age: int) -> None:
"""
Initializes the person class requires a name and an age.
"""
self.name = name
self.age = age
self.friends = []
def introduce(self) -> str:
"""
Introduces the person.
"""
return f'Hello my name is {self.name} and I am {self.age} years old.'
def get_older(self, years: int) -> None:
"""
Ages the person by an amount of years
"""
self.age += years
def add_friend(self, person) -> None:
"""
Adds another person to this persons friend list
"""
self.friends.append(person)
return self
def list_friends(self) -> str:
"""
Returns a string containg the names of this persons friends
"""
friends = ''
for friend in self.friends:
friends += friend.name + ' '
return self.name + "'s friends list is " + friends
def __str__(self) -> str:
return f'Person {self.name}, age {self.age}'
"""
By using classes you can inherit from another class and receive their methods or
overide them with something else.
"""
class Student (Person):
def __init__(self, name, age, grade):
"""
Initializes a student.
"""
super().__init__(name, age)
self.grade = grade
def introduce(self) -> str:
"""
Introduces a student.
"""
return f"I'm a student my name is {self.name}. I'm in grade \
{self.grade}, and I'm {self.age} years old"
def __str__(self) -> str:
return f'Student {self.name}, grade {self.grade}'
"""
Object oreiented programming is useful and many if not all jobs for coders will
require you to be familiar with how it works but its also important to note that
you can do much the same thing without it. For most of your personal projects
you can decide to use object oriented or functional paradigms or a mix of both
whatever you want.
"""
def create_person(name, age) -> dict:
"""
Creates a dictionary representation of a person
"""
return {'name': name, 'age': age, 'friends': []}
def introduce(person) -> str:
"""
Introduces a dictionary representation of a person
"""
return f'Hello my name is {person["name"]} and I am {person["age"]} years old.'
def get_older(person, years) -> None:
"""
Increments the age of a person
"""
person['age'] += years
def string_rep(person) -> str:
"""
Represents the dictionary representation of a preson as a string
"""
return f'Person {person["name"]}, age {person["age"]}'
def add_friend(person, person2) -> None:
"""
Adds a person to this functional persons friends list
"""
person['friends'].append(person2)
return person
def list_friends(person) -> str:
"""
Returns a string containg the names of this functional persons friends
"""
friends = ''
for friend in person['friends']:
friends += friend['name'] + ' '
return person['name'] + "'s friends list is " + friends
def create_student(name, age, grade) -> dict:
"""
Creates a dictionary representation of a student.
"""
student = create_person(name, age)
student['grade'] = grade
return student
def introduce_student(student) -> str:
"""
Introduces a functional student.
"""
return f"I'm a student my name is {student['name']}. I'm in grade \
{student['grade']}, and I'm {student['age']} years old"
if __name__ == '__main__':
print('Doing some things in an object oriented way')
person1 = Person('John', 20)
print(person1.introduce())
person1.get_older(6)
print(person1.introduce())
student1 = Student('Baki', 18, 12)
print(student1.introduce())
student1.get_older(3) # Still can get older even if the method isn't eplicately defined because it subclasses person
print(student1.introduce())
student1.add_friend(person1)
print(student1.list_friends())
print('')
print('*' * 80)
print('')
print('Doing the same thing functionaly.')
person2 = create_person('John', 20)
print(introduce(person2))
get_older(person2, 6)
print(introduce(person2))
student2 = create_student('Baki', 18, 12)
print(introduce_student(student2))
get_older(student2,3)
print(introduce_student(student2))
add_friend(student2, person2)
print(list_friends(student2))
|
"""
Classes are a way to encapsulate code. It is a way of keeping functions and data
that represent something together and is a core concept to understand for object
oreinted programing.
"""
class Person:
def __init__(self, name: str, age: int) -> None:
"""
Initializes the person class requires a name and an age.
"""
self.name = name
self.age = age
self.friends = []
def introduce(self) -> str:
"""
Introduces the person.
"""
return f'Hello my name is {self.name} and I am {self.age} years old.'
def get_older(self, years: int) -> None:
"""
Ages the person by an amount of years
"""
self.age += years
def add_friend(self, person) -> None:
"""
Adds another person to this persons friend list
"""
self.friends.append(person)
return self
def list_friends(self) -> str:
"""
Returns a string containg the names of this persons friends
"""
friends = ''
for friend in self.friends:
friends += friend.name + ' '
return self.name + "'s friends list is " + friends
def __str__(self) -> str:
return f'Person {self.name}, age {self.age}'
'\nBy using classes you can inherit from another class and receive their methods or\noveride them with something else.\n'
class Student(Person):
def __init__(self, name, age, grade):
"""
Initializes a student.
"""
super().__init__(name, age)
self.grade = grade
def introduce(self) -> str:
"""
Introduces a student.
"""
return f"I'm a student my name is {self.name}. I'm in grade {self.grade}, and I'm {self.age} years old"
def __str__(self) -> str:
return f'Student {self.name}, grade {self.grade}'
'\nObject oreiented programming is useful and many if not all jobs for coders will\nrequire you to be familiar with how it works but its also important to note that\nyou can do much the same thing without it. For most of your personal projects\nyou can decide to use object oriented or functional paradigms or a mix of both\nwhatever you want.\n'
def create_person(name, age) -> dict:
"""
Creates a dictionary representation of a person
"""
return {'name': name, 'age': age, 'friends': []}
def introduce(person) -> str:
"""
Introduces a dictionary representation of a person
"""
return f"Hello my name is {person['name']} and I am {person['age']} years old."
def get_older(person, years) -> None:
"""
Increments the age of a person
"""
person['age'] += years
def string_rep(person) -> str:
"""
Represents the dictionary representation of a preson as a string
"""
return f"Person {person['name']}, age {person['age']}"
def add_friend(person, person2) -> None:
"""
Adds a person to this functional persons friends list
"""
person['friends'].append(person2)
return person
def list_friends(person) -> str:
"""
Returns a string containg the names of this functional persons friends
"""
friends = ''
for friend in person['friends']:
friends += friend['name'] + ' '
return person['name'] + "'s friends list is " + friends
def create_student(name, age, grade) -> dict:
"""
Creates a dictionary representation of a student.
"""
student = create_person(name, age)
student['grade'] = grade
return student
def introduce_student(student) -> str:
"""
Introduces a functional student.
"""
return f"I'm a student my name is {student['name']}. I'm in grade {student['grade']}, and I'm {student['age']} years old"
if __name__ == '__main__':
print('Doing some things in an object oriented way')
person1 = person('John', 20)
print(person1.introduce())
person1.get_older(6)
print(person1.introduce())
student1 = student('Baki', 18, 12)
print(student1.introduce())
student1.get_older(3)
print(student1.introduce())
student1.add_friend(person1)
print(student1.list_friends())
print('')
print('*' * 80)
print('')
print('Doing the same thing functionaly.')
person2 = create_person('John', 20)
print(introduce(person2))
get_older(person2, 6)
print(introduce(person2))
student2 = create_student('Baki', 18, 12)
print(introduce_student(student2))
get_older(student2, 3)
print(introduce_student(student2))
add_friend(student2, person2)
print(list_friends(student2))
|
class Pessoa:
menbros_superiores = 2
menbro_inferiores=2
def __init__(self,*familia,name=None,idade=17):
self.name= name
self.familia= list(familia)
self.idade= idade
def comprimentar(self):
return 'hello my code'
def despedisir(self):
return 'diz tchau ;3'
def contar_1(self):
return list(range(10,1,-1))
@staticmethod
def estatico ():
return 50
@classmethod
def atributodeclasse(cls):
return f'{cls} - membros superiores {cls.menbros_superiores},membros inferiores {cls.menbro_inferiores}'
if __name__ == '__main__':
djony = Pessoa(name='djony', idade=17)
mother = Pessoa(djony,name='mother',idade=46)
type (djony)
print(djony.comprimentar())
print(djony.contar_1())
print(djony.name)
print(mother.name)
for familia in mother.familia:
print(familia.name,familia.idade)
print(djony.__dict__)
print(Pessoa.estatico())
print(Pessoa.atributodeclasse())
|
class Pessoa:
menbros_superiores = 2
menbro_inferiores = 2
def __init__(self, *familia, name=None, idade=17):
self.name = name
self.familia = list(familia)
self.idade = idade
def comprimentar(self):
return 'hello my code'
def despedisir(self):
return 'diz tchau ;3'
def contar_1(self):
return list(range(10, 1, -1))
@staticmethod
def estatico():
return 50
@classmethod
def atributodeclasse(cls):
return f'{cls} - membros superiores {cls.menbros_superiores},membros inferiores {cls.menbro_inferiores}'
if __name__ == '__main__':
djony = pessoa(name='djony', idade=17)
mother = pessoa(djony, name='mother', idade=46)
type(djony)
print(djony.comprimentar())
print(djony.contar_1())
print(djony.name)
print(mother.name)
for familia in mother.familia:
print(familia.name, familia.idade)
print(djony.__dict__)
print(Pessoa.estatico())
print(Pessoa.atributodeclasse())
|
# Given a non-negative number represented as an array of digits,
# plus one to the number.
# The digits are stored such that the most significant
# digit is at the head of the list.
def plusOne(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
res = []
ten = 0
i = len(digits)-1
while i >= 0 or ten == 1:
sum = 0
if i >= 0:
sum += digits[i]
if ten:
sum += 1
res.append(sum % 10)
ten = sum / 10
i -= 1
return res[::-1]
def plus_one(digits):
n = len(digits)
for i in range(n-1, -1, -1):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
new_num = [0] * (n+1)
new_num[0] = 1
return new_num
|
def plus_one(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
res = []
ten = 0
i = len(digits) - 1
while i >= 0 or ten == 1:
sum = 0
if i >= 0:
sum += digits[i]
if ten:
sum += 1
res.append(sum % 10)
ten = sum / 10
i -= 1
return res[::-1]
def plus_one(digits):
n = len(digits)
for i in range(n - 1, -1, -1):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
new_num = [0] * (n + 1)
new_num[0] = 1
return new_num
|
# coding: utf-8
def is_bool(var):
return isinstance(var, bool)
if __name__ == '__main__':
a = False
b = 0
print(is_bool(a))
print(is_bool(b))
|
def is_bool(var):
return isinstance(var, bool)
if __name__ == '__main__':
a = False
b = 0
print(is_bool(a))
print(is_bool(b))
|
class Conta:
def __init__(self, numero, nome, saldo=0):
self._numero = numero
self._nome = nome
self._saldo = saldo
def atualiza(self, taxa):
self._saldo += self._saldo * taxa
def deposita(self, valor):
self._saldo += valor - 0.10
class ContaCorrente(Conta):
def atualiza(self, taxa):
self._saldo += self._saldo * taxa * 2
class ContaPoupanca(Conta):
def atualiza(self, taxa):
self._saldo += self._saldo * taxa * 3
if __name__ == "__main__":
c = Conta('123-4', 'joao', 1000)
cc = ContaCorrente('123-5', 'pedro', 1000)
cp = ContaPoupanca('123-6', 'Maria', 1000)
c.atualiza(0.01)
cc.atualiza(0.01)
cp.atualiza(0.01)
print(c._saldo, cc._saldo, cp._saldo)
|
class Conta:
def __init__(self, numero, nome, saldo=0):
self._numero = numero
self._nome = nome
self._saldo = saldo
def atualiza(self, taxa):
self._saldo += self._saldo * taxa
def deposita(self, valor):
self._saldo += valor - 0.1
class Contacorrente(Conta):
def atualiza(self, taxa):
self._saldo += self._saldo * taxa * 2
class Contapoupanca(Conta):
def atualiza(self, taxa):
self._saldo += self._saldo * taxa * 3
if __name__ == '__main__':
c = conta('123-4', 'joao', 1000)
cc = conta_corrente('123-5', 'pedro', 1000)
cp = conta_poupanca('123-6', 'Maria', 1000)
c.atualiza(0.01)
cc.atualiza(0.01)
cp.atualiza(0.01)
print(c._saldo, cc._saldo, cp._saldo)
|
# -*- coding: utf-8 -*-
# Coded by Sungwook Kim
# 2020-12-13
# IDE: Jupyter Notebook
def Fact(a):
res = 1
for i in range(a):
res = res * (i + 1)
return res
T = int(input())
for i in range(T):
r, n = map(int, input().split())
a = Fact(n)
b = Fact(r)
c = Fact(n-r)
print(int(a / (c * b)))
|
def fact(a):
res = 1
for i in range(a):
res = res * (i + 1)
return res
t = int(input())
for i in range(T):
(r, n) = map(int, input().split())
a = fact(n)
b = fact(r)
c = fact(n - r)
print(int(a / (c * b)))
|
# The base class for application-specific states.
class SarifState(object):
def __init__(self):
self.parser = None
self.ppass = 1
# Taking the easy way out.
# We need something in case a descendent wants to trigger
# on change to ppass.
def set_ppass(self, ppass):
self.ppass = ppass
def get_ppass(self):
return self.ppass
def set_parser(self, parser):
self.parser = parser
def get_parser(self):
return self.parser
# These functions are named for the handler they reside in
# plus the function in that handler.
# Only functions that called the state are here.
def original_uri_base_id_add(self, uri, uriBaseId, key):
raise NotImplementedError("original_uri_base_id_add")
def resources_object_member_end(self, parser, key):
raise NotImplementedError("resources_object_member_end")
def rules_v1_object_member_end(self, parser, key):
raise NotImplementedError("rules_v1_object_member_end")
def rules_item_array_element_end(self, parser, idx):
raise NotImplementedError("rules_item_array_element_end")
def run_object_member_end(self, tool_name):
raise NotImplementedError("run_object_member_end")
def run_object_start(self, parser):
raise NotImplementedError("run_object_start")
def results_item_array_element_end(self, parser, idx):
raise NotImplementedError("results_item_array_element_end")
def file_item_add(self, file_item):
raise NotImplementedError("file_item_add")
|
class Sarifstate(object):
def __init__(self):
self.parser = None
self.ppass = 1
def set_ppass(self, ppass):
self.ppass = ppass
def get_ppass(self):
return self.ppass
def set_parser(self, parser):
self.parser = parser
def get_parser(self):
return self.parser
def original_uri_base_id_add(self, uri, uriBaseId, key):
raise not_implemented_error('original_uri_base_id_add')
def resources_object_member_end(self, parser, key):
raise not_implemented_error('resources_object_member_end')
def rules_v1_object_member_end(self, parser, key):
raise not_implemented_error('rules_v1_object_member_end')
def rules_item_array_element_end(self, parser, idx):
raise not_implemented_error('rules_item_array_element_end')
def run_object_member_end(self, tool_name):
raise not_implemented_error('run_object_member_end')
def run_object_start(self, parser):
raise not_implemented_error('run_object_start')
def results_item_array_element_end(self, parser, idx):
raise not_implemented_error('results_item_array_element_end')
def file_item_add(self, file_item):
raise not_implemented_error('file_item_add')
|
# store the input from the user into age
age = input("How old are you? ")
# store the input from the user into height
height = input(f"You're {age}? Nice. How tall are you? ")
# store the input from the user into weight
weight = input("How much do you weigh? ")
# print the f-string with the age, height and weight
print(f"So you're {age} old. {height} tall and {weight} heavy.")
|
age = input('How old are you? ')
height = input(f"You're {age}? Nice. How tall are you? ")
weight = input('How much do you weigh? ')
print(f"So you're {age} old. {height} tall and {weight} heavy.")
|
def loss_layer(self, predicts, labels, scope='loss_layer'):
with tf.variable_scope(scope):
predict_classes = tf.reshape(predicts[:, :self.boundary1],
[self.batch_size, self.cell_size, self.cell_size, self.num_class])
predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2],
[self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell])
predict_boxes = tf.reshape(predicts[:, self.boundary2:],
[self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell, 4])
response = tf.reshape(labels[:, :, :, 0], [self.batch_size, self.cell_size, self.cell_size, 1])
boxes = tf.reshape(labels[:, :, :, 1:5], [self.batch_size, self.cell_size, self.cell_size, 1, 4])
boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]) / self.image_size
classes = labels[:, :, :, 5:]
offset = tf.constant(self.offset, dtype=tf.float32)
offset = tf.reshape(offset, [1, self.cell_size, self.cell_size, self.boxes_per_cell])
offset = tf.tile(offset, [self.batch_size, 1, 1, 1])
predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] + offset) / self.cell_size,
(predict_boxes[:, :, :, :, 1] + tf.transpose(offset,
(0, 2, 1, 3))) / self.cell_size,
tf.square(predict_boxes[:, :, :, :, 2]),
tf.square(predict_boxes[:, :, :, :, 3])])
predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3, 4, 0])
iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)
# calculate I tensor [BATCH_SIZE, CELL_SIZE, CELL_SIZE, BOXES_PER_CELL]
object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)
object_mask = tf.cast((iou_predict_truth >= object_mask), tf.float32) * response
# calculate no_I tensor [CELL_SIZE, CELL_SIZE, BOXES_PER_CELL]
noobject_mask = tf.ones_like(object_mask, dtype=tf.float32) - object_mask
boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size - offset,
boxes[:, :, :, :, 1] * self.cell_size - tf.transpose(offset, (0, 2, 1, 3)),
tf.sqrt(boxes[:, :, :, :, 2]),
tf.sqrt(boxes[:, :, :, :, 3])])
boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])
# class_loss
class_delta = response * (predict_classes - classes)
class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta), axis=[1, 2, 3]),
name='class_loss') * self.class_scale
# object_loss
object_delta = object_mask * (predict_scales - iou_predict_truth)
object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(object_delta), axis=[1, 2, 3]),
name='object_loss') * self.object_scale
# noobject_loss
noobject_delta = noobject_mask * predict_scales
noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(noobject_delta), axis=[1, 2, 3]),
name='noobject_loss') * self.noobject_scale
# coord_loss
coord_mask = tf.expand_dims(object_mask, 4)
boxes_delta = coord_mask * (predict_boxes - boxes_tran)
coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta), axis=[1, 2, 3, 4]),
name='coord_loss') * self.coord_scale
tf.losses.add_loss(class_loss)
tf.losses.add_loss(object_loss)
tf.losses.add_loss(noobject_loss)
tf.losses.add_loss(coord_loss)
|
def loss_layer(self, predicts, labels, scope='loss_layer'):
with tf.variable_scope(scope):
predict_classes = tf.reshape(predicts[:, :self.boundary1], [self.batch_size, self.cell_size, self.cell_size, self.num_class])
predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2], [self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell])
predict_boxes = tf.reshape(predicts[:, self.boundary2:], [self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell, 4])
response = tf.reshape(labels[:, :, :, 0], [self.batch_size, self.cell_size, self.cell_size, 1])
boxes = tf.reshape(labels[:, :, :, 1:5], [self.batch_size, self.cell_size, self.cell_size, 1, 4])
boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]) / self.image_size
classes = labels[:, :, :, 5:]
offset = tf.constant(self.offset, dtype=tf.float32)
offset = tf.reshape(offset, [1, self.cell_size, self.cell_size, self.boxes_per_cell])
offset = tf.tile(offset, [self.batch_size, 1, 1, 1])
predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] + offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] + tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.square(predict_boxes[:, :, :, :, 2]), tf.square(predict_boxes[:, :, :, :, 3])])
predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3, 4, 0])
iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes)
object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True)
object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32) * response
noobject_mask = tf.ones_like(object_mask, dtype=tf.float32) - object_mask
boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size - offset, boxes[:, :, :, :, 1] * self.cell_size - tf.transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :, 2]), tf.sqrt(boxes[:, :, :, :, 3])])
boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0])
class_delta = response * (predict_classes - classes)
class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta), axis=[1, 2, 3]), name='class_loss') * self.class_scale
object_delta = object_mask * (predict_scales - iou_predict_truth)
object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(object_delta), axis=[1, 2, 3]), name='object_loss') * self.object_scale
noobject_delta = noobject_mask * predict_scales
noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(noobject_delta), axis=[1, 2, 3]), name='noobject_loss') * self.noobject_scale
coord_mask = tf.expand_dims(object_mask, 4)
boxes_delta = coord_mask * (predict_boxes - boxes_tran)
coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale
tf.losses.add_loss(class_loss)
tf.losses.add_loss(object_loss)
tf.losses.add_loss(noobject_loss)
tf.losses.add_loss(coord_loss)
|
# -*-- coding: utf-8 -*
def discretize(self, Npoint=-1):
"""Returns the discretize version of the SurfRing
Parameters
----------
self: SurfRing
A SurfRing object
Npoint : int
Number of point on each line (Default value = -1 => use the line default discretization)
Returns
-------
point_list : list
List of complex coordinates
"""
# check if the SurfRing is correct
self.check()
# getting lines that delimit the SurfLine
point_list = self.out_surf.discretize(Npoint=Npoint)
point_list.extend(self.in_surf.discretize(Npoint=Npoint))
return point_list
|
def discretize(self, Npoint=-1):
"""Returns the discretize version of the SurfRing
Parameters
----------
self: SurfRing
A SurfRing object
Npoint : int
Number of point on each line (Default value = -1 => use the line default discretization)
Returns
-------
point_list : list
List of complex coordinates
"""
self.check()
point_list = self.out_surf.discretize(Npoint=Npoint)
point_list.extend(self.in_surf.discretize(Npoint=Npoint))
return point_list
|
# AKSHITH K
# BUBBLE SORT IMPLEMENTED IN PYTHON RECURSIVELY.
def bubblesort(arr, n):
# checking if the array does not need to be sorted and has a length of 1.
if n <= 1:
return
# creating a for-loop to iterate for the elements in the array.
for i in range(0, n - 1):
# creating an if-statement to check for the element not being in the right position.
if arr[i] > arr[i + 1]:
# code to perform the swapping method.
arr[i], arr[i + 1] = arr[i + 1], arr[i]
# recursively calling the function for the sorting.
return bubblesort(arr, n - 1)
# DRIVER CODE FOR TESTING THE ALGORITHM.
arr = [4, 9, 1, 3, 0, 2, 6, 8, 5, 7]
n = len(arr)
bubblesort(arr, n)
print(arr)
|
def bubblesort(arr, n):
if n <= 1:
return
for i in range(0, n - 1):
if arr[i] > arr[i + 1]:
(arr[i], arr[i + 1]) = (arr[i + 1], arr[i])
return bubblesort(arr, n - 1)
arr = [4, 9, 1, 3, 0, 2, 6, 8, 5, 7]
n = len(arr)
bubblesort(arr, n)
print(arr)
|
## Problem 10.2
# write a program to read through the mbox-short.txt
# and figure out the distribution by hour of the day for each of the messages.
file_name = input("Enter file:")
file_handle = open(file_name)
hour_list = list()
for line in file_handle:
# pull the hour out from the 'From ' line
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
if line.startswith("From"):
line_list = line.split()
if len(line_list) > 2:
# find the time and then split the string a second time
hour = line_list[5][:2]
hour_list.append(hour)
# accumulate the counts for each hour
hour_dict = dict()
for key in hour_list:
hour_dict[key] = hour_dict.get(key, 0) + 1
# sort by hour
srt_list = sorted(hour_dict.items())
# print out the counts, sorted by hour
for (k,v) in srt_list:
print (k,v)
|
file_name = input('Enter file:')
file_handle = open(file_name)
hour_list = list()
for line in file_handle:
if line.startswith('From'):
line_list = line.split()
if len(line_list) > 2:
hour = line_list[5][:2]
hour_list.append(hour)
hour_dict = dict()
for key in hour_list:
hour_dict[key] = hour_dict.get(key, 0) + 1
srt_list = sorted(hour_dict.items())
for (k, v) in srt_list:
print(k, v)
|
# Copyright 2006 James Tauber and contributors
# Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
# Copyright (C) 2010 Serge Tarkovski <serge.tarkovski@gmail.com>
# Copyright (C) 2010 Rich Newpol (IE override) <rich.newpol@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This IE-specific override is required because IE doesn't allow
# empty element to generate events. Therefore, when the mouse moves
# (or clicks) happen over *only* the GlassWidget (which is empty)
# they stop flowing. however, IE does provide setCapture/releaseCapture
# methods on elements which can be used to same effect as a regular
# GlassWidget.
# This file implements the IE version of GlassWidget simply by mapping
# the GlassWidget API to the use of setCapture/releaseCapture
# we re-use the global 'mousecapturer' to prevent GlassWidget.hide()
# from releasing someone else's capture
def show(mousetarget, **kwargs):
global mousecapturer
# get the element that wants events
target_element = mousetarget.getElement()
# insure element can capture events
if hasattr(target_element,"setCapture"):
# remember it
mousecapturer = target_element
# start capturing
DOM.setCapture(target_element)
def hide():
global mousecapturer
if hasattr(mousecapturer,"releaseCapture"):
DOM.releaseCapture(mousecapturer)
mousecapturer = None
|
def show(mousetarget, **kwargs):
global mousecapturer
target_element = mousetarget.getElement()
if hasattr(target_element, 'setCapture'):
mousecapturer = target_element
DOM.setCapture(target_element)
def hide():
global mousecapturer
if hasattr(mousecapturer, 'releaseCapture'):
DOM.releaseCapture(mousecapturer)
mousecapturer = None
|
# WAP to show the use of if..elif..else
season= input("Enter season : ")
print(season)
if season == 'spring':
print('plant the garden!')
elif season == 'summer':
print('water the garden!')
elif season == 'fall':
print('harvest the garden!')
elif season == 'winter':
print('stay indoors!')
else:
print('unrecognized season')
|
season = input('Enter season : ')
print(season)
if season == 'spring':
print('plant the garden!')
elif season == 'summer':
print('water the garden!')
elif season == 'fall':
print('harvest the garden!')
elif season == 'winter':
print('stay indoors!')
else:
print('unrecognized season')
|
#
# PySNMP MIB module HH3C-L2TP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-L2TP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:14:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint")
hh3cCommon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cCommon")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, TimeTicks, Counter64, NotificationType, ObjectIdentity, Gauge32, MibIdentifier, iso, Integer32, ModuleIdentity, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "TimeTicks", "Counter64", "NotificationType", "ObjectIdentity", "Gauge32", "MibIdentifier", "iso", "Integer32", "ModuleIdentity", "IpAddress")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
hh3cL2tp = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 139))
hh3cL2tp.setRevisions(('2013-07-05 15:18',))
if mibBuilder.loadTexts: hh3cL2tp.setLastUpdated('201307051518Z')
if mibBuilder.loadTexts: hh3cL2tp.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
hh3cL2tpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1))
hh3cL2tpScalar = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1))
hh3cL2tpStats = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1))
hh3cL2tpStatsTotalTunnels = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cL2tpStatsTotalTunnels.setStatus('current')
hh3cL2tpStatsTotalSessions = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cL2tpStatsTotalSessions.setStatus('current')
hh3cL2tpSessionRate = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cL2tpSessionRate.setStatus('current')
mibBuilder.exportSymbols("HH3C-L2TP-MIB", PYSNMP_MODULE_ID=hh3cL2tp, hh3cL2tpObjects=hh3cL2tpObjects, hh3cL2tpStatsTotalTunnels=hh3cL2tpStatsTotalTunnels, hh3cL2tpScalar=hh3cL2tpScalar, hh3cL2tpStatsTotalSessions=hh3cL2tpStatsTotalSessions, hh3cL2tp=hh3cL2tp, hh3cL2tpSessionRate=hh3cL2tpSessionRate, hh3cL2tpStats=hh3cL2tpStats)
|
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint')
(hh3c_common,) = mibBuilder.importSymbols('HH3C-OID-MIB', 'hh3cCommon')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(counter32, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, time_ticks, counter64, notification_type, object_identity, gauge32, mib_identifier, iso, integer32, module_identity, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'TimeTicks', 'Counter64', 'NotificationType', 'ObjectIdentity', 'Gauge32', 'MibIdentifier', 'iso', 'Integer32', 'ModuleIdentity', 'IpAddress')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
hh3c_l2tp = module_identity((1, 3, 6, 1, 4, 1, 25506, 2, 139))
hh3cL2tp.setRevisions(('2013-07-05 15:18',))
if mibBuilder.loadTexts:
hh3cL2tp.setLastUpdated('201307051518Z')
if mibBuilder.loadTexts:
hh3cL2tp.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
hh3c_l2tp_objects = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1))
hh3c_l2tp_scalar = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1))
hh3c_l2tp_stats = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1))
hh3c_l2tp_stats_total_tunnels = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cL2tpStatsTotalTunnels.setStatus('current')
hh3c_l2tp_stats_total_sessions = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cL2tpStatsTotalSessions.setStatus('current')
hh3c_l2tp_session_rate = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 3), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cL2tpSessionRate.setStatus('current')
mibBuilder.exportSymbols('HH3C-L2TP-MIB', PYSNMP_MODULE_ID=hh3cL2tp, hh3cL2tpObjects=hh3cL2tpObjects, hh3cL2tpStatsTotalTunnels=hh3cL2tpStatsTotalTunnels, hh3cL2tpScalar=hh3cL2tpScalar, hh3cL2tpStatsTotalSessions=hh3cL2tpStatsTotalSessions, hh3cL2tp=hh3cL2tp, hh3cL2tpSessionRate=hh3cL2tpSessionRate, hh3cL2tpStats=hh3cL2tpStats)
|
kuukiondo = 70
shitsudo = 100
if kuukiondo >= 100:
print("A")
elif kuukiondo >= 92 and shitsudo > 75:
print("B")
elif kuukiondo > 88 and shitsudo >= 85:
print("C")
elif kuukiondo == 75 and shitsudo <= 65:
print("D")
else:
print("E")
|
kuukiondo = 70
shitsudo = 100
if kuukiondo >= 100:
print('A')
elif kuukiondo >= 92 and shitsudo > 75:
print('B')
elif kuukiondo > 88 and shitsudo >= 85:
print('C')
elif kuukiondo == 75 and shitsudo <= 65:
print('D')
else:
print('E')
|
class Solution1:
def maxSubArray(self, nums: List[int]) -> int:
total_max, total = -1e10, 0
for i in range( len(nums) ):
if total > 0:
total += nums[i]
else:
total = nums[i]
if total > total_max:
total_max = total
return total_max
class Solution2:
## divide and conquer approach
def middlemax( self, nums, LL, mid, RR ):
totalL, totalR, totalL_max, totalR_max = 0, 0, nums[mid], nums[mid+1]
# Left
for i in range( mid, LL-1, -1 ):
totalL += nums[i]
if( totalL_max < totalL ):
totalL_max = totalL
# Right
for i in range( mid+1, RR+1 ):
totalR += nums[i]
if( totalR_max < totalR ):
totalR_max = totalR
return totalR_max + totalL_max
def findmax( self, nums, LL, RR ):
if LL >= RR:
return nums[LL]
mid = LL + (RR-LL)//2
mmax = self.middlemax( nums, LL, mid, RR )
lmax = self.findmax( nums, LL, mid )
rmax = self.findmax( nums, mid+1, RR )
return max( [mmax, lmax, rmax] )
def maxSubArray(self, nums: List[int]) -> int:
Length = len(nums)
return self.findmax( nums, 0, Length-1 )
|
class Solution1:
def max_sub_array(self, nums: List[int]) -> int:
(total_max, total) = (-10000000000.0, 0)
for i in range(len(nums)):
if total > 0:
total += nums[i]
else:
total = nums[i]
if total > total_max:
total_max = total
return total_max
class Solution2:
def middlemax(self, nums, LL, mid, RR):
(total_l, total_r, total_l_max, total_r_max) = (0, 0, nums[mid], nums[mid + 1])
for i in range(mid, LL - 1, -1):
total_l += nums[i]
if totalL_max < totalL:
total_l_max = totalL
for i in range(mid + 1, RR + 1):
total_r += nums[i]
if totalR_max < totalR:
total_r_max = totalR
return totalR_max + totalL_max
def findmax(self, nums, LL, RR):
if LL >= RR:
return nums[LL]
mid = LL + (RR - LL) // 2
mmax = self.middlemax(nums, LL, mid, RR)
lmax = self.findmax(nums, LL, mid)
rmax = self.findmax(nums, mid + 1, RR)
return max([mmax, lmax, rmax])
def max_sub_array(self, nums: List[int]) -> int:
length = len(nums)
return self.findmax(nums, 0, Length - 1)
|
"""
ID: tony_hu1
PROG: sort3
LANG: PYTHON3
"""
def check_swap(current_num):
global unsorted
global sorted
global num
global steps
global area
for i in range(num):
if sorted[i] > current_num:
return
if sorted[i] == current_num:
if unsorted[i] == current_num:
unsorted[i] = 0
else:
wrong_num = unsorted[i]
area[1] = unsorted[0:count_1]
area[2] = unsorted[count_1:count_1 + count_2]
area[3]= unsorted[count_1 + count_2 : num]
if current_num in area[wrong_num]:
to_be_changed = area[wrong_num].index(current_num) + alterable[wrong_num-1]
else:
to_be_changed = unsorted[alterable[current_num]:num].index(current_num) + alterable[current_num]
unsorted[i],unsorted[to_be_changed] = 0,unsorted[i]
steps += 1
sorted = []
with open('sort3.in') as filename:
for line in filename:
sorted.append(int(line.rstrip()))
num = sorted[0]
del sorted[0]
unsorted = sorted[0:num]
sorted.sort()
area = dict()
steps = 0
count_1 = sorted.count(1)
count_2 = sorted.count(2)
alterable = {1:count_1,2:count_1+count_2}
for i in range(1,3):
check_swap(i)
fout = open('sort3.out', 'w')
fout.write(str(steps)+'\n')
|
"""
ID: tony_hu1
PROG: sort3
LANG: PYTHON3
"""
def check_swap(current_num):
global unsorted
global sorted
global num
global steps
global area
for i in range(num):
if sorted[i] > current_num:
return
if sorted[i] == current_num:
if unsorted[i] == current_num:
unsorted[i] = 0
else:
wrong_num = unsorted[i]
area[1] = unsorted[0:count_1]
area[2] = unsorted[count_1:count_1 + count_2]
area[3] = unsorted[count_1 + count_2:num]
if current_num in area[wrong_num]:
to_be_changed = area[wrong_num].index(current_num) + alterable[wrong_num - 1]
else:
to_be_changed = unsorted[alterable[current_num]:num].index(current_num) + alterable[current_num]
(unsorted[i], unsorted[to_be_changed]) = (0, unsorted[i])
steps += 1
sorted = []
with open('sort3.in') as filename:
for line in filename:
sorted.append(int(line.rstrip()))
num = sorted[0]
del sorted[0]
unsorted = sorted[0:num]
sorted.sort()
area = dict()
steps = 0
count_1 = sorted.count(1)
count_2 = sorted.count(2)
alterable = {1: count_1, 2: count_1 + count_2}
for i in range(1, 3):
check_swap(i)
fout = open('sort3.out', 'w')
fout.write(str(steps) + '\n')
|
################################################################################
# #
# ____ _ #
# | _ \ ___ __| |_ __ _ _ _ __ ___ #
# | |_) / _ \ / _` | '__| | | | '_ ` _ \ #
# | __/ (_) | (_| | | | |_| | | | | | | #
# |_| \___/ \__,_|_| \__,_|_| |_| |_| #
# #
# Copyright 2021 Podrum Studios #
# #
# Permission is hereby granted, free of charge, to any person #
# obtaining a copy of this software and associated documentation #
# files (the "Software"), to deal in the Software without restriction, #
# including without limitation the rights to use, copy, modify, merge, #
# publish, distribute, sublicense, and/or sell copies of the Software, #
# and to permit persons to whom the Software is furnished to do so, #
# subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included #
# in all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS #
# IN THE SOFTWARE. #
# #
################################################################################
class metadata_dictionary_type:
key_flags: int = 0
key_health: int = 1
key_variant: int = 2
key_color: int = 3
key_nametag: int = 4
key_owner_eid: int = 5
key_target_eid: int = 6
key_air: int = 7
key_potion_color: int = 8
key_potion_ambient: int = 9
key_jump_duration: int = 10
key_hurt_time: int = 11
key_hurt_direction: int = 12
key_paddle_time_left: int = 13
key_paddle_time_right: int = 14
key_experience_value: int = 15
key_minecart_display_block: int = 16
key_minecart_display_offset: int = 17
key_minecart_has_display: int = 18
key_old_swell: int = 20
key_swell_dir: int = 21
key_charge_amount: int = 22
key_enderman_held_runtime_id: int = 23
key_entity_age: int = 24
key_player_flags: int = 26
key_player_index: int = 27
key_player_bed_position: int = 28
key_fireball_power_x: int = 29
key_fireball_power_y: int = 30
key_fireball_power_z: int = 31
key_aux_power: int = 32
key_fish_x: int = 33
key_fish_z: int = 34
key_fish_angle: int = 35
key_potion_aux_value: int = 36
key_lead_holder_eid: int = 37
key_scale: int = 38
key_interactive_tag: int = 39
key_npc_skin_id: int = 40
key_url_tag: int = 41
key_max_airdata_max_air: int = 42
key_mark_variant: int = 43
key_container_type: int = 44
key_container_base_size: int = 45
key_container_extra_slots_per_strength: int = 46
key_block_target: int = 47
key_wither_invulnerable_ticks: int = 48
key_wither_target_1: int = 49
key_wither_target_2: int = 50
key_wither_target_3: int = 51
key_aerial_attack: int = 52
key_boundingbox_width: int = 53
key_boundingbox_height: int = 54
key_fuse_length: int = 55
key_rider_seat_position: int = 57
key_rider_rotation_locked: int = 58
key_rider_max_rotation: int = 58
key_rider_min_rotation: int = 59
key_rider_rotation_offset: int = 60
key_area_effect_clound_radius: int = 61
key_area_effect_clound_waiting: int = 62
key_area_effect_clound_particle_id: int = 63
key_shulker_peak_id: int = 64
key_shulker_attach_face: int = 65
key_shulker_attached: int = 66
key_shulker_attach_pos: int = 67
key_trading_player_eid: int = 68
key_trading_career: int = 69
key_has_command_block: int = 70
key_command_block_command: int = 71
key_command_block_last_output: int = 72
key_command_block_track_output: int = 73
key_controlling_rider_seat_number: int = 74
key_strength: int = 75
key_max_strength: int = 76
key_spell_casting_color: int = 77
key_limited_life: int = 78
key_armor_stand_pose_index: int = 79
key_ender_crystal_time_offset: int = 80
key_always_show_nametag: int = 81
key_color_2: int = 82
key_name_author: int = 83
key_score_tag: int = 84
key_baloon_attached_entity: int = 85
key_pufferfish_size: int = 86
key_bubble_time: int = 87
key_agent: int = 88
key_sitting_amount: int = 89
key_sitting_amount_previous: int = 90
key_eating_counter: int = 91
key_flags_extended: int = 92
key_laying_amount: int = 93
key_laying_amount_previous: int = 94
key_duration: int = 95
key_spawn_time: int = 96
key_change_rate: int = 97
key_change_on_pickup: int = 98
key_pickup_count: int = 99
key_interact_text: int = 100
key_trade_tier: int = 101
key_max_trade_tier: int = 102
key_trade_experience: int = 103
key_skin_id: int = 104
key_spawning_flames: int = 105
key_command_block_tick_delay: int = 106
key_command_block_execute_on_first_tick: int = 107
key_ambient_sound_interval: int = 108
key_ambient_sound_interval_range: int = 109
key_ambient_sound_event_name: int = 110
key_fall_damage_multiplier: int = 111
key_name_raw_text: int = 112
key_can_ride_target: int = 113
key_low_tier_cured_discount: int = 114
key_high_tier_cured_discount: int = 115
key_nearby_cured_discount: int = 116
key_nearby_cured_discount_timestamp: int = 117
key_hitbox: int = 118
key_is_buoyant: int = 119
key_buoyancy_data: int = 120
key_goat_horn_count: int = 121
type_byte: int = 0
type_short: int = 1
type_int: int = 2
type_float: int = 3
type_string: int = 4
type_compound: int = 5
type_vector_3_i: int = 6
type_long: int = 7
type_vector_3_f: int = 8
|
class Metadata_Dictionary_Type:
key_flags: int = 0
key_health: int = 1
key_variant: int = 2
key_color: int = 3
key_nametag: int = 4
key_owner_eid: int = 5
key_target_eid: int = 6
key_air: int = 7
key_potion_color: int = 8
key_potion_ambient: int = 9
key_jump_duration: int = 10
key_hurt_time: int = 11
key_hurt_direction: int = 12
key_paddle_time_left: int = 13
key_paddle_time_right: int = 14
key_experience_value: int = 15
key_minecart_display_block: int = 16
key_minecart_display_offset: int = 17
key_minecart_has_display: int = 18
key_old_swell: int = 20
key_swell_dir: int = 21
key_charge_amount: int = 22
key_enderman_held_runtime_id: int = 23
key_entity_age: int = 24
key_player_flags: int = 26
key_player_index: int = 27
key_player_bed_position: int = 28
key_fireball_power_x: int = 29
key_fireball_power_y: int = 30
key_fireball_power_z: int = 31
key_aux_power: int = 32
key_fish_x: int = 33
key_fish_z: int = 34
key_fish_angle: int = 35
key_potion_aux_value: int = 36
key_lead_holder_eid: int = 37
key_scale: int = 38
key_interactive_tag: int = 39
key_npc_skin_id: int = 40
key_url_tag: int = 41
key_max_airdata_max_air: int = 42
key_mark_variant: int = 43
key_container_type: int = 44
key_container_base_size: int = 45
key_container_extra_slots_per_strength: int = 46
key_block_target: int = 47
key_wither_invulnerable_ticks: int = 48
key_wither_target_1: int = 49
key_wither_target_2: int = 50
key_wither_target_3: int = 51
key_aerial_attack: int = 52
key_boundingbox_width: int = 53
key_boundingbox_height: int = 54
key_fuse_length: int = 55
key_rider_seat_position: int = 57
key_rider_rotation_locked: int = 58
key_rider_max_rotation: int = 58
key_rider_min_rotation: int = 59
key_rider_rotation_offset: int = 60
key_area_effect_clound_radius: int = 61
key_area_effect_clound_waiting: int = 62
key_area_effect_clound_particle_id: int = 63
key_shulker_peak_id: int = 64
key_shulker_attach_face: int = 65
key_shulker_attached: int = 66
key_shulker_attach_pos: int = 67
key_trading_player_eid: int = 68
key_trading_career: int = 69
key_has_command_block: int = 70
key_command_block_command: int = 71
key_command_block_last_output: int = 72
key_command_block_track_output: int = 73
key_controlling_rider_seat_number: int = 74
key_strength: int = 75
key_max_strength: int = 76
key_spell_casting_color: int = 77
key_limited_life: int = 78
key_armor_stand_pose_index: int = 79
key_ender_crystal_time_offset: int = 80
key_always_show_nametag: int = 81
key_color_2: int = 82
key_name_author: int = 83
key_score_tag: int = 84
key_baloon_attached_entity: int = 85
key_pufferfish_size: int = 86
key_bubble_time: int = 87
key_agent: int = 88
key_sitting_amount: int = 89
key_sitting_amount_previous: int = 90
key_eating_counter: int = 91
key_flags_extended: int = 92
key_laying_amount: int = 93
key_laying_amount_previous: int = 94
key_duration: int = 95
key_spawn_time: int = 96
key_change_rate: int = 97
key_change_on_pickup: int = 98
key_pickup_count: int = 99
key_interact_text: int = 100
key_trade_tier: int = 101
key_max_trade_tier: int = 102
key_trade_experience: int = 103
key_skin_id: int = 104
key_spawning_flames: int = 105
key_command_block_tick_delay: int = 106
key_command_block_execute_on_first_tick: int = 107
key_ambient_sound_interval: int = 108
key_ambient_sound_interval_range: int = 109
key_ambient_sound_event_name: int = 110
key_fall_damage_multiplier: int = 111
key_name_raw_text: int = 112
key_can_ride_target: int = 113
key_low_tier_cured_discount: int = 114
key_high_tier_cured_discount: int = 115
key_nearby_cured_discount: int = 116
key_nearby_cured_discount_timestamp: int = 117
key_hitbox: int = 118
key_is_buoyant: int = 119
key_buoyancy_data: int = 120
key_goat_horn_count: int = 121
type_byte: int = 0
type_short: int = 1
type_int: int = 2
type_float: int = 3
type_string: int = 4
type_compound: int = 5
type_vector_3_i: int = 6
type_long: int = 7
type_vector_3_f: int = 8
|
class Base(object):
def __secret(self):
print("don't tell")
def public(self):
self.__secret()
class Derived(Base):
def __secret(self):
print("never ever")
if __name__ == "__main__":
print("Base class members:", dir(Base))
print("Derived class members:", dir(Derived))
print("Base.public() result:")
Base().public()
print("Derived.public() result:")
Derived().public()
|
class Base(object):
def __secret(self):
print("don't tell")
def public(self):
self.__secret()
class Derived(Base):
def __secret(self):
print('never ever')
if __name__ == '__main__':
print('Base class members:', dir(Base))
print('Derived class members:', dir(Derived))
print('Base.public() result:')
base().public()
print('Derived.public() result:')
derived().public()
|
# Basic script to find primer candidates
# Hits are 20bp in length, with 50-55% GC content, GC clamps in the 3' end, and no more than 3xGC at the clamp
# Paste the target exon sequences from a FASTA sequence with no white spaces
# Exon 1 is where forward primer candidates will be identified
exon1 = "GCAGTGTCACTAGGCCGGCTGGGGGCCCTGGGTACGCTGTAGACCAGACCGCGACAGGCCAGAACACGGGCGGCGGCTTCGGGCCGGGAGACCCGCGCAGCCCTCGGGGCATCTCAGTGCCTCACTCCCCACCCCCTCCCCCGGGTCGGGGGAGGCGGCGCGTCCGGCGGAGGGTTGAGGGGAGCGGGGCAGGCCTGGAGCGCCATGAGCAGCCCGGATGCGGGATACGCCAGTGACGACCAGAGCCAGACCCAGAGCGCGCTGCCCGCGGTGATGGCCGGGCTGGGCCCCTGCCCCTGGGCCGAGTCGCTGAGCCCCATCGGGGACATGAAGGTGAAGGGCGAGGCGCCGGCGAACAGCGGAGCACCGGCCGGGGCCGCGGGCCGAGCCAAGGGCGAGTCCCGTATCCGGCGGCCGATGAACGCTTTCATGGTGTGGGCTAAGGACGAGCGCAAGCGGCTGGCGCAGCAGAATCCAGACCTGCACAACGCCGAGTTGAGCAAGATGCTGG"
# Exon 2 is where reverse primer candidates will be identified
exon2 = "GCAAGTCGTGGAAGGCGCTGACGCTGGCGGAGAAGCGGCCCTTCGTGGAGGAGGCAGAGCGGCTGCGCGTGCAGCACATGCAGGACCACCCCAACTACAAGTACCGGCCGCGGCGGCGCAAGCAGGTGAAGCGGCTGAAGCGGGTGGAGGGCGGCTTCCTGCACGGCCTGGCTGAGCCGCAGGCGGCCGCGCTGGGCCCCGAGGGCGGCCGCGTGGCCATGGACGGCCTGGGCCTCCAGTTCCCCGAGCAGGGCTTCCCCGCCGGCCCGCCGCTGCTGCCTCCGCACATGGGCGGCCACTACCGCGACTGCCAGAGTCTGGGCGCGCCTCCGCTCGACGGCTACCCGTTGCCCACGCCCGACACGTCCCCGCTGGACGGCGTGGACCCCGACCCGGCTTTCTTCGCCGCCCCGATGCCCGGGGACTGCCCGGCGGCCGGCACCTACAGCTACGCGCAGGTCTCGGACTACGCTGGCCCCCCGGAGCCTCCCGCCGGTCCCATGCACCCCCGACTCGGCCCAGAGCCCGCGGGTCCCTCGATTCCGGGCCTCCTGGCGCCACCCAGCGCCCTTCACGTGTACTACGGCGCGATGGGCTCGCCCGGGGCGGGCGGCGGGCGCGGCTTCCAGATGCAGCCGCAACACCAGCACCAGCACCAGCACCAGCACCACCCCCCGGGCCCCGGACAGCCGTCGCCCCCTCCGGAGGCACTGCCCTGCCGGGACGGCACGGACCCCAGTCAGCCCGCCGAGCTCCTCGGGGAGGTGGACCGCACGGAATTTGAACAGTATCTGCACTTC"
# Function that receives a gene string (only C, G, T or A characters) and outputs an array of primer hits
# Looks for a GC clamp reading from start to end of the string
def find_hit(gene) -> object:
hits = []
for i in range(len(gene) - 20):
if gene[i] == 'C' or gene[i] == 'G':
if gene[i + 1] == 'C' or gene[i + 1] == 'G':
if gene[i + 2] != 'C' and gene[i + 2] != 'G':
cg_count = 0
for base in gene[i:i + 20]:
if base == 'C' or base == 'G':
cg_count += 1
if cg_count == 10 or cg_count == 11:
hits.append(gene[i:i + 20])
return hits
# Reverse exon 1 as GC clamp should be at the end of the primer
exon1 = exon1[::-1]
hits_exon1 = find_hit(exon1)
hits_rev = []
for elem in hits_exon1:
hits_rev.append(elem[::-1])
# Prints out the hits as read in a FASTA sequence (5' to 3')
print("Forward primer candidates:")
print(hits_rev)
print("Reverse primer candidates:")
print(find_hit(exon2))
|
exon1 = 'GCAGTGTCACTAGGCCGGCTGGGGGCCCTGGGTACGCTGTAGACCAGACCGCGACAGGCCAGAACACGGGCGGCGGCTTCGGGCCGGGAGACCCGCGCAGCCCTCGGGGCATCTCAGTGCCTCACTCCCCACCCCCTCCCCCGGGTCGGGGGAGGCGGCGCGTCCGGCGGAGGGTTGAGGGGAGCGGGGCAGGCCTGGAGCGCCATGAGCAGCCCGGATGCGGGATACGCCAGTGACGACCAGAGCCAGACCCAGAGCGCGCTGCCCGCGGTGATGGCCGGGCTGGGCCCCTGCCCCTGGGCCGAGTCGCTGAGCCCCATCGGGGACATGAAGGTGAAGGGCGAGGCGCCGGCGAACAGCGGAGCACCGGCCGGGGCCGCGGGCCGAGCCAAGGGCGAGTCCCGTATCCGGCGGCCGATGAACGCTTTCATGGTGTGGGCTAAGGACGAGCGCAAGCGGCTGGCGCAGCAGAATCCAGACCTGCACAACGCCGAGTTGAGCAAGATGCTGG'
exon2 = 'GCAAGTCGTGGAAGGCGCTGACGCTGGCGGAGAAGCGGCCCTTCGTGGAGGAGGCAGAGCGGCTGCGCGTGCAGCACATGCAGGACCACCCCAACTACAAGTACCGGCCGCGGCGGCGCAAGCAGGTGAAGCGGCTGAAGCGGGTGGAGGGCGGCTTCCTGCACGGCCTGGCTGAGCCGCAGGCGGCCGCGCTGGGCCCCGAGGGCGGCCGCGTGGCCATGGACGGCCTGGGCCTCCAGTTCCCCGAGCAGGGCTTCCCCGCCGGCCCGCCGCTGCTGCCTCCGCACATGGGCGGCCACTACCGCGACTGCCAGAGTCTGGGCGCGCCTCCGCTCGACGGCTACCCGTTGCCCACGCCCGACACGTCCCCGCTGGACGGCGTGGACCCCGACCCGGCTTTCTTCGCCGCCCCGATGCCCGGGGACTGCCCGGCGGCCGGCACCTACAGCTACGCGCAGGTCTCGGACTACGCTGGCCCCCCGGAGCCTCCCGCCGGTCCCATGCACCCCCGACTCGGCCCAGAGCCCGCGGGTCCCTCGATTCCGGGCCTCCTGGCGCCACCCAGCGCCCTTCACGTGTACTACGGCGCGATGGGCTCGCCCGGGGCGGGCGGCGGGCGCGGCTTCCAGATGCAGCCGCAACACCAGCACCAGCACCAGCACCAGCACCACCCCCCGGGCCCCGGACAGCCGTCGCCCCCTCCGGAGGCACTGCCCTGCCGGGACGGCACGGACCCCAGTCAGCCCGCCGAGCTCCTCGGGGAGGTGGACCGCACGGAATTTGAACAGTATCTGCACTTC'
def find_hit(gene) -> object:
hits = []
for i in range(len(gene) - 20):
if gene[i] == 'C' or gene[i] == 'G':
if gene[i + 1] == 'C' or gene[i + 1] == 'G':
if gene[i + 2] != 'C' and gene[i + 2] != 'G':
cg_count = 0
for base in gene[i:i + 20]:
if base == 'C' or base == 'G':
cg_count += 1
if cg_count == 10 or cg_count == 11:
hits.append(gene[i:i + 20])
return hits
exon1 = exon1[::-1]
hits_exon1 = find_hit(exon1)
hits_rev = []
for elem in hits_exon1:
hits_rev.append(elem[::-1])
print('Forward primer candidates:')
print(hits_rev)
print('Reverse primer candidates:')
print(find_hit(exon2))
|
# Objective
# Today we're discussing scope. Check out the Tutorial tab for learning materials and an instructional video!
# The absolute difference between two integers,
# and , is written as . The maximum absolute difference between two integers in a set of positive integers, , is the largest absolute difference between any two integers in
# .
# The Difference class is started for you in the editor. It has a private integer array (
# ) for storing non-negative integers, and a public integer (
# ) for storing the maximum absolute difference.
# Task
# Complete the Difference class by writing the following:
# A class constructor that takes an array of integers as a parameter and saves it to the
# instance variable.
# A computeDifference method that finds the maximum absolute difference between any
# numbers in and stores it in the
# instance variable.
# Input Format
# You are not responsible for reading any input from stdin. The locked Solution class in the editor reads in
# lines of input. The first line contains , the size of the elements array. The second line has space-separated integers that describe the
# array.
# Constraints
# , where
# Output Format
# You are not responsible for printing any output; the Solution class will print the value of the
# instance variable.
# Sample Input
# STDIN Function
# ----- --------
# 3 __elements[] size N = 3
# 1 2 5 __elements = [1, 2, 5]
# Sample Output
# 4
# Explanation
# The scope of the
# array and integer is the entire class instance. The class constructor saves the argument passed to the constructor as the
# instance variable (where the computeDifference method can access it).
# To find the maximum difference, computeDifference checks each element in the array and finds the maximum difference between any
# elements:
# The maximum of these differences is , so it saves the value as the instance variable. The locked stub code in the editor then prints the value stored as , which is .
class Difference:
def __init__(self, a):
self.__elements = a
# Add your code here
def computeDifference(self):
diff_array=[]
#loop through the i+1 to the last element and through the first ement to the second last element
for i in range(len(self.__elements)-1):
for j in range(i+1,len(self.__elements)):
diff=abs(self.__elements[j]-self.__elements[i])
diff_array.append(diff)
self.maximumDifference=max(diff_array)
# End of Difference class
_ = input()
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
|
class Difference:
def __init__(self, a):
self.__elements = a
def compute_difference(self):
diff_array = []
for i in range(len(self.__elements) - 1):
for j in range(i + 1, len(self.__elements)):
diff = abs(self.__elements[j] - self.__elements[i])
diff_array.append(diff)
self.maximumDifference = max(diff_array)
_ = input()
a = [int(e) for e in input().split(' ')]
d = difference(a)
d.computeDifference()
print(d.maximumDifference)
|
#another way of doing recursive palindrome
def is_palindrome(s):
ln = len(s)
if s != '':
if s[ln-1] == s[0]:
return True and is_palindrome(s[1:ln-1])
return False
return True
assert is_palindrome('abab') == False
assert is_palindrome('abba') == True
assert is_palindrome('madam') == True
assert is_palindrome('madame') == False
assert is_palindrome('') == True
#non recursive loop method
def is_palindrome_loop(s):
ln = len(s)
for i in xrange(ln/2):
if not (s[i] == s[ln-i-1]): return False
return True
assert is_palindrome_loop('abab') == False
assert is_palindrome_loop('abba') == True
assert is_palindrome_loop('madam') == True
assert is_palindrome_loop('madame') == False
assert is_palindrome_loop('') == True
#easier pythonic way
def is_pal_easy(s): return s == s[::-1]
assert is_pal_easy('abab') == False
assert is_pal_easy('abba') == True
assert is_pal_easy('madam') == True
assert is_pal_easy('madame') == False
assert is_pal_easy('') == True
|
def is_palindrome(s):
ln = len(s)
if s != '':
if s[ln - 1] == s[0]:
return True and is_palindrome(s[1:ln - 1])
return False
return True
assert is_palindrome('abab') == False
assert is_palindrome('abba') == True
assert is_palindrome('madam') == True
assert is_palindrome('madame') == False
assert is_palindrome('') == True
def is_palindrome_loop(s):
ln = len(s)
for i in xrange(ln / 2):
if not s[i] == s[ln - i - 1]:
return False
return True
assert is_palindrome_loop('abab') == False
assert is_palindrome_loop('abba') == True
assert is_palindrome_loop('madam') == True
assert is_palindrome_loop('madame') == False
assert is_palindrome_loop('') == True
def is_pal_easy(s):
return s == s[::-1]
assert is_pal_easy('abab') == False
assert is_pal_easy('abba') == True
assert is_pal_easy('madam') == True
assert is_pal_easy('madame') == False
assert is_pal_easy('') == True
|
class Profile(object):
@property
def name(self):
return self.__name
@property
def trustRoleArn(self):
return self.__trustRoleArn
@property
def sourceProfile(self):
return self.__sourceProfile
@property
def credentials(self):
return self.__credentials
@name.setter
def name(self, value):
self.name = value
@trustRoleArn.setter
def trustRoleArn(self, value):
self.__trustRoleArn = value
@sourceProfile.setter
def sourceProfile(self, value):
self.__sourceProfile = value
@credentials.setter
def credentials(self, value):
self.__credentials = value
def __init__(self, name = None, trustRoleArn = None, sourceProfile = None, credentials = None):
self.__name = name
self.__trustRoleArn = trustRoleArn
self.__sourceProfile = sourceProfile
self.__credentials = credentials
|
class Profile(object):
@property
def name(self):
return self.__name
@property
def trust_role_arn(self):
return self.__trustRoleArn
@property
def source_profile(self):
return self.__sourceProfile
@property
def credentials(self):
return self.__credentials
@name.setter
def name(self, value):
self.name = value
@trustRoleArn.setter
def trust_role_arn(self, value):
self.__trustRoleArn = value
@sourceProfile.setter
def source_profile(self, value):
self.__sourceProfile = value
@credentials.setter
def credentials(self, value):
self.__credentials = value
def __init__(self, name=None, trustRoleArn=None, sourceProfile=None, credentials=None):
self.__name = name
self.__trustRoleArn = trustRoleArn
self.__sourceProfile = sourceProfile
self.__credentials = credentials
|
# f_name = 'ex1.txt'
f_name = 'input.txt'
all_ingredients = set()
possible_allergens = dict()
recipes = list()
with open(f_name, 'r') as f:
for i, line in enumerate(f.readlines()):
# get a list of the ingredients and record the food recipe as a set of the
# ingredients (recipes = [{'aaa', 'bbb'}, {...}]
ingredients = line.split(' (')[0].strip().split()
recipes.append(set(ingredients))
all_ingredients |= set(ingredients)
# get a list of the allergens and store a dict of allergens with the food it is
# contained in (allergens_in_food[dairy] = {1, 2, 3...}
allergens = line.split(' (')[1][9:-2].strip().split(', ')
for a in allergens:
if a not in possible_allergens:
possible_allergens[a] = set(ingredients)
else:
possible_allergens[a] &= set(ingredients)
# Part 1: count occurence of each ingredient not a possible allergen in the recipes
all_possible_allergens = set((x for ing_set in possible_allergens.values() for x in ing_set))
no_allergens = all_ingredients - all_possible_allergens
part1 = 0
for ing in no_allergens:
part1 += sum(1 for r in recipes if ing in r)
print(f'Part 1: {part1}')
# Part 2
final_allergens = dict()
queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1]
while queue:
allg = queue.pop(0)
ing = possible_allergens[allg].pop()
final_allergens[allg] = ing
possible_allergens.pop(allg)
for x in possible_allergens:
if ing in possible_allergens[x]:
possible_allergens[x].remove(ing)
queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1]
# generate the part2 output, ingredients sorted by allergen name
part2 = ','.join([final_allergens[x] for x in sorted(final_allergens)])
print('Part 2:', part2)
|
f_name = 'input.txt'
all_ingredients = set()
possible_allergens = dict()
recipes = list()
with open(f_name, 'r') as f:
for (i, line) in enumerate(f.readlines()):
ingredients = line.split(' (')[0].strip().split()
recipes.append(set(ingredients))
all_ingredients |= set(ingredients)
allergens = line.split(' (')[1][9:-2].strip().split(', ')
for a in allergens:
if a not in possible_allergens:
possible_allergens[a] = set(ingredients)
else:
possible_allergens[a] &= set(ingredients)
all_possible_allergens = set((x for ing_set in possible_allergens.values() for x in ing_set))
no_allergens = all_ingredients - all_possible_allergens
part1 = 0
for ing in no_allergens:
part1 += sum((1 for r in recipes if ing in r))
print(f'Part 1: {part1}')
final_allergens = dict()
queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1]
while queue:
allg = queue.pop(0)
ing = possible_allergens[allg].pop()
final_allergens[allg] = ing
possible_allergens.pop(allg)
for x in possible_allergens:
if ing in possible_allergens[x]:
possible_allergens[x].remove(ing)
queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1]
part2 = ','.join([final_allergens[x] for x in sorted(final_allergens)])
print('Part 2:', part2)
|
S = 0
T = 0
L = []
for i in range(11):
L.append(list(map(int,input().split())))
L.sort(key = lambda t:(t[0],t[1]))
for i in L:
T+=i[0]
S += T + i[1]*20
print(S)
|
s = 0
t = 0
l = []
for i in range(11):
L.append(list(map(int, input().split())))
L.sort(key=lambda t: (t[0], t[1]))
for i in L:
t += i[0]
s += T + i[1] * 20
print(S)
|
# Evaluacion de expresiones
print(3+5)
print(3+2*5)
print((3+2)*5)
print(2**3)
print(4**0.5)
print(10%3)
print('abra' + 'cadabra')
print('ja'*3)
print(1+2)
print(1.0+2.0)
print(1.0+2)
print(1/2)
print(1//2)
print(1.0//2.0)
print('En el curso hay ' + str(30) + ' alumnos')
print('100'+'1')
print(int('100') +1)
# Variables
a = 8 # la variable contiene el valor 8
b = 12 # la variable contiene el valor 12
print(a)
print(a+b)
c = a + 2 * b #creamos una expresion, se evalua y define c
print(c)
a = 10 #redefinimos a
print(c) # el valor de c no cambia
# Usar nombre descriptivos para variables
a = 8
b = 12
c = a * b
# Mejor:
ancho = 8
largo = 12
area = ancho * largo
print(area)
dia = '12'; mes = 'marzo'; agno = '2018'
hoy = dia + ' de ' + mes + ' de '+ agno
print(hoy)
# Errores
'''
No incluidos directamente para que el programa corra
# Errores de tipo
dia = 13
mes = 'marzo'
print('Hoy es ' + dia + ' de ' + mes) # Mes es tipo int
# solucion
print('Hoy es ' + str(dia) + ' de ' + mes) # Transformamos a string
# Errores de identacion
x = 3
x #tiene un 'tab' de diferencia'
# Errores de sintaxis
numero = 15
antecesor = (numero -1)) # Un ) de mas
# Errores de nombre
lado1 = 15
area = lado1/lado2 # lado2 no definido
'''
|
print(3 + 5)
print(3 + 2 * 5)
print((3 + 2) * 5)
print(2 ** 3)
print(4 ** 0.5)
print(10 % 3)
print('abra' + 'cadabra')
print('ja' * 3)
print(1 + 2)
print(1.0 + 2.0)
print(1.0 + 2)
print(1 / 2)
print(1 // 2)
print(1.0 // 2.0)
print('En el curso hay ' + str(30) + ' alumnos')
print('100' + '1')
print(int('100') + 1)
a = 8
b = 12
print(a)
print(a + b)
c = a + 2 * b
print(c)
a = 10
print(c)
a = 8
b = 12
c = a * b
ancho = 8
largo = 12
area = ancho * largo
print(area)
dia = '12'
mes = 'marzo'
agno = '2018'
hoy = dia + ' de ' + mes + ' de ' + agno
print(hoy)
"\nNo incluidos directamente para que el programa corra\n\n# Errores de tipo\ndia = 13\nmes = 'marzo'\nprint('Hoy es ' + dia + ' de ' + mes) # Mes es tipo int\n# solucion\nprint('Hoy es ' + str(dia) + ' de ' + mes) # Transformamos a string\n\n# Errores de identacion \nx = 3\n x #tiene un 'tab' de diferencia' \n\n# Errores de sintaxis\n\nnumero = 15 \nantecesor = (numero -1)) # Un ) de mas\n\n# Errores de nombre \nlado1 = 15\n\narea = lado1/lado2 # lado2 no definido\n\n"
|
class GameStats():
"""TRACK STATISTICS FOR FROM ANOTHER WORLD"""
def __init__(self, ai_settings):
"""INITIALIZE STATISTICS"""
self.ai_settings = ai_settings
self.reset_stats()
# START GAME IN AN INACTIVE STATE
self.game_active = False
def reset_stats(self):
"""INITIALIZE STATISTICS THAT CAN CHANGE DURING THE GAME"""
self.ships_left = self.ai_settings.ship_limit
self.score = 0
self.level = 1
|
class Gamestats:
"""TRACK STATISTICS FOR FROM ANOTHER WORLD"""
def __init__(self, ai_settings):
"""INITIALIZE STATISTICS"""
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
def reset_stats(self):
"""INITIALIZE STATISTICS THAT CAN CHANGE DURING THE GAME"""
self.ships_left = self.ai_settings.ship_limit
self.score = 0
self.level = 1
|
a, b, c, d = 1, 2, 3, 4
print(a, b, c, d)
a, b, c, d = d, c, b, a
print(a, b, c, d)
|
(a, b, c, d) = (1, 2, 3, 4)
print(a, b, c, d)
(a, b, c, d) = (d, c, b, a)
print(a, b, c, d)
|
def test_metadata(system_config) -> None:
assert system_config.provider_code == "system"
assert system_config._prefix == "TEST"
def test_prefixize(system_config) -> None:
assert system_config.prefixize("key1") == "TEST_KEY1"
assert system_config.unprefixize("TEST_KEY1") == "key1"
def test_get_variable(monkeypatch, system_config) -> None:
monkeypatch.setenv("TEST_KEY1", "1")
monkeypatch.setenv("TEST_KEY2", "2")
assert system_config.get("key1") == "1"
assert system_config.get("key2") == "2"
monkeypatch.undo()
def test_get_variables_list(monkeypatch, system_config) -> None:
monkeypatch.setenv("TEST_KEY1", "1")
monkeypatch.setenv("TEST_KEY2", "2")
monkeypatch.setenv("TEZT_T1", "1")
monkeypatch.setenv("TEZT_T2", "2")
assert "key1" in system_config.keys()
assert "key2" in system_config.keys()
assert "t1" not in system_config.keys()
assert "t2" not in system_config.keys()
monkeypatch.undo()
|
def test_metadata(system_config) -> None:
assert system_config.provider_code == 'system'
assert system_config._prefix == 'TEST'
def test_prefixize(system_config) -> None:
assert system_config.prefixize('key1') == 'TEST_KEY1'
assert system_config.unprefixize('TEST_KEY1') == 'key1'
def test_get_variable(monkeypatch, system_config) -> None:
monkeypatch.setenv('TEST_KEY1', '1')
monkeypatch.setenv('TEST_KEY2', '2')
assert system_config.get('key1') == '1'
assert system_config.get('key2') == '2'
monkeypatch.undo()
def test_get_variables_list(monkeypatch, system_config) -> None:
monkeypatch.setenv('TEST_KEY1', '1')
monkeypatch.setenv('TEST_KEY2', '2')
monkeypatch.setenv('TEZT_T1', '1')
monkeypatch.setenv('TEZT_T2', '2')
assert 'key1' in system_config.keys()
assert 'key2' in system_config.keys()
assert 't1' not in system_config.keys()
assert 't2' not in system_config.keys()
monkeypatch.undo()
|
def read_matrix():
rows_count = int(input())
matrix = []
for _ in range(rows_count):
row = [int(r) for r in input().split(' ')]
matrix.append(row)
return matrix
def get_primary_diagonal_sum(matrix):
p_d_sum = 0
for i in range(len(matrix)):
p_d_sum += matrix[i][i]
return p_d_sum
def get_secondary_diagonal_sum(matrix):
s_d_sum = 0
for i in range(len(matrix)):
s_d_sum += matrix[i][len(matrix) - i - 1]
return s_d_sum
matrix = read_matrix()
primary_diagonal_sum = get_primary_diagonal_sum(matrix)
secondary_diagonal_sum = get_secondary_diagonal_sum(matrix)
print(abs(primary_diagonal_sum - secondary_diagonal_sum))
|
def read_matrix():
rows_count = int(input())
matrix = []
for _ in range(rows_count):
row = [int(r) for r in input().split(' ')]
matrix.append(row)
return matrix
def get_primary_diagonal_sum(matrix):
p_d_sum = 0
for i in range(len(matrix)):
p_d_sum += matrix[i][i]
return p_d_sum
def get_secondary_diagonal_sum(matrix):
s_d_sum = 0
for i in range(len(matrix)):
s_d_sum += matrix[i][len(matrix) - i - 1]
return s_d_sum
matrix = read_matrix()
primary_diagonal_sum = get_primary_diagonal_sum(matrix)
secondary_diagonal_sum = get_secondary_diagonal_sum(matrix)
print(abs(primary_diagonal_sum - secondary_diagonal_sum))
|
'''
1. The algorithm is a substitution cipher. It shifts each letter by a certain key.
2. Python Library Functions used :
a) ord() : Converts a character to its equivalent ASCII value.
b) chr() : Converts an ASCII value to its equivalent character.
3. What are 65 and 97?
a) 65 is the ASCII value of 'A'.
b) 97 is the ASCII value of 'a'.
'''
# Get number equivalent of a character
def get_num_equivalent(char):
return (
ord(char) - 65) if char.isupper() else (ord(char) - 97)
# Get character equivalent of a number
def get_char_equivalent(char, num):
return chr(num + 65) if char.isupper() else chr(num + 97)
# Encryption Algorithm
def encrypt(plain_text, key):
encrypted_text = ''
for char in plain_text:
num_equivalent = get_num_equivalent(char)
# Formula : (num_equivalent + key) mod 26
encrypted_num = (num_equivalent + key) % 26
encrypted_text += get_char_equivalent(char, encrypted_num)
return encrypted_text
# Decryption Algorithm
def decrypt(encrypted_text, key):
decrypted_text = ''
for char in encrypted_text:
num_equivalent = get_num_equivalent(char)
# Formula : (num_equivalent - key) mod 26
decrypted_num = (num_equivalent - key) % 26
decrypted_text += get_char_equivalent(char, decrypted_num)
return decrypted_text
# Driver Code
if __name__ == '__main__':
plain_text, key = 'TheSkinnyCoder', 3
encrypted_text = encrypt(plain_text, key)
decrypted_text = decrypt(encrypted_text, key)
print(f'The Original Text is : {plain_text}')
print(f'The Encrypted Cipher Text is : {encrypted_text}')
print(f'The Decrypted Text is : {decrypted_text}')
|
"""
1. The algorithm is a substitution cipher. It shifts each letter by a certain key.
2. Python Library Functions used :
a) ord() : Converts a character to its equivalent ASCII value.
b) chr() : Converts an ASCII value to its equivalent character.
3. What are 65 and 97?
a) 65 is the ASCII value of 'A'.
b) 97 is the ASCII value of 'a'.
"""
def get_num_equivalent(char):
return ord(char) - 65 if char.isupper() else ord(char) - 97
def get_char_equivalent(char, num):
return chr(num + 65) if char.isupper() else chr(num + 97)
def encrypt(plain_text, key):
encrypted_text = ''
for char in plain_text:
num_equivalent = get_num_equivalent(char)
encrypted_num = (num_equivalent + key) % 26
encrypted_text += get_char_equivalent(char, encrypted_num)
return encrypted_text
def decrypt(encrypted_text, key):
decrypted_text = ''
for char in encrypted_text:
num_equivalent = get_num_equivalent(char)
decrypted_num = (num_equivalent - key) % 26
decrypted_text += get_char_equivalent(char, decrypted_num)
return decrypted_text
if __name__ == '__main__':
(plain_text, key) = ('TheSkinnyCoder', 3)
encrypted_text = encrypt(plain_text, key)
decrypted_text = decrypt(encrypted_text, key)
print(f'The Original Text is : {plain_text}')
print(f'The Encrypted Cipher Text is : {encrypted_text}')
print(f'The Decrypted Text is : {decrypted_text}')
|
#!/usr/bin/env python3
#!/usr/bin/python3
dict1 = {
'a': 1,
'b': 2,
}
dict2 = {
'a': 0,
'b': 2,
}
if dict1 == dict2:
print("FAIL")
else:
print("PASS")
dict1 = {
'a': {
'c': 'bake'
},
'b': 2,
}
dict2 = {
'a': {
'c': 'shake'
},
'b': 2,
}
if dict1 == dict2:
print("FAIL")
else:
print("PASS")
dict1 = {
'a': {
'c': [0, 1]
},
'b': 2,
}
dict2 = {
'a': {
'c': [0, 2]
},
'b': 2,
}
if dict1 == dict2:
print("FAIL")
else:
print("PASS")
|
dict1 = {'a': 1, 'b': 2}
dict2 = {'a': 0, 'b': 2}
if dict1 == dict2:
print('FAIL')
else:
print('PASS')
dict1 = {'a': {'c': 'bake'}, 'b': 2}
dict2 = {'a': {'c': 'shake'}, 'b': 2}
if dict1 == dict2:
print('FAIL')
else:
print('PASS')
dict1 = {'a': {'c': [0, 1]}, 'b': 2}
dict2 = {'a': {'c': [0, 2]}, 'b': 2}
if dict1 == dict2:
print('FAIL')
else:
print('PASS')
|
## Grasshopper - Summation
## 8 kyu
## https://www.codewars.com/kata/55d24f55d7dd296eb9000030
def summation(num):
return sum([i for i in range(num+1)])
|
def summation(num):
return sum([i for i in range(num + 1)])
|
LEFT_ALIGNED = 0
RIGHT_ALIGNED = 1
CENTER_ALIGNED = 2
JUSTIFIED_ALIGNED = 3
NATURAL_ALIGNED = 4
|
left_aligned = 0
right_aligned = 1
center_aligned = 2
justified_aligned = 3
natural_aligned = 4
|
score_1 = float(input('Type your 1st score: '))
score_2 = float(input('Type your 2nd score: '))
average = (score_1 + score_2) / 2
print(f'Your average is {average}, therefore you...')
print('Pass. Congrats.') if average > 6 \
else print('Fail. Study again, you\'ll get it. :)')
|
score_1 = float(input('Type your 1st score: '))
score_2 = float(input('Type your 2nd score: '))
average = (score_1 + score_2) / 2
print(f'Your average is {average}, therefore you...')
print('Pass. Congrats.') if average > 6 else print("Fail. Study again, you'll get it. :)")
|
class NoDataError(Exception):
def __init__(self, field, obj, module):
message = "Missing field '" + field + "' in the object " + str(obj) + " needed in " + module
super(NoDataError, self).__init__(message)
|
class Nodataerror(Exception):
def __init__(self, field, obj, module):
message = "Missing field '" + field + "' in the object " + str(obj) + ' needed in ' + module
super(NoDataError, self).__init__(message)
|
"""
Should specifically use:
touchtechnology.common.backends.auth.UserSubclassBackend
touchtechnology.common.backends.auth.EmailUserSubclassBackend
"""
|
"""
Should specifically use:
touchtechnology.common.backends.auth.UserSubclassBackend
touchtechnology.common.backends.auth.EmailUserSubclassBackend
"""
|
""" ``mixin`` module.
"""
class ErrorsMixin(object):
"""Used primary by service layer to validate business rules.
Requirements:
- self.errors
Example::
class MyService(ValidationMixin):
def __init__(self, repository, errors, locale):
# ...
def authenticate(self, credential):
if not self.factory.membership.authenticate(credentials):
self.error('The username or password provided '
'is incorrect.')
return False
# ...
return True
"""
def error(self, message, name="__ERROR__"):
"""Add `message` to errors."""
self.errors.setdefault(name, []).append(message)
class ValidationMixin(object):
"""Used primary by service layer to validate domain model.
Requirements:
- self.errors
- self.translations
Example::
class MyService(ValidationMixin):
def __init__(self, repository, errors, translations, locale):
# ...
def authenticate(self, credential):
if not self.validate(credential, credential_validator):
return False
# ...
return True
"""
def error(self, message, name="__ERROR__"):
"""Add `message` to errors."""
self.errors.setdefault(name, []).append(message)
def validate(self, model, validator):
"""Validate given `model` using `validator`."""
return validator.validate(
model, self.errors, translations=self.translations["validation"]
)
|
""" ``mixin`` module.
"""
class Errorsmixin(object):
"""Used primary by service layer to validate business rules.
Requirements:
- self.errors
Example::
class MyService(ValidationMixin):
def __init__(self, repository, errors, locale):
# ...
def authenticate(self, credential):
if not self.factory.membership.authenticate(credentials):
self.error('The username or password provided '
'is incorrect.')
return False
# ...
return True
"""
def error(self, message, name='__ERROR__'):
"""Add `message` to errors."""
self.errors.setdefault(name, []).append(message)
class Validationmixin(object):
"""Used primary by service layer to validate domain model.
Requirements:
- self.errors
- self.translations
Example::
class MyService(ValidationMixin):
def __init__(self, repository, errors, translations, locale):
# ...
def authenticate(self, credential):
if not self.validate(credential, credential_validator):
return False
# ...
return True
"""
def error(self, message, name='__ERROR__'):
"""Add `message` to errors."""
self.errors.setdefault(name, []).append(message)
def validate(self, model, validator):
"""Validate given `model` using `validator`."""
return validator.validate(model, self.errors, translations=self.translations['validation'])
|
class Event():
def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None):
self.guild_id = guild_id
self.event_type = event_type
self.target_id = target_id
self.target_name = target_name
self.actor = actor
self.reason = reason
self.timestamp = timestamp
self.role_id = role_id
self.role_name = role_name
self.count = count
self.message_id = message_id
@classmethod
def from_row(cls, row, actor=None, reason=None):
return cls(row.get("guild_id"), row.get("event_type"), row.get("target_id"), row.get("target_name"), row.get("actor") if not actor else actor, row.get("reason") if not reason else reason, row.get("timestamp"), row.get("role_id"), row.get("role_name"), row.get("event_id"), row.get("message_id"))
def set_actor(self, actor):
self.actor = actor
def set_count(self, count):
self.count = count
def db_insert(self):
return (self.guild_id, self.event_type, self.target_id, self.target_name, self.actor if type(self.actor) == int else self.actor.id, self.reason, self.timestamp, self.role_id, self.role_name, self.count)
|
class Event:
def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None):
self.guild_id = guild_id
self.event_type = event_type
self.target_id = target_id
self.target_name = target_name
self.actor = actor
self.reason = reason
self.timestamp = timestamp
self.role_id = role_id
self.role_name = role_name
self.count = count
self.message_id = message_id
@classmethod
def from_row(cls, row, actor=None, reason=None):
return cls(row.get('guild_id'), row.get('event_type'), row.get('target_id'), row.get('target_name'), row.get('actor') if not actor else actor, row.get('reason') if not reason else reason, row.get('timestamp'), row.get('role_id'), row.get('role_name'), row.get('event_id'), row.get('message_id'))
def set_actor(self, actor):
self.actor = actor
def set_count(self, count):
self.count = count
def db_insert(self):
return (self.guild_id, self.event_type, self.target_id, self.target_name, self.actor if type(self.actor) == int else self.actor.id, self.reason, self.timestamp, self.role_id, self.role_name, self.count)
|
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda']
nintendo_games.remove('Zelda')
print(nintendo_games)
if 'Wario' in nintendo_games:
nintendo_games.remove('Wario')
|
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda']
nintendo_games.remove('Zelda')
print(nintendo_games)
if 'Wario' in nintendo_games:
nintendo_games.remove('Wario')
|
class Test:
def initialize(self):
self.x = 42
t = Test()
t.initialize()
def calc(self, n):
return self.x + n
Test.calc = calc
assert t.calc(4) == 46
|
class Test:
def initialize(self):
self.x = 42
t = test()
t.initialize()
def calc(self, n):
return self.x + n
Test.calc = calc
assert t.calc(4) == 46
|
# Time: O(n)
# Space: O(1)
#
# 123
# Say you have an array for which the ith element
# is the price of a given stock on day i.
#
# Design an algorithm to find the maximum profit.
# You may complete at most two transactions.
#
# Note:
# You may not engage in multiple transactions at the same time
# (ie, you must sell the stock before you buy again).
#
# Input: [3,3,5,0,0,3,1,4]
# Output: 6 (= 3-0 + 4-1)
# Input: [1,2,3,4,5]
# Output: 4
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
class Solution(object): # USE THIS: CAN EXTEND to k transactions.
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
hold1, hold2 = float('-inf'), float('-inf')
cash1, cash2 = 0, 0
for p in prices:
# to be sequential, hold[j] refers to cash[j-1], and cash[j] refers to hold[j].
# because it is ok to buy then sell in the same day, so the 4 lines
# don't need to execute simultaneously (i.e. write in 1 line)
hold1 = max(hold1, -p)
cash1 = max(cash1, hold1+p)
hold2 = max(hold2, cash1-p)
cash2 = max(cash2, hold2+p)
return cash2
# This solution is AN EXTENSION OF SOLUTION for buy-and-sell-stock-i, and can extend to k.
# hold[i] is the balance after ith buy, cash[i] is the balance after ith sell.
def maxProfit_extend(self, prices):
n, k = len(prices), 2
hold = [float('-inf')] * (k + 1) # entry at index 0 is easy to calculate boundary value
cash = [0] * (k + 1)
for i in range(n):
# because k is constant, won't benefit much by doing the following optimization:
# optimization skip unnecessary large k. Need to be i+1, so when i is 0, still set hold[0].
# kamyu solution uses min(k, i//2+1) + 1, but I think for day i, we can do i transactions.
#for j in range(1, min(k, i+1)+1):
for j in range(1, k + 1):
# to be sequential, hold[j] refers to cash[j-1], and cash[j] refers to hold[j]
hold[j] = max(hold[j], cash[j-1] - prices[i]) # maximize max_buy means price at buy point needs to be as small as possible
cash[j] = max(cash[j], hold[j] + prices[i])
return cash[-1]
# Time: O(n)
# Space: O(1)
class Solution2(object):
# similar to Solution 1, but track cost/profit instead of balances.
# Maintain the min COST of if we just buy 1, 2, 3... stock, and the max PROFIT (balance) of if we just sell 1,2,3... stock.
# In order to get the final max profit, profit1 must be as relatively large as possible to produce a small cost2,
# and therefore cost2 can be as small as possible to give the final max profit2.
def maxProfit(self, prices):
cost1, cost2 = float("inf"), float("inf")
profit1, profit2 = 0, 0
for p in prices:
cost1 = min(cost1, p) # lowest price
profit1 = max(profit1, p - cost1) # global max profit for 1 buy-sell transaction
cost2 = min(cost2, p - profit1) # adjust the cost by reducing 1st profit
profit2 = max(profit2, p - cost2) # global max profit for 1 to 2 transactions
return profit2
# This solution CANNOT extend to k transactions.
# Time: O(n)
# Space: O(n)
class Solution3(object):
# @param prices, a list of integer
# @return an integer
# use any day as divider for 1st and 2nd stock transaction. Compare all possible division
# (linear time). Ok to sell then buy at the same day, so divider is on each day (dp array
# is length N), not between two days.
def maxProfit(self, prices):
N = len(prices)
_min, maxProfitLeft, maxProfitsLeft = float("inf"), 0, [0]*N
_max, maxProfitRight, maxProfitsRight = 0, 0, [0]*N
for i in range(N):
_min = min(_min, prices[i])
maxProfitLeft = max(maxProfitLeft, prices[i] - _min)
maxProfitsLeft[i] = maxProfitLeft
_max = max(_max, prices[N-1-i])
maxProfitRight = max(maxProfitRight, _max - prices[N-1-i])
maxProfitsRight[N-1-i] = maxProfitRight
return max(maxProfitsLeft[i]+maxProfitsRight[i]
for i in range(N)) if N else 0
print(Solution().maxProfit([1,3,2,8,4,9])) # 12
print(Solution().maxProfit([1,2,3,4,5])) # 4
print(Solution().maxProfit([3,3,5,0,0,3,1,4])) # 6
|
try:
xrange
except NameError:
xrange = range
class Solution(object):
def max_profit(self, prices):
(hold1, hold2) = (float('-inf'), float('-inf'))
(cash1, cash2) = (0, 0)
for p in prices:
hold1 = max(hold1, -p)
cash1 = max(cash1, hold1 + p)
hold2 = max(hold2, cash1 - p)
cash2 = max(cash2, hold2 + p)
return cash2
def max_profit_extend(self, prices):
(n, k) = (len(prices), 2)
hold = [float('-inf')] * (k + 1)
cash = [0] * (k + 1)
for i in range(n):
for j in range(1, k + 1):
hold[j] = max(hold[j], cash[j - 1] - prices[i])
cash[j] = max(cash[j], hold[j] + prices[i])
return cash[-1]
class Solution2(object):
def max_profit(self, prices):
(cost1, cost2) = (float('inf'), float('inf'))
(profit1, profit2) = (0, 0)
for p in prices:
cost1 = min(cost1, p)
profit1 = max(profit1, p - cost1)
cost2 = min(cost2, p - profit1)
profit2 = max(profit2, p - cost2)
return profit2
class Solution3(object):
def max_profit(self, prices):
n = len(prices)
(_min, max_profit_left, max_profits_left) = (float('inf'), 0, [0] * N)
(_max, max_profit_right, max_profits_right) = (0, 0, [0] * N)
for i in range(N):
_min = min(_min, prices[i])
max_profit_left = max(maxProfitLeft, prices[i] - _min)
maxProfitsLeft[i] = maxProfitLeft
_max = max(_max, prices[N - 1 - i])
max_profit_right = max(maxProfitRight, _max - prices[N - 1 - i])
maxProfitsRight[N - 1 - i] = maxProfitRight
return max((maxProfitsLeft[i] + maxProfitsRight[i] for i in range(N))) if N else 0
print(solution().maxProfit([1, 3, 2, 8, 4, 9]))
print(solution().maxProfit([1, 2, 3, 4, 5]))
print(solution().maxProfit([3, 3, 5, 0, 0, 3, 1, 4]))
|
def firstDuplicateValue(array):
for n in array:
n = abs(n)
if array[n - 1] < 0:
return n
array[n - 1] *= -1
return -1
|
def first_duplicate_value(array):
for n in array:
n = abs(n)
if array[n - 1] < 0:
return n
array[n - 1] *= -1
return -1
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
def read_gowalla_data(file_path):
train_file = open(file_path, 'r')
x_data = {}
for i in open(file_path):
line = train_file.readline()
# line = line.strip('\n')
if len(line) == 0:
continue
items = line.split("\t")
user_id = items[0]
if len(user_id) == 0:
continue
user_id = int(user_id)
if user_id not in x_data.keys():
x_data[user_id] = list()
poi_id = items[4]
if len(poi_id) == 0:
continue
else:
poi_id = int(poi_id)
x_data[user_id].append(poi_id)
train_file.close()
return x_data
def read_foursquare_data(file_path):
train_file = open(file_path, 'r')
x_data = {}
while 1:
line = train_file.readline()
if not line:
break
if len(line) == 0:
continue
items = line.split("\t")
user_id = items[0].split("_")[1]
if len(user_id) == 0:
continue
user_id = int(user_id)
if user_id not in x_data.keys():
x_data[user_id] = list()
poi_id = items[1].split("_")[1]
if len(poi_id) == 0:
continue
else:
poi_id = int(poi_id)
x_data[user_id].append(poi_id)
train_file.close()
return x_data
def read_gtd_data(file_path):
train_file = open(file_path, 'r')
x_data = {}
while 1:
line = train_file.readline()
if not line:
break
if len(line) == 0:
continue
items = line.split("\t")
user_id = items[6]
if len(user_id) == 0:
continue
user_id = int(user_id)
if user_id not in x_data.keys():
x_data[user_id] = list()
poi_id = items[2]
if len(poi_id) == 0:
continue
else:
poi_id = int(poi_id)
x_data[user_id].append(poi_id)
train_file.close()
return x_data
def read_foursquare_users():
users = set()
t_file = open('../foursquare/foursquare_records.txt', 'r')
for i in open('../foursquare/foursquare_records.txt'):
line = t_file.readline()
items = line.split("\t")
user_id = int(items[0].split("_")[1])
users.add(user_id)
t_file.close()
num_users = len(users)
return num_users
def read_foursquare_pois():
pois = set()
t_file = open('../foursquare/foursquare_records.txt', 'r')
for i in open('../foursquare/foursquare_records.txt'):
line = t_file.readline()
items = line.split("\t")
poi_id = int(items[1].split("_")[1])
pois.add(poi_id)
t_file.close()
num_pois = len(pois)
return num_pois
def read_gtd_users():
users = set()
t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r')
for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'):
line = t_file.readline()
items = line.split("\t")
user_id = int(items[6])
users.add(user_id)
t_file.close()
num_users = len(users)
return num_users
def read_gtd_pois():
pois = set()
t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r')
for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'):
line = t_file.readline()
items = line.split("\t")
poi_id = int(items[2])
pois.add(poi_id)
t_file.close()
num_pois = len(pois)
return num_pois
def read_gowalla_users():
users = set()
t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r')
for i in open('../gowalla/sorted_indexed_final_gowalla.txt'):
line = t_file.readline()
items = line.split("\t")
user_id = int(items[0])
users.add(user_id)
t_file.close()
num_users = len(users)
return num_users
def read_gowalla_pois():
pois = set()
t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r')
for i in open('../gowalla/sorted_indexed_final_gowalla.txt'):
line = t_file.readline()
items = line.split("\t")
poi_id = int(items[4])
pois.add(poi_id)
t_file.close()
num_pois = len(pois)
return num_pois
|
def read_gowalla_data(file_path):
train_file = open(file_path, 'r')
x_data = {}
for i in open(file_path):
line = train_file.readline()
if len(line) == 0:
continue
items = line.split('\t')
user_id = items[0]
if len(user_id) == 0:
continue
user_id = int(user_id)
if user_id not in x_data.keys():
x_data[user_id] = list()
poi_id = items[4]
if len(poi_id) == 0:
continue
else:
poi_id = int(poi_id)
x_data[user_id].append(poi_id)
train_file.close()
return x_data
def read_foursquare_data(file_path):
train_file = open(file_path, 'r')
x_data = {}
while 1:
line = train_file.readline()
if not line:
break
if len(line) == 0:
continue
items = line.split('\t')
user_id = items[0].split('_')[1]
if len(user_id) == 0:
continue
user_id = int(user_id)
if user_id not in x_data.keys():
x_data[user_id] = list()
poi_id = items[1].split('_')[1]
if len(poi_id) == 0:
continue
else:
poi_id = int(poi_id)
x_data[user_id].append(poi_id)
train_file.close()
return x_data
def read_gtd_data(file_path):
train_file = open(file_path, 'r')
x_data = {}
while 1:
line = train_file.readline()
if not line:
break
if len(line) == 0:
continue
items = line.split('\t')
user_id = items[6]
if len(user_id) == 0:
continue
user_id = int(user_id)
if user_id not in x_data.keys():
x_data[user_id] = list()
poi_id = items[2]
if len(poi_id) == 0:
continue
else:
poi_id = int(poi_id)
x_data[user_id].append(poi_id)
train_file.close()
return x_data
def read_foursquare_users():
users = set()
t_file = open('../foursquare/foursquare_records.txt', 'r')
for i in open('../foursquare/foursquare_records.txt'):
line = t_file.readline()
items = line.split('\t')
user_id = int(items[0].split('_')[1])
users.add(user_id)
t_file.close()
num_users = len(users)
return num_users
def read_foursquare_pois():
pois = set()
t_file = open('../foursquare/foursquare_records.txt', 'r')
for i in open('../foursquare/foursquare_records.txt'):
line = t_file.readline()
items = line.split('\t')
poi_id = int(items[1].split('_')[1])
pois.add(poi_id)
t_file.close()
num_pois = len(pois)
return num_pois
def read_gtd_users():
users = set()
t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r')
for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'):
line = t_file.readline()
items = line.split('\t')
user_id = int(items[6])
users.add(user_id)
t_file.close()
num_users = len(users)
return num_users
def read_gtd_pois():
pois = set()
t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r')
for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'):
line = t_file.readline()
items = line.split('\t')
poi_id = int(items[2])
pois.add(poi_id)
t_file.close()
num_pois = len(pois)
return num_pois
def read_gowalla_users():
users = set()
t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r')
for i in open('../gowalla/sorted_indexed_final_gowalla.txt'):
line = t_file.readline()
items = line.split('\t')
user_id = int(items[0])
users.add(user_id)
t_file.close()
num_users = len(users)
return num_users
def read_gowalla_pois():
pois = set()
t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r')
for i in open('../gowalla/sorted_indexed_final_gowalla.txt'):
line = t_file.readline()
items = line.split('\t')
poi_id = int(items[4])
pois.add(poi_id)
t_file.close()
num_pois = len(pois)
return num_pois
|
# Which environment frames do we need to keep during evaluation?
# There is a set of active environments Values and frames in active environments consume memory
# Memory that is used for other values and frames can be recycled
# Active environments:
# Environments for any functions calls currently being evaluated
# Parent environments of functions named in active environments
# Functions returned can be reused
# max length of active frames at any given time determines how many memory we need
def count_frames(f):
def counted(*arg):
counted.open_count += 1
if counted.max_count < counted.open_count:
counted.max_count = counted.open_count
result = f(*arg)
counted.open_count -= 1
return result
counted.open_count = 0
counted.max_count = 0
return counted
@count_frames
def fib(n):
if n ==0 or n ==1:
return n
else:
return fib(n-2) + fib(n-1)
|
def count_frames(f):
def counted(*arg):
counted.open_count += 1
if counted.max_count < counted.open_count:
counted.max_count = counted.open_count
result = f(*arg)
counted.open_count -= 1
return result
counted.open_count = 0
counted.max_count = 0
return counted
@count_frames
def fib(n):
if n == 0 or n == 1:
return n
else:
return fib(n - 2) + fib(n - 1)
|
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
return [[nums[j] for j in range(len(nums)) if i&2**j] for i in range(2**len(nums))]
|
class Solution:
def xxx(self, nums: List[int]) -> List[List[int]]:
return [[nums[j] for j in range(len(nums)) if i & 2 ** j] for i in range(2 ** len(nums))]
|
def viralAdvertising(n):
return
if __name__ == '__main__':
n = int(input())
viralAdvertising(n)
|
def viral_advertising(n):
return
if __name__ == '__main__':
n = int(input())
viral_advertising(n)
|
# This is just a demo file
print("Hello world")
print("this is update to my previous code")
|
print('Hello world')
print('this is update to my previous code')
|
n = int(input())
# n = 3
sum1 = 0
sum2 = 0
for i in range(1, n + 1):
# print("i = ", i)
if i % 2 == 0:
sum1 += i
else:
sum2 += i
if sum1 == 0:
print(sum2)
else:
print(sum2 - sum1)
|
n = int(input())
sum1 = 0
sum2 = 0
for i in range(1, n + 1):
if i % 2 == 0:
sum1 += i
else:
sum2 += i
if sum1 == 0:
print(sum2)
else:
print(sum2 - sum1)
|
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
length = len(num)
# use dict: value: index + 1
# since there is only one solution, the right value must not be duplicated
dic = {}
for i in xrange(0, length):
val = num[i]
if (target - val) in dic:
return (dic[target - val], i + 1)
dic[val] = i + 1
## test code
# num=[2, 7, 11, 15]
# t= 26
# s = Solution()
# print s.twoSum(num, t)
|
class Solution:
def two_sum(self, num, target):
length = len(num)
dic = {}
for i in xrange(0, length):
val = num[i]
if target - val in dic:
return (dic[target - val], i + 1)
dic[val] = i + 1
|
#Tree Size
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def sizeTree(node):
if node is None:
return 0
else:
return (sizeTree(node.left) + 1 + sizeTree(node.right))
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Size of the tree is {}".format(sizeTree(root)))
|
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def size_tree(node):
if node is None:
return 0
else:
return size_tree(node.left) + 1 + size_tree(node.right)
root = node(1)
root.left = node(2)
root.right = node(3)
root.left.left = node(4)
root.left.right = node(5)
print('Size of the tree is {}'.format(size_tree(root)))
|
'''
One Away: There are three types of edits that can be performed on strings:
insert a character, remove a character, or replace a character.
Given two strings, write a function to check if they are one edit (or zero edits) away.
Example:
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bake -> false
bla, bleble -> false
'''
def is_two_chars_away(str1, str2):
return (len(str1) - len(str2) >= 2) or (len(str2) - len(str1) >= 2)
def number_of_needed_changes(bigger_str, smaller_str):
str_counter = {}
for char in bigger_str:
if char in str_counter:
str_counter[char] += 1
else:
str_counter[char] = 1
for char in smaller_str:
if char in str_counter:
str_counter[char] -= 1
needed_changes = 0
for char, counter in str_counter.items():
needed_changes += counter
return needed_changes
def one_away(str1, str2):
if is_two_chars_away(str1, str2):
return False
needed_changes = 0
if len(str1) >= len(str2):
needed_changes = number_of_needed_changes(str1, str2)
else:
needed_changes = number_of_needed_changes(str2, str1)
return needed_changes <= 1
data = [
('pale', 'ple', True),
('pales', 'pale', True),
('pale', 'bale', True),
('paleabc', 'pleabc', True),
('pale', 'ble', False),
('a', 'b', True),
('', 'd', True),
('d', 'de', True),
('pale', 'pale', True),
('pale', 'ple', True),
('ple', 'pale', True),
('pale', 'bale', True),
('pale', 'bake', False),
('pale', 'pse', False),
('ples', 'pales', True),
('pale', 'pas', False),
('pas', 'pale', False),
('pale', 'pkle', True),
('pkle', 'pable', False),
('pal', 'palks', False),
('palks', 'pal', False),
('bla', 'bleble', False)
]
for [test_s1, test_s2, expected] in data:
actual = one_away(test_s1, test_s2)
print(actual == expected)
|
"""
One Away: There are three types of edits that can be performed on strings:
insert a character, remove a character, or replace a character.
Given two strings, write a function to check if they are one edit (or zero edits) away.
Example:
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bake -> false
bla, bleble -> false
"""
def is_two_chars_away(str1, str2):
return len(str1) - len(str2) >= 2 or len(str2) - len(str1) >= 2
def number_of_needed_changes(bigger_str, smaller_str):
str_counter = {}
for char in bigger_str:
if char in str_counter:
str_counter[char] += 1
else:
str_counter[char] = 1
for char in smaller_str:
if char in str_counter:
str_counter[char] -= 1
needed_changes = 0
for (char, counter) in str_counter.items():
needed_changes += counter
return needed_changes
def one_away(str1, str2):
if is_two_chars_away(str1, str2):
return False
needed_changes = 0
if len(str1) >= len(str2):
needed_changes = number_of_needed_changes(str1, str2)
else:
needed_changes = number_of_needed_changes(str2, str1)
return needed_changes <= 1
data = [('pale', 'ple', True), ('pales', 'pale', True), ('pale', 'bale', True), ('paleabc', 'pleabc', True), ('pale', 'ble', False), ('a', 'b', True), ('', 'd', True), ('d', 'de', True), ('pale', 'pale', True), ('pale', 'ple', True), ('ple', 'pale', True), ('pale', 'bale', True), ('pale', 'bake', False), ('pale', 'pse', False), ('ples', 'pales', True), ('pale', 'pas', False), ('pas', 'pale', False), ('pale', 'pkle', True), ('pkle', 'pable', False), ('pal', 'palks', False), ('palks', 'pal', False), ('bla', 'bleble', False)]
for [test_s1, test_s2, expected] in data:
actual = one_away(test_s1, test_s2)
print(actual == expected)
|
max_n = 10**17
fibs = [
(1, 1),
(2, 1),
]
while fibs[-1][0] < max_n:
fibs.append(
(fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1])
)
print(fibs)
counts = [
1,
1
]
for i in range(2, len(fibs)):
fib = fibs[i]
counts.append(fib[1] + sum(counts[j] for j in range(i - 1)))
print(counts)
def count(n):
smallest_over_index = 0
smallest_over = fibs[smallest_over_index][0]
while smallest_over < n:
smallest_over_index += 1
smallest_over = fibs[smallest_over_index][0]
if smallest_over == n + 1:
return sum(counts[i] for i in range(smallest_over_index))
if smallest_over == n:
return 1 + count(n - 1)
smallest_under = fibs[smallest_over_index - 1][0]
return sum(counts[i] for i in range(smallest_over_index - 1)) + count(n - smallest_under) + n - smallest_under
print(count(10**17) - 1)
|
max_n = 10 ** 17
fibs = [(1, 1), (2, 1)]
while fibs[-1][0] < max_n:
fibs.append((fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1]))
print(fibs)
counts = [1, 1]
for i in range(2, len(fibs)):
fib = fibs[i]
counts.append(fib[1] + sum((counts[j] for j in range(i - 1))))
print(counts)
def count(n):
smallest_over_index = 0
smallest_over = fibs[smallest_over_index][0]
while smallest_over < n:
smallest_over_index += 1
smallest_over = fibs[smallest_over_index][0]
if smallest_over == n + 1:
return sum((counts[i] for i in range(smallest_over_index)))
if smallest_over == n:
return 1 + count(n - 1)
smallest_under = fibs[smallest_over_index - 1][0]
return sum((counts[i] for i in range(smallest_over_index - 1))) + count(n - smallest_under) + n - smallest_under
print(count(10 ** 17) - 1)
|
class StateMachine:
def __init__(self, initialState):
self.currentState = initialState
self.currentState.run()
# Template method:
def runAll(self, inputs):
self.currentState = self.currentState.next_state(inputs)
self.currentState.run()
|
class Statemachine:
def __init__(self, initialState):
self.currentState = initialState
self.currentState.run()
def run_all(self, inputs):
self.currentState = self.currentState.next_state(inputs)
self.currentState.run()
|
def palindrome(word : str) -> int:
"""
Given a string, calculates the amount of palindromes that exist within that string
Parameters
----------
word : str
String that may contain palindrome sub-strings
Returns
-------
int
number of palindromes in string
"""
word = word.lower()
count = []
for i in range(len(word)):
for p in range(i+1, len(word)+1):
count.append(word[i : p])
t = [i for i in set(count) if len(i) > 1 and i == i[::-1]]
return len(t)
if __name__ == '__main__':
print(palindrome('ada')) # 1
print(palindrome('eadae')) # 2
print(palindrome('ade')) # 0
|
def palindrome(word: str) -> int:
"""
Given a string, calculates the amount of palindromes that exist within that string
Parameters
----------
word : str
String that may contain palindrome sub-strings
Returns
-------
int
number of palindromes in string
"""
word = word.lower()
count = []
for i in range(len(word)):
for p in range(i + 1, len(word) + 1):
count.append(word[i:p])
t = [i for i in set(count) if len(i) > 1 and i == i[::-1]]
return len(t)
if __name__ == '__main__':
print(palindrome('ada'))
print(palindrome('eadae'))
print(palindrome('ade'))
|
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2]
def pancake_sort(array):
target_index = len(array)-1
while target_index > 0:
max_value = array[target_index]
max_index = target_index
for number in range(0, target_index):
if array[number] > max_value:
max_value = array[number]
max_index = number
array = flip(array, max_index)
array = flip(array, target_index)
target_index -= 1
return array
def flip(array, end_index):
unreversed_part = array[end_index+1:]
reversed_part = array[end_index::-1]
return reversed_part + unreversed_part
print(pancake_sort(numbers))
|
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2]
def pancake_sort(array):
target_index = len(array) - 1
while target_index > 0:
max_value = array[target_index]
max_index = target_index
for number in range(0, target_index):
if array[number] > max_value:
max_value = array[number]
max_index = number
array = flip(array, max_index)
array = flip(array, target_index)
target_index -= 1
return array
def flip(array, end_index):
unreversed_part = array[end_index + 1:]
reversed_part = array[end_index::-1]
return reversed_part + unreversed_part
print(pancake_sort(numbers))
|
# Following are the basic concepts to get started with Python 3.7
"""This is a sample Python
multiline docstring"""
# Display
print("Let's get started with Python")
print("Let's understand", end=" ")
print("The Basic Concepts first")
print("**********************************************************")
# Variables
# In Python, there is no need for variable type declaration
# Every Python variable is an object and a variable is created the moment we first assign a value to it.
# A variable name must start with a letter or the underscore character.
# It cannot start with a number and can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
# Python variables are case-sensitive
myAge = 30
myName = "Sam"
myHeight = 1.72
# To get the type of the declared variables
print(type(myAge))
print(type(myName))
print(type(myHeight))
print("**********************************************************")
# Type Casting (to specify a type to a variable using constructor functions)
# Adding different data types will throw error
# constructs Strings from other data types
myAgeInString = str(myAge)
myHeightInString = str(myHeight)
print("My name is: " + myName + ", my age is: " + myAgeInString + " and my height is: " + myHeightInString)
# constructs integers from other data types
print(int("125"))
print(int(3.2))
# constructs float from other data types
print(float("4.22"))
print(float(22242))
print("**********************************************************")
# Numeric Types
myIntValue = 24
myFloatValue = 4.5433
myScientificFloatValue = 35e3
myComplexValue = 4 + 3j
print(myIntValue)
print(myFloatValue)
print(myScientificFloatValue)
print(myComplexValue)
print("**********************************************************")
|
"""This is a sample Python
multiline docstring"""
print("Let's get started with Python")
print("Let's understand", end=' ')
print('The Basic Concepts first')
print('**********************************************************')
my_age = 30
my_name = 'Sam'
my_height = 1.72
print(type(myAge))
print(type(myName))
print(type(myHeight))
print('**********************************************************')
my_age_in_string = str(myAge)
my_height_in_string = str(myHeight)
print('My name is: ' + myName + ', my age is: ' + myAgeInString + ' and my height is: ' + myHeightInString)
print(int('125'))
print(int(3.2))
print(float('4.22'))
print(float(22242))
print('**********************************************************')
my_int_value = 24
my_float_value = 4.5433
my_scientific_float_value = 35000.0
my_complex_value = 4 + 3j
print(myIntValue)
print(myFloatValue)
print(myScientificFloatValue)
print(myComplexValue)
print('**********************************************************')
|
print("Enter the name of the file along with it's extension:-")
a=str(input())
if('.py' in a):
print("The extension of the file is : python")
else:
print("The extension of the file is not python")
|
print("Enter the name of the file along with it's extension:-")
a = str(input())
if '.py' in a:
print('The extension of the file is : python')
else:
print('The extension of the file is not python')
|
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2018
# All rights reserved
__author__ = 'Wu Dong <wudong@eastwu.cn>'
__time__ = '2018/9/6 11:07'
|
__author__ = 'Wu Dong <wudong@eastwu.cn>'
__time__ = '2018/9/6 11:07'
|
"""
`EqualizeStrings <http://community.topcoder.com/stat?c=problem_statement&pm=10933>`__
"""
def solution (s, t):
out = ""
for i in range(len(s)):
x = s[i]
y = t[i]
diff = abs(ord(x) - ord(y))
if diff < 26 / 2:
# values are close by, use minimum
out += min([x, y])
else:
# values are far, wrapping always uses 'a'
out += 'a'
return out
|
"""
`EqualizeStrings <http://community.topcoder.com/stat?c=problem_statement&pm=10933>`__
"""
def solution(s, t):
out = ''
for i in range(len(s)):
x = s[i]
y = t[i]
diff = abs(ord(x) - ord(y))
if diff < 26 / 2:
out += min([x, y])
else:
out += 'a'
return out
|
# ABC167B - Easy Linear Programming
def main():
# input
A, B, C, K = map(int, input().split())
# compute
kotae = A+(K-A)*0-(K-A-B)
# output
print(kotae)
if __name__ == '__main__':
main()
|
def main():
(a, b, c, k) = map(int, input().split())
kotae = A + (K - A) * 0 - (K - A - B)
print(kotae)
if __name__ == '__main__':
main()
|
def lin():
print('-'*20)
lin()
def msg(m):
lin()
print(m)
lin()
msg('SISTEMA')
def s(a,b):
print(a+b)
s(2,3)
def cont(*num):
for v in num:
print(v,end=' ')
print('\nfim')
cont(2,3,7)
def dobra(lst):
pos = 0
while pos < len(lst):
lst[pos] *= 2
pos += 1
valores = [6,4,5,8,2,7]
dobra(valores)
print(valores)
def soma(*val):
s = 0
for num in val:
s += num
print(s)
soma(3,6,4)
|
def lin():
print('-' * 20)
lin()
def msg(m):
lin()
print(m)
lin()
msg('SISTEMA')
def s(a, b):
print(a + b)
s(2, 3)
def cont(*num):
for v in num:
print(v, end=' ')
print('\nfim')
cont(2, 3, 7)
def dobra(lst):
pos = 0
while pos < len(lst):
lst[pos] *= 2
pos += 1
valores = [6, 4, 5, 8, 2, 7]
dobra(valores)
print(valores)
def soma(*val):
s = 0
for num in val:
s += num
print(s)
soma(3, 6, 4)
|
inst = set()
with open('tools/write_bytecode.py') as file:
for line in file:
if line.strip().startswith('#'):
continue
if '$' in line:
instruction = line.split('$')[1].strip()
print(instruction)
inst.add(instruction.split()[0].strip().replace('32', '').replace('64', ''))
# print(len(inst))
# print((inst))
|
inst = set()
with open('tools/write_bytecode.py') as file:
for line in file:
if line.strip().startswith('#'):
continue
if '$' in line:
instruction = line.split('$')[1].strip()
print(instruction)
inst.add(instruction.split()[0].strip().replace('32', '').replace('64', ''))
|
input = """
q(X) :- p(f(X)).
p(f(X)) :- r(X), q(X).
q(a).
r(a).
"""
output = """
q(X) :- p(f(X)).
p(f(X)) :- r(X), q(X).
q(a).
r(a).
"""
|
input = '\nq(X) :- p(f(X)).\np(f(X)) :- r(X), q(X).\n\nq(a).\nr(a).\n'
output = '\nq(X) :- p(f(X)).\np(f(X)) :- r(X), q(X).\n\nq(a).\nr(a).\n'
|
################################################################
# compareTools.py
#
# Defines how nodes and edges are compared.
# Usable by other packages such as smallGraph
#
# Author: H. Mouchere, Oct. 2013
# Copyright (c) 2013-2014 Richard Zanibbi and Harold Mouchere
################################################################
def generateListErr(ab,ba):
listErr = []
if len(ab) == 0:
ab = ['_']
if len(ba) == 0:
ba = ['_']
for c1 in ab:
for c2 in ba:
listErr.append((c1,c2))
return listErr
def defaultMetric(labelList1, labelList2):
#new way but with 1 label per node
diff = set(labelList1) ^ (set(labelList2)) # symetric diff
if len(diff) == 0:
return (0,[])
else:
ab = diff&set(labelList1)
ba = diff&set(labelList2)
cost = max(len(ab),len(ba) )
return (cost,generateListErr(ab,ba))
synonym = {'X':'x','\\times':'x', 'P':'p', 'O':'o','C':'c', '\\prime':'COMMA'}
def synonymMetric(labelList1, labelList2):
def replace(x):
if x in synonym.keys():
return synonym[x]
else:
return x
a = map(replace, labelList1)
b = map(replace, labelList2)
diff = set(a) ^ (set(b)) # symetric diff
if len(diff) == 0:
return (0,[])
else:
ab = diff&set(a)
ba = diff&set(b)
cost = max(len(ab),len(ba) )
return (cost,generateListErr(ab,ba))
ignoredLabelSet = set([])
selectedLabelSet = set([])
def filteredMetric(labelList1, labelList2):
labelS1 = set(labelList1) - ignoredLabelSet # removing the ignored labels
labelS2 = set(labelList2) - ignoredLabelSet # removing the ignored labels
if len(selectedLabelSet) > 0:
labelS1 &= selectedLabelSet # keep only the selected labels
labelS2 &= selectedLabelSet # keep only the selected labels
return defaultMetric(labelS1,labelS2)
# no error if at least one symbol is OK
def intersectMetric(labelList1, labelList2):
#new way but with 1 label per node
inter = set(labelList1) & (set(labelList2)) # symetric diff
if len(inter) > 0:
return (0,[])
else:
ab = set(labelList1)-inter
ba = set(labelList2)-inter
return (1,generateListErr(ab,ba))
cmpNodes = defaultMetric
cmpEdges = defaultMetric
|
def generate_list_err(ab, ba):
list_err = []
if len(ab) == 0:
ab = ['_']
if len(ba) == 0:
ba = ['_']
for c1 in ab:
for c2 in ba:
listErr.append((c1, c2))
return listErr
def default_metric(labelList1, labelList2):
diff = set(labelList1) ^ set(labelList2)
if len(diff) == 0:
return (0, [])
else:
ab = diff & set(labelList1)
ba = diff & set(labelList2)
cost = max(len(ab), len(ba))
return (cost, generate_list_err(ab, ba))
synonym = {'X': 'x', '\\times': 'x', 'P': 'p', 'O': 'o', 'C': 'c', '\\prime': 'COMMA'}
def synonym_metric(labelList1, labelList2):
def replace(x):
if x in synonym.keys():
return synonym[x]
else:
return x
a = map(replace, labelList1)
b = map(replace, labelList2)
diff = set(a) ^ set(b)
if len(diff) == 0:
return (0, [])
else:
ab = diff & set(a)
ba = diff & set(b)
cost = max(len(ab), len(ba))
return (cost, generate_list_err(ab, ba))
ignored_label_set = set([])
selected_label_set = set([])
def filtered_metric(labelList1, labelList2):
label_s1 = set(labelList1) - ignoredLabelSet
label_s2 = set(labelList2) - ignoredLabelSet
if len(selectedLabelSet) > 0:
label_s1 &= selectedLabelSet
label_s2 &= selectedLabelSet
return default_metric(labelS1, labelS2)
def intersect_metric(labelList1, labelList2):
inter = set(labelList1) & set(labelList2)
if len(inter) > 0:
return (0, [])
else:
ab = set(labelList1) - inter
ba = set(labelList2) - inter
return (1, generate_list_err(ab, ba))
cmp_nodes = defaultMetric
cmp_edges = defaultMetric
|
"""Define the abstract class for similarity search service controllers"""
class SearchService:
"""Search Service handles all controllers in the search service"""
def __init__(self):
pass
def load_index(self):
pass
def load_labels(self):
pass
def similar_search_vectors(self):
pass
def refresh_index(self):
pass
def health_check(self):
pass
|
"""Define the abstract class for similarity search service controllers"""
class Searchservice:
"""Search Service handles all controllers in the search service"""
def __init__(self):
pass
def load_index(self):
pass
def load_labels(self):
pass
def similar_search_vectors(self):
pass
def refresh_index(self):
pass
def health_check(self):
pass
|
# -*- coding: utf-8 -*-
def main():
n = int(input())
s = list()
t = list()
for i in range(n):
si, ti = map(str, input().split())
s.append(si)
t.append(int(ti))
x = input()
index = s.index(x)
print(sum(t[index + 1:]))
if __name__ == '__main__':
main()
|
def main():
n = int(input())
s = list()
t = list()
for i in range(n):
(si, ti) = map(str, input().split())
s.append(si)
t.append(int(ti))
x = input()
index = s.index(x)
print(sum(t[index + 1:]))
if __name__ == '__main__':
main()
|
### Alternating Characters - Solution
def alternatingCharacters():
q = int(input())
while q:
s = input()
del_count = 0
for i in range(len(s)-1):
if s[i] == s[i+1]:
del_count += 1
print(del_count)
q -= 1
alternatingCharacters()
|
def alternating_characters():
q = int(input())
while q:
s = input()
del_count = 0
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
del_count += 1
print(del_count)
q -= 1
alternating_characters()
|
class FileWarning(Exception):
def __init__(self, file, message, *args, **kwargs):
file.warn(message, *args, **kwargs)
super().__init__(message % args)
class FileError(Exception):
def __init__(self, file, message, *args, **kwargs):
file.error(message, *args, **kwargs)
super().__init__(message % args)
class FileCritical(Exception):
def __init__(self, file, message, *args, **kwargs):
file.critical(message, *args, **kwargs)
super().__init__(message % args)
|
class Filewarning(Exception):
def __init__(self, file, message, *args, **kwargs):
file.warn(message, *args, **kwargs)
super().__init__(message % args)
class Fileerror(Exception):
def __init__(self, file, message, *args, **kwargs):
file.error(message, *args, **kwargs)
super().__init__(message % args)
class Filecritical(Exception):
def __init__(self, file, message, *args, **kwargs):
file.critical(message, *args, **kwargs)
super().__init__(message % args)
|
class RenderedView(object):
def __init__(self, view_file: str, data):
self.view_file = view_file
self.data = data
|
class Renderedview(object):
def __init__(self, view_file: str, data):
self.view_file = view_file
self.data = data
|
# PART 1
def game_of_cups(starting_sequence,num_of_moves,min_cup=None,max_cup=None):
# create a "linked list" dict
cups = {
starting_sequence[i] : starting_sequence[i+1]
for i in range(len(starting_sequence)-1)
}
cups[starting_sequence[-1]] = starting_sequence[0]
#
current_cup = starting_sequence[0]
max_cup = max_cup or max(starting_sequence)
min_cup = min_cup or min(starting_sequence)
for _ in range(num_of_moves):
# cups to move are 3 ones after the current
cups_to_move = (
first := cups[current_cup],
second := cups[first],
third := cups[second]
)
# selects next current cup
next_current_cup = cups[third]
# destination is 1 less than current
# if it's in the next 3 cups, it's 1 less than that, etc.
# if it gets less than min, it loops back to max
destination = current_cup - 1
while destination in cups_to_move or destination<min_cup:
destination -= 1
if destination<min_cup:
destination = max_cup
# moves 3 cups after destination
# by relinking destination to 1st cup
# & third cup to cup after destination
cup_after_destination = cups[destination]
cups[destination] = first
cups[third] = cup_after_destination
# relinks current cup to next current cup
cups[current_cup] = next_current_cup
current_cup = next_current_cup
return cups
def collect_result(cups_dict):
output_string = ""
next_cup = cups_dict[1]
while next_cup!=1:
output_string += str(next_cup)
next_cup = cups_dict[next_cup]
return output_string
# PART 2
def hyper_game_of_cups(starting_sequence):
min_cup = min(starting_sequence)
max_cup = max(starting_sequence)
filled_starting_sequence = starting_sequence + list(range(max_cup+1,1_000_000+1))
return game_of_cups(filled_starting_sequence,10_000_000,min_cup,1_000_000)
def hyper_collect_result(cups_dict):
first = cups_dict[1]
second = cups_dict[first]
return first * second
|
def game_of_cups(starting_sequence, num_of_moves, min_cup=None, max_cup=None):
cups = {starting_sequence[i]: starting_sequence[i + 1] for i in range(len(starting_sequence) - 1)}
cups[starting_sequence[-1]] = starting_sequence[0]
current_cup = starting_sequence[0]
max_cup = max_cup or max(starting_sequence)
min_cup = min_cup or min(starting_sequence)
for _ in range(num_of_moves):
cups_to_move = ((first := cups[current_cup]), (second := cups[first]), (third := cups[second]))
next_current_cup = cups[third]
destination = current_cup - 1
while destination in cups_to_move or destination < min_cup:
destination -= 1
if destination < min_cup:
destination = max_cup
cup_after_destination = cups[destination]
cups[destination] = first
cups[third] = cup_after_destination
cups[current_cup] = next_current_cup
current_cup = next_current_cup
return cups
def collect_result(cups_dict):
output_string = ''
next_cup = cups_dict[1]
while next_cup != 1:
output_string += str(next_cup)
next_cup = cups_dict[next_cup]
return output_string
def hyper_game_of_cups(starting_sequence):
min_cup = min(starting_sequence)
max_cup = max(starting_sequence)
filled_starting_sequence = starting_sequence + list(range(max_cup + 1, 1000000 + 1))
return game_of_cups(filled_starting_sequence, 10000000, min_cup, 1000000)
def hyper_collect_result(cups_dict):
first = cups_dict[1]
second = cups_dict[first]
return first * second
|
txt = 'asdf;lkajsdf,as;lfkja'
for i in txt:
txt = txt[1:]
if i == ",":
break
print(txt)
|
txt = 'asdf;lkajsdf,as;lfkja'
for i in txt:
txt = txt[1:]
if i == ',':
break
print(txt)
|
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data # replace
else:
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslot] != key:
naxtslot = self.rehash(hashvalue, len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data #replace
def hashfunction(self, key, size):
return key%size
def rehash(self, oldhash, size):
return (oldhash+1)%size
def get(self, key):
startslot = self.hashfunction(key, len(self.slots))
found = False
stop = False
data = None
while self.slots[startslot] != None and not found and not stop:
if self.slots[startslot] == key:
found = True
data = self.data[startslot]
else:
position = self.rehash(startslot, len(self.size))
if self.slots[startslot] == self.slots[position]:
stop = True
return data
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
return self.put(key, data)
if __name__ == "__main__":
H = HashTable()
H[12] = 'Dasha'
print(H[12], 'H')
print(H)
|
class Hashtable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
elif self.slots[hashvalue] == key:
self.data[hashvalue] = data
else:
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslot] != key:
naxtslot = self.rehash(hashvalue, len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data
def hashfunction(self, key, size):
return key % size
def rehash(self, oldhash, size):
return (oldhash + 1) % size
def get(self, key):
startslot = self.hashfunction(key, len(self.slots))
found = False
stop = False
data = None
while self.slots[startslot] != None and (not found) and (not stop):
if self.slots[startslot] == key:
found = True
data = self.data[startslot]
else:
position = self.rehash(startslot, len(self.size))
if self.slots[startslot] == self.slots[position]:
stop = True
return data
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
return self.put(key, data)
if __name__ == '__main__':
h = hash_table()
H[12] = 'Dasha'
print(H[12], 'H')
print(H)
|
description = 'Email and SMS notifiers'
group = 'lowlevel'
devices = dict(
email = device('nicos.devices.notifiers.Mailer',
mailserver = 'mailhost.frm2.tum.de',
sender = 'kws1@frm2.tum.de',
copies = [
('g.brandl@fz-juelich.de', 'all'),
('a.feoktystov@fz-juelich.de', 'all'),
('h.frielinghaus@fz-juelich.de', 'all'),
('z.mahhouti@fz-juelich.de', 'all'),
],
subject = '[KWS-1]',
),
smser = device('nicos.devices.notifiers.SMSer',
server = 'triton.admin.frm2',
receivers = [],
),
)
|
description = 'Email and SMS notifiers'
group = 'lowlevel'
devices = dict(email=device('nicos.devices.notifiers.Mailer', mailserver='mailhost.frm2.tum.de', sender='kws1@frm2.tum.de', copies=[('g.brandl@fz-juelich.de', 'all'), ('a.feoktystov@fz-juelich.de', 'all'), ('h.frielinghaus@fz-juelich.de', 'all'), ('z.mahhouti@fz-juelich.de', 'all')], subject='[KWS-1]'), smser=device('nicos.devices.notifiers.SMSer', server='triton.admin.frm2', receivers=[]))
|
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height > 120:
print("you can ride the rollercoaster!")
age = int(input("What is your age? "))
if age <= 18:
print("$7")
else:
print("$12")
else:
print("no")
|
print('Welcome to the rollercoaster!')
height = int(input('What is your height in cm? '))
if height > 120:
print('you can ride the rollercoaster!')
age = int(input('What is your age? '))
if age <= 18:
print('$7')
else:
print('$12')
else:
print('no')
|
# "Config.py"
# - config file for ConfigGUI.py
# This is Python, therefore this is a comment
# NOTE: variable names cannot start with '__'
ECGColumn = True
HRColumn = False
PeakColumn = True
RRColumn = True
SeparateECGFile = True
TCP_Host = "localhost"
TCP_Port = 1000
TCPtimeout = 3
TimeColumn = True
UDPConnectTimeout = 1
UDPReceiveTimeout = 5
UDP_ClientIP = "localhost"
UDP_ClientPort = 1001
UDP_ServerIP = "localhost"
UDP_ServerPort = 1003
UDPtimeout = 1
askConfirm = False
askSend = False
clientAskConfirm = False
debugPrinter = True
debugRepetitions = False
debugRun = False
filePath = "F:/Project/mwilson/Code/ECG_soft/RTHRV_Faros/LSL_tests/WILMA_Rest3_Game3_Rest3_run64_2016_05_26__14_54_45_#ECG.txt"
hexDebugPrinter = False
ignoreTCP = True
liveWindowTime = 3
noNetwork = True
noPlot = False
plot_rate = 10
procWindowTime = 3
processing_rate = 5
rate = 64
recDebugPrinter = False
runName = "WILMA"
simpleSTOP = False
valDebugPrinter = True
writeOutput = True
write_header = True
write_type = "txt"
|
ecg_column = True
hr_column = False
peak_column = True
rr_column = True
separate_ecg_file = True
tcp__host = 'localhost'
tcp__port = 1000
tc_ptimeout = 3
time_column = True
udp_connect_timeout = 1
udp_receive_timeout = 5
udp__client_ip = 'localhost'
udp__client_port = 1001
udp__server_ip = 'localhost'
udp__server_port = 1003
ud_ptimeout = 1
ask_confirm = False
ask_send = False
client_ask_confirm = False
debug_printer = True
debug_repetitions = False
debug_run = False
file_path = 'F:/Project/mwilson/Code/ECG_soft/RTHRV_Faros/LSL_tests/WILMA_Rest3_Game3_Rest3_run64_2016_05_26__14_54_45_#ECG.txt'
hex_debug_printer = False
ignore_tcp = True
live_window_time = 3
no_network = True
no_plot = False
plot_rate = 10
proc_window_time = 3
processing_rate = 5
rate = 64
rec_debug_printer = False
run_name = 'WILMA'
simple_stop = False
val_debug_printer = True
write_output = True
write_header = True
write_type = 'txt'
|
class Dictionary(object):
def __init__(self):
self.my_dict = {}
def look(self, key):
return self.my_dict.get(key, "Can't find entry for {}".format(key))
def newentry(self, key, value):
""" new_entry == PEP8 (forced by Codewars) """
self.my_dict[key] = value
|
class Dictionary(object):
def __init__(self):
self.my_dict = {}
def look(self, key):
return self.my_dict.get(key, "Can't find entry for {}".format(key))
def newentry(self, key, value):
""" new_entry == PEP8 (forced by Codewars) """
self.my_dict[key] = value
|
hidden_dim = 128
dilation = [1,2,4,8,16,32,64,128,256,512]
sample_rate = 16000
timestep = 6080
is_training = True
use_mulaw = True
batch_size = 1
num_epochs = 10000
save_dir = './logdir'
test_data = 'test.wav'
|
hidden_dim = 128
dilation = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
sample_rate = 16000
timestep = 6080
is_training = True
use_mulaw = True
batch_size = 1
num_epochs = 10000
save_dir = './logdir'
test_data = 'test.wav'
|
# This file provides an object for version numbers.
class Version:
def __init__(self, major: int, minor: int=0, patch: int=0, tag: str=""):
self.major = major
self.minor = minor
self.patch = patch
self.tag = tag
def __repr__(self):
return "Version(" + str(self.major) + ", " + str(self.minor) + ", " + str(self.patch) + ", \"" + self.tag + "\")"
def __str__(self):
return str(self.major) + "." + str(self.minor) + (("." + str(self.patch)) if ((self.patch != 0) or self.tag != "") else "") + (self.tag if (self.tag != "") else "")
def __len__(self):
if self.tag == "":
if self.patch == 0:
if self.minor == 0: return 1
else: return 2
else: return 3
else: return 4
def __int__(self):
return self.major
#def __float__(self):
# return self.major + (self.minor / (10 ** len(self.minor)))
def __eq__(self, o):
if type(o) == str:
if len(o.split(".")) == 3:
try: return ((int(o.split(".")[0]) == self.major) and (int(o.split(".")[1]) == self.minor) and (int(o.split(".")[2]) == self.patch))
except ValueError: return NotImplemented
except: raise
elif len(o.split(".")) == 2:
try: return ((int(o.split(".")[0]) == self.major) and (int(o.split(".")[1]) == self.minor))
except ValueError: return NotImplemented
except: raise
elif len(o.split(".")) == 1:
try: return (int(o.split(".")[0]) == self.major)
except ValueError: return NotImplemented
except: raise
else: return NotImplemented
elif type(o) == int:
if (self.minor == 0) and (self.patch == 0): return (self.major == o)
else: return NotImplemented
elif type(o) == float:
if (self.patch == 0): return (float(self) == o)
else: return NotImplemented
elif type(o) == Version: return (self.major == o.major) and (self.minor == o.minor) and (self.patch == o.patch)
else: return NotImplemented
def __lt__(self, o):
if type(o) == str:
if len(o.split(".")) == 1:
try: return (int(o.split(".")[0]) < self.major)
except ValueError: return NotImplemented
except: raise
else: return NotImplemented
elif type(o) == int:
if (self.minor == 0) and (self.patch == 0): return (self.major < o)
else: return NotImplemented
elif type(o) == Version:
if (self.major < o.major): return True
elif (self.major == o.major):
if (self.minor < o.minor): return True
elif (self.minor == o.minor):
if (self.patch < o.patch): return True
else: return False
else: return False
else: return False
else: return NotImplemented
def __le__(self, o):
hold = (self < o)
hold2 = (self == o)
if (hold == NotImplemented) or (hold2 == NotImplemented): return NotImplemented
else: return (hold or hold2)
def __gt__(self, o):
hold = (self <= o)
if hold == NotImplemented: return NotImplemented
else: return not hold
def __ge__(self, o):
hold = (self < o)
if hold == NotImplemented: return NotImplemented
else: return not hold
def __iter__(self):
if self.tag == "":
for i in (self.major, self.minor, self.patch):
yield i
else:
for i in (self.major, self.minor, self.patch, self.tag):
yield i
def asdict(self):
return {"major": self.major, "minor": self.minor, "patch": self.patch, "tag": self.tag}
__version__ = Version(1, 1, 1)
|
class Version:
def __init__(self, major: int, minor: int=0, patch: int=0, tag: str=''):
self.major = major
self.minor = minor
self.patch = patch
self.tag = tag
def __repr__(self):
return 'Version(' + str(self.major) + ', ' + str(self.minor) + ', ' + str(self.patch) + ', "' + self.tag + '")'
def __str__(self):
return str(self.major) + '.' + str(self.minor) + ('.' + str(self.patch) if self.patch != 0 or self.tag != '' else '') + (self.tag if self.tag != '' else '')
def __len__(self):
if self.tag == '':
if self.patch == 0:
if self.minor == 0:
return 1
else:
return 2
else:
return 3
else:
return 4
def __int__(self):
return self.major
def __eq__(self, o):
if type(o) == str:
if len(o.split('.')) == 3:
try:
return int(o.split('.')[0]) == self.major and int(o.split('.')[1]) == self.minor and (int(o.split('.')[2]) == self.patch)
except ValueError:
return NotImplemented
except:
raise
elif len(o.split('.')) == 2:
try:
return int(o.split('.')[0]) == self.major and int(o.split('.')[1]) == self.minor
except ValueError:
return NotImplemented
except:
raise
elif len(o.split('.')) == 1:
try:
return int(o.split('.')[0]) == self.major
except ValueError:
return NotImplemented
except:
raise
else:
return NotImplemented
elif type(o) == int:
if self.minor == 0 and self.patch == 0:
return self.major == o
else:
return NotImplemented
elif type(o) == float:
if self.patch == 0:
return float(self) == o
else:
return NotImplemented
elif type(o) == Version:
return self.major == o.major and self.minor == o.minor and (self.patch == o.patch)
else:
return NotImplemented
def __lt__(self, o):
if type(o) == str:
if len(o.split('.')) == 1:
try:
return int(o.split('.')[0]) < self.major
except ValueError:
return NotImplemented
except:
raise
else:
return NotImplemented
elif type(o) == int:
if self.minor == 0 and self.patch == 0:
return self.major < o
else:
return NotImplemented
elif type(o) == Version:
if self.major < o.major:
return True
elif self.major == o.major:
if self.minor < o.minor:
return True
elif self.minor == o.minor:
if self.patch < o.patch:
return True
else:
return False
else:
return False
else:
return False
else:
return NotImplemented
def __le__(self, o):
hold = self < o
hold2 = self == o
if hold == NotImplemented or hold2 == NotImplemented:
return NotImplemented
else:
return hold or hold2
def __gt__(self, o):
hold = self <= o
if hold == NotImplemented:
return NotImplemented
else:
return not hold
def __ge__(self, o):
hold = self < o
if hold == NotImplemented:
return NotImplemented
else:
return not hold
def __iter__(self):
if self.tag == '':
for i in (self.major, self.minor, self.patch):
yield i
else:
for i in (self.major, self.minor, self.patch, self.tag):
yield i
def asdict(self):
return {'major': self.major, 'minor': self.minor, 'patch': self.patch, 'tag': self.tag}
__version__ = version(1, 1, 1)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
self.result = []
self.wft([root])
return self.result
def wft(self, nodes):
newNodes = []
values = []
for n in nodes:
if n is not None:
values.append(n.val)
newNodes += [n.left, n.right]
if len(values) != 0:
self.result = [values] + self.result
self.wft(newNodes)
|
class Solution:
def level_order_bottom(self, root: TreeNode) -> List[List[int]]:
self.result = []
self.wft([root])
return self.result
def wft(self, nodes):
new_nodes = []
values = []
for n in nodes:
if n is not None:
values.append(n.val)
new_nodes += [n.left, n.right]
if len(values) != 0:
self.result = [values] + self.result
self.wft(newNodes)
|
class airQuality:
def __init__(self, bus):
self.iaq = 0
self.bus = bus
self.address = 0x5A
self.datablock = 9
self.data = 0
def read(self):
data = self.bus.read_i2c_block_data(self.address, 0x00, self.datablock)
#WIP
# Convert the data
#if( eco2 !=0 ) *eco2 = (buf[0]<<8) + (buf[1]<<0);
#if( stat !=0 ) *stat = ( num==IAQCORE_SIZE ? 0 : IAQCORE_STAT_I2CERR ) + (buf[2]<<0); // Add I2C status to chip status
#if( resist!=0 ) *resist= ((uint32_t)buf[3]<<24) + ((uint32_t)buf[4]<<16) + ((uint32_t)buf[5]<<8) + ((uint32_t)buf[6]<<0);
#if( etvoc !=0 ) *etvoc = (buf[7]<<8) + (buf[8]<<0);
# Output data to screen
#Print values, interpret as datasheet
#Based on maarten's ESP project
#https://github.com/maarten-pennings/iAQcore/blob/master/src/iAQcore.cpp
|
class Airquality:
def __init__(self, bus):
self.iaq = 0
self.bus = bus
self.address = 90
self.datablock = 9
self.data = 0
def read(self):
data = self.bus.read_i2c_block_data(self.address, 0, self.datablock)
|
#You are given a list of n-1 integers and these integers are in the range of 1 to n.
#There are no duplicates in the list.
#One of the integers is missing in the list. Write an efficient code to find the missing integer
ar=[ 1, 2, 4, 5, 6 ]
def missing_(a):
print("l",l)
for i in range(1,l+2):
if(i not in a):
return(i)
print(missing_(ar))
|
ar = [1, 2, 4, 5, 6]
def missing_(a):
print('l', l)
for i in range(1, l + 2):
if i not in a:
return i
print(missing_(ar))
|
class Utils():
""" This is just methods stored as methods of a class.
It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy.
(It is nice, as in this case, to separate constants from methods.)
"""
def __init__(self):
self.species = {'canines' : ['Doggy', 'Hyena'], 'felines' : ['Cheetah', 'Panther'], 'bugs' : ['Nullpointer']}
def inputs(self):
return None
def output(self):
return None
def build(self):
pass
def list_animals(self, kind):
return self.species[kind]
|
class Utils:
""" This is just methods stored as methods of a class.
It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy.
(It is nice, as in this case, to separate constants from methods.)
"""
def __init__(self):
self.species = {'canines': ['Doggy', 'Hyena'], 'felines': ['Cheetah', 'Panther'], 'bugs': ['Nullpointer']}
def inputs(self):
return None
def output(self):
return None
def build(self):
pass
def list_animals(self, kind):
return self.species[kind]
|
print('Enter a text and when finished press Enter twice: ')
text = ''
while True:
line = input()
if line:
text += line + '\n '
else:
break
def wc(text):
n_words = len(text.split(' ')) - 1
n_lines = len(text.split('\n')) - 1
n_characters = len(text) - 2*n_lines
print(f'Characters in text - {n_characters}')
print(f'Words in text - {n_words}')
print(f'Lines in text - {n_lines}')
wc(text)
|
print('Enter a text and when finished press Enter twice: ')
text = ''
while True:
line = input()
if line:
text += line + '\n '
else:
break
def wc(text):
n_words = len(text.split(' ')) - 1
n_lines = len(text.split('\n')) - 1
n_characters = len(text) - 2 * n_lines
print(f'Characters in text - {n_characters}')
print(f'Words in text - {n_words}')
print(f'Lines in text - {n_lines}')
wc(text)
|
def sample_anchors_pre(df, n_samples= 256, neg_ratio= 0.5):
'''
Sample total of n samples across both BG and FG classes.
If one of the classes have less samples than n/2, we will sample from majority class to make up for short.
Args:
df with column named labels_anchors, containing 1 for foreground and 0 for background
n_samples: number of samples to take in total. default 256, so 128 BG and 128 FG.
neg_ratio: 1/2
'''
n_fg = int((1-neg_ratio) * n_samples)
n_bg = int(neg_ratio * n_samples)
fg_list = [x for x in df['labels_anchors'] if x == 1]
bg_list = [x for x in df['labels_anchors'] if x == 0]
# check if we have excessive positive samples
if len(fg_list) > n_fg:
# mark excessive samples as -1 (ignore)
ignore_index = fg_list[n_bg:]
df.loc[ignore_index, "labels_anchors"] = -1
# sample background examples if we don't have enough positive examples to match the anchor batch size
if len(fg_list) < n_fg:
diff = n_fg - len(fg_list)
# add remaining to background examples
n_bg += diff
# check if we have excessive background samples
if len(bg_list) > n_bg:
# mark excessive samples as -1 (ignore)
ignore_index = fg_list[n_bg:]
df.loc[ignore_index, "labels_anchors"] = -1
|
def sample_anchors_pre(df, n_samples=256, neg_ratio=0.5):
"""
Sample total of n samples across both BG and FG classes.
If one of the classes have less samples than n/2, we will sample from majority class to make up for short.
Args:
df with column named labels_anchors, containing 1 for foreground and 0 for background
n_samples: number of samples to take in total. default 256, so 128 BG and 128 FG.
neg_ratio: 1/2
"""
n_fg = int((1 - neg_ratio) * n_samples)
n_bg = int(neg_ratio * n_samples)
fg_list = [x for x in df['labels_anchors'] if x == 1]
bg_list = [x for x in df['labels_anchors'] if x == 0]
if len(fg_list) > n_fg:
ignore_index = fg_list[n_bg:]
df.loc[ignore_index, 'labels_anchors'] = -1
if len(fg_list) < n_fg:
diff = n_fg - len(fg_list)
n_bg += diff
if len(bg_list) > n_bg:
ignore_index = fg_list[n_bg:]
df.loc[ignore_index, 'labels_anchors'] = -1
|
ansOut = []
coin = [10, 50, 100, 500]
while True:
price = int(input())
if price == 0:
break
cash = list(map(int, input().split()))
sumCash = sum(c * n for c, n in zip(coin, cash))
change = sumCash - price
changeCoins = [(change % 50) // 10, (change % 100) // 50, (change % 500) // 100, change // 500]
out = []
for i in range(4):
if cash[i] > changeCoins[i]:
out.append('{} {}'.format(coin[i], cash[i] - changeCoins[i]))
ansOut.append('\n'.join(out))
print('\n\n'.join(ansOut))
|
ans_out = []
coin = [10, 50, 100, 500]
while True:
price = int(input())
if price == 0:
break
cash = list(map(int, input().split()))
sum_cash = sum((c * n for (c, n) in zip(coin, cash)))
change = sumCash - price
change_coins = [change % 50 // 10, change % 100 // 50, change % 500 // 100, change // 500]
out = []
for i in range(4):
if cash[i] > changeCoins[i]:
out.append('{} {}'.format(coin[i], cash[i] - changeCoins[i]))
ansOut.append('\n'.join(out))
print('\n\n'.join(ansOut))
|
def isBalanced(expr):
if len(expr)%2!=0:
return False
opening=set('([{')
match=set([ ('(',')'), ('[',']'), ('{','}') ])
stack=[]
for char in expr:
if char in opening:
stack.append(char)
else:
if len(stack)==0:
return False
lastOpen=stack.pop()
if (lastOpen, char) not in match:
return False
return len(stack)==0
|
def is_balanced(expr):
if len(expr) % 2 != 0:
return False
opening = set('([{')
match = set([('(', ')'), ('[', ']'), ('{', '}')])
stack = []
for char in expr:
if char in opening:
stack.append(char)
else:
if len(stack) == 0:
return False
last_open = stack.pop()
if (lastOpen, char) not in match:
return False
return len(stack) == 0
|
class Solution:
def mySqrt(self, x: int) -> int:
left, right = 0, x
while left <= right:
mid = left + (right - left) // 2
square = mid ** 2
if square <= x:
left = mid + 1
elif square > x :
right = mid -1
return left-1
# n : the number of input value
## Time Complexity: O( log n )
#
# The overhead in time is the upper-bound of binary search, which is of O( log n ).
## Space Complexity: O( 1 )
#
# The overhead in space is the variable for mathematical computation, which is of O( 1 )
def test_bench():
test_data = [0, 1, 80, 63, 48 ]
# expected output:
'''
0
1
8
7
6
'''
for n in test_data:
print( Solution().mySqrt(n) )
return
if __name__ == '__main__':
test_bench()
|
class Solution:
def my_sqrt(self, x: int) -> int:
(left, right) = (0, x)
while left <= right:
mid = left + (right - left) // 2
square = mid ** 2
if square <= x:
left = mid + 1
elif square > x:
right = mid - 1
return left - 1
def test_bench():
test_data = [0, 1, 80, 63, 48]
'\n 0\n 1\n 8\n 7\n 6\n '
for n in test_data:
print(solution().mySqrt(n))
return
if __name__ == '__main__':
test_bench()
|
In [18]: my_list = [27, "11-13-2017", 84.98, 5]
In [19]: store27 = salesReceipt._make(my_list)
In [20]: print(store27)
salesReceipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
|
In[18]: my_list = [27, '11-13-2017', 84.98, 5]
In[19]: store27 = salesReceipt._make(my_list)
In[20]: print(store27)
sales_receipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
|
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []}
def dfs_topsort(graph): # recursive dfs with
L = [] # additional list for order of nodes
color = { u : "white" for u in graph }
found_cycle = [False]
for u in graph:
if color[u] == "white":
dfs_visit(graph, u, color, L, found_cycle)
if found_cycle[0]:
break
if found_cycle[0]: # if there is a cycle,
L = [] # then return an empty list
L.reverse() # reverse the list
return L # L contains the topological sort
def dfs_visit(graph, u, color, L, found_cycle):
if found_cycle[0]:
return
color[u] = "gray"
for v in graph[u]:
if color[v] == "gray":
found_cycle[0] = True
return
if color[v] == "white":
dfs_visit(graph, v, color, L, found_cycle)
color[u] = "black" # when we're done with u,
L.append(u) # add u to list (reverse it later!)
def has_hamiltonian(adj_list):
graph_sorted = dfs_topsort(adj_list)
print(graph_sorted)
for i in range(0, len(graph_sorted) - 1):
cur_node = graph_sorted[i]
next_node = graph_sorted[i + 1]
if next_node not in adj_list[cur_node]:
return False
return True
print(has_hamiltonian(adj_list_moo))
|
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []}
def dfs_topsort(graph):
l = []
color = {u: 'white' for u in graph}
found_cycle = [False]
for u in graph:
if color[u] == 'white':
dfs_visit(graph, u, color, L, found_cycle)
if found_cycle[0]:
break
if found_cycle[0]:
l = []
L.reverse()
return L
def dfs_visit(graph, u, color, L, found_cycle):
if found_cycle[0]:
return
color[u] = 'gray'
for v in graph[u]:
if color[v] == 'gray':
found_cycle[0] = True
return
if color[v] == 'white':
dfs_visit(graph, v, color, L, found_cycle)
color[u] = 'black'
L.append(u)
def has_hamiltonian(adj_list):
graph_sorted = dfs_topsort(adj_list)
print(graph_sorted)
for i in range(0, len(graph_sorted) - 1):
cur_node = graph_sorted[i]
next_node = graph_sorted[i + 1]
if next_node not in adj_list[cur_node]:
return False
return True
print(has_hamiltonian(adj_list_moo))
|
#!/usr/bin/env python3
flags = ['QCTF{e51f2dad87875d76fb081f2b467535ef}', 'QCTF{c89a4b8b181ea0e7666dc8bf93b34779}', 'QCTF{50b59ef5ba8ca7650323b96119507a98}', 'QCTF{fb1c1b7f76e5ca22411fcee3d024ff46}', 'QCTF{4909e8138219a1f5f166e6e06e057cbc}', 'QCTF{649d0b63d4bd82a9af7af03ba46838d3}', 'QCTF{af043650dc65acce4e001425bacbd3f2}', 'QCTF{8e4225e08e6ec2ec1808b6212e8fd813}', 'QCTF{31b1951f567876b0ad957c250402e3e2}', 'QCTF{959f2b0d3fcd298adc4c63fed56c1c5b}', 'QCTF{3a05bfaa08b653a8b9fc085ebd089f62}', 'QCTF{20d739e7472dcf27e77ffb4be40fd3e5}', 'QCTF{eb35b55b59653643a2e625d8826bc84b}', 'QCTF{311e4b1943c17659b9ded0a3e0f57b2b}', 'QCTF{040eaadc3df6ae0ecb33a404f8e03453}', 'QCTF{84801c28a6619841c425f4c13b867a32}', 'QCTF{ab56c77c46c40354e2f38559c034f348}', 'QCTF{f1f9e7257150d40ce3f481aa44517757}', 'QCTF{9d45092f74d5e74772c9e08a7c25690f}', 'QCTF{f0310ec009bdf2c487d7c149b767078b}', 'QCTF{00bc89904ed8ebffc430ca0f64a0467c}', 'QCTF{7984fbee8ea7d5f0e07c36803e2aacc5}', 'QCTF{0088ba127fb34ffa22023757734ad619}', 'QCTF{97589ca529c64e79a73824e9335c3905}', 'QCTF{30dfe9e4228863f2e9c45508753a9c84}', 'QCTF{a12aa8fdacf39cdf8d031ebb1141ade5}', 'QCTF{3114013f1aea003dc644cd686be073f7}', 'QCTF{c959542546b08485d4c76c6df9034c32}', 'QCTF{4fa407b4fe6f3be4afec15c10e5b60b5}', 'QCTF{b8bac3402e1ae6e42353eb0dbb6e1187}', 'QCTF{71ea738f80df88fe27c7952ee0a08fe9}', 'QCTF{52ef2660af4c18564e75e0421e7be56e}', 'QCTF{41088927caebd4c35d6a5c8c45876ae5}', 'QCTF{90afac1d3e10fa71d8d554c6584cc157}', 'QCTF{6c4f93cd891d991a5f6d21baee73b1a8}', 'QCTF{2fb6f9546cd09b2406f9b9aa0045b4b7}', 'QCTF{1aa150bac71e54372ca54ca412c11f40}', 'QCTF{e0a712bf6d89c9871e833bd936aac979}', 'QCTF{de50d0d2811dd9cb41a633a2f250b680}', 'QCTF{0bb67bdba8a748ddd1968ac66cf5c075}', 'QCTF{661133e4774d75ab7534f967dfe1b78c}', 'QCTF{7edf018896320cf9599a5c13fb3af3a8}', 'QCTF{c976ef4b78ae682d4b854a04f620fb0f}', 'QCTF{4b5436f5f3d9ac23473d4dca41a4dd63}', 'QCTF{d1947ab453f3922436adda4a6716d409}', 'QCTF{162ac50561fae2f9cd40c36e09e24705}', 'QCTF{80fca1b74687d4c0b11313dcf040bbf6}', 'QCTF{f65e11eddbf3cad560ebd96ba4f92461}', 'QCTF{c3b916d43e70181a655b4463ef945661}', 'QCTF{e19df794949bd9d80eef3cb4172dea31}', 'QCTF{a3a759941a10450905b0852b003a82c7}', 'QCTF{533705986a35606e97807ee37ab2c863}', 'QCTF{8aef26a1028de761735a39b27752b9c4}', 'QCTF{70926ffcaf4ff487d0d99fbdf0c78834}', 'QCTF{530cfc0e08a756dcf0f90c2d67c33b40}', 'QCTF{96a2c9e6ca7d6668399c6985d5d2458c}', 'QCTF{6a256384fb72333455da5b04d8495fbe}', 'QCTF{633febe4ec366bc11da19dff3e931521}', 'QCTF{66d6674fec3c7a14cf5c3af6cd467b8e}', 'QCTF{29bfba8ec4e44a5cc33fd099bdb0316b}', 'QCTF{45f3d7645b685042e7e68ad0d309fcec}', 'QCTF{94afe993a0028625d2a22de5c88293e1}', 'QCTF{d272dc01edf11d10730a64cd22827335}', 'QCTF{623cd04ddaccfc4a0d1523bc27bc32ae}', 'QCTF{bf6a6af3f83259e2f66d9b3fce376dce}', 'QCTF{91c134d6a9cd7699ec3a3b5f85a583f0}', 'QCTF{6c85e3fb56c89d62d5fe9e3d27e4a5aa}', 'QCTF{7e4164b2bb4afa5c25682bc4a8c53e66}', 'QCTF{5bc3631a6896269fe77c6bdaf9d27c78}', 'QCTF{6e1b9877716685cac3d549e865a7c85b}', 'QCTF{28fd1487a42cd3e45c98f9876e3c6728}', 'QCTF{6805c31e2276a8daa8826852ca2b0b83}', 'QCTF{2b121dafdfb150cd369e8720b59d82f7}', 'QCTF{ec31421b9f66116a02ca6b773c993358}', 'QCTF{558186ebec8b8653bb18933d198c3ece}', 'QCTF{267b5a5f8bb98b7342148c6106eb2d2c}', 'QCTF{aa38fe9f4141311d709346ead027b507}', 'QCTF{f66f66413048d100ee15c570ac585b13}', 'QCTF{7491e7cd71d16bc2446f3bcf0c92ad2d}', 'QCTF{054c7ac021fbe87042832f8c7bad3a43}', 'QCTF{0fb5425a7fcce56802da00e476347823}', 'QCTF{5299eb9d08eee8fb3f864b999806e88e}', 'QCTF{44c0b9528001db285e167339f84c7e2d}', 'QCTF{397f79c2fedb5281d5ee6662091cbf32}', 'QCTF{741bc53922594cd54deba4c2da166ba5}', 'QCTF{21e2d583596bccdafec4644614841a30}', 'QCTF{61117cdba7b47d2b0b782ebb887b37c9}', 'QCTF{690e749a4c3cc43ca6e9568e48a85f34}', 'QCTF{cf6152c25f81266612090ac7698c10cc}', 'QCTF{56133fb27d94c097e448cd6c54604241}', 'QCTF{9ada31f4d1ee3665867ac40cd576547f}', 'QCTF{fc726ff171101080f64f0a2b06f62264}', 'QCTF{d7dad3c2d7da424d112e3f5685bc3a84}', 'QCTF{71d3e6428dcfc74e4002ed3ad26ed639}', 'QCTF{a0122c5fb3937c487285d0e3051d2d32}', 'QCTF{d456e533f3e963940f17adeb2a898c1f}', 'QCTF{fda977c62519b775fd52b33b7ee3c59d}', 'QCTF{85bb44511da219a6f20706dc232a5036}', 'QCTF{67a79a883ba2bf8eb1905817db7c5455}', 'QCTF{e86fbd286f9a5e507f977fce01d8f546}', 'QCTF{2df725e5277ae0cda2e1b62c670200bb}', 'QCTF{04249a31c87f0bbba3c5d658f8534424}', 'QCTF{9a28f64f49d9e0e3cbd4b9be7d70c389}', 'QCTF{842bb11fa6d69059b8c151a54c2c97f5}', 'QCTF{d426e9a1daa917b243579c1f8fdf8388}', 'QCTF{b8bbd65882ce11f20637d2d66e69c605}', 'QCTF{06756225de4f362c80ecf2aa11e1cf3b}', 'QCTF{0848575c514d3b762f06a8e93dabf370}', 'QCTF{4e9c1a7d8e588a65ef640fed086f417f}', 'QCTF{a52e79bcba9b01a7a07f24b226c12848}', 'QCTF{3d18d085b0e51c6a02daaed5a759930f}', 'QCTF{779194626871433c31f7812157d3b8cb}', 'QCTF{3c3c5107ed05970963fa016b6d6be7eb}', 'QCTF{aa05136c8c46d67cdfc69f47d18aa51b}', 'QCTF{1e85348d600b9019b216f2515beb0945}', 'QCTF{0349bdc14f7ff8b7052c9eb4db1e5a21}', 'QCTF{30dcbb8b9c67edacb4bbed10cb07cc07}', 'QCTF{5b09db09bfaf3a02dc17bfd8771bae8f}', 'QCTF{6e7d07f9c31357ed68590bc24a2ece08}', 'QCTF{d46e9b29270c59845095d97ef9337e95}', 'QCTF{ec118d128f18ca77e0c67d7e66409a7f}', 'QCTF{626af7a6c7005d23b960a02ce128273c}', 'QCTF{05d11133f11f7ea1fa9f009af57f5a57}', 'QCTF{28d876b112787b2ee599929c1f9de7b6}', 'QCTF{100187062f58e52a3b8bd79170b65f8d}', 'QCTF{8b5c6fb2ba52a12763d64631c63ad01c}', 'QCTF{07ffbf77145fd46dc5b19c7464f8e94a}', 'QCTF{8f86963b93b526c663bc51a403a41165}', 'QCTF{eadb09f8f6afc668c3c03976693a7c9e}', 'QCTF{93ddbf8e42e6b4d136bae5d3f1158d70}', 'QCTF{a809ecbc8776a603744cf537e9b71329}', 'QCTF{b75aaea7fabc8f889dc74944c6a4e3c0}', 'QCTF{a416acd8208ccd0f2df531f33d2b6cbe}', 'QCTF{8597e9700045b0dee3fe0a4a2f751af1}', 'QCTF{729f67a65769222200269d1c3efe50f6}', 'QCTF{21f4a9b77d313354bb0951949f559efb}', 'QCTF{6a9d138c62a731982c21a0951cac751f}', 'QCTF{b2a353a1231651b2373e0f4f9863d67c}', 'QCTF{6b8646481367974201ad3763ac09f01b}', 'QCTF{4733d8e51be03a5e7e1421fcb9461946}', 'QCTF{d5671bfab2e102d6ef436310cea556e5}', 'QCTF{fe0dc7f1ad3e3ab1804ac552b5a1014e}', 'QCTF{cd04131fb76d78b75ad4ad3dc241c078}', 'QCTF{b0c3b58624595631a928614c481ef803}', 'QCTF{c3677adad49d8c7b58adcd8d1f41fd8e}', 'QCTF{24dd83a9fa8249b194a53b73f3e12ae8}', 'QCTF{1324a272b619f33ba6c906cd1241cb9a}', 'QCTF{8c4818398ff7e32749c55b19ef965e6e}', 'QCTF{8ee7652cd55d983b708494d85cdba5f2}', 'QCTF{f5601c9718694cfdb754eeb160e77c66}', 'QCTF{4bc1ee7c77ab31f93c314c9cee197d59}', 'QCTF{dfa5bf7ee0a60998035561854ed84677}', 'QCTF{91ff0390d23c0bc1f98d9b19f95cbf93}', 'QCTF{df1135299838932c7b99e8bde9ad8cee}', 'QCTF{056c0210269af051143085248957b3d5}', 'QCTF{6fc42ebaae905d9787d39ad2790b61a5}', 'QCTF{3556c554530023aa02c98a2640a8bacb}', 'QCTF{50a7a712e483aeb523eb00a3a3a4cac6}', 'QCTF{118206c65e16c8314c390914f4a1e59b}', 'QCTF{d456ee30a2399e16f992f9ac2a433d24}', 'QCTF{30a9fb0469aee8878738fa99b7aec8cb}', 'QCTF{b8e518cf71866653f21f4ac241c82d76}', 'QCTF{63117b1c93ec4ff2debd0b0753bb1eb3}', 'QCTF{5665a9accc75c6a1f1882a857c8bbe38}', 'QCTF{565c5a9ece2c891371311c9b0913ddb1}', 'QCTF{8de1cc37b69d6f40bfa2c00fd9e48028}', 'QCTF{50acfa0e810ef4f1cf81462fc77aa8e8}', 'QCTF{33ac115dda168b4eef1a7dc035031e2b}', 'QCTF{e78911a8fc02ed099996bd8e9721dc8d}', 'QCTF{dfe2b8379694a980a3794fd3ce5e61fe}', 'QCTF{eee7da02d350b537783ecead890dd540}', 'QCTF{2aad8accd248b7ca47ae29d5e11f7975}', 'QCTF{8e480455d1e43048616831a59e51fc84}', 'QCTF{986cbb4487b1a8a91ad1827a97bda900}', 'QCTF{48d538cd70bc824dd494562842a24c1b}', 'QCTF{17fa5c186d0bb555c17c7b61f50d0fee}', 'QCTF{9aa99fd3e183fab6071715fb95f2e533}', 'QCTF{58b7096db82c5c7d9ec829abe0a016f3}', 'QCTF{30464a8db4b8f0ae8dc49e8734ed66cb}', 'QCTF{83655c6bd0619b6454ceb273de2d369f}', 'QCTF{72d81a3037fbc8c015bcb0adb87df0db}', 'QCTF{c62bece5781ab571b6ead773f950578c}', 'QCTF{ccd16df0466399ce0424e0102e8bf207}', 'QCTF{9cf7d5815e5bdfccadbb77ffedffa159}', 'QCTF{5ea628391c00c852a73c1a248325cc36}', 'QCTF{8d1daaf1742890409c76c7e5c7496e74}', 'QCTF{19258fe7a929318e6a6c841b54376ea7}', 'QCTF{dc0f86d1e9c1dc1ac4bd4ecad118496b}', 'QCTF{a1a10660a9e023db4803963d0163f915}', 'QCTF{76bdb8507907572d7bba4e53c66b7c94}', 'QCTF{daa9cc55d45641b647449f5a0f4b8431}', 'QCTF{bfa029f704d1f2e81ee9f1ff125d9208}', 'QCTF{356ff001060180459cef071fe033a5f5}', 'QCTF{2b5288c1aad44a9412fcd6bb27dcea7a}', 'QCTF{44172306ed32d70629eace8b445fd894}', 'QCTF{8783ab2b9bc9a89d60c00c715c87c92e}', 'QCTF{a0351089fc58958fb27e55af695bb35e}', 'QCTF{c0de87abadd65ee4e2dba80de610e50a}', 'QCTF{c99b6e9bb5fce478cdc6bca666679c4a}', 'QCTF{0397b5cb327fcc1d94d7edb0f6e1ec15}', 'QCTF{9479a5ca5aef08cacde956246fa2edd3}', 'QCTF{2063acf3a9fd072febe2575151c670cb}', 'QCTF{d6ed4333159c278d22c5527c2a3da633}', 'QCTF{08a811c51b0f0173f0edef63d8326378}', 'QCTF{65dbdc8a0e1b52a07e59248a2e9e456b}', 'QCTF{573a7f0ce4d2cf3e08d452c743fee1ce}', 'QCTF{435089a171f209a66a966e377dba9501}', 'QCTF{81f7f819f6b71eb7720fad3d16dc2373}', 'QCTF{be50a207baaa5e3a491ef7aaeb245abf}', 'QCTF{a996d4647adbc12a69165587a08346e9}', 'QCTF{999d36dee80b90eec6a580cd1f344a08}', 'QCTF{3da3e486913a793a1317da22d8a9a29e}', 'QCTF{809e95f98ba199180cd860ba41d62c5c}', 'QCTF{67524c5080a8b674dcf064494ef7c70f}', 'QCTF{cefcc52f59a484f62b7ba7e62e88e06f}', 'QCTF{241cdfbf606848c9f67589bf2f269206}', 'QCTF{efc924775d7b859411f3bf5a61e85a07}', 'QCTF{63b4e85e20331f52a187318ba2edfd7a}', 'QCTF{a65f5925508331f0b8deda5f67781bc5}', 'QCTF{356ed7e0ab149db06806cc0e6ca6fd5f}', 'QCTF{304d3a7970cf4717dccf3dffbed06874}', 'QCTF{99a747c8723a889bdea5e4f283c20df7}', 'QCTF{c8d7f74205797b602d25852caad49fb1}', 'QCTF{b9248c3a252601dd106d9c0462a9bab7}', 'QCTF{ea86b2a12458a6990d5bae35a73168a0}', 'QCTF{1ca4ecbf8f4ea2d0e2b832c44746ec3b}', 'QCTF{59ee4bf3aedc20d469e788486a9ead6c}', 'QCTF{73720bdd5a424570e5be571021dc4fb8}', 'QCTF{8c04511bedfe9f8c388e4d2f8aba1be5}', 'QCTF{98e34760371fa91407546ba8ac379c09}', 'QCTF{d33cb59a700fb8521a8cb5471048e15e}', 'QCTF{09d317a825132c255ea11c1f41aab1f3}', 'QCTF{a3850a970f2330d1ff6d704061967318}', 'QCTF{93ad167555f15f0901b729f488fc7720}', 'QCTF{61fd9c59cfe8c20d90649bec48424ea1}', 'QCTF{bedf1e7e966f54474931e8cfd141a6ca}', 'QCTF{5ad8a1ce7ec8ab9cdc05553cfd306382}', 'QCTF{3320b3f0490d0949786a894b7f621746}', 'QCTF{57d1dc2f73193dca32535a48650b3a66}', 'QCTF{5c48d6bbfd4fb91d63f21cbe99ece20b}', 'QCTF{2cacdb709e0c230b54e732829b514f92}', 'QCTF{079d0cf77acaebbdbbe8037a35bba5d7}', 'QCTF{d87badd74be817e6acb63d64ecc05ac8}', 'QCTF{f67dffa3ee05d9f096b45c37895d7629}', 'QCTF{1bf708a5a3c9ef47ca7eb8138a052d1b}', 'QCTF{1adf18338f26d19b22f63a4e8eec6e91}', 'QCTF{870d781a223a9112cbb2fb5548e10906}', 'QCTF{8851c98297c5a74ac40cf59875186bd8}', 'QCTF{f83377875176bed6b33e06e9896edded}', 'QCTF{1715727cbb24140bacd2838fc0199bc4}', 'QCTF{c77578152cc09addb4751158bccc7fea}', 'QCTF{7155fb7eb62e6c78ddf3ec44375d3fa9}', 'QCTF{57214d23681056a6596f75372e5cd41b}', 'QCTF{92dcab5e2109673b56d7dc07897055bd}', 'QCTF{131bb9ead4a7d0eb7d2f5540f4929c2d}', 'QCTF{e436dc01fa926f4e48f6920c69c2f54c}', 'QCTF{4b7d2c9245bd28d9c783863ab43202be}', 'QCTF{e23e27790ea55f3093b40d7fdf21b821}', 'QCTF{93e2f15ce929e3d6508543d4378735c3}', 'QCTF{0a18798c331b7f4b4dd14fad01ca3b1f}', 'QCTF{cde9927b04feeaa0f876cecb9e0268e3}', 'QCTF{ba6c8af3c6e58b74438dbf6a04c13258}', 'QCTF{72212e5eb60e430f6ff39f8c2d1ba70d}', 'QCTF{3912316e516adab7e9dfbe5e32c2e8cc}', 'QCTF{960dce50df3f583043cddf4b86b20217}', 'QCTF{6cd9ea76bf5a071ab53053a485c0911a}', 'QCTF{36300e6a9421da59e6fdeefffd64bd50}', 'QCTF{5c3e73a3187dc242b8b538cae5a37e6f}', 'QCTF{9744c67d417a22b7fe1733a54bb0e344}', 'QCTF{28d249578bf8facdf7240b860c4f3ae0}', 'QCTF{a1e9913a8b4b75dd095db103f0287079}', 'QCTF{c4f0f3deafa52c3314fd4542a634933c}', 'QCTF{35a39749f9bea6c90a45fd3e8cc88ca5}', 'QCTF{755cb7e40752b07ed04b12c59b9ce656}', 'QCTF{89e8208c492574de6735b0b5fbe471f5}', 'QCTF{a242f710bd67754b594969a449119434}', 'QCTF{26ded88b4d6b4d9278148de9c911cfb6}', 'QCTF{b6ac8ca7cfd8f3dc075f5f086def5ea2}', 'QCTF{27bb11fe3208f50caafe37b0bd90f070}', 'QCTF{5f058bf0d3991227b49980b9e226c548}', 'QCTF{9fb934712199835ad48f097e5adedbf1}', 'QCTF{8acd08daa256cda637666543042d8d04}', 'QCTF{f19749ece3b079f28397fc6dafc7c5f8}', 'QCTF{8df2b36bc88bdd6419312a3b1e918ac4}', 'QCTF{3f853785bb79075c902c1fcb86b72db8}', 'QCTF{26950b99d1de657f1840f3b1efd117f9}', 'QCTF{57a0747d5a0e9d621b15efc07c721c47}', 'QCTF{164847eb1667c64c70d835cdfa2fed13}', 'QCTF{aeb04f7e9be0e8fb15ec608e93abf7c6}', 'QCTF{f65a2292ea6c9f731fde36f5f92403dc}', 'QCTF{9cff82f318a13f072dadb63e47a16823}', 'QCTF{6a0a50e5f4b8a5878ec6e5e32b8aa4f3}', 'QCTF{9439eb494febbcb498417bab268786f3}', 'QCTF{68a4215f9d77de4875958d2129b98c3e}', 'QCTF{bf83c9d150ed6777d6f2b5581ce75bf1}', 'QCTF{7c6530f3d07598d62a3566173f2cc4a1}', 'QCTF{9dd20e6699b5c69f432914b0196b5b17}', 'QCTF{3a675c1934b1f44b5b73bfd8cee887b9}', 'QCTF{b5e67c6f319acdfed3c47a280f871c7e}', 'QCTF{b88dad61f68da779fad66fa4442eb337}', 'QCTF{3af8a9807a6d0e4b50c1687c07c1d891}', 'QCTF{e78168930647856b94840ce84fab26b4}', 'QCTF{ab88b2ea7e66dd35bdff4d03a15d3dc1}', 'QCTF{78e20f8707184aea4227c98107c95fdb}', 'QCTF{f1b279cc0839c830e07f6e73bb9654fe}', 'QCTF{71fc41f44593348bb1e4a0938526f0f9}', 'QCTF{f8b9207f02330a7d9a762ab4c1cace2b}', 'QCTF{12efdafbe2e29645abc3296178891ed6}', 'QCTF{c5d813b31a0534341a1c4b64e554c488}', 'QCTF{1a63a760f782eecf21234c815b5748bf}', 'QCTF{b6dee11cd1b0382986738826a5c04d7a}', 'QCTF{0d0d99976206194e426b95873720a440}', 'QCTF{d4030405263f8eec80a3855ba066eb76}', 'QCTF{c249cd1f9f86aa5ff2fe0e94da247578}', 'QCTF{ba8adfd031159e41cbfb26193b2aeee1}', 'QCTF{14dc10f84625fc031dd5cdad7b6a82af}', 'QCTF{be7c2d83d34846ece6fe5f25f0700f74}', 'QCTF{d7f1d87ad0386f695cd022617bf134d8}', 'QCTF{6a3a915957dbcd817876854902f30a6a}', 'QCTF{4663ffd40db950abddb4d09122eb1dcd}', 'QCTF{f72c028fdfeb0c42e3d311295ac42ff2}', 'QCTF{901b065b0d0569f161f0ba7f1cc711bc}', 'QCTF{8f707798947c3335d685d7e3b761c2c4}', 'QCTF{746ffa1fc14609d13dde8d540c5d402a}', 'QCTF{1b92b1e84712dd9084dea96e9f67c659}', 'QCTF{2d8976f6ef6da5b843823940660be68a}', 'QCTF{d1e00391c9bd7c2ecc2b19e6d177e4af}', 'QCTF{cea54a59af20fdfa06c8e8357fec663d}', 'QCTF{1f2b8d5fceea39243fa966d638efc92e}', 'QCTF{0f6faa584c642fc21879f4358fdfb01c}', 'QCTF{acac74237614850fbfbd97410013daa2}', 'QCTF{57fce704c2dbdb5e3034b67a7984bb0c}', 'QCTF{e20bc6c0a13114f7fd29ad9661a946e9}', 'QCTF{92c4dfc79749e9310b7ab64c3d9780d0}', 'QCTF{c6a49485ff92a292f0ae9fca4b1f3314}', 'QCTF{be0f0be2f0fb165a16a62aee2dcd0258}', 'QCTF{052fcc31b1b26484fe9da51fb89ba34d}', 'QCTF{b156eb9c86c03d0fae3c883f5b317dcb}', 'QCTF{ff83da3b5ca61495d0acd623dc2d796e}', 'QCTF{3fce7a6ba38ed1a381dae3686919c902}', 'QCTF{889591a0a7d29579546adaad1d0b5b86}', 'QCTF{9c378d9aa63fca7d5f7f275a9566f264}', 'QCTF{e32a672a6673bc56d8b109952403aae9}', 'QCTF{bc6a3a213102b2dc5f946d5655026352}', 'QCTF{30d04471a675aeeec45b8f6143085f46}', 'QCTF{3b4d06e0c2cd20a177fa277bbbc0a1a2}', 'QCTF{bdf4879a061a3a751f91ece53657a53e}', 'QCTF{d8721fc7d32499aa692b04d7eacc8624}', 'QCTF{09d3580e9431327fbf4ccc53efb0a970}', 'QCTF{814356913a352dfe15b851e52cc55c0d}', 'QCTF{cd9de5c50a3ffb20ea08cb083004252c}', 'QCTF{79de86d819cfc03ac6b98fbc29fac36d}', 'QCTF{63663214499a85208c4f7dc529c05ea5}', 'QCTF{171798109c343a3303020f0a24259e5e}', 'QCTF{611a9181a1f7c45c6c715e494bccd1b9}', 'QCTF{da4e7cc4b461aaedd1bfc45533723b8a}', 'QCTF{2ea7d755b255a6f5376d22f8113a2cfa}', 'QCTF{2a741c8199e13853f8195613ef037ced}', 'QCTF{1b66523f2b665c3dfea91aece42273d3}', 'QCTF{42a46422d8faa1ec3e768580b2dec713}', 'QCTF{ca9d7ac177d049416354a0fbd76a89b9}', 'QCTF{9bb379b6c775b738069ae0ab7accf2dd}', 'QCTF{bacec59ecbc809f7ab27a9169500883a}', 'QCTF{0ef59b9a33046aa124bb87df30934714}', 'QCTF{1b646109ed4bfa30f29d6666b2090701}', 'QCTF{65727e2ba028dc6e9ac572ed6a6ebc6f}', 'QCTF{784c261a9f564d4387d035ce57b05e3e}', 'QCTF{e68fb87f2cad4a3da5799fc982ec82ff}', 'QCTF{ba003b186368bf16c19c71332a95efee}', 'QCTF{6d695ed5a0c2d04722716210b5bcfda6}', 'QCTF{7eb1c12dc09b138a1d7e40058fa7a04a}', 'QCTF{64a545320b2928f88b6c6c27f34d2e3c}', 'QCTF{8cdf05aeb3fa5bb07157db87d2b45755}', 'QCTF{48f8e1742b60e1734f6580ab654f9b6f}', 'QCTF{fb14f2533750f7849b071c9a286c9529}', 'QCTF{47f7996ec34bf04863272d7fc36a1eb1}', 'QCTF{919f49d2f324ae91956c3d97b727c24a}', 'QCTF{336f9d8d23fbb50810c1c0b549ad13bf}', 'QCTF{b316f48f8ed4443a117b7a8752d062cb}', 'QCTF{ea5818adad537c87ddb9ce339c0bbb84}', 'QCTF{d510dfbd781d15b674c63489f55191b2}', 'QCTF{df1d534fcc36d5049b5b607499a74f75}', 'QCTF{2781aa19764810125b745b001dd09090}', 'QCTF{0920b2f44311ed5239e8c2d90c991417}', 'QCTF{da22adea508dc7d5bc9ec5cd5378ef20}', 'QCTF{30f69464f59bf44cba73e6430591acb9}', 'QCTF{2239ffe2985776b1d459a729035e6105}', 'QCTF{07a3846e68534b08abec6761492dfd7c}', 'QCTF{2876a617fcb9d33b1a457e2a1f22982b}', 'QCTF{76471463a11b3f5830d6c98bdc188410}', 'QCTF{64b115efe8a4acaab08f40e83d174953}', 'QCTF{2b9fece3ca12493fa34027cfe34a827d}', 'QCTF{72ceded3364700e5a163cd1fa809f2b5}', 'QCTF{a52ab44fe70adc1964442347fe0bc389}', 'QCTF{ffb4560d742fd8dae61edda32628d5d9}', 'QCTF{fe274231e80419937813cbd55441f8b5}', 'QCTF{38ec71804dca70480b9714ae809bf843}', 'QCTF{2876bb27e398963331099a10e9c1b5b1}', 'QCTF{c8eacb1f0f7ea7a130fe97aa903bc52d}', 'QCTF{91d895637bf21849d8ac97072d9aa66c}', 'QCTF{487a3428ab723d4e9bca30342180612a}', 'QCTF{0ca2e9a4b4fb5298b84a2ae097303615}', 'QCTF{1017c0fad5211fa1a8bd05e2c12e1ab5}', 'QCTF{0772fc3bb68132cc47fc6a26bb23a2eb}', 'QCTF{54808c739cc835327ba82b17dda37765}', 'QCTF{5ba1b7f137a0a269d77db75c1609d015}', 'QCTF{3f59447502e3ccd8db93f57f6b64a869}', 'QCTF{3d33a10890e1797b3518f2032228ef97}', 'QCTF{538226c6e2932fb2c0890fa660707081}', 'QCTF{03dea04fa6f9bf11854a62f92f95028c}', 'QCTF{7ebbc2f97c8e02947eb7537e6e35bf4d}', 'QCTF{7fabc82da5e59469a31d6ae73b0ba8dd}', 'QCTF{99d11087195ac95f9a4bf220346c7ae8}', 'QCTF{6ba3b8dff5b591a308616a485802eb1a}', 'QCTF{73e10bd2e77da35988a91f2b39ba4032}', 'QCTF{d41e8b2244e4e72a04f5229bc61e0a4a}', 'QCTF{1f1c22d0e0dcf0d73b5562f604805060}', 'QCTF{e45fba7380d70df6de5353f6bd1326df}', 'QCTF{c4eb636d6329e437d2ece74b439d905b}', 'QCTF{166f03d5b2a6172ebdfe62790d40ea08}', 'QCTF{c9e2d3fed043ae7ff086944ddb92a595}', 'QCTF{c3683790714524bf741f442cf6f75816}', 'QCTF{c3552856294a7c882abe5bfeb08d40b3}', 'QCTF{2028f8e09d41c758c78b5f1bff9a7730}', 'QCTF{7b28486de1bf56b716f77ab14ac1dc2f}', 'QCTF{e445025dcc35e0f7ad5ffc4c1f736857}', 'QCTF{c977b87449d7461cd45ec2b076754b77}', 'QCTF{9626d8f7759943dedefedffc96ac2489}', 'QCTF{52af66f7f1005968a3057ca76c69b488}', 'QCTF{f7791cfb47893204998bc864a0454767}', 'QCTF{c1325f2049b792f8330ab51d8012138a}', 'QCTF{e6e088ba12752fb97aadaa34ab41b118}', 'QCTF{41051ffcbd702005b7f5c4bae392bb4a}', 'QCTF{58bfe4a9f82ae56f4fab8f2d57470f2f}', 'QCTF{a0ac496ce45f06890c045235eb2547a7}', 'QCTF{0c22482b6a4533ba449d4ec1762494ba}', 'QCTF{4466193f2c65c5d072ecb82277657780}', 'QCTF{43689b43469374eb768fb5d4269be92a}', 'QCTF{e31ff94e5ee5638e7b3c0cde3c2b50dd}', 'QCTF{4cc47b59341b7f0112ba8f4dbdda527c}', 'QCTF{e11501e1bb7da841a2c715eafedccb55}', 'QCTF{6acd2208d0d86fcb796cf8264973fee6}', 'QCTF{d8ee1b7b2772d6aea857929d10fbca8e}', 'QCTF{8c27329ebfdef6480d0c60393a573137}', 'QCTF{b9f5190eb71ca8203f60e2a1a6a652af}', 'QCTF{7e5aa6d503c4c2c944a8148fdf633694}', 'QCTF{9ddcb0e99371e60bbb6cbcae87899fc5}', 'QCTF{e7e75d8e6a4789ea242ece7be93bfc89}', 'QCTF{86546326f5bf721792154c91ede0656d}', 'QCTF{6d36f257d24ee06cc402c3b125d5eaa7}']
def check(attempt, context):
if attempt.answer == flags[attempt.participant.id % len(flags)]:
return Checked(True)
if attempt.answer in flags:
return CheckedPlagiarist(False, flags.index(attempt.answer))
return Checked(False)
|
flags = ['QCTF{e51f2dad87875d76fb081f2b467535ef}', 'QCTF{c89a4b8b181ea0e7666dc8bf93b34779}', 'QCTF{50b59ef5ba8ca7650323b96119507a98}', 'QCTF{fb1c1b7f76e5ca22411fcee3d024ff46}', 'QCTF{4909e8138219a1f5f166e6e06e057cbc}', 'QCTF{649d0b63d4bd82a9af7af03ba46838d3}', 'QCTF{af043650dc65acce4e001425bacbd3f2}', 'QCTF{8e4225e08e6ec2ec1808b6212e8fd813}', 'QCTF{31b1951f567876b0ad957c250402e3e2}', 'QCTF{959f2b0d3fcd298adc4c63fed56c1c5b}', 'QCTF{3a05bfaa08b653a8b9fc085ebd089f62}', 'QCTF{20d739e7472dcf27e77ffb4be40fd3e5}', 'QCTF{eb35b55b59653643a2e625d8826bc84b}', 'QCTF{311e4b1943c17659b9ded0a3e0f57b2b}', 'QCTF{040eaadc3df6ae0ecb33a404f8e03453}', 'QCTF{84801c28a6619841c425f4c13b867a32}', 'QCTF{ab56c77c46c40354e2f38559c034f348}', 'QCTF{f1f9e7257150d40ce3f481aa44517757}', 'QCTF{9d45092f74d5e74772c9e08a7c25690f}', 'QCTF{f0310ec009bdf2c487d7c149b767078b}', 'QCTF{00bc89904ed8ebffc430ca0f64a0467c}', 'QCTF{7984fbee8ea7d5f0e07c36803e2aacc5}', 'QCTF{0088ba127fb34ffa22023757734ad619}', 'QCTF{97589ca529c64e79a73824e9335c3905}', 'QCTF{30dfe9e4228863f2e9c45508753a9c84}', 'QCTF{a12aa8fdacf39cdf8d031ebb1141ade5}', 'QCTF{3114013f1aea003dc644cd686be073f7}', 'QCTF{c959542546b08485d4c76c6df9034c32}', 'QCTF{4fa407b4fe6f3be4afec15c10e5b60b5}', 'QCTF{b8bac3402e1ae6e42353eb0dbb6e1187}', 'QCTF{71ea738f80df88fe27c7952ee0a08fe9}', 'QCTF{52ef2660af4c18564e75e0421e7be56e}', 'QCTF{41088927caebd4c35d6a5c8c45876ae5}', 'QCTF{90afac1d3e10fa71d8d554c6584cc157}', 'QCTF{6c4f93cd891d991a5f6d21baee73b1a8}', 'QCTF{2fb6f9546cd09b2406f9b9aa0045b4b7}', 'QCTF{1aa150bac71e54372ca54ca412c11f40}', 'QCTF{e0a712bf6d89c9871e833bd936aac979}', 'QCTF{de50d0d2811dd9cb41a633a2f250b680}', 'QCTF{0bb67bdba8a748ddd1968ac66cf5c075}', 'QCTF{661133e4774d75ab7534f967dfe1b78c}', 'QCTF{7edf018896320cf9599a5c13fb3af3a8}', 'QCTF{c976ef4b78ae682d4b854a04f620fb0f}', 'QCTF{4b5436f5f3d9ac23473d4dca41a4dd63}', 'QCTF{d1947ab453f3922436adda4a6716d409}', 'QCTF{162ac50561fae2f9cd40c36e09e24705}', 'QCTF{80fca1b74687d4c0b11313dcf040bbf6}', 'QCTF{f65e11eddbf3cad560ebd96ba4f92461}', 'QCTF{c3b916d43e70181a655b4463ef945661}', 'QCTF{e19df794949bd9d80eef3cb4172dea31}', 'QCTF{a3a759941a10450905b0852b003a82c7}', 'QCTF{533705986a35606e97807ee37ab2c863}', 'QCTF{8aef26a1028de761735a39b27752b9c4}', 'QCTF{70926ffcaf4ff487d0d99fbdf0c78834}', 'QCTF{530cfc0e08a756dcf0f90c2d67c33b40}', 'QCTF{96a2c9e6ca7d6668399c6985d5d2458c}', 'QCTF{6a256384fb72333455da5b04d8495fbe}', 'QCTF{633febe4ec366bc11da19dff3e931521}', 'QCTF{66d6674fec3c7a14cf5c3af6cd467b8e}', 'QCTF{29bfba8ec4e44a5cc33fd099bdb0316b}', 'QCTF{45f3d7645b685042e7e68ad0d309fcec}', 'QCTF{94afe993a0028625d2a22de5c88293e1}', 'QCTF{d272dc01edf11d10730a64cd22827335}', 'QCTF{623cd04ddaccfc4a0d1523bc27bc32ae}', 'QCTF{bf6a6af3f83259e2f66d9b3fce376dce}', 'QCTF{91c134d6a9cd7699ec3a3b5f85a583f0}', 'QCTF{6c85e3fb56c89d62d5fe9e3d27e4a5aa}', 'QCTF{7e4164b2bb4afa5c25682bc4a8c53e66}', 'QCTF{5bc3631a6896269fe77c6bdaf9d27c78}', 'QCTF{6e1b9877716685cac3d549e865a7c85b}', 'QCTF{28fd1487a42cd3e45c98f9876e3c6728}', 'QCTF{6805c31e2276a8daa8826852ca2b0b83}', 'QCTF{2b121dafdfb150cd369e8720b59d82f7}', 'QCTF{ec31421b9f66116a02ca6b773c993358}', 'QCTF{558186ebec8b8653bb18933d198c3ece}', 'QCTF{267b5a5f8bb98b7342148c6106eb2d2c}', 'QCTF{aa38fe9f4141311d709346ead027b507}', 'QCTF{f66f66413048d100ee15c570ac585b13}', 'QCTF{7491e7cd71d16bc2446f3bcf0c92ad2d}', 'QCTF{054c7ac021fbe87042832f8c7bad3a43}', 'QCTF{0fb5425a7fcce56802da00e476347823}', 'QCTF{5299eb9d08eee8fb3f864b999806e88e}', 'QCTF{44c0b9528001db285e167339f84c7e2d}', 'QCTF{397f79c2fedb5281d5ee6662091cbf32}', 'QCTF{741bc53922594cd54deba4c2da166ba5}', 'QCTF{21e2d583596bccdafec4644614841a30}', 'QCTF{61117cdba7b47d2b0b782ebb887b37c9}', 'QCTF{690e749a4c3cc43ca6e9568e48a85f34}', 'QCTF{cf6152c25f81266612090ac7698c10cc}', 'QCTF{56133fb27d94c097e448cd6c54604241}', 'QCTF{9ada31f4d1ee3665867ac40cd576547f}', 'QCTF{fc726ff171101080f64f0a2b06f62264}', 'QCTF{d7dad3c2d7da424d112e3f5685bc3a84}', 'QCTF{71d3e6428dcfc74e4002ed3ad26ed639}', 'QCTF{a0122c5fb3937c487285d0e3051d2d32}', 'QCTF{d456e533f3e963940f17adeb2a898c1f}', 'QCTF{fda977c62519b775fd52b33b7ee3c59d}', 'QCTF{85bb44511da219a6f20706dc232a5036}', 'QCTF{67a79a883ba2bf8eb1905817db7c5455}', 'QCTF{e86fbd286f9a5e507f977fce01d8f546}', 'QCTF{2df725e5277ae0cda2e1b62c670200bb}', 'QCTF{04249a31c87f0bbba3c5d658f8534424}', 'QCTF{9a28f64f49d9e0e3cbd4b9be7d70c389}', 'QCTF{842bb11fa6d69059b8c151a54c2c97f5}', 'QCTF{d426e9a1daa917b243579c1f8fdf8388}', 'QCTF{b8bbd65882ce11f20637d2d66e69c605}', 'QCTF{06756225de4f362c80ecf2aa11e1cf3b}', 'QCTF{0848575c514d3b762f06a8e93dabf370}', 'QCTF{4e9c1a7d8e588a65ef640fed086f417f}', 'QCTF{a52e79bcba9b01a7a07f24b226c12848}', 'QCTF{3d18d085b0e51c6a02daaed5a759930f}', 'QCTF{779194626871433c31f7812157d3b8cb}', 'QCTF{3c3c5107ed05970963fa016b6d6be7eb}', 'QCTF{aa05136c8c46d67cdfc69f47d18aa51b}', 'QCTF{1e85348d600b9019b216f2515beb0945}', 'QCTF{0349bdc14f7ff8b7052c9eb4db1e5a21}', 'QCTF{30dcbb8b9c67edacb4bbed10cb07cc07}', 'QCTF{5b09db09bfaf3a02dc17bfd8771bae8f}', 'QCTF{6e7d07f9c31357ed68590bc24a2ece08}', 'QCTF{d46e9b29270c59845095d97ef9337e95}', 'QCTF{ec118d128f18ca77e0c67d7e66409a7f}', 'QCTF{626af7a6c7005d23b960a02ce128273c}', 'QCTF{05d11133f11f7ea1fa9f009af57f5a57}', 'QCTF{28d876b112787b2ee599929c1f9de7b6}', 'QCTF{100187062f58e52a3b8bd79170b65f8d}', 'QCTF{8b5c6fb2ba52a12763d64631c63ad01c}', 'QCTF{07ffbf77145fd46dc5b19c7464f8e94a}', 'QCTF{8f86963b93b526c663bc51a403a41165}', 'QCTF{eadb09f8f6afc668c3c03976693a7c9e}', 'QCTF{93ddbf8e42e6b4d136bae5d3f1158d70}', 'QCTF{a809ecbc8776a603744cf537e9b71329}', 'QCTF{b75aaea7fabc8f889dc74944c6a4e3c0}', 'QCTF{a416acd8208ccd0f2df531f33d2b6cbe}', 'QCTF{8597e9700045b0dee3fe0a4a2f751af1}', 'QCTF{729f67a65769222200269d1c3efe50f6}', 'QCTF{21f4a9b77d313354bb0951949f559efb}', 'QCTF{6a9d138c62a731982c21a0951cac751f}', 'QCTF{b2a353a1231651b2373e0f4f9863d67c}', 'QCTF{6b8646481367974201ad3763ac09f01b}', 'QCTF{4733d8e51be03a5e7e1421fcb9461946}', 'QCTF{d5671bfab2e102d6ef436310cea556e5}', 'QCTF{fe0dc7f1ad3e3ab1804ac552b5a1014e}', 'QCTF{cd04131fb76d78b75ad4ad3dc241c078}', 'QCTF{b0c3b58624595631a928614c481ef803}', 'QCTF{c3677adad49d8c7b58adcd8d1f41fd8e}', 'QCTF{24dd83a9fa8249b194a53b73f3e12ae8}', 'QCTF{1324a272b619f33ba6c906cd1241cb9a}', 'QCTF{8c4818398ff7e32749c55b19ef965e6e}', 'QCTF{8ee7652cd55d983b708494d85cdba5f2}', 'QCTF{f5601c9718694cfdb754eeb160e77c66}', 'QCTF{4bc1ee7c77ab31f93c314c9cee197d59}', 'QCTF{dfa5bf7ee0a60998035561854ed84677}', 'QCTF{91ff0390d23c0bc1f98d9b19f95cbf93}', 'QCTF{df1135299838932c7b99e8bde9ad8cee}', 'QCTF{056c0210269af051143085248957b3d5}', 'QCTF{6fc42ebaae905d9787d39ad2790b61a5}', 'QCTF{3556c554530023aa02c98a2640a8bacb}', 'QCTF{50a7a712e483aeb523eb00a3a3a4cac6}', 'QCTF{118206c65e16c8314c390914f4a1e59b}', 'QCTF{d456ee30a2399e16f992f9ac2a433d24}', 'QCTF{30a9fb0469aee8878738fa99b7aec8cb}', 'QCTF{b8e518cf71866653f21f4ac241c82d76}', 'QCTF{63117b1c93ec4ff2debd0b0753bb1eb3}', 'QCTF{5665a9accc75c6a1f1882a857c8bbe38}', 'QCTF{565c5a9ece2c891371311c9b0913ddb1}', 'QCTF{8de1cc37b69d6f40bfa2c00fd9e48028}', 'QCTF{50acfa0e810ef4f1cf81462fc77aa8e8}', 'QCTF{33ac115dda168b4eef1a7dc035031e2b}', 'QCTF{e78911a8fc02ed099996bd8e9721dc8d}', 'QCTF{dfe2b8379694a980a3794fd3ce5e61fe}', 'QCTF{eee7da02d350b537783ecead890dd540}', 'QCTF{2aad8accd248b7ca47ae29d5e11f7975}', 'QCTF{8e480455d1e43048616831a59e51fc84}', 'QCTF{986cbb4487b1a8a91ad1827a97bda900}', 'QCTF{48d538cd70bc824dd494562842a24c1b}', 'QCTF{17fa5c186d0bb555c17c7b61f50d0fee}', 'QCTF{9aa99fd3e183fab6071715fb95f2e533}', 'QCTF{58b7096db82c5c7d9ec829abe0a016f3}', 'QCTF{30464a8db4b8f0ae8dc49e8734ed66cb}', 'QCTF{83655c6bd0619b6454ceb273de2d369f}', 'QCTF{72d81a3037fbc8c015bcb0adb87df0db}', 'QCTF{c62bece5781ab571b6ead773f950578c}', 'QCTF{ccd16df0466399ce0424e0102e8bf207}', 'QCTF{9cf7d5815e5bdfccadbb77ffedffa159}', 'QCTF{5ea628391c00c852a73c1a248325cc36}', 'QCTF{8d1daaf1742890409c76c7e5c7496e74}', 'QCTF{19258fe7a929318e6a6c841b54376ea7}', 'QCTF{dc0f86d1e9c1dc1ac4bd4ecad118496b}', 'QCTF{a1a10660a9e023db4803963d0163f915}', 'QCTF{76bdb8507907572d7bba4e53c66b7c94}', 'QCTF{daa9cc55d45641b647449f5a0f4b8431}', 'QCTF{bfa029f704d1f2e81ee9f1ff125d9208}', 'QCTF{356ff001060180459cef071fe033a5f5}', 'QCTF{2b5288c1aad44a9412fcd6bb27dcea7a}', 'QCTF{44172306ed32d70629eace8b445fd894}', 'QCTF{8783ab2b9bc9a89d60c00c715c87c92e}', 'QCTF{a0351089fc58958fb27e55af695bb35e}', 'QCTF{c0de87abadd65ee4e2dba80de610e50a}', 'QCTF{c99b6e9bb5fce478cdc6bca666679c4a}', 'QCTF{0397b5cb327fcc1d94d7edb0f6e1ec15}', 'QCTF{9479a5ca5aef08cacde956246fa2edd3}', 'QCTF{2063acf3a9fd072febe2575151c670cb}', 'QCTF{d6ed4333159c278d22c5527c2a3da633}', 'QCTF{08a811c51b0f0173f0edef63d8326378}', 'QCTF{65dbdc8a0e1b52a07e59248a2e9e456b}', 'QCTF{573a7f0ce4d2cf3e08d452c743fee1ce}', 'QCTF{435089a171f209a66a966e377dba9501}', 'QCTF{81f7f819f6b71eb7720fad3d16dc2373}', 'QCTF{be50a207baaa5e3a491ef7aaeb245abf}', 'QCTF{a996d4647adbc12a69165587a08346e9}', 'QCTF{999d36dee80b90eec6a580cd1f344a08}', 'QCTF{3da3e486913a793a1317da22d8a9a29e}', 'QCTF{809e95f98ba199180cd860ba41d62c5c}', 'QCTF{67524c5080a8b674dcf064494ef7c70f}', 'QCTF{cefcc52f59a484f62b7ba7e62e88e06f}', 'QCTF{241cdfbf606848c9f67589bf2f269206}', 'QCTF{efc924775d7b859411f3bf5a61e85a07}', 'QCTF{63b4e85e20331f52a187318ba2edfd7a}', 'QCTF{a65f5925508331f0b8deda5f67781bc5}', 'QCTF{356ed7e0ab149db06806cc0e6ca6fd5f}', 'QCTF{304d3a7970cf4717dccf3dffbed06874}', 'QCTF{99a747c8723a889bdea5e4f283c20df7}', 'QCTF{c8d7f74205797b602d25852caad49fb1}', 'QCTF{b9248c3a252601dd106d9c0462a9bab7}', 'QCTF{ea86b2a12458a6990d5bae35a73168a0}', 'QCTF{1ca4ecbf8f4ea2d0e2b832c44746ec3b}', 'QCTF{59ee4bf3aedc20d469e788486a9ead6c}', 'QCTF{73720bdd5a424570e5be571021dc4fb8}', 'QCTF{8c04511bedfe9f8c388e4d2f8aba1be5}', 'QCTF{98e34760371fa91407546ba8ac379c09}', 'QCTF{d33cb59a700fb8521a8cb5471048e15e}', 'QCTF{09d317a825132c255ea11c1f41aab1f3}', 'QCTF{a3850a970f2330d1ff6d704061967318}', 'QCTF{93ad167555f15f0901b729f488fc7720}', 'QCTF{61fd9c59cfe8c20d90649bec48424ea1}', 'QCTF{bedf1e7e966f54474931e8cfd141a6ca}', 'QCTF{5ad8a1ce7ec8ab9cdc05553cfd306382}', 'QCTF{3320b3f0490d0949786a894b7f621746}', 'QCTF{57d1dc2f73193dca32535a48650b3a66}', 'QCTF{5c48d6bbfd4fb91d63f21cbe99ece20b}', 'QCTF{2cacdb709e0c230b54e732829b514f92}', 'QCTF{079d0cf77acaebbdbbe8037a35bba5d7}', 'QCTF{d87badd74be817e6acb63d64ecc05ac8}', 'QCTF{f67dffa3ee05d9f096b45c37895d7629}', 'QCTF{1bf708a5a3c9ef47ca7eb8138a052d1b}', 'QCTF{1adf18338f26d19b22f63a4e8eec6e91}', 'QCTF{870d781a223a9112cbb2fb5548e10906}', 'QCTF{8851c98297c5a74ac40cf59875186bd8}', 'QCTF{f83377875176bed6b33e06e9896edded}', 'QCTF{1715727cbb24140bacd2838fc0199bc4}', 'QCTF{c77578152cc09addb4751158bccc7fea}', 'QCTF{7155fb7eb62e6c78ddf3ec44375d3fa9}', 'QCTF{57214d23681056a6596f75372e5cd41b}', 'QCTF{92dcab5e2109673b56d7dc07897055bd}', 'QCTF{131bb9ead4a7d0eb7d2f5540f4929c2d}', 'QCTF{e436dc01fa926f4e48f6920c69c2f54c}', 'QCTF{4b7d2c9245bd28d9c783863ab43202be}', 'QCTF{e23e27790ea55f3093b40d7fdf21b821}', 'QCTF{93e2f15ce929e3d6508543d4378735c3}', 'QCTF{0a18798c331b7f4b4dd14fad01ca3b1f}', 'QCTF{cde9927b04feeaa0f876cecb9e0268e3}', 'QCTF{ba6c8af3c6e58b74438dbf6a04c13258}', 'QCTF{72212e5eb60e430f6ff39f8c2d1ba70d}', 'QCTF{3912316e516adab7e9dfbe5e32c2e8cc}', 'QCTF{960dce50df3f583043cddf4b86b20217}', 'QCTF{6cd9ea76bf5a071ab53053a485c0911a}', 'QCTF{36300e6a9421da59e6fdeefffd64bd50}', 'QCTF{5c3e73a3187dc242b8b538cae5a37e6f}', 'QCTF{9744c67d417a22b7fe1733a54bb0e344}', 'QCTF{28d249578bf8facdf7240b860c4f3ae0}', 'QCTF{a1e9913a8b4b75dd095db103f0287079}', 'QCTF{c4f0f3deafa52c3314fd4542a634933c}', 'QCTF{35a39749f9bea6c90a45fd3e8cc88ca5}', 'QCTF{755cb7e40752b07ed04b12c59b9ce656}', 'QCTF{89e8208c492574de6735b0b5fbe471f5}', 'QCTF{a242f710bd67754b594969a449119434}', 'QCTF{26ded88b4d6b4d9278148de9c911cfb6}', 'QCTF{b6ac8ca7cfd8f3dc075f5f086def5ea2}', 'QCTF{27bb11fe3208f50caafe37b0bd90f070}', 'QCTF{5f058bf0d3991227b49980b9e226c548}', 'QCTF{9fb934712199835ad48f097e5adedbf1}', 'QCTF{8acd08daa256cda637666543042d8d04}', 'QCTF{f19749ece3b079f28397fc6dafc7c5f8}', 'QCTF{8df2b36bc88bdd6419312a3b1e918ac4}', 'QCTF{3f853785bb79075c902c1fcb86b72db8}', 'QCTF{26950b99d1de657f1840f3b1efd117f9}', 'QCTF{57a0747d5a0e9d621b15efc07c721c47}', 'QCTF{164847eb1667c64c70d835cdfa2fed13}', 'QCTF{aeb04f7e9be0e8fb15ec608e93abf7c6}', 'QCTF{f65a2292ea6c9f731fde36f5f92403dc}', 'QCTF{9cff82f318a13f072dadb63e47a16823}', 'QCTF{6a0a50e5f4b8a5878ec6e5e32b8aa4f3}', 'QCTF{9439eb494febbcb498417bab268786f3}', 'QCTF{68a4215f9d77de4875958d2129b98c3e}', 'QCTF{bf83c9d150ed6777d6f2b5581ce75bf1}', 'QCTF{7c6530f3d07598d62a3566173f2cc4a1}', 'QCTF{9dd20e6699b5c69f432914b0196b5b17}', 'QCTF{3a675c1934b1f44b5b73bfd8cee887b9}', 'QCTF{b5e67c6f319acdfed3c47a280f871c7e}', 'QCTF{b88dad61f68da779fad66fa4442eb337}', 'QCTF{3af8a9807a6d0e4b50c1687c07c1d891}', 'QCTF{e78168930647856b94840ce84fab26b4}', 'QCTF{ab88b2ea7e66dd35bdff4d03a15d3dc1}', 'QCTF{78e20f8707184aea4227c98107c95fdb}', 'QCTF{f1b279cc0839c830e07f6e73bb9654fe}', 'QCTF{71fc41f44593348bb1e4a0938526f0f9}', 'QCTF{f8b9207f02330a7d9a762ab4c1cace2b}', 'QCTF{12efdafbe2e29645abc3296178891ed6}', 'QCTF{c5d813b31a0534341a1c4b64e554c488}', 'QCTF{1a63a760f782eecf21234c815b5748bf}', 'QCTF{b6dee11cd1b0382986738826a5c04d7a}', 'QCTF{0d0d99976206194e426b95873720a440}', 'QCTF{d4030405263f8eec80a3855ba066eb76}', 'QCTF{c249cd1f9f86aa5ff2fe0e94da247578}', 'QCTF{ba8adfd031159e41cbfb26193b2aeee1}', 'QCTF{14dc10f84625fc031dd5cdad7b6a82af}', 'QCTF{be7c2d83d34846ece6fe5f25f0700f74}', 'QCTF{d7f1d87ad0386f695cd022617bf134d8}', 'QCTF{6a3a915957dbcd817876854902f30a6a}', 'QCTF{4663ffd40db950abddb4d09122eb1dcd}', 'QCTF{f72c028fdfeb0c42e3d311295ac42ff2}', 'QCTF{901b065b0d0569f161f0ba7f1cc711bc}', 'QCTF{8f707798947c3335d685d7e3b761c2c4}', 'QCTF{746ffa1fc14609d13dde8d540c5d402a}', 'QCTF{1b92b1e84712dd9084dea96e9f67c659}', 'QCTF{2d8976f6ef6da5b843823940660be68a}', 'QCTF{d1e00391c9bd7c2ecc2b19e6d177e4af}', 'QCTF{cea54a59af20fdfa06c8e8357fec663d}', 'QCTF{1f2b8d5fceea39243fa966d638efc92e}', 'QCTF{0f6faa584c642fc21879f4358fdfb01c}', 'QCTF{acac74237614850fbfbd97410013daa2}', 'QCTF{57fce704c2dbdb5e3034b67a7984bb0c}', 'QCTF{e20bc6c0a13114f7fd29ad9661a946e9}', 'QCTF{92c4dfc79749e9310b7ab64c3d9780d0}', 'QCTF{c6a49485ff92a292f0ae9fca4b1f3314}', 'QCTF{be0f0be2f0fb165a16a62aee2dcd0258}', 'QCTF{052fcc31b1b26484fe9da51fb89ba34d}', 'QCTF{b156eb9c86c03d0fae3c883f5b317dcb}', 'QCTF{ff83da3b5ca61495d0acd623dc2d796e}', 'QCTF{3fce7a6ba38ed1a381dae3686919c902}', 'QCTF{889591a0a7d29579546adaad1d0b5b86}', 'QCTF{9c378d9aa63fca7d5f7f275a9566f264}', 'QCTF{e32a672a6673bc56d8b109952403aae9}', 'QCTF{bc6a3a213102b2dc5f946d5655026352}', 'QCTF{30d04471a675aeeec45b8f6143085f46}', 'QCTF{3b4d06e0c2cd20a177fa277bbbc0a1a2}', 'QCTF{bdf4879a061a3a751f91ece53657a53e}', 'QCTF{d8721fc7d32499aa692b04d7eacc8624}', 'QCTF{09d3580e9431327fbf4ccc53efb0a970}', 'QCTF{814356913a352dfe15b851e52cc55c0d}', 'QCTF{cd9de5c50a3ffb20ea08cb083004252c}', 'QCTF{79de86d819cfc03ac6b98fbc29fac36d}', 'QCTF{63663214499a85208c4f7dc529c05ea5}', 'QCTF{171798109c343a3303020f0a24259e5e}', 'QCTF{611a9181a1f7c45c6c715e494bccd1b9}', 'QCTF{da4e7cc4b461aaedd1bfc45533723b8a}', 'QCTF{2ea7d755b255a6f5376d22f8113a2cfa}', 'QCTF{2a741c8199e13853f8195613ef037ced}', 'QCTF{1b66523f2b665c3dfea91aece42273d3}', 'QCTF{42a46422d8faa1ec3e768580b2dec713}', 'QCTF{ca9d7ac177d049416354a0fbd76a89b9}', 'QCTF{9bb379b6c775b738069ae0ab7accf2dd}', 'QCTF{bacec59ecbc809f7ab27a9169500883a}', 'QCTF{0ef59b9a33046aa124bb87df30934714}', 'QCTF{1b646109ed4bfa30f29d6666b2090701}', 'QCTF{65727e2ba028dc6e9ac572ed6a6ebc6f}', 'QCTF{784c261a9f564d4387d035ce57b05e3e}', 'QCTF{e68fb87f2cad4a3da5799fc982ec82ff}', 'QCTF{ba003b186368bf16c19c71332a95efee}', 'QCTF{6d695ed5a0c2d04722716210b5bcfda6}', 'QCTF{7eb1c12dc09b138a1d7e40058fa7a04a}', 'QCTF{64a545320b2928f88b6c6c27f34d2e3c}', 'QCTF{8cdf05aeb3fa5bb07157db87d2b45755}', 'QCTF{48f8e1742b60e1734f6580ab654f9b6f}', 'QCTF{fb14f2533750f7849b071c9a286c9529}', 'QCTF{47f7996ec34bf04863272d7fc36a1eb1}', 'QCTF{919f49d2f324ae91956c3d97b727c24a}', 'QCTF{336f9d8d23fbb50810c1c0b549ad13bf}', 'QCTF{b316f48f8ed4443a117b7a8752d062cb}', 'QCTF{ea5818adad537c87ddb9ce339c0bbb84}', 'QCTF{d510dfbd781d15b674c63489f55191b2}', 'QCTF{df1d534fcc36d5049b5b607499a74f75}', 'QCTF{2781aa19764810125b745b001dd09090}', 'QCTF{0920b2f44311ed5239e8c2d90c991417}', 'QCTF{da22adea508dc7d5bc9ec5cd5378ef20}', 'QCTF{30f69464f59bf44cba73e6430591acb9}', 'QCTF{2239ffe2985776b1d459a729035e6105}', 'QCTF{07a3846e68534b08abec6761492dfd7c}', 'QCTF{2876a617fcb9d33b1a457e2a1f22982b}', 'QCTF{76471463a11b3f5830d6c98bdc188410}', 'QCTF{64b115efe8a4acaab08f40e83d174953}', 'QCTF{2b9fece3ca12493fa34027cfe34a827d}', 'QCTF{72ceded3364700e5a163cd1fa809f2b5}', 'QCTF{a52ab44fe70adc1964442347fe0bc389}', 'QCTF{ffb4560d742fd8dae61edda32628d5d9}', 'QCTF{fe274231e80419937813cbd55441f8b5}', 'QCTF{38ec71804dca70480b9714ae809bf843}', 'QCTF{2876bb27e398963331099a10e9c1b5b1}', 'QCTF{c8eacb1f0f7ea7a130fe97aa903bc52d}', 'QCTF{91d895637bf21849d8ac97072d9aa66c}', 'QCTF{487a3428ab723d4e9bca30342180612a}', 'QCTF{0ca2e9a4b4fb5298b84a2ae097303615}', 'QCTF{1017c0fad5211fa1a8bd05e2c12e1ab5}', 'QCTF{0772fc3bb68132cc47fc6a26bb23a2eb}', 'QCTF{54808c739cc835327ba82b17dda37765}', 'QCTF{5ba1b7f137a0a269d77db75c1609d015}', 'QCTF{3f59447502e3ccd8db93f57f6b64a869}', 'QCTF{3d33a10890e1797b3518f2032228ef97}', 'QCTF{538226c6e2932fb2c0890fa660707081}', 'QCTF{03dea04fa6f9bf11854a62f92f95028c}', 'QCTF{7ebbc2f97c8e02947eb7537e6e35bf4d}', 'QCTF{7fabc82da5e59469a31d6ae73b0ba8dd}', 'QCTF{99d11087195ac95f9a4bf220346c7ae8}', 'QCTF{6ba3b8dff5b591a308616a485802eb1a}', 'QCTF{73e10bd2e77da35988a91f2b39ba4032}', 'QCTF{d41e8b2244e4e72a04f5229bc61e0a4a}', 'QCTF{1f1c22d0e0dcf0d73b5562f604805060}', 'QCTF{e45fba7380d70df6de5353f6bd1326df}', 'QCTF{c4eb636d6329e437d2ece74b439d905b}', 'QCTF{166f03d5b2a6172ebdfe62790d40ea08}', 'QCTF{c9e2d3fed043ae7ff086944ddb92a595}', 'QCTF{c3683790714524bf741f442cf6f75816}', 'QCTF{c3552856294a7c882abe5bfeb08d40b3}', 'QCTF{2028f8e09d41c758c78b5f1bff9a7730}', 'QCTF{7b28486de1bf56b716f77ab14ac1dc2f}', 'QCTF{e445025dcc35e0f7ad5ffc4c1f736857}', 'QCTF{c977b87449d7461cd45ec2b076754b77}', 'QCTF{9626d8f7759943dedefedffc96ac2489}', 'QCTF{52af66f7f1005968a3057ca76c69b488}', 'QCTF{f7791cfb47893204998bc864a0454767}', 'QCTF{c1325f2049b792f8330ab51d8012138a}', 'QCTF{e6e088ba12752fb97aadaa34ab41b118}', 'QCTF{41051ffcbd702005b7f5c4bae392bb4a}', 'QCTF{58bfe4a9f82ae56f4fab8f2d57470f2f}', 'QCTF{a0ac496ce45f06890c045235eb2547a7}', 'QCTF{0c22482b6a4533ba449d4ec1762494ba}', 'QCTF{4466193f2c65c5d072ecb82277657780}', 'QCTF{43689b43469374eb768fb5d4269be92a}', 'QCTF{e31ff94e5ee5638e7b3c0cde3c2b50dd}', 'QCTF{4cc47b59341b7f0112ba8f4dbdda527c}', 'QCTF{e11501e1bb7da841a2c715eafedccb55}', 'QCTF{6acd2208d0d86fcb796cf8264973fee6}', 'QCTF{d8ee1b7b2772d6aea857929d10fbca8e}', 'QCTF{8c27329ebfdef6480d0c60393a573137}', 'QCTF{b9f5190eb71ca8203f60e2a1a6a652af}', 'QCTF{7e5aa6d503c4c2c944a8148fdf633694}', 'QCTF{9ddcb0e99371e60bbb6cbcae87899fc5}', 'QCTF{e7e75d8e6a4789ea242ece7be93bfc89}', 'QCTF{86546326f5bf721792154c91ede0656d}', 'QCTF{6d36f257d24ee06cc402c3b125d5eaa7}']
def check(attempt, context):
if attempt.answer == flags[attempt.participant.id % len(flags)]:
return checked(True)
if attempt.answer in flags:
return checked_plagiarist(False, flags.index(attempt.answer))
return checked(False)
|
#!/usr/bin/python3.5
def fib(n: int):
fibs = [1, 1]
for _ in range(max(n-2, 0)):
fibs.append(fibs[-1] + fibs[-2])
return fibs[n-1]
print("%s" % fib(38))
|
def fib(n: int):
fibs = [1, 1]
for _ in range(max(n - 2, 0)):
fibs.append(fibs[-1] + fibs[-2])
return fibs[n - 1]
print('%s' % fib(38))
|
"""
Sponge Knowledge Base
Remote API
"""
class UpperCase(Action):
def onConfigure(self):
self.withArg(StringType("text").withLabel("Text to upper case")).withResult(StringType().withLabel("Upper case text"))
def onCall(self, text):
self.logger.info("Action {} called", self.meta.name)
return text.upper()
|
"""
Sponge Knowledge Base
Remote API
"""
class Uppercase(Action):
def on_configure(self):
self.withArg(string_type('text').withLabel('Text to upper case')).withResult(string_type().withLabel('Upper case text'))
def on_call(self, text):
self.logger.info('Action {} called', self.meta.name)
return text.upper()
|
def method1(str1: str, str2: str) -> int:
def compare(str1, str2):
for i in range(256):
if str1[i] != str2[i]:
return False
return True
def search(pat, txt):
m = len(pat)
n = len(txt)
count_p = [0] * 256
count_t = [0] * 256
for i in range(m):
count_p[ord(pat[i])] += 1
count_t[ord(txt[i])] += 1
for i in range(m, n):
if compare(count_p, count_t):
return ("Found at ", i - m)
count_t[ord(txt[i])] += 1
count_t[ord(txt[i-m])] -= 1
if compare(count_p, count_t):
return ("Found at ", n - m)
txt = "thisisastringtocompare"
pat = "thisisiastring"
search(pat, txt)
if __name__ == "__main__":
"""
from timeit import timeit
txt = "thisisastringtocompare"
pat = "thisisiastring"
print(timeit(lambda: method1(pat, txt), number=10000)) # 0.4546106020006846
"""
|
def method1(str1: str, str2: str) -> int:
def compare(str1, str2):
for i in range(256):
if str1[i] != str2[i]:
return False
return True
def search(pat, txt):
m = len(pat)
n = len(txt)
count_p = [0] * 256
count_t = [0] * 256
for i in range(m):
count_p[ord(pat[i])] += 1
count_t[ord(txt[i])] += 1
for i in range(m, n):
if compare(count_p, count_t):
return ('Found at ', i - m)
count_t[ord(txt[i])] += 1
count_t[ord(txt[i - m])] -= 1
if compare(count_p, count_t):
return ('Found at ', n - m)
txt = 'thisisastringtocompare'
pat = 'thisisiastring'
search(pat, txt)
if __name__ == '__main__':
'\n from timeit import timeit\n txt = "thisisastringtocompare"\n pat = "thisisiastring"\n print(timeit(lambda: method1(pat, txt), number=10000)) # 0.4546106020006846\n '
|
# coding=utf8
class Error(Exception):
pass
class TitleRequiredError(Error):
pass
class TextRequiredError(Error):
pass
class APITokenRequiredError(Error):
pass
class GetImageRequestError(Error):
pass
class ImageUploadHTTPError(Error):
pass
class FileTypeNotSupported(Error):
pass
class TelegraphUnknownError(Error):
pass
class TelegraphPageSaveFailed(Error):
# reason is unknown
pass
class TelegraphContentTooBigError(Error):
def __init__(self, message):
message += ". Max size is 64kb including markup"
super(Error, TelegraphError).__init__(self, message)
class TelegraphFloodWaitError(Error):
def __init__(self, message):
super(Error, TelegraphError).__init__(self, message)
self.FLOOD_WAIT_IN_SECONDS = int(message.split('FLOOD_WAIT_')[1])
class TelegraphError(Error):
def __init__(self, message):
if 'Unknown error' in message:
raise TelegraphUnknownError(message)
elif 'Content is too big' in message:
raise TelegraphContentTooBigError(message)
elif 'FLOOD_WAIT_' in message:
raise TelegraphFloodWaitError(message)
elif 'PAGE_SAVE_FAILED' in message:
raise TelegraphPageSaveFailed(message)
else:
super(Error, TelegraphError).__init__(self, message)
|
class Error(Exception):
pass
class Titlerequirederror(Error):
pass
class Textrequirederror(Error):
pass
class Apitokenrequirederror(Error):
pass
class Getimagerequesterror(Error):
pass
class Imageuploadhttperror(Error):
pass
class Filetypenotsupported(Error):
pass
class Telegraphunknownerror(Error):
pass
class Telegraphpagesavefailed(Error):
pass
class Telegraphcontenttoobigerror(Error):
def __init__(self, message):
message += '. Max size is 64kb including markup'
super(Error, TelegraphError).__init__(self, message)
class Telegraphfloodwaiterror(Error):
def __init__(self, message):
super(Error, TelegraphError).__init__(self, message)
self.FLOOD_WAIT_IN_SECONDS = int(message.split('FLOOD_WAIT_')[1])
class Telegrapherror(Error):
def __init__(self, message):
if 'Unknown error' in message:
raise telegraph_unknown_error(message)
elif 'Content is too big' in message:
raise telegraph_content_too_big_error(message)
elif 'FLOOD_WAIT_' in message:
raise telegraph_flood_wait_error(message)
elif 'PAGE_SAVE_FAILED' in message:
raise telegraph_page_save_failed(message)
else:
super(Error, TelegraphError).__init__(self, message)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.