content
stringlengths 7
1.05M
|
---|
"""
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
"""
def count_bits(n):
binaryversion = str(bin(n))
return str(binaryversion[2:]).count("1")
|
#!/usr/bin/env python
# coding: utf-8
# # *section 2: Basic Data Type*
#
# ### writer : Faranak Alikhah 1954128
# ### 4. Lists :
#
# In[ ]:
if __name__ == '__main__':
N = int(input())
my_list=[]
for i in range(N):
A=input().split();
if A[0]=="sort":
my_list.sort();
elif A[0]=="insert":
my_list.insert(int(A[1]),int(A[2]))
elif A[0]=="remove":
my_list.remove(int(A[1]))
elif A[0]=="append":
my_list.append(int(A[1]))
elif A[0]=="pop":
my_list.pop()
elif A[0]=="reverse":
my_list.reverse()
elif A[0]=="print":
print(my_list)
#
|
class Solution:
def hasZeroSumSubarray(self, nums: List[int]) -> bool:
vis = set()
x = 0
for n in nums :
x+=n
if x==0 or x in vis :
return 1
vis.add(x)
return 0
|
# -*- coding: utf-8 -*-
# File defines a single function, a set cookie that takes a configuration
# Use only if the app cannot be imported, otherwise use .cookies
def set_cookie(config, response, key, val):
response.set_cookie(key, val,
secure = config['COOKIES_SECURE'],
httponly = config['COOKIES_HTTPONLY'],
samesite = config['COOKIES_SAMESITE']) |
class Solution:
def minSwaps(self, data: List[int]) -> int:
k = data.count(1)
ones = 0 # ones in window
maxOnes = 0 # max ones in window
for i, num in enumerate(data):
if i >= k and data[i - k]:
ones -= 1
if num:
ones += 1
maxOnes = max(maxOnes, ones)
return k - maxOnes
|
class DNSimpleException(Exception):
def __init__(self, message=None, errors=None):
self.message = message
self.errors = errors
|
polygon = [
[2000, 1333],
[2000, 300],
[500, 900],
[0, 1333],
[2000, 1333]
]
'''
polygon = [
[0, 0],
[0, 600],
[900, 600],
[1800, 0],
[0, 0]
]
''' |
class A:
def __init__(self):
self._x = 5
class B(A):
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main() |
"""
Ideas:
1. The widest container (using first and last line) is a good candidate, because of its width. Its water level is the height of the smaller one of first and last line.
2. All other containers are less wide and thus would need a higher water level in order to hold more water.
3. The smaller one of first and last line doesn't support a higher water level and can thus be safely removed from further consideration.
"""
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i, j = 0, len(height)-1
water = 0
while i < j:
water = max(water, (j-i)*min(height[i],height[j]))
if height[i] < height[j]:
i += 1
else:
j -= 1
return water
|
arr = []
for x in range(100):
arr.append([])
arr[x] = [0 for i in range(100)]
n = int(input())
ans=0
for x in range(n):
a, b, c, d = map(int, input().split())
ans=ans+(c-a+1)*(d-b+1)
print(ans) |
alp = "abcdefghijklmnopqrstuvwxyz"
res = ""
while True:
s = __import__('sys').stdin.readline().strip()
if s == "#":
break
x, y, z = s.split()
t = ""
for i in range(len(x)):
dif = (ord(y[i]) - ord(x[i]) + 26) % 26
t += alp[(ord(z[i]) - ord('a') + dif) % 26]
res += s + " " + t + "\n"
print(res, end="")
|
# Faรงa um Programa que peรงa dois nรบmeros e imprima a soma.
# Ivo Dias
# Recebe os numeros
primeiroNumero = int(input("Informe um numero: "))
segundoNumero = int(input("Informe outro numero: "))
# Faz a soma
soma = primeiroNumero + segundoNumero
# Mostra na tela
print("A soma do numero %s com %s รฉ %s" % (primeiroNumero, segundoNumero, soma)) |
class Day10:
ILLEGAL_CHAR_TO_POINTS = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
def __init__(self, input="src/input/day10.txt"):
self.INPUT = input
def read_input(self):
input = []
with open(self.INPUT, "r") as fp:
lines = fp.readlines()
input = [line.strip() for line in lines]
return input
def part1(self):
input = self.read_input()
# remove all legal chunks
legal_chunks = ["()", "{}", "<>", "[]"]
cleaned_input = []
for line in input:
prev_length = float("inf")
while prev_length > len(line):
prev_length = len(line)
for chunk in legal_chunks:
line = line.replace(chunk, "")
cleaned_input.append(line)
# check if incomplete or illegal
illegal_characters = []
for line in cleaned_input:
for char in line:
if char not in ["(", "{", "<", "["]:
illegal_characters.append(char)
break
return sum([self.ILLEGAL_CHAR_TO_POINTS[char] for char in illegal_characters])
def part2(self):
input = self.read_input()
# remove all legal chunks
legal_chunks = ["()", "{}", "<>", "[]"]
cleaned_input = []
for line in input:
prev_length = float("inf")
while prev_length > len(line):
prev_length = len(line)
for chunk in legal_chunks:
line = line.replace(chunk, "")
cleaned_input.append(line)
# discard corrupted lines
incomplete_input = []
for line in cleaned_input:
closings = [")", "}", ">", "]"]
check = False
for closing in closings:
if closing in line:
check = True
if not check:
incomplete_input.append(line)
# reverse the order
missing_input = [line[::-1] for line in incomplete_input]
# reverse doesn't change opening to closing brackets,
# which is why we use opening brackets to calculate the final score
char_to_points = {
"(": 1,
"[": 2,
"{": 3,
"<": 4,
}
# calculate result
scores = []
for line in missing_input:
score = 0
for char in line:
score *= 5
score += char_to_points[char]
scores.append(score)
# sort scores and return middle
return sorted(scores)[len(scores) // 2]
def execute(self):
print(f"Solution for part 1: {self.part1()}")
print(f"Solution for part 2: {self.part2()}")
if __name__ == "__main__":
Day10().execute()
|
def ways(n, m):
grid = [[None]*m]*n
for i in range(m):
grid[n-1][i] = 1
for i in range(n):
grid[i][m-1] = 1
for i in range(n-2,-1,-1):
for j in range(m-2,-1,-1):
grid[i][j] = grid[i][j+1] + grid[i+1][j]
return grid[0][0]
if __name__ == "__main__":
t = int(input("Number of times you want to run this Program: "))
for i in range(t):
n, m = map(int, input(f"\n{i+1}. Grid Size (n*m): ").split())
result = ways(n, m)
print(f"There are {result} ways.\n")
|
message = input().split()
def asci_change(message):
numbers = [num for num in i if num.isdigit()]
numbers_in_chr = chr(int(''.join(numbers)))
letters = [letter for letter in i if not letter.isdigit()]
letters_split = ''.join(letters)
final_word = numbers_in_chr + str(letters_split)
return final_word
def index_change(message):
letters = [letter for letter in j]
letters[1], letters[-1] = letters[-1], letters[1]
letters_split = ''.join(letters)
return letters_split
index_i = 0
for i in message:
message[index_i] = asci_change(message)
index_i += 1
index_j = 0
for j in message:
message[index_j] = index_change(message)
index_j += 1
print(' '.join(message)) |
star_wars = [125, 1977]
raiders = [115, 1981]
mean_girls = [97, 2004]
def distance(movie1, movie2):
length_difference = (movie1[0] - movie2[0]) ** 2
year_difference = (movie1[1] - movie2[1]) ** 2
distance = (length_difference + year_difference) ** 0.5
return distance
print(distance(star_wars, raiders))
print(distance(star_wars, mean_girls)) |
# Annotaion(ํจ์๋ ํด๋์ค์ ์ธ์๊ฐ ๋๋ ๋ฐํ๊ฐ์ ํํ๋ฅผ ์๋ ค์ฃผ๊ธฐ ์ํด ํ์
์ ์ง์ ํ๋ ๋ฐฉ๋ฒ)์ ์ํ ํด๋์ค
# bool ํ์
์ ok
class BooleanOk:
@staticmethod
def __type__():
return bool
# dict ํ์
์ uses
class DictionaryUser:
@staticmethod
def __type__():
fields = {
"_id": str,
"user_id": str,
"user_name": str,
"user_passwd": str
}
return fields
# dict ํ์
์ payload
class DictionaryPayload:
@staticmethod
def __type__():
fields = {
"user_id": str,
"user_name": str,
}
return fields
# string ํ์
์ token
class StringToken:
@staticmethod
def __type__():
return str
# string ํ์
์ user_id
class StringUserId:
@staticmethod
def __type__():
return str
# string ํ์
์ message
class StringMessage:
@staticmethod
def __type__():
return str
# string ํ์
์ objectId
class StringObjectId:
@staticmethod
def __type__():
return str
# list ํ์
์ words
class ArrayWords:
@staticmethod
def __type__():
return str
|
def get_distribution_steps(distribution):
i = 0
distributed_loaves = 0
while i < len(distribution):
if distribution[i] % 2 == 0:
i += 1
continue
next_item_index = i + 1
if next_item_index == len(distribution):
return -1
distribution[next_item_index] += 1
distributed_loaves += 2
i += 1
return distributed_loaves
N = int(input().strip())
current_distribution = [
int(B_temp)
for B_temp
in input().strip().split(' ')
]
steps = get_distribution_steps(current_distribution)
print(steps if steps != -1 else 'NO')
|
class File:
def __init__(
self,
name: str,
display_str: str,
short_status: str,
has_staged_change: bool,
has_unstaged_change: bool,
tracked: bool,
deleted: bool,
added: bool,
has_merged_conflicts: bool,
has_inline_merged_conflicts: bool,
) -> None:
self.name = name
self.display_str = display_str
self.short_status = short_status
self.has_staged_change = has_staged_change
self.has_unstaged_change = has_unstaged_change
self.tracked = tracked
self.deleted = deleted
self.added = added
self.has_merged_conflicts = has_merged_conflicts
self.has_inline_merged_conflicts = has_inline_merged_conflicts
|
with open('input') as f:
instructions = []
for line in f:
op, arg = line.split()
instructions.append((op, int(arg)))
# Part 1
executed = [False] * len(instructions)
accumulator = 0
i = 0
while i < len(instructions):
if executed[i]: break
executed[i] = True
op, n = instructions[i]
if op == 'acc':
accumulator += n
i += 1
elif op == 'jmp':
i += n
elif op == 'nop':
i += 1
else:
print('invalid operator')
exit(1)
print(accumulator)
# Part 2
mod = ['jmp', 'nop']
def fix(j):
executed = [False] * len(instructions)
accumulator = 0
i = 0
while i < len(instructions):
if executed[i]:
return False
executed[i] = True
op, n = instructions[i]
if i == j:
op = mod[mod.index(op) ^ 1] # Swap
if op == 'acc':
accumulator += n
i += 1
elif op == 'jmp':
i += n
elif op == 'nop':
i += 1
else:
print('invalid operator')
exit(1)
return accumulator
for i, (op, _) in enumerate(instructions):
if op in mod:
res = fix(i)
if res != False:
print(res)
break
|
# encoding: utf-8
SECRET_KEY = 'a unique and long key'
TITLE = 'Riki'
HISTORY_SHOW_MAX = 30
PIC_BASE = '/static/content/'
CONTENT_DIR = '///D:\\School\\Riki\\content'
USER_DIR = '///D:\\School\\Riki\\user'
NUMBER_OF_HISTORY = 5
PRIVATE = False
|
###############################################################
# LeetCode Problem Number : 622
# Difficulty Level : Medium
# URL : https://leetcode.com/problems/design-circular-queue/
###############################################################
class CircularQueue:
def __init__(self, size):
"""initialize your data structure here"""
self.max_size = size
""" set head and tail pointer to -1 """
self.head = -1
self.tail = -1
""" initialize internal array """
self.data = [[] for _ in range(size)]
def isEmpty(self) -> bool:
"""checks whether the circular queue is empty or not"""
return self.computeSize() == 0
def isFull(self) -> bool:
"""checks whether the circular queue is full or not"""
return self.computeSize() == self.max_size
def enqueue(self, val: int) -> bool:
"""insert an element into the circular queue
return true if the operation is successful
"""
if self.isFull():
return False
""" move tail pointer to the next valid index
example : max_size : 5, tail : 2, next tail : 3
max_size : 5, tail : 4, next tail : 0
"""
self.tail = (self.tail + 1) % self.max_size
self.data[self.tail] = val
""" for the first enqueue operation, set head to point to tail """
if self.head == -1:
self.head = self.tail
return True
def dequeue(self) -> bool:
"""delete an element from the circular queue
return true if the operation is successful
"""
if self.isEmpty():
return False
self.data[self.head] = None
""" if empty queue, set head to -1
else move head to the next valid insert position
"""
self.head = -1 if self.computeSize() == 1 else (self.head + 1) % self.max_size
""" reset tail pointer for an empty queue """
if self.head == -1:
self.tail = -1
return True
def front(self) -> int:
"""get the front item from the queue"""
if self.isEmpty():
return -1
""" return value pointed by head pointer """
return self.data[self.head]
def rear(self) -> int:
"""get the last item from the queue"""
if self.isEmpty():
return -1
""" return value pointed by tail pointer """
return self.data[self.tail]
def computeSize(self) -> int:
""" queue is empty if head pointer is set to -1 """
if self.head == -1:
return 0
""" if both head and tail pointers are set to the same index,
then queue has only 1 item
"""
if self.tail == self.head:
return 1
""" if tail points to an index after head, then current size : (tail - head) + 1
if tail points to an index before head, then current size : (tail - head) + 1 + max-size
"""
diff = self.tail - self.head
return diff + 1 if diff > 0 else diff + 1 + self.max_size
def executeCommands(self, command: str, operands: list):
"""Automate execution of large number of operations to test implementation.
Not part of main queue implementation.
"""
if command == "enQueue":
return self.enqueue(operands[0])
elif command == "deQueue":
return self.dequeue()
elif command == "Rear":
return self.rear()
elif command == "Front":
return self.front()
elif command == "isFull":
return self.isFull()
elif command == "isEmpty":
return self.isEmpty()
return
|
while True:
T = int(input('Digite um nรบmero para mostrar a tabuada:'))
if T > 0:
print(f"""{T} X 1 = {T*1}
{T} X 2 = {T*2}
{T} X 3 = {T*3}
{T} X 4 = {T*4}
{T} X 5 = {T*5}
{T} X 6 = {T*6}
{T} X 7 = {T*7}
{T} X 8 = {T*8}
{T} X 9 = {T*9}
{T} X 10 = {T*10}""")
elif T < 0:
break
print('Obrigado por usar a tabuada, volte sempre!')
|
"""
STIX 2.0 open vocabularies and enums
"""
ATTACK_MOTIVATION_ACCIDENTAL = "accidental"
ATTACK_MOTIVATION_COERCION = "coercion"
ATTACK_MOTIVATION_DOMINANCE = "dominance"
ATTACK_MOTIVATION_IDEOLOGY = "ideology"
ATTACK_MOTIVATION_NOTORIETY = "notoriety"
ATTACK_MOTIVATION_ORGANIZATIONAL_GAIN = "organizational-gain"
ATTACK_MOTIVATION_PERSONAL_GAIN = "personal-gain"
ATTACK_MOTIVATION_PERSONAL_SATISFACTION = "personal-satisfaction"
ATTACK_MOTIVATION_REVENGE = "revenge"
ATTACK_MOTIVATION_UNPREDICTABLE = "unpredictable"
ATTACK_MOTIVATION = [
ATTACK_MOTIVATION_ACCIDENTAL,
ATTACK_MOTIVATION_COERCION,
ATTACK_MOTIVATION_DOMINANCE,
ATTACK_MOTIVATION_IDEOLOGY,
ATTACK_MOTIVATION_NOTORIETY,
ATTACK_MOTIVATION_ORGANIZATIONAL_GAIN,
ATTACK_MOTIVATION_PERSONAL_GAIN,
ATTACK_MOTIVATION_PERSONAL_SATISFACTION,
ATTACK_MOTIVATION_REVENGE,
ATTACK_MOTIVATION_UNPREDICTABLE,
]
ATTACK_RESOURCE_LEVEL_INDIVIDUAL = "individual"
ATTACK_RESOURCE_LEVEL_CLUB = "club"
ATTACK_RESOURCE_LEVEL_CONTEST = "contest"
ATTACK_RESOURCE_LEVEL_TEAM = "team"
ATTACK_RESOURCE_LEVEL_ORGANIZATION = "organization"
ATTACK_RESOURCE_LEVEL_GOVERNMENT = "government"
ATTACK_RESOURCE_LEVEL = [
ATTACK_RESOURCE_LEVEL_INDIVIDUAL,
ATTACK_RESOURCE_LEVEL_CLUB,
ATTACK_RESOURCE_LEVEL_CONTEST,
ATTACK_RESOURCE_LEVEL_TEAM,
ATTACK_RESOURCE_LEVEL_ORGANIZATION,
ATTACK_RESOURCE_LEVEL_GOVERNMENT,
]
HASHING_ALGORITHM_MD5 = "MD5"
HASHING_ALGORITHM_MD6 = "MD6"
HASHING_ALGORITHM_RIPEMD_160 = "RIPEMD-160"
HASHING_ALGORITHM_SHA_1 = "SHA-1"
HASHING_ALGORITHM_SHA_224 = "SHA-224"
HASHING_ALGORITHM_SHA_256 = "SHA-256"
HASHING_ALGORITHM_SHA_384 = "SHA-384"
HASHING_ALGORITHM_SHA_512 = "SHA-512"
HASHING_ALGORITHM_SHA3_224 = "SHA3-224"
HASHING_ALGORITHM_SHA3_256 = "SHA3-256"
HASHING_ALGORITHM_SHA3_384 = "SHA3-384"
HASHING_ALGORITHM_SHA3_512 = "SHA3-512"
HASHING_ALGORITHM_SSDEEP = "ssdeep"
HASHING_ALGORITHM_WHIRLPOOL = "WHIRLPOOL"
HASHING_ALGORITHM = [
HASHING_ALGORITHM_MD5,
HASHING_ALGORITHM_MD6,
HASHING_ALGORITHM_RIPEMD_160,
HASHING_ALGORITHM_SHA_1,
HASHING_ALGORITHM_SHA_224,
HASHING_ALGORITHM_SHA_256,
HASHING_ALGORITHM_SHA_384,
HASHING_ALGORITHM_SHA_512,
HASHING_ALGORITHM_SHA3_224,
HASHING_ALGORITHM_SHA3_256,
HASHING_ALGORITHM_SHA3_384,
HASHING_ALGORITHM_SHA3_512,
HASHING_ALGORITHM_SSDEEP,
HASHING_ALGORITHM_WHIRLPOOL,
]
IDENTITY_CLASS_INDIVIDUAL = "individual"
IDENTITY_CLASS_GROUP = "group"
IDENTITY_CLASS_ORGANIZATION = "organization"
IDENTITY_CLASS_CLASS = "class"
IDENTITY_CLASS_UNKNOWN = "unknown"
IDENTITY_CLASS = [
IDENTITY_CLASS_INDIVIDUAL,
IDENTITY_CLASS_GROUP,
IDENTITY_CLASS_ORGANIZATION,
IDENTITY_CLASS_CLASS,
IDENTITY_CLASS_UNKNOWN,
]
INDICATOR_LABEL_ANOMALOUS_ACTIVITY = "anomalous-activity"
INDICATOR_LABEL_ANONYMIZATION = "anonymization"
INDICATOR_LABEL_BENIGN = "benign"
INDICATOR_LABEL_COMPROMISED = "compromised"
INDICATOR_LABEL_MALICIOUS_ACTIVITY = "malicious-activity"
INDICATOR_LABEL_ATTRIBUTION = "attribution"
INDICATOR_LABEL = [
INDICATOR_LABEL_ANOMALOUS_ACTIVITY,
INDICATOR_LABEL_ANONYMIZATION,
INDICATOR_LABEL_BENIGN,
INDICATOR_LABEL_COMPROMISED,
INDICATOR_LABEL_MALICIOUS_ACTIVITY,
INDICATOR_LABEL_ATTRIBUTION,
]
INDUSTRY_SECTOR_AGRICULTURE = "agriculture"
INDUSTRY_SECTOR_AEROSPACE = "aerospace"
INDUSTRY_SECTOR_AUTOMOTIVE = "automotive"
INDUSTRY_SECTOR_COMMUNICATIONS = "communications"
INDUSTRY_SECTOR_CONSTRUCTION = "construction"
INDUSTRY_SECTOR_DEFENCE = "defence"
INDUSTRY_SECTOR_EDUCATION = "education"
INDUSTRY_SECTOR_ENERGY = "energy"
INDUSTRY_SECTOR_ENTERTAINMENT = "entertainment"
INDUSTRY_SECTOR_FINANCIAL_SERVICES = "financial-services"
INDUSTRY_SECTOR_GOVERNMENT_NATIONAL = "government-national"
INDUSTRY_SECTOR_GOVERNMENT_REGIONAL = "government-regional"
INDUSTRY_SECTOR_GOVERNMENT_LOCAL = "government-local"
INDUSTRY_SECTOR_GOVERNMENT_PUBLIC_SERVICES = "government-public-services"
INDUSTRY_SECTOR_HEALTHCARE = "healthcare"
INDUSTRY_SECTOR_HOSPITALITY_LEISURE = "hospitality-leisure"
INDUSTRY_SECTOR_INFRASTRUCTURE = "infrastructure"
INDUSTRY_SECTOR_INSURANCE = "insurance"
INDUSTRY_SECTOR_MANUFACTURING = "manufacturing"
INDUSTRY_SECTOR_MINING = "mining"
INDUSTRY_SECTOR_NON_PROFIT = "non-profit"
INDUSTRY_SECTOR_PHARMACEUTICALS = "pharmaceuticals"
INDUSTRY_SECTOR_RETAIL = "retail"
INDUSTRY_SECTOR_TECHNOLOGY = "technology"
INDUSTRY_SECTOR_TELECOMMUNICATIONS = "telecommunications"
INDUSTRY_SECTOR_TRANSPORTATION = "transportation"
INDUSTRY_SECTOR_UTILITIES = "utilities"
INDUSTRY_SECTOR = [
INDUSTRY_SECTOR_AGRICULTURE,
INDUSTRY_SECTOR_AEROSPACE,
INDUSTRY_SECTOR_AUTOMOTIVE,
INDUSTRY_SECTOR_COMMUNICATIONS,
INDUSTRY_SECTOR_CONSTRUCTION,
INDUSTRY_SECTOR_DEFENCE,
INDUSTRY_SECTOR_EDUCATION,
INDUSTRY_SECTOR_ENERGY,
INDUSTRY_SECTOR_ENTERTAINMENT,
INDUSTRY_SECTOR_FINANCIAL_SERVICES,
INDUSTRY_SECTOR_GOVERNMENT_NATIONAL,
INDUSTRY_SECTOR_GOVERNMENT_REGIONAL,
INDUSTRY_SECTOR_GOVERNMENT_LOCAL,
INDUSTRY_SECTOR_GOVERNMENT_PUBLIC_SERVICES,
INDUSTRY_SECTOR_HEALTHCARE,
INDUSTRY_SECTOR_HOSPITALITY_LEISURE,
INDUSTRY_SECTOR_INFRASTRUCTURE,
INDUSTRY_SECTOR_INSURANCE,
INDUSTRY_SECTOR_MANUFACTURING,
INDUSTRY_SECTOR_MINING,
INDUSTRY_SECTOR_NON_PROFIT,
INDUSTRY_SECTOR_PHARMACEUTICALS,
INDUSTRY_SECTOR_RETAIL,
INDUSTRY_SECTOR_TECHNOLOGY,
INDUSTRY_SECTOR_TELECOMMUNICATIONS,
INDUSTRY_SECTOR_TRANSPORTATION,
INDUSTRY_SECTOR_UTILITIES,
]
MALWARE_LABEL_ADWARE = "adware"
MALWARE_LABEL_BACKDOOR = "backdoor"
MALWARE_LABEL_BOT = "bot"
MALWARE_LABEL_DDOS = "ddos"
MALWARE_LABEL_DROPPER = "dropper"
MALWARE_LABEL_EXPLOIT_KIT = "exploit-kit"
MALWARE_LABEL_KEYLOGGER = "keylogger"
MALWARE_LABEL_RANSOMWARE = "ransomware"
MALWARE_LABEL_REMOTE_ACCESS_TROJAN = "remote-access-trojan"
MALWARE_LABEL_RESOURCE_EXPLOITATION = "resource-exploitation"
MALWARE_LABEL_ROGUE_SECURITY_SOFTWARE = "rogue-security-software"
MALWARE_LABEL_ROOTKIT = "rootkit"
MALWARE_LABEL_SCREEN_CAPTURE = "screen-capture"
MALWARE_LABEL_SPYWARE = "spyware"
MALWARE_LABEL_TROJAN = "trojan"
MALWARE_LABEL_VIRUS = "virus"
MALWARE_LABEL_WORM = "worm"
MALWARE_LABEL = [
MALWARE_LABEL_ADWARE,
MALWARE_LABEL_BACKDOOR,
MALWARE_LABEL_BOT,
MALWARE_LABEL_DDOS,
MALWARE_LABEL_DROPPER,
MALWARE_LABEL_EXPLOIT_KIT,
MALWARE_LABEL_KEYLOGGER,
MALWARE_LABEL_RANSOMWARE,
MALWARE_LABEL_REMOTE_ACCESS_TROJAN,
MALWARE_LABEL_RESOURCE_EXPLOITATION,
MALWARE_LABEL_ROGUE_SECURITY_SOFTWARE,
MALWARE_LABEL_ROOTKIT,
MALWARE_LABEL_SCREEN_CAPTURE,
MALWARE_LABEL_SPYWARE,
MALWARE_LABEL_TROJAN,
MALWARE_LABEL_VIRUS,
MALWARE_LABEL_WORM,
]
REPORT_LABEL_THREAT_REPORT = "threat-report"
REPORT_LABEL_ATTACK_PATTERN = "attack-pattern"
REPORT_LABEL_CAMPAIGN = "campaign"
REPORT_LABEL_IDENTITY = "identity"
REPORT_LABEL_INDICATOR = "indicator"
REPORT_LABEL_INTRUSION_SET = "intrusion-set"
REPORT_LABEL_MALWARE = "malware"
REPORT_LABEL_OBSERVED_DATA = "observed-data"
REPORT_LABEL_THREAT_ACTOR = "threat-actor"
REPORT_LABEL_TOOL = "tool"
REPORT_LABEL_VULNERABILITY = "vulnerability"
REPORT_LABEL = [
REPORT_LABEL_THREAT_REPORT,
REPORT_LABEL_ATTACK_PATTERN,
REPORT_LABEL_CAMPAIGN,
REPORT_LABEL_IDENTITY,
REPORT_LABEL_INDICATOR,
REPORT_LABEL_INTRUSION_SET,
REPORT_LABEL_MALWARE,
REPORT_LABEL_OBSERVED_DATA,
REPORT_LABEL_THREAT_ACTOR,
REPORT_LABEL_TOOL,
REPORT_LABEL_VULNERABILITY,
]
THREAT_ACTOR_LABEL_ACTIVIST = "activist"
THREAT_ACTOR_LABEL_COMPETITOR = "competitor"
THREAT_ACTOR_LABEL_CRIME_SYNDICATE = "crime-syndicate"
THREAT_ACTOR_LABEL_CRIMINAL = "criminal"
THREAT_ACTOR_LABEL_HACKER = "hacker"
THREAT_ACTOR_LABEL_INSIDER_ACCIDENTAL = "insider-accidental"
THREAT_ACTOR_LABEL_INSIDER_DISGRUNTLED = "insider-disgruntled"
THREAT_ACTOR_LABEL_NATION_STATE = "nation-state"
THREAT_ACTOR_LABEL_SENSATIONALIST = "sensationalist"
THREAT_ACTOR_LABEL_SPY = "spy"
THREAT_ACTOR_LABEL_TERRORIST = "terrorist"
THREAT_ACTOR_LABEL = [
THREAT_ACTOR_LABEL_ACTIVIST,
THREAT_ACTOR_LABEL_COMPETITOR,
THREAT_ACTOR_LABEL_CRIME_SYNDICATE,
THREAT_ACTOR_LABEL_CRIMINAL,
THREAT_ACTOR_LABEL_HACKER,
THREAT_ACTOR_LABEL_INSIDER_ACCIDENTAL,
THREAT_ACTOR_LABEL_INSIDER_DISGRUNTLED,
THREAT_ACTOR_LABEL_NATION_STATE,
THREAT_ACTOR_LABEL_SENSATIONALIST,
THREAT_ACTOR_LABEL_SPY,
THREAT_ACTOR_LABEL_TERRORIST,
]
THREAT_ACTOR_ROLE_AGENT = "agent"
THREAT_ACTOR_ROLE_DIRECTOR = "director"
THREAT_ACTOR_ROLE_INDEPENDENT = "independent"
THREAT_ACTOR_ROLE_INFRASTRUCTURE_ARCHITECT = "infrastructure-architect"
THREAT_ACTOR_ROLE_INFRASTRUCTURE_OPERATOR = "infrastructure-operator"
THREAT_ACTOR_ROLE_MALWARE_AUTHOR = "malware-author"
THREAT_ACTOR_ROLE_SPONSOR = "sponsor"
THREAT_ACTOR_ROLE = [
THREAT_ACTOR_ROLE_AGENT,
THREAT_ACTOR_ROLE_DIRECTOR,
THREAT_ACTOR_ROLE_INDEPENDENT,
THREAT_ACTOR_ROLE_INFRASTRUCTURE_ARCHITECT,
THREAT_ACTOR_ROLE_INFRASTRUCTURE_OPERATOR,
THREAT_ACTOR_ROLE_MALWARE_AUTHOR,
THREAT_ACTOR_ROLE_SPONSOR,
]
THREAT_ACTOR_SOPHISTICATION_NONE = "none"
THREAT_ACTOR_SOPHISTICATION_MINIMAL = "minimal"
THREAT_ACTOR_SOPHISTICATION_INTERMEDIATE = "intermediate"
THREAT_ACTOR_SOPHISTICATION_ADVANCED = "advanced"
THREAT_ACTOR_SOPHISTICATION_EXPERT = "expert"
THREAT_ACTOR_SOPHISTICATION_INNOVATOR = "innovator"
THREAT_ACTOR_SOPHISTICATION_STRATEGIC = "strategic"
THREAT_ACTOR_SOPHISTICATION = [
THREAT_ACTOR_SOPHISTICATION_NONE,
THREAT_ACTOR_SOPHISTICATION_MINIMAL,
THREAT_ACTOR_SOPHISTICATION_INTERMEDIATE,
THREAT_ACTOR_SOPHISTICATION_ADVANCED,
THREAT_ACTOR_SOPHISTICATION_EXPERT,
THREAT_ACTOR_SOPHISTICATION_INNOVATOR,
THREAT_ACTOR_SOPHISTICATION_STRATEGIC,
]
TOOL_LABEL_DENIAL_OF_SERVICE = "denial-of-service"
TOOL_LABEL_EXPLOITATION = "exploitation"
TOOL_LABEL_INFORMATION_GATHERING = "information-gathering"
TOOL_LABEL_NETWORK_CAPTURE = "network-capture"
TOOL_LABEL_CREDENTIAL_EXPLOITATION = "credential-exploitation"
TOOL_LABEL_REMOTE_ACCESS = "remote-access"
TOOL_LABEL_VULNERABILITY_SCANNING = "vulnerability-scanning"
TOOL_LABEL = [
TOOL_LABEL_DENIAL_OF_SERVICE,
TOOL_LABEL_EXPLOITATION,
TOOL_LABEL_INFORMATION_GATHERING,
TOOL_LABEL_NETWORK_CAPTURE,
TOOL_LABEL_CREDENTIAL_EXPLOITATION,
TOOL_LABEL_REMOTE_ACCESS,
TOOL_LABEL_VULNERABILITY_SCANNING,
]
|
#!/usr/bin/env python
OUTPUT_FILENAME = "output"
TOTAL_OF_FILES = 2
if __name__ == "__main__":
# make an array of files of size 100
results = []
for i in range(1, TOTAL_OF_FILES+1):
a = open("./{}{}.txt".format(OUTPUT_FILENAME, i), 'r')
text = a.read()
a.close()
text = text.split('\n')
results.append(text[1:-2])
text = "Original_variable | real_parameters | number_of_observations | log-likelihood_of_real_params | Estim_params_T2_SSPSC | log-likelihood_T2_SSPSC | p-value_T2_SSPSC | Estim_params_T2_StSI | log-likelihood_T2_StSI | p-value_T2_StSI | AIC_selected_model | AIC_relative_prob\n"
for line in range(len(results[0])):
for i in range(TOTAL_OF_FILES):
text+=(i+1).__str__() + ' | ' + results[i][line]+'\n'
a = open('100exp_OUTPUT', 'w')
a.write(text)
a.close()
|
def func(word):
word = word.split(", ")
dic = {"Magic":[],"Normal":[]}
for elm in word:
decide = ""
first = elm[0]
first = int(first)
sum1 = 0
for sval in elm[1::]:
sum1 += int(sval)
if first == sum1:
decide = "Magic"
else:
decide = "Normal"
dic[decide].append(int(elm))
fdic = {}
for key,val in dic.items():
fdic[key] = tuple(val)
return fdic
word = input("Enter your numbers: ")
print(func(word))
|
def contador(i,f,p):
"""
Faz a contagem e mostra na tela
:param i: inicio da contagem
:param f: fim da contagem
:param p: passo da contagem
:return: sem retorno
"""
c=i
while c<=f:
print(f'{c} ', end='')
c +=p
print('FIMMM')
contador(2,10,2)
help(contador)
|
#!/usr/bin/python3
#-*- coding: utf8 -*-
# @author : Sรฉbastien LOZANO
"""
Gรฉnรฉrer les parties communes aux fichiers HTML.
On met les constantes dans des chaรฎnes.
"""
pass
docTypeHead = (
"""
<!doctype html>
<html lang=\"fr\">
<head>
<meta charset=\"UTF-8\">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>DNB-APMEP-MATHALEA</title>
</head>
"""
)
style = (
"""
<style>
</style>
"""
)
docTypeHeadStyle = (
"""
<!doctype html>
<html lang=\"fr\">
<head>
<meta charset=\"UTF-8\">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Projet DNB APMEP MATHALEA</title>
<style>
.navButton {
display: inline-block;
border-radius: 4px;
background-color: #ff7f00;
color: #FFFFFF;
text-align: center;
font-size: 1rem;
padding: 0.75rem;
width: auto;
transition: all 0.5s;
margin: 0.3rem;
}
.navButton {
font-weight: bold;
}
.navButton {
border: none;
cursor: pointer;
}
.navButton span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
.navButton span:after {
content: '\\00bb';
position: absolute;
opacity: 0;
top: 0;
right: -1.25rem;
transition: 0.5s;
}
.navButton:hover span {
padding-right: 1.5rem;
}
.navButton:hover span:after {
opacity: 1;
right: 0;
}
</style>
</head>
"""
)
barreDeNavigation = (
"""
<h1>PROJET DNB APMEP MATHALEA</h1>
<hr>
<h4>Source des donnรฉes : <a href=\"https://www.apmep.fr/-Brevet-289-sujets-tous-corriges-\" target=\"_blank\">https://www.apmep.fr/-Brevet-289-sujets-tous-corriges-</a></h4>
<hr>
<a class="navButton" href=\"index.html\" target=\"_self\"><span>Accueil</span></a>
<a class="navButton" href=\"../docs/pyPack/index.html\" target=\"_blank\"><span>Documentation</span></a>
<hr>
"""
) |
class Node:
def __init__(self, data):
self.data = data # Assign the data here
self.next = None # Set next to None by default.
class LinkedList:
def __init__(self):
self.head = None
# Display the list. Linked list traversal.
def display(self):
temp = self.head
display = ""
while temp:
display+=(str(temp.data)+" -> ")
temp = temp.next
display+="None"
print(display)
def push(self, data):
# Create the new node before we insert it at the beginning of the LL
new_node = Node(data)
# Assign the next pointer to the head
new_node.next = self.head
# Move the head pointer to the new node.
self.head = new_node
def append(self, data):
# Inserting data at the end of the linked list.
new_node = Node(data)
if self.head == None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def insert(self, previous_node, data):
if previous_node == None:
return
# Create a new node with new data
new_node = Node(data)
new_node.next = previous_node.next
previous_node.next = new_node
# Tests
# Initialize linked list
llist = LinkedList()
# Create some nodes.
llist.push(2)
llist.push(3)
llist.push(4)
llist.append(1)
llist.display()
|
"""This program takes a score between 0.0 and 1.0 and
returns an appropriate grade for score inputted"""
try:
grade = float(input('Enter your score: '))
if grade < 0.6:
print('Your score', grade, 'is F')
elif 0.6 <= grade <= 0.7:
print('Your score', grade, 'is D')
elif 0.7 <= grade <= 0.8:
print('Your score', grade, 'is C')
elif 0.8 <= grade <= 0.9:
print('Your score', grade, 'is B')
elif 0.9 <= grade <= 1.0:
print('Your score', grade, 'is A')
elif grade > 1.0:
print('Your score', grade, 'is out of range')
except:
print('Bad score') |
# You can gen a bcrypt hash here:
## http://bcrypthashgenerator.apphb.com/
pwhash = 'bcrypt'
# You can generate salts and other secrets with openssl
# For example:
# $ openssl rand -hex 16
# 1ca632d8567743f94352545abe2e313d
salt = "141202e6b20aa53596a339a0d0b92e79"
secret_key = 'fe65757e00193b8bc2e18444fa51d873'
mongo_db = 'mydatabase'
mongo_host = 'localhost'
mongo_port = 27017
user_enable_registration = True
user_enable_tracking = True
user_from_email = "[email protected]"
user_register_email_subject = "Thank you for signing up"
mail_url = "mail.yoursite.com"
mail_port = "25"
mail_SSL = False
mail_TLS = False
mail_user = "username_goes_here"
mail_pass = "password_goes_here"
|
'''
* ์ค๋ฆ์ฐจ์์ด ์ด๋ฏ๋ก max๋ฅผ ์ฒดํฌํ ํ์๊ฐ ์๋ค.
'''
N = int(input())
data = list(map(int, input().split()))
data.sort()
# debug
print(N)
print(data)
result = 0
max = 0
count = 0
for num in data:
if max == 0:
max = num
elif max < num:
max = num
count += 1
if max == count:
result += 1
max = 0
count = 0
print(result)
'''
5
2 3 1 2 2
10
1 2 3 4 3 2 1 2 5 7
20
1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 5 5 5 6
'''
'''
<Answer>
n = int(input())
data = list(map(int, input().split()))
data.sort()
result = 0 # ์ด ๊ทธ๋ฃน์ ์
count = 0 # ํ์ฌ ๊ทธ๋ฃน์ ํฌํจ๋ ๋ชจํ๊ฐ์ ์
for i in data:
count += 1 # ํ์ฌ ๊ทธ๋ฃน์ ํด๋น ๋ชจํ๊ฐ๋ฅผ ํฌํจ์ํค๊ธฐ
if count >= i: # ํ์ฌ ๊ทธ๋ฃน์ ํฌํจ๋ ๋ชจํ๊ฐ์ ์๊ฐ ํ์ฌ์ ๊ณตํฌ๋ ์ด์์ด๋ผ๋ฉด, ๊ทธ๋ฃน ๊ฒฐ์ฑ
result += 1 # ์ด ๊ทธ๋ฃน์ ์ ์ฆ๊ฐ์ํค๊ธฐ
count = 0 # ํ์ฌ ๊ทธ๋ฃน์ ํฌํจ๋ ๋ชจํ๊ฐ์ ์ ์ด๊ธฐํ
print(result) # ์ด ๊ทธ๋ฃน์ ์ ์ถ๋ ฅ
''' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def shell_sort(list_: list) -> list:
"""Returns a sorted list, by shell sort method
:param list_: The list to be sorted
:type list_: list
:rtype: list
:return: Sorted list, by shell sort method
"""
half = len(list_) // 2
while half > 0:
for i in range(half, len(list_)):
tmp = list_[i]
j = i
while j >= half and list_[j - half] > tmp:
list_[j] = list_[j - half]
j -= half
list_[j] = tmp
half //= 2
return list_
|
sbox = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A,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0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56,
0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d,
0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d] |
"""
Syntax Scoring
https://adventofcode.com/2021/day/10
"""
MATCHES = {
'<': '>',
'(': ')',
'{': '}',
'[': ']'
}
ERROR_SCORE = {
')': 3,
']': 57,
'}': 1197,
'>': 25137,
}
AUTOCOMPLETE_SCORE = {
')': 1,
']': 2,
'}': 3,
'>': 4,
}
def find_error(line):
"""returns error score and remaining stack"""
stack = []
for char in line:
if char in '[({<':
stack.append(char)
else:
m = stack.pop()
match = MATCHES[m]
if char != match:
return ERROR_SCORE[char], []
return 0, stack
def autocomplete(stack):
prod = 0
for char in stack[::-1]:
prod *= 5
prod += AUTOCOMPLETE_SCORE[MATCHES[char]]
return prod
def solve(data):
total = 0
for line in data.strip().split('\n'):
score, _ = find_error(line)
total += score
return total
def solve2(data):
autos = []
for line in data.strip().split('\n'):
score, stack = find_error(line)
if score == 0:
autos.append(autocomplete(stack))
autos.sort()
middle = len(autos) // 2
return autos[middle]
if __name__ == '__main__':
input_data = open('input_data.txt').read()
result = solve(input_data)
print(f'Example 1: {result}')
# 268845
result = solve2(input_data)
print(f'Example 2: {result}')
# 4038824534 |
TAG_TYPE = "#type"
TAG_XML = "#xml"
TAG_VERSION = "@version"
TAG_UIVERSION = "@uiVersion"
TAG_NAMESPACE = "@xmlns"
TAG_NAME = "@name"
TAG_META = "meta"
TAG_FORM = 'form'
ATTACHMENT_NAME = "form.xml"
MAGIC_PROPERTY = 'xml_submission_file'
RESERVED_WORDS = [TAG_TYPE, TAG_XML, TAG_VERSION, TAG_UIVERSION, TAG_NAMESPACE,
TAG_NAME, TAG_META, ATTACHMENT_NAME, 'case', MAGIC_PROPERTY]
DEVICE_LOG_XMLNS = 'http://code.javarosa.org/devicereport'
|
def Merge_Sort(list):
n= len(list)
if n > 1 :
mid = int(n/2)
left =list[0:mid]
right = list[mid:n]
Merge_Sort(left)
Merge_Sort(right)
Merge (left, right, list)
return list
def Merge(left, right, list):
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
list[k] = left[i]
i = i + 1
else :
list[k] = right[j]
j = j + 1
k = k + 1
while i < len(left):
list[k] = left[i]
i += 1
k += 1
while j < len(right):
list[k] = right[j]
j += 1
k += 1
if __name__=="__main__":
list1=[8,4,23,42,16,15]
print(Merge_Sort(list1))
list_2=[20,18,12,8,5,-2] #Reverse-sorted
print(Merge_Sort(list_2)) #[-2, 5, 8, 12, 18, 20]
list_3=[5,12,7,5,5,7] #Few uniques
print(Merge_Sort(list_3)) #[5, 5, 5, 7, 7, 12]
list_4=[2,3,5,7,13,11] #Nearly-sorted
print(Merge_Sort(list_4)) #[2, 3, 5, 7, 11, 13]
|
#!python
def merge(items1, items2):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
merge_list = []
index_items1 = 0
index_items2 = 0
# comparing both lists and adding the element to the merge_list or/and to know the point where both list are in order correctly, this loop stops when you have completely traverse one of the arrays to merge
while index_items1 < len(items1) and index_items2 < len(items2):
# compare the two sorted arrays, items1 and items2
if items1[index_items1] < items2[index_items2]:
# element in items1 is smaller than items 2 so append to merge_list
merge_list.append(items1[index_items1])
index_items1 += 1
else:
# element in items1 is greater than items 2 so append element of items2 to list
merge_list.append(items2[index_items2])
index_items2 += 1
# add whatever is left because in our while loop we stop the moment either the index left or index right is > len(items)
merge_list += items1[index_items1:]
merge_list += items2[index_items2:]
return merge_list
def merge_sort(items):
"""Sort given items by splitting list into two approximately equal halves,
sorting each recursively, and merging results into a list in sorted order.
Running time: O(nlogn) because breaking the list down every recursive call; divide and conquer
Memory usage: O(n) because calling function resursively so just grows linearly with input"""
if items == []:
return items
# base case in recursive call
if len(items) == 1:
return items
else: # not necessary cause then return is run the function stops but helpful to understand
mid = len(items) // 2
left = items[0:mid]
right = items[mid:]
# return merge(merge_sort(left), merge_sort(right))
# items[:] = this so it's manipulating the items array instead of returning a new array
items[:] = merge(merge_sort(left), merge_sort(right))
return items[:]
def partition(items, low, high):
"""Return index `p` after in-place partitioning given items in range
`[low...high]` by choosing a pivot (TODO: document your method here) from
that range, moving pivot into index `p`, items less than pivot into range
`[low...p-1]`, and items greater than pivot into range `[p+1...high]`.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Choose a pivot any way and document your method in docstring above
# TODO: Loop through all items in range [low...high]
# TODO: Move items less than pivot into front of range [low...p-1]
# TODO: Move items greater than pivot into back of range [p+1...high]
# TODO: Move pivot item into final position [p] and return index p
pass
def quick_sort(arr, low=None, high=None):
"""Sort given items in place by partitioning items in range `[low...high]`
around a pivot item and recursively sorting each remaining sublist range.
Best case running time: O(nlogn) because your unsort list gets smaller and smaller with each recursive call
Worst case running time: O(n^2) when you pick all high numbers then you need to traverse entire length of array and made only progress sorting on that highest number.
Memory usage: O(n) because calling function recursively"""
# base case in recursive call <=1 because last element is the pivot and poping it
if len(arr) <= 1:
return arr
else: # not necessary cause when return is run the function stops but helpful to understand
# pops and sets first item as pivot _value until len(arr) is 1 or less
pivot_value = arr.pop(0)
# 2 lists for items that are greater or less than pivot
items_greater_pivot = []
items_lower_pivot = []
# loop through array to see if element is less or greater than pivot_value and add to proper list
for num in arr:
if num > pivot_value:
items_greater_pivot.append(num)
else:
items_lower_pivot.append(num)
# arr[:] = just so to get to pass sorting_test.py by mutating original array
# recursively calls items_lower_pivot and items_greater_pivot to add to final sorted array.
# each call will have quick_sort(items_lower_pivot) + pivot_value and pivot_value + quick_sort(items_greater_pivot)
arr[:] = quick_sort(items_lower_pivot) + [pivot_value] + quick_sort(items_greater_pivot)
return arr[:]
|
def default_copts(ignored = []):
opts = [
"-std=c++20",
"-Wall",
"-Werror",
"-Wextra",
"-Wno-ignored-qualifiers",
"-Wvla",
]
ignored_map = {opt: opt for opt in ignored}
return [opt for opt in opts if ignored_map.get(opt) == None]
|
{
"targets": [
{
"target_name": "usb",
"conditions": [
[
"OS==\"win\"",
{
"sources": [
"third_party/usb/src/win.cc"
],
"libraries": [
"-lhid"
]
}
],
[
"OS==\"linux\"",
{
"sources": [
"third_party/usb/src/linux.cc"
],
"libraries": [
"-ludev"
]
}
],
[
"OS==\"mac\"",
{
"sources": [
"third_party/usb/src/mac.cc"
],
"LDFLAGS": [
"-framework IOKit",
"-framework CoreFoundation",
"-framework AppKit"
],
"xcode_settings": {
"OTHER_LDFLAGS": [
"-framework IOKit",
"-framework CoreFoundation",
"-framework AppKit"
],
}
}
]
]
},
{
"target_name": "sign",
"conditions": [
[
"OS==\"win\"",
{
"sources": [
"third_party/sign/src/win.cc"
],
"libraries": [
"-lcrypt32"
]
}
],
[
"OS==\"linux\"",
{
"sources": [
"third_party/sign/src/linux.cc"
]
}
],
[
"OS==\"mac\"",
{
"sources": [
"third_party/sign/src/mac.cc"
],
"LDFLAGS": [
"-framework CoreFoundation",
"-framework AppKit"
],
"xcode_settings": {
"OTHER_LDFLAGS": [
"-framework CoreFoundation",
"-framework AppKit"
],
}
}
]
]
},
{
"target_name": "pcsc",
"sources": [
"third_party/pcsc/src/pcsc.cc",
"third_party/pcsc/src/service.cc",
"third_party/pcsc/src/card.cc",
"third_party/pcsc/src/device.cc"
],
"include_dirs": [
"third_party/pcsc/src"
],
"conditions": [
[
"OS==\"win\"",
{
"libraries": [
"-lwinscard"
]
}
],
[
"OS==\"mac\"",
{
"LDFLAGS": [
"-framework PCSC"
],
"xcode_settings": {
"OTHER_LDFLAGS": [
"-framework PCSC"
]
}
}
],
[
"OS==\"linux\"",
{
"include_dirs": [
"/usr/include/PCSC"
],
"cflags": [
"-pthread",
"-Wno-cast-function-type"
],
"libraries": [
"-lpcsclite"
]
}
]
]
}
]
} |
# Challenge 4 : Create a function named movie_review() that has one parameter named rating.
# If rating is less than or equal to 5, return "Avoid at all costs!".
# If rating is between 5 and 9, return "This one was fun.".
# If rating is 9 or above, return "Outstanding!"
# Date : Thu 28 May 2020 07:31:11 AM IST
def movie_review(rating):
if rating <= 5:
return "Avoid at all costs!"
elif (rating >= 5) and (rating <= 9):
return "This one was fun."
elif rating >= 9:
return "Outstanding!"
print(movie_review(9))
print(movie_review(4))
print(movie_review(6))
|
# Exercรญcio Python 52: Faรงa um programa que leia um nรบmero inteiro e diga se ele รฉ ou nรฃo um nรบmero primo.
n = int(input("Digite um nรบmero inteiro: "))
co = 0
for c in range(1, n + 1):
if n % c == 0:
co += 1
if co == 2:
print(f"{n} รฉ primo.")
else:
print(f"{n} nรฃo รฉ primo.")
|
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
msg = "Hello World!!!"
print("{}{}".format(colors["cian"], msg))
|
def difference(a, b):
c = []
for el in a:
if el not in b:
c.append(el)
return c
ll = [1, 2, 3, 4, 5]
ll2 = [4, 5, 6, 7, 8]
# print(difference(ll, ll2))
# = CTRL + /
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set_difference = set1.difference(set2)
# print(set_difference)
# print(difference(ll, ll2) == list(set_difference))
|
# --
# File: a1000_consts.py
#
# Copyright (c) ReversingLabs Inc 2016-2018
#
# This unpublished material is proprietary to ReversingLabs Inc.
# All rights reserved.
# Reproduction or distribution, in whole
# or in part, is forbidden except by express written permission
# of ReversingLabs Inc.
#
# --
A1000_JSON_BASE_URL = "base_url"
A1000_JSON_TASK_ID = "task_id"
A1000_JSON_API_KEY = "api_key"
A1000_JSON_MALWARE = "malware"
A1000_JSON_TASK_ID = "id"
A1000_JSON_VAULT_ID = "vault_id"
A1000_JSON_URL = "url"
A1000_JSON_HASH = "hash"
A1000_JSON_PLATFORM = "platform"
A1000_JSON_POLL_TIMEOUT_MINS = "timeout"
A1000_ERR_UNABLE_TO_PARSE_REPLY = "Unable to parse reply from device"
A1000_ERR_REPLY_FORMAT_KEY_MISSING = "None '{key}' missing in reply from device"
A1000_ERR_REPLY_NOT_SUCCESS = "REST call returned '{status}'"
A1000_SUCC_REST_CALL_SUCCEEDED = "REST Api call succeeded"
A1000_ERR_REST_API = "REST Api Call returned error, status_code: {status_code}, detail: {detail}"
A1000_TEST_PDF_FILE = "a1000_test_connectivity.pdf"
A1000_SLEEP_SECS = 3
A1000_MSG_REPORT_PENDING = "Report Not Found"
A1000_MSG_MAX_POLLS_REACHED = "Reached max polling attempts. Please use the MD5 or Sha256 of the file as a parameter to <b>get report</b> to query the report status."
A1000_PARAM_LIST = {
"fields": [
"file_type",
"file_subtype",
"file_size",
"extracted_file_count",
"local_first_seen",
"local_last_seen",
"classification_origin",
"classification_reason",
"threat_status",
"trust_factor",
"threat_level",
"threat_name",
"summary"]
}
# in minutes
A1000_MAX_TIMEOUT_DEF = 10
|
# Provided by Dr. Marzieh Ahmadzadeh & Nick Cheng. Edited by Yufei Cui
class DNode(object):
'''represents a node as a building block of a double linked list'''
def __init__(self, element, prev_node=None, next_node=None):
'''(Node, obj, Node, Node) -> NoneType
construct a Dnode as building block of a double linked list'''
# Representation invariant:
# element is an object, that is hold this node
# _prev is a DNode
# _next is a DNode
# _prev is the node immediately before this node (i.e. self)
# _next is the node immediately after this node (i.e. self)
self._element = element
self._next = next_node
self._prev = prev_node
def set_next(self, next_node):
'''(Node, Node) -> NoneType
set node to point to next_node'''
self._next = next_node
def set_prev(self, prev_node):
'''(Node, Node) -> NoneType
set node to point to prev_node'''
self._prev = prev_node
def set_element(self, element):
'''(Node, obj) ->NoneType
set the _element to a new value'''
self._element = element
def get_next(self):
'''(Node) -> Node
returns the reference to next node'''
return self._next
def get_prev(self):
'''(Node) -> Node
returns the reference to previous node'''
return self._prev
def get_element(self):
'''(Node) -> obj
returns the element of this node'''
return self._element
def __str__(self):
'''(Node) -> str
returns the element of this node and the reference to next node'''
return "(" + str(hex(id(self._prev))) + ", " + str(self._element) + ", " + str(hex(id(self._next))) + ")"
class DoubleLinkedList(object):
''' represents a double linked list'''
def __init__(self):
'''(DoubleLinkedList) ->NoneType
initializes the references of an empty DLL'''
# set the size
self._size = 0
# head and tails are a dummy node
self._head = DNode(None, None, None)
self._tail = DNode(None, None, None)
# head points to tail and tail to head
self._head.set_next(self._tail)
self._tail.set_prev(self._head)
def is_empty(self):
'''(DoubleLinkedList) -> bool
returns true if no item is in this DLL'''
return self._size == 0
def size(self):
'''(DoubleLinkedList) -> int
returns the number of items in this DLL'''
return self._size
def add_first(self, element):
'''(DoubleLinkedList, obj) -> NoneType
adds a node to the front of the DLL, after the head'''
# create a node that head points to. Also the node points to the node after the head
node = DNode(element, self._head, self._head.get_next())
# have the node after head to point to this node (_prev)
self._head.get_next().set_prev(node)
# have the head to point to this new node
self._head.set_next(node)
# increment the size
self._size += 1
def add_last(self, element):
'''(DoubleLinkedList, obj) -> NoneType
adds a node to the end of this DLL'''
# create a DNode with the given element that points to tail from right and to the node before the tail from left
node = DNode(element, self._tail.get_prev(), self._tail)
# let the node to the left of the tail to point to this new node
self._tail.get_prev().set_next(node)
# let the _prev part of the tail to point to newly created node
self._tail.set_prev(node)
# increment the size
self._size += 1
def remove_first(self):
'''(DoubleLinkedList, obj) -> obj
remove the node from the head of this DLL and returns the element stored in this node'''
# set element to None in case DLL was empty
element = None
# if DLL is not empty
if not self.is_empty():
# get the first node to the right of the head
node = self._head.get_next()
# have head point to the second node after the head
self._head.set_next(node.get_next())
# have the second node after the head to point to head from left
node.get_next().set_prev(self._head)
# decrement the size
self._size -= 1
# set the _next & _prev of the removed node to point to None (for garbage collection purpose)
node.set_next(None)
node.set_prev(None)
# get the element stored in the node
element = node.get_element()
# return the element of the removed node
return element
def remove_last(self):
'''(DoubleLinkedList, obj) -> obj
remove the node from the tail of this DLL and returns the element stored in this node'''
# set element to None in case DLL was empty
element = None
# if DLL is not empty
if not self.is_empty():
# get the first node to the left of the tail
node = self._tail.get_prev()
# have tail point to the second node before the tail
self._tail.set_prev(node.get_prev())
# have the second node before the tail to point to tail from right
node.get_prev().set_next(self._tail)
# decrement the size
self._size -= 1
# set the _next, _prev of removed node to point to None (for garbage collection purpose)
node.set_next(None)
node.set_prev(None)
# get the element stored in the node
element = node.get_element()
# return the element of the removed node
return element
def __str__(self):
'''(DoubleLinkedList) -> str
returns the items in the DLL in a string form
'''
# define a node, which points to the first node after the head
cur = self._head.get_next()
# define an empty string to be used as a container for the items in the SLL
result = ""
# loop over the DLL until you get to the end of the DLL
while cur is not self._tail:
# get the element of the current node and attach it to the final result
result = result + str(cur.get_element()) + ", "
# proceed to next node
cur = cur.get_next()
# enclose the result in a parentheses
result = "(" + result[:-2] + ")"
# return the result
return result
if __name__ == "__main__":
node_1 = DNode("A")
node_2 = DNode("B", node_1)
node_3 = DNode("C", node_1, node_2)
print(node_1)
print(node_2)
print(node_3)
print(str(hex(id(node_1))))
print(str(hex(id(node_2))))
dll = DoubleLinkedList()
print(dll)
dll.add_first("A")
dll.add_first("B")
dll.add_last("C")
dll.add_last("D")
print(dll)
print(dll.remove_last())
print(dll.remove_last())
print(dll.remove_last())
print(dll.remove_last())
print(dll)
|
a = 256
b = 256
print(a is b)
"""
output:True
"""
c = 257
d = 257
print(id(c),id(d)) |
class ProductLabels(object):
def __init__(self, labels, labels_tags, labels_fr):
self.Labels = labels
self.LabelsTags = labels_tags
self.LabelsFr = labels_fr
def __str__(self):
return self .Labels
|
def dds_insert(d, s, p, o):
if d.get(s) is None:
d[s] = {}
if d[s].get(p) is None:
d[s][p] = set()
d[s][p].add(o)
def dds_remove(d, s, p, o):
if d.get(s) is not None and d[s].get(p) is not None:
d[s][p].remove(o)
if not d[s][p]:
del d[s][p]
if not d[s]:
del d[s]
class JsonLDIndex:
def __init__(self, spo=None, pos=None):
self.spo = {} if spo is None else spo
self.pos = {} if pos is None else pos
#
def insert_triples(self, triples):
for subj, pred, obj in triples:
dds_insert(self.spo, subj, pred, obj)
# dds_insert(self.spo, obj, '~'+pred, subj)
dds_insert(self.pos, pred, obj, subj)
dds_insert(self.pos, '~'+pred, subj, obj)
#
return self
#
def remove_triples(self, triples):
for subj, pred, obj in triples:
dds_remove(self.spo, subj, pred, obj)
# dds_remove(self.spo, obj, '~'+pred, subj)
dds_remove(self.pos, pred, obj, subj)
dds_remove(self.pos, '~'+pred, subj, obj)
#
return self
|
# BGR colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY25 = (64, 64, 64)
GRAY50 = (128, 128, 128)
GRAY75 = (192, 192, 192)
GRAY33 = (85, 85, 85)
GRAY66 = (170, 170, 170)
BLUE = (255, 0, 0)
GREEN = (0, 255, 0)
RED = (0, 0, 255)
CYAN = (255, 255, 0)
MAGENTA = (255, 0, 255)
YELLOW = (0, 255, 255)
ORANGE = (0, 128, 255)
PURPLE = (255, 0, 128)
MINT = (128, 255, 0)
LIME = (0, 255, 128)
PINK = (128, 0, 255)
|
#Altere o programa anterior para mostrar no final a soma dos nรบmeros.
n1 = int(input("Digite um nรบmero: "))
n2 = int(input("Digite outro nรบmero: "))
for i in range(n1 + 1, n2):
print(i)
for i in range(n2 + 1, n1):
print(i)
print("Soma dos nรบmeros: ", i + i)
|
class Node(object):
value = None
left_child = None
right_child = None
def __init__(self, value, left=None, right=None):
self.value = value
if left:
self.left_child = left
if right:
self.right_child = right
def __str__(self):
return self.value
def has_left(self):
return True if self.left_child else False
def has_right(self):
return True if self.right_child else False
class BinaryTree(object):
root: Node = None
def __init__(self, node: Node = None):
if not self.root and node:
self.root = node
def __add__(self, node: Node, parent: Node = None):
if not self.root:
self.__init__(node=node)
else:
if parent:
if parent.value >= node.value:
if parent.has_right():
self.__add__(node=node, parent=parent.right_child)
else:
parent.right_child = node
else:
if parent.has_left():
self.__add__(node=node, parent=parent.left_child)
else:
parent.left_child = node
else:
self.__add__(node=node, parent=self.root)
def search_back(self, number, node: Node, level_count):
if number == node.value:
return level_count, True
else:
if number < node.value:
if node.has_left():
self.search_back(number=number, node=node.left_child, level_count=level_count + 1)
else:
return False
else:
if node.has_right():
self.search_back(number=number, node=node.right_child, level_count=level_count + 1)
else:
return False
def search(self, number):
return self.search_back(number=number, node=self.root, level_count=0)
def print_level(self, level_count, node: Node, result: list):
if not node:
return
else:
if level_count == 0:
result.append(node)
self.print_level(level_count=level_count - 1, node=node.left_child, result=result)
self.print_level(level_count=level_count - 1, node=node.right_child, result=result)
def print_tree(self, result: list, node: Node):
result.append(node)
if node.has_left():
self.print_tree(result=result, node=node.left_child)
elif node.has_right():
self.print_tree(result=result, node=node.right_child)
def height(self, node: Node):
if not node:
return 0
else:
if node.has_left():
l_height = self.height(node=node.left_child)
else:
l_height = -1
if node.has_right():
r_height = self.height(node=node.right_child)
else:
r_height = -1
max_height = l_height if l_height > r_height else r_height
return max_height + 1
def to_array_values(self, result: list, node: Node):
result.append(node.value)
if node.has_left():
self.to_array_values(result=result, node=node.left_child)
elif node.has_right():
self.to_array_values(result=result, node=node.right_child)
def to_array_nodes(self, result: list, node: Node):
result.append(node)
if node.has_left():
self.to_array_values(result=result, node=node.left_child)
elif node.has_right():
self.to_array_values(result=result, node=node.right_child)
def join_trees(bst_1: BinaryTree, bst_2: BinaryTree):
tree_array_1 = []
tree_array_2 = []
bst_1.to_array_values(tree_array_1, bst_1.root)
bst_2.to_array_values(tree_array_2, bst_2.root)
result_array = [*tree_array_1, *tree_array_2]
bst_result = BinaryTree()
for item in result_array:
node = Node(item)
bst_result.__add__(node=node)
return bst_result
|
# START LAB EXERCISE 04
print('Lab Exercise 04 \n')
# SETUP
city_state = ["Detroit|MI", "Philadelphia|PA", "Hollywood|CA",
"Oakland|CA", "Boston|MA", "Atlanta|GA",
"Phoenix|AZ", "Birmingham|AL", "Houston|TX", "Tampa|FL"]
# END SETUP
# PROBLEM 1.0 (5 Points)
# PROBLEM 2.0 (5 Points)
# PROBLEM 3.0 (10 Points)
# END LAB EXERCISE |
# -*- coding: utf-8 -*-
string1 = "Becomes"
string2 = "becomes"
string3 = "BEAR"
string4 = " bEautiful"
string1 = string1.lower()
# (string2 will pass unmodified)
string3 = string3.lower()
string4 = string4.strip().lower()
print(string1.startswith("be"))
print(string2.startswith("be"))
print(string3.startswith("be"))
print(string4.startswith("be"))
|
class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
class BinarySearchTree(object):
def __init__(self, root=None):
self.root = root
def get_root(self):
return self.root
def insert(self, item):
if self.root is None:
self.root = Node(item)
else:
cur_node = self.root
while cur_node is not None:
if item < cur_node.data:
if cur_node.left is None:
cur_node = Node(item)
return
else:
cur_node = cur_node.left
else:
if cur_node.right is None:
cur_node = Node(item)
return
else:
cur_node = cur_node.right
|
input = """af AND ah -> ai
NOT lk -> ll
hz RSHIFT 1 -> is
NOT go -> gp
du OR dt -> dv
x RSHIFT 5 -> aa
at OR az -> ba
eo LSHIFT 15 -> es
ci OR ct -> cu
b RSHIFT 5 -> f
fm OR fn -> fo
NOT ag -> ah
v OR w -> x
g AND i -> j
an LSHIFT 15 -> ar
1 AND cx -> cy
jq AND jw -> jy
iu RSHIFT 5 -> ix
gl AND gm -> go
NOT bw -> bx
jp RSHIFT 3 -> jr
hg AND hh -> hj
bv AND bx -> by
er OR es -> et
kl OR kr -> ks
et RSHIFT 1 -> fm
e AND f -> h
u LSHIFT 1 -> ao
he RSHIFT 1 -> hx
eg AND ei -> ej
bo AND bu -> bw
dz OR ef -> eg
dy RSHIFT 3 -> ea
gl OR gm -> gn
da LSHIFT 1 -> du
au OR av -> aw
gj OR gu -> gv
eu OR fa -> fb
lg OR lm -> ln
e OR f -> g
NOT dm -> dn
NOT l -> m
aq OR ar -> as
gj RSHIFT 5 -> gm
hm AND ho -> hp
ge LSHIFT 15 -> gi
jp RSHIFT 1 -> ki
hg OR hh -> hi
lc LSHIFT 1 -> lw
km OR kn -> ko
eq LSHIFT 1 -> fk
1 AND am -> an
gj RSHIFT 1 -> hc
aj AND al -> am
gj AND gu -> gw
ko AND kq -> kr
ha OR gz -> hb
bn OR by -> bz
iv OR jb -> jc
NOT ac -> ad
bo OR bu -> bv
d AND j -> l
bk LSHIFT 1 -> ce
de OR dk -> dl
dd RSHIFT 1 -> dw
hz AND ik -> im
NOT jd -> je
fo RSHIFT 2 -> fp
hb LSHIFT 1 -> hv
lf RSHIFT 2 -> lg
gj RSHIFT 3 -> gl
ki OR kj -> kk
NOT ak -> al
ld OR le -> lf
ci RSHIFT 3 -> ck
1 AND cc -> cd
NOT kx -> ky
fp OR fv -> fw
ev AND ew -> ey
dt LSHIFT 15 -> dx
NOT ax -> ay
bp AND bq -> bs
NOT ii -> ij
ci AND ct -> cv
iq OR ip -> ir
x RSHIFT 2 -> y
fq OR fr -> fs
bn RSHIFT 5 -> bq
0 -> c
14146 -> b
d OR j -> k
z OR aa -> ab
gf OR ge -> gg
df OR dg -> dh
NOT hj -> hk
NOT di -> dj
fj LSHIFT 15 -> fn
lf RSHIFT 1 -> ly
b AND n -> p
jq OR jw -> jx
gn AND gp -> gq
x RSHIFT 1 -> aq
ex AND ez -> fa
NOT fc -> fd
bj OR bi -> bk
as RSHIFT 5 -> av
hu LSHIFT 15 -> hy
NOT gs -> gt
fs AND fu -> fv
dh AND dj -> dk
bz AND cb -> cc
dy RSHIFT 1 -> er
hc OR hd -> he
fo OR fz -> ga
t OR s -> u
b RSHIFT 2 -> d
NOT jy -> jz
hz RSHIFT 2 -> ia
kk AND kv -> kx
ga AND gc -> gd
fl LSHIFT 1 -> gf
bn AND by -> ca
NOT hr -> hs
NOT bs -> bt
lf RSHIFT 3 -> lh
au AND av -> ax
1 AND gd -> ge
jr OR js -> jt
fw AND fy -> fz
NOT iz -> ja
c LSHIFT 1 -> t
dy RSHIFT 5 -> eb
bp OR bq -> br
NOT h -> i
1 AND ds -> dt
ab AND ad -> ae
ap LSHIFT 1 -> bj
br AND bt -> bu
NOT ca -> cb
NOT el -> em
s LSHIFT 15 -> w
gk OR gq -> gr
ff AND fh -> fi
kf LSHIFT 15 -> kj
fp AND fv -> fx
lh OR li -> lj
bn RSHIFT 3 -> bp
jp OR ka -> kb
lw OR lv -> lx
iy AND ja -> jb
dy OR ej -> ek
1 AND bh -> bi
NOT kt -> ku
ao OR an -> ap
ia AND ig -> ii
NOT ey -> ez
bn RSHIFT 1 -> cg
fk OR fj -> fl
ce OR cd -> cf
eu AND fa -> fc
kg OR kf -> kh
jr AND js -> ju
iu RSHIFT 3 -> iw
df AND dg -> di
dl AND dn -> do
la LSHIFT 15 -> le
fo RSHIFT 1 -> gh
NOT gw -> gx
NOT gb -> gc
ir LSHIFT 1 -> jl
x AND ai -> ak
he RSHIFT 5 -> hh
1 AND lu -> lv
NOT ft -> fu
gh OR gi -> gj
lf RSHIFT 5 -> li
x RSHIFT 3 -> z
b RSHIFT 3 -> e
he RSHIFT 2 -> hf
NOT fx -> fy
jt AND jv -> jw
hx OR hy -> hz
jp AND ka -> kc
fb AND fd -> fe
hz OR ik -> il
ci RSHIFT 1 -> db
fo AND fz -> gb
fq AND fr -> ft
gj RSHIFT 2 -> gk
cg OR ch -> ci
cd LSHIFT 15 -> ch
jm LSHIFT 1 -> kg
ih AND ij -> ik
fo RSHIFT 3 -> fq
fo RSHIFT 5 -> fr
1 AND fi -> fj
1 AND kz -> la
iu AND jf -> jh
cq AND cs -> ct
dv LSHIFT 1 -> ep
hf OR hl -> hm
km AND kn -> kp
de AND dk -> dm
dd RSHIFT 5 -> dg
NOT lo -> lp
NOT ju -> jv
NOT fg -> fh
cm AND co -> cp
ea AND eb -> ed
dd RSHIFT 3 -> df
gr AND gt -> gu
ep OR eo -> eq
cj AND cp -> cr
lf OR lq -> lr
gg LSHIFT 1 -> ha
et RSHIFT 2 -> eu
NOT jh -> ji
ek AND em -> en
jk LSHIFT 15 -> jo
ia OR ig -> ih
gv AND gx -> gy
et AND fe -> fg
lh AND li -> lk
1 AND io -> ip
kb AND kd -> ke
kk RSHIFT 5 -> kn
id AND if -> ig
NOT ls -> lt
dw OR dx -> dy
dd AND do -> dq
lf AND lq -> ls
NOT kc -> kd
dy AND ej -> el
1 AND ke -> kf
et OR fe -> ff
hz RSHIFT 5 -> ic
dd OR do -> dp
cj OR cp -> cq
NOT dq -> dr
kk RSHIFT 1 -> ld
jg AND ji -> jj
he OR hp -> hq
hi AND hk -> hl
dp AND dr -> ds
dz AND ef -> eh
hz RSHIFT 3 -> ib
db OR dc -> dd
hw LSHIFT 1 -> iq
he AND hp -> hr
NOT cr -> cs
lg AND lm -> lo
hv OR hu -> hw
il AND in -> io
NOT eh -> ei
gz LSHIFT 15 -> hd
gk AND gq -> gs
1 AND en -> eo
NOT kp -> kq
et RSHIFT 5 -> ew
lj AND ll -> lm
he RSHIFT 3 -> hg
et RSHIFT 3 -> ev
as AND bd -> bf
cu AND cw -> cx
jx AND jz -> ka
b OR n -> o
be AND bg -> bh
1 AND ht -> hu
1 AND gy -> gz
NOT hn -> ho
ck OR cl -> cm
ec AND ee -> ef
lv LSHIFT 15 -> lz
ks AND ku -> kv
NOT ie -> if
hf AND hl -> hn
1 AND r -> s
ib AND ic -> ie
hq AND hs -> ht
y AND ae -> ag
NOT ed -> ee
bi LSHIFT 15 -> bm
dy RSHIFT 2 -> dz
ci RSHIFT 2 -> cj
NOT bf -> bg
NOT im -> in
ev OR ew -> ex
ib OR ic -> id
bn RSHIFT 2 -> bo
dd RSHIFT 2 -> de
bl OR bm -> bn
as RSHIFT 1 -> bl
ea OR eb -> ec
ln AND lp -> lq
kk RSHIFT 3 -> km
is OR it -> iu
iu RSHIFT 2 -> iv
as OR bd -> be
ip LSHIFT 15 -> it
iw OR ix -> iy
kk RSHIFT 2 -> kl
NOT bb -> bc
ci RSHIFT 5 -> cl
ly OR lz -> ma
z AND aa -> ac
iu RSHIFT 1 -> jn
cy LSHIFT 15 -> dc
cf LSHIFT 1 -> cz
as RSHIFT 3 -> au
cz OR cy -> da
kw AND ky -> kz
lx -> a
iw AND ix -> iz
lr AND lt -> lu
jp RSHIFT 5 -> js
aw AND ay -> az
jc AND je -> jf
lb OR la -> lc
NOT cn -> co
kh LSHIFT 1 -> lb
1 AND jj -> jk
y OR ae -> af
ck AND cl -> cn
kk OR kv -> kw
NOT cv -> cw
kl AND kr -> kt
iu OR jf -> jg
at AND az -> bb
jp RSHIFT 2 -> jq
iv AND jb -> jd
jn OR jo -> jp
x OR ai -> aj
ba AND bc -> bd
jl OR jk -> jm
b RSHIFT 1 -> v
o AND q -> r
NOT p -> q
k AND m -> n
as RSHIFT 2 -> at"""
values = {}
mapping = {}
for line in input.split("\n"):
destination = line.split("->")[-1].strip()
provider = line.split("->")[0].strip()
mapping[destination] = provider
# evaluate for a
def evaluate(target):
if target.isnumeric():
return int(target)
if target in values:
return values[target]
if target not in mapping:
print("Unknown target", target)
exit(1)
target_provider = mapping[target]
args = target_provider.split()
if len(args) == 1:
# Assignment
values[target] = evaluate(args[0])
elif len(args) == 2:
# NOT
values[target] = ~evaluate(args[1])
else:
if args[1] == "AND":
values[target] = evaluate(args[0]) & evaluate(args[2])
elif args[1] == "OR":
values[target] = evaluate(args[0]) | evaluate(args[2])
elif args[1] == "LSHIFT":
values[target] = evaluate(args[0]) << evaluate(args[2])
elif args[1] == "RSHIFT":
values[target] = evaluate(args[0]) >> evaluate(args[2])
else:
print("unknown operator", args[1])
exit(1)
if target not in values:
print("How did i get here")
exit(1)
return values[target]
print(evaluate("a")) |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CentrifySchemaEnum(object):
"""Implementation of the 'CentrifySchema' enum.
Specifies the schema of this Centrify zone.
The below list of schemas and their values are taken from the document
Centrify Server Suite 2016 Windows API Programmer's Guide
https://docs.centrify.com/en/css/suite2016/centrify-win-progguide.pdf
'kCentrifyDynamicSchema_1_0' specifies dynamic schema, version 1.0.
'kCentrifyDynamicSchema_2_0' specifies dynamic schema, version 2.0.
'kCentrifyDynamicSchema_3_0' specifies dynamic schema, version 3.0.
'kCentrifyDynamicSchema_5_0' specifies dynamic schema, version 5.0.
'kCentrifySfu_3_0' specifies sfu schema, version 3.0.
'kCentrifySfu_3_0_V5' specifies sfu schema, 3.0.5.
'kCentrifySfu_4_0' specifies sfu schema, version 4.0.
'kCentrifyCdcRfc2307' specifies cdcrfc2307 schema.
'kCentrifyCdcRfc2307_2' specifies cdcrfc2307, version 2.
'kCentrifyCdcRfc2307_3' specifies cdcrfc2307, version 3.
Attributes:
KCENTRIFYDYNAMICSCHEMA_1_0: TODO: type description here.
KCENTRIFYDYNAMICSCHEMA_2_0: TODO: type description here.
KCENTRIFYSFU_3_0: TODO: type description here.
KCENTRIFYSFU_4_0: TODO: type description here.
KCENTRIFYCDCRFC2307: TODO: type description here.
KCENTRIFYDYNAMICSCHEMA_3_0: TODO: type description here.
KCENTRIFYCDCRFC2307_2: TODO: type description here.
KCENTRIFYDYNAMICSCHEMA_5_0: TODO: type description here.
KCENTRIFYCDCRFC2307_3: TODO: type description here.
KCENTRIFYSFU_3_0_V5: TODO: type description here.
"""
KCENTRIFYDYNAMICSCHEMA_1_0 = 'kCentrifyDynamicSchema_1_0'
KCENTRIFYDYNAMICSCHEMA_2_0 = 'kCentrifyDynamicSchema_2_0'
KCENTRIFYSFU_3_0 = 'kCentrifySfu_3_0'
KCENTRIFYSFU_4_0 = 'kCentrifySfu_4_0'
KCENTRIFYCDCRFC2307 = 'kCentrifyCdcRfc2307'
KCENTRIFYDYNAMICSCHEMA_3_0 = 'kCentrifyDynamicSchema_3_0'
KCENTRIFYCDCRFC2307_2 = 'kCentrifyCdcRfc2307_2'
KCENTRIFYDYNAMICSCHEMA_5_0 = 'kCentrifyDynamicSchema_5_0'
KCENTRIFYCDCRFC2307_3 = 'kCentrifyCdcRfc2307_3'
KCENTRIFYSFU_3_0_V5 = 'kCentrifySfu_3_0_V5'
|
# Quebrando um nรบmero
'''Minha Soluรงรฃo'''
'''from math import floor
valor = float(input('Digite um valor: '))
numQuebrado = floor(valor)
print('O valor digitado foi {} e a sua porรงรฃo inteira รฉ {}'.format(valor, numQuebrado))'''
'''Soluรงรฃo Professor '''
'''from math import trunc
num = float(input('Digite um valor: '))
print('O valor digitado foi {} e a sua porรงรฃo inteira รฉ {}'.format(num, trunc(num)))'''
num = float(input('Digite um valor: '))
print('o valor digitado foi {} e a sua porรงรฃo inteira รฉ {}'.format(num, int(num)))
|
def ask_question():
print("Who is the founder of Facebook?")
option=["Mark Zuckerberg","Bill Gates","Steve Jobs","Larry Page"]
for i in option:
print(i)
ask_question()
i=0
while i<100:
ask_question()
i+=1
def say_hello(name):
print ("Hello ", name)
print ("Aap kaise ho?")
say_hello("jai")
def add_number(num1,num2):
print("hum2 numbers ko add krenge")
print(num1+num2)
add_number(112,3)
varx=10
vary=20
add_number(varx,vary)
def say_lang(name,language):
if language=="punjabi":
print("sat sri akaal",name)
elif language=="hindi":
print("Namestye",name)
elif language=="English":
print("good morning",name)
say_lang("rishabh","hindi")
say_lang("jai","English")
def print_lines(name,position):
print("mera naam "+str(name)+" hai")
print("mein "+str(position)+" ka co-founder hu")
print_lines("jai","Navgurkul")
def add_numbers(number1,number2):
add=number1+number2
print(number1,"aur",number2," ka sum:-",add)
add_numbers(56,12)
num1=[15,20,30]
num2=[20,30,40]
def add_num_list(num1,num2):
i=0
b = []
while i<len(num1):
add = num1[i]+num2[i]
i+=1
b.append(add)
return (b)
print(add_num_list(num1,num2))
num1=[15,20,30,2, 6, 18, 10, 3, 75]
num2=[20,30,40,6, 19, 24, 12, 3, 87]
def add_num_list(num1,num2):
i=0
while i<len(num1):
if num1[i]%2==0 and num2[i]%2==0:
print("even hai")
else:
print("odd hai")
i+=1
(add_num_list(num1,num2))
def add_numbers_print(number_x, number_y):
number_sum = number_x + number_y
return number_sum
sum4 = add_numbers_print(4, 5)
print (sum4)
print (type(sum4))
def calculator(numx,numy,operator):
if operator=="add":
add=numx+numy
return add
elif operator=="subtract":
subtract=numx-numy
return subtract
elif operator=="multiply":
multiply=numx*numy
return multiply
elif operator=="divide":
divide=numx/numy
return divide
num1=int(input("Enter the 1st number :- "))
num2=int(input("Enter the 2nd number :- "))
num3=input("which action you want to perform (add/subtract/multiply/divide)")
print(calculator(num1,num2,num3))
a=[3,4,5,6]
b=[2,4,5,6]
def list_change(a,b):
i=0
multiply=0
c=[]
while i<len(a):
multiply=a[i]*b[i]
c.append(multiply)
i+=1
return c
print(list_change(a,b))
|
input_file = open("input.txt","r")
lines = input_file.readlines()
count = 0
answers = set()
for line in lines:
if line == "\n":
count += len(answers)
print(answers)
answers.clear()
for character in line:
#print(character)
if character != "\n":
answers.add(character)
count += len(answers)
print(answers)
answers.clear()
print(count) |
def fn():
num1=1
num3=20
sum=num1+num2
print(sum)
num=10
def school():
students=1000
classes=12
avg=students/classes
return avg
num1=school()
if num1>500:
print('ไบบๆฐๅพๅฅฝ')
|
class BankAccount:
def __init__(self):
self.accountNum = 0
self.accountOwner = ""
self.accountBalance = 0.00
def ModifyAccount(self, id, name, balance):
self.accountNum = id
self.accountOwner = name
self.accountBalance = balance
account = BankAccount()
account.ModifyAccount(12345, "John Doe", 123456.78)
print("Account ID: {}, Name: {}, Balance: ${}".format(account.accountNum, account.accountOwner, account.accountBalance)) |
# Tai Sakuma <[email protected]>
##__________________________________________________________________||
def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }):
"""expand a path config
Args:
path_cfg (str, tuple, dict): a config for path
alias_dict (dict): a dict for aliases
overriding_kargs (dict): to be used for recursive call
"""
if isinstance(path_cfg, str):
return _expand_str(path_cfg, alias_dict, overriding_kargs)
if isinstance(path_cfg, dict):
return _expand_dict(path_cfg, alias_dict)
# assume tuple or list
return _expand_tuple(path_cfg, alias_dict, overriding_kargs)
##__________________________________________________________________||
def _expand_str(path_cfg, alias_dict, overriding_kargs):
"""expand a path config given as a string
"""
if path_cfg in alias_dict:
# e.g., path_cfg = 'var_cut'
return _expand_str_alias(path_cfg, alias_dict, overriding_kargs)
# e.g., path_cfg = 'ev : {low} <= ev.var[0] < {high}'
return _expand_for_lambda_str(path_cfg, alias_dict, overriding_kargs)
def _expand_for_lambda_str(path_cfg, alias_dict, overriding_kargs):
# e.g.,
# path_cfg = 'ev : {low} <= ev.var[0] < {high}'
ret = dict(factory='LambdaStrFactory', lambda_str=path_cfg, components=())
# e.g.,
# {
# 'factory': 'LambdaStrFactory',
# 'lambda_str': 'ev : {low} <= ev.var[0] < {high}'
# }
overriding_kargs_copy = overriding_kargs.copy()
# e.g., {'low': 25, 'high': 200, 'alias': 'var_cut', 'name': 'var_cut25'}
if 'alias' in overriding_kargs:
ret['name'] = overriding_kargs_copy.pop('alias')
if 'name' in overriding_kargs:
ret['name'] = overriding_kargs_copy.pop('name')
ret.update(overriding_kargs_copy)
# e.g.,
# {
# 'factory': 'LambdaStrFactory',
# 'lambda_str': 'ev : {low} <= ev.var[0] < {high}',
# 'name': 'var_cut25',
# 'low': 25, 'high': 200
# }
return ret
def _expand_str_alias(path_cfg, alias_dict, overriding_kargs):
"""expand a path config given as a string
Args:
path_cfg (str): an alias
alias_dict (dict):
overriding_kargs (dict):
"""
# e.g.,
# path_cfg = 'var_cut'
new_path_cfg = alias_dict[path_cfg]
# e.g., ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200})
new_overriding_kargs = dict(alias=path_cfg)
# e.g., {'alias': 'var_cut'}
new_overriding_kargs.update(overriding_kargs)
# e.g., {'alias': 'var_cut', 'name': 'var_cut25', 'low': 25}
return expand_path_cfg(new_path_cfg, alias_dict,new_overriding_kargs)
##__________________________________________________________________||
def _expand_tuple(path_cfg, alias_dict, overriding_kargs):
"""expand a path config given as a tuple
"""
# e.g.,
# path_cfg = ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200})
# overriding_kargs = {'alias': 'var_cut', 'name': 'var_cut25', 'low': 25}
new_path_cfg = path_cfg[0]
# e.g., 'ev : {low} <= ev.var[0] < {high}'
new_overriding_kargs = path_cfg[1].copy()
# e.g., {'low': 10, 'high': 200}
new_overriding_kargs.update(overriding_kargs)
# e.g., {'low': 25, 'high': 200, 'alias': 'var_cut', 'name': 'var_cut25'}
return expand_path_cfg(
new_path_cfg,
overriding_kargs=new_overriding_kargs,
alias_dict=alias_dict
)
##__________________________________________________________________||
def _expand_dict(path_cfg, alias_dict):
if 'factory' in path_cfg:
return path_cfg
if not sum([k in path_cfg for k in ('All', 'Any', 'Not')]) <= 1:
raise ValueError("Any pair of 'All', 'Any', 'Not' cannot be simultaneously given unless factory is given!")
if 'All' in path_cfg:
new_path_cfg = path_cfg.copy()
new_path_cfg['factory'] = 'AllFactory'
new_path_cfg['components'] = tuple([expand_path_cfg(p, alias_dict=alias_dict) for p in new_path_cfg.pop('All')])
return new_path_cfg
if 'Any' in path_cfg:
new_path_cfg = path_cfg.copy()
new_path_cfg['factory'] = 'AnyFactory'
new_path_cfg['components'] = tuple([expand_path_cfg(p, alias_dict=alias_dict) for p in new_path_cfg.pop('Any')])
return new_path_cfg
if 'Not' in path_cfg:
new_path_cfg = path_cfg.copy()
new_path_cfg['factory'] = 'NotFactory'
new_path_cfg['components'] = (expand_path_cfg(new_path_cfg.pop('Not'), alias_dict=alias_dict), )
return new_path_cfg
raise ValueError("cannot recognize the path_cfg")
##__________________________________________________________________||
|
class Solution:
def maxDepth(self, root):
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
|
"""
Extension 3 (ext3)
Used primarily for concurrent Linux systems (ext2 + journalling)
"""
|
termo1 = int(input('Digite o 1ยบ termo da P.A: '))
razao = int(input('Digite a razรฃo desta P.A: '))
decimo = termo1 + (10 - 1) * razao
for i in range(termo1, decimo + 1, razao):
print(i, end=' ')
|
lis = []
for i in range (10):
num = int(input())
lis.append(num)
print(lis)
for i in range (len(lis)):
print(lis[i])
|
n = int(input('enter number to find the factorial: '))
fact=1;
for i in range(1,n+1,1):
fact=fact*i
print(fact)
|
"""Configuration package.
This package handle all information that could be given to pycodeanalyzer in the configuration.
"""
|
Automoviles=['Dodge Challeger', 'VW Gti', 'Jeep Rubicon', 'Alfa Romeo Quadro', 'Ford ST', 'Dodge RAM', 'Ford FX4']
M1="Me gustaria compar un " + Automoviles[0].title()+"."
M2="Mi vecino choco su nuevo " + Automoviles[1].title() + "."
M3="El nuevo " + Automoviles[2].title()+ " es mucho mas economico."
M4="Hay una gran diferencia entre el " + Automoviles[3].title() + " y el " + Automoviles[4].title()+"."
M5="La camioneta " + Automoviles[5].title() + " es de gasolina, mientras que la " + Automoviles[6].title() +" es de Diesel."
print(M1)
print(M2)
print(M3)
print(M4)
print(M5)
|
class Stock:
def __init__(self, symbol, name):
self.__name = name
self.__symbol = symbol
self.__stockPlate = []
self.__carePlate = []
@property
def name(self):
return self.__name
@property
def symbol(self):
return self.__symbol
@property
def stockPlate(self):
return self.stockPlate
@property
def carePlate(self):
return self.__carePlate
def addCarePlate(self, cp):
if cp in self.__carePlate:
print("Already exist!")
else:
self.__carePlate.append(cp)
def addStockPlate(self, sp):
if sp in self.__stockPlate:
print("Already exist!")
else:
self.__stockPlate.append(sp)
# print("Success")
def formatPlateInfo(self):
# print(self.__carePlate)
return {"name": self.__name, "carePlate":self.__carePlate, "stockPlate": self.__stockPlate} |
#Programa para evaluar si un numero es feliz
numero_a_evaluar = input("Introduce el numero a evaluar: ")
n = numero_a_evaluar
suma = 2
primer_digito = 0
segundo_digito = 0
tercer_digito = 0
cuarto_digito = 0
while suma > 1:
primer_digito = numero_a_evaluar[0]
primer_digito = int(primer_digito)
print(primer_digito)
try:
segundo_digito = numero_a_evaluar[1]
segundo_digito = int(segundo_digito)
print(segundo_digito)
except IndexError as Numeromenorandigits:
pass
try:
tercer_digito = numero_a_evaluar[2]
tercer_digito = int(tercer_digito)
print(tercer_digito)
except IndexError as Numeromenorandigits:
pass
try:
cuarto_digito = numero_a_evaluar[3]
cuarto_digito = int(cuarto_digito)
print(cuarto_digito)
except IndexError as Numeromenorandigits:
pass
suma = primer_digito ** 2 + segundo_digito ** 2 + tercer_digito ** 2
print (suma)
numero_a_evaluar = suma
numero_a_evaluar = str(numero_a_evaluar)
if suma == 1:
print(n,"es un numero feliz")
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
""" A property set is maintained by the PassManager to keep information
about the current state of the circuit """
class PropertySet(dict):
""" A default dictionary-like object """
def __missing__(self, key):
return None
|
def read_label_pbtxt(label_path: str) -> dict:
with open(label_path, "r") as label_file:
lines = label_file.readlines()
labels = {}
for row, content in enumerate(lines):
labels[row] = {"id": row, "name": content.strip()}
return labels
|
co2 = input("Please input air quality value: ")
co2 = int(co2)
if co2 > 399 and co2 < 698:
print("Excelent")
elif co2 > 699 and co2 < 898:
print("Good")
elif co2 > 899 and co2 < 1098:
print("Fair")
elif co2 > 1099 and co2 < 1598:
print("Mediocre, contaminated indoor air")
elif co2 > 1599 and co2 < 2101:
print("Bad, heavily contaminated indoor air")
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"GH_HOST": "00_core.ipynb",
"GhApi": "00_core.ipynb",
"date2gh": "00_core.ipynb",
"gh2date": "00_core.ipynb",
"print_summary": "00_core.ipynb",
"GhApi.delete_release": "00_core.ipynb",
"GhApi.upload_file": "00_core.ipynb",
"GhApi.create_release": "00_core.ipynb",
"GhApi.list_tags": "00_core.ipynb",
"GhApi.list_branches": "00_core.ipynb",
"EMPTY_TREE_SHA": "00_core.ipynb",
"GhApi.create_branch_empty": "00_core.ipynb",
"GhApi.delete_tag": "00_core.ipynb",
"GhApi.delete_branch": "00_core.ipynb",
"GhApi.get_branch": "00_core.ipynb",
"GhApi.list_files": "00_core.ipynb",
"GhApi.get_content": "00_core.ipynb",
"GhApi.update_contents": "00_core.ipynb",
"GhApi.enable_pages": "00_core.ipynb",
"contexts": "01_actions.ipynb",
"env_github": "01_actions.ipynb",
"user_repo": "01_actions.ipynb",
"Event": "01_actions.ipynb",
"create_workflow_files": "01_actions.ipynb",
"fill_workflow_templates": "01_actions.ipynb",
"env_contexts": "01_actions.ipynb",
"def_pipinst": "01_actions.ipynb",
"create_workflow": "01_actions.ipynb",
"gh_create_workflow": "01_actions.ipynb",
"example_payload": "01_actions.ipynb",
"github_token": "01_actions.ipynb",
"actions_output": "01_actions.ipynb",
"actions_debug": "01_actions.ipynb",
"actions_warn": "01_actions.ipynb",
"actions_error": "01_actions.ipynb",
"actions_group": "01_actions.ipynb",
"actions_endgroup": "01_actions.ipynb",
"actions_mask": "01_actions.ipynb",
"set_git_user": "01_actions.ipynb",
"Scope": "02_auth.ipynb",
"scope_str": "02_auth.ipynb",
"GhDeviceAuth": "02_auth.ipynb",
"GhDeviceAuth.url_docs": "02_auth.ipynb",
"GhDeviceAuth.open_browser": "02_auth.ipynb",
"GhDeviceAuth.auth": "02_auth.ipynb",
"GhDeviceAuth.wait": "02_auth.ipynb",
"paged": "03_page.ipynb",
"parse_link_hdr": "03_page.ipynb",
"GhApi.last_page": "03_page.ipynb",
"pages": "03_page.ipynb",
"GhApi.list_events": "04_event.ipynb",
"GhApi.list_events_parallel": "04_event.ipynb",
"GhEvent": "04_event.ipynb",
"GhApi.fetch_events": "04_event.ipynb",
"load_sample_events": "04_event.ipynb",
"save_sample_events": "04_event.ipynb",
"full_type": "04_event.ipynb",
"evt_emojis": "04_event.ipynb",
"description": "04_event.ipynb",
"emoji": "04_event.ipynb",
"text": "04_event.ipynb",
"described_evts": "04_event.ipynb",
"ghapi": "10_cli.ipynb",
"ghpath": "10_cli.ipynb",
"ghraw": "10_cli.ipynb",
"completion_ghapi": "10_cli.ipynb",
"GH_OPENAPI_URL": "90_build_lib.ipynb",
"build_funcs": "90_build_lib.ipynb",
"GhMeta": "90_build_lib.ipynb"}
modules = ["core.py",
"actions.py",
"auth.py",
"page.py",
"event.py",
"cli.py",
"build_lib.py"]
doc_url = "https://ghapi.fast.ai/"
git_url = "https://github.com/fastai/ghapi/tree/master/"
def custom_doc_links(name): return None
|
def wypisz(par1, par2):
print('{0} {1}'.format(par1, par2))
def sprawdz(arg1, arg2):
if arg1 > arg2:
return True
else:
return False
|
ce,nll=input("<<")
lx=ce*(nll/1200)
print("The interest is",lx)
|
valor1 = int(input('Digite um valor:'))
valor2 = int(input('Digite outro valor:'))
soma = valor1 + valor2
print(f'A soma entre os valores {valor1} e {valor2} รฉ igual a {soma}!')
|
class Edge:
def __init__(self, src, dst, line):
self.src = src
self.dst = dst
self.line = line
assert src != dst, f"Source and destination are the same!"
def reverse(self):
return Edge(self.dst, self.src, self.line.reverse())
def to_dict(self):
return {
"src": self.src.id if self.src else None,
"dst": self.dst.id if self.dst else None,
}
def __str__(self):
src_id = self.src.id if self.src else "None"
dst_id = self.dst.id if self.dst else "None"
return f"{src_id} -> {dst_id}"
|
def to_url_representation(path: str) -> str:
"""Convert path to a representation that can be used in urls/queries"""
return path.replace("_", "-_-").replace("/", "__")
def from_url_representation(url_rep: str) -> str:
"""Reconvert url representation of path to actual path"""
return url_rep.replace("__", "/").replace("-_-", "_")
|
with open('log', 'r') as logfile:
for line in logfile:
if line.__contains__('LOG'):
print(line)
#pvahdatn@cs-arch-20:~/git/dandelion-lib$ sbt "testOnly dataflow.test03Tester" > log
|
'''
Write a function to delete a node (except the tail) in a singly
linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked
list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked
list should become 4 -> 5 -> 9 after calling your function.
Note:
* The linked list will have at least two elements.
* All of the nodes' values will be unique.
* The given node will not be the tail and it will always be a valid node of the linked list.
* Do not return anything from your function.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
output = ""
curr = self
while curr != None:
output = output + str(curr.val) + "-> "
curr = curr.next
output += "NULL"
return output
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
sol = Solution()
x_1, x_2, x_3, x_4 = ListNode(1), ListNode(2), ListNode(3), ListNode(4)
x_1.next = x_2
x_2.next = x_3
x_3.next = x_4
# print(x_1)
sol.deleteNode(x_2)
print(x_1) |
class SortStrategy:
def sort(self, dataset):
pass
class BubbleSortStrategy(SortStrategy):
def sort(self, dataset):
print('Sorting using bubble sort')
return dataset
class QuickSortStrategy(SortStrategy):
def sort(self, dataset):
print('Sorting using quick sort')
return dataset
class Sorter:
_sorter = None
def __init__(self, sorter):
self._sorter = sorter
def sort(self, dataset):
return self._sorter.sort(dataset)
dataset = [1, 5, 4, 3, 2, 8]
sorter = Sorter(BubbleSortStrategy())
sorter.sort(dataset)
sorter = Sorter(QuickSortStrategy())
sorter.sort(dataset) |
'''
BF C(n,k)*n O(n!)
LeetCode 516
DP find the longest palindrome sequence O(n^2)
'''
class Solution:
def isValidPalindrome(self, s: str, k: int) -> bool:
n = len(str)
dp = [[0]*n for _ in range(n)]
for i in range(n-2, -1, -1):
dp[i][i] = 1
for j in range(i+1, n):
if s[i]==s[j]:
dp[i][j] = dp[i+1][j-1] + 2
else:
dp[i][j] = max(dp[i+1][j], dp[i][j-1])
return dp[0][n-1]+k >=len(s) |
def calcula_se_um_numero_eh_par(numero):
if type(numero) == int:
if numero % 2 == 0:
return True
return False
|
class StompError(Exception):
def __init__(self, message, detail):
super(StompError, self).__init__(message)
self.detail = detail
class StompDisconnectedError(Exception):
pass
class ExceededRetryCount(Exception):
pass
|
"""
BiNode: Consider a simple data structure called BiNode, which has pointers to two other nodes. The
data structure BiNode could be used to represent both a binary tree (where nodel is the left node
and node2 is the right node) or a doubly linked list (where nodel is the previous node and node2
is the next node). Implement a method to convert a binary search tree (implemented with BiNode)
into a doubly linked list. The values should be kept in order and the operation should be performed
in place (that is, on the original data structure).
(17.12, p571)
SOLUTION: recursion
Left and right halves of the tree form their own "sub-parts" of the linked list (i.e., they
appear consecutively in the linked list). So, if we recursively converted the left and right
subtrees to a doubly linked list, we can build the final linked list from those parts.
How to return the head and tail of a linked list? Return the head of a doubly linked list.
Tree as doubly linked list: form the triangle where root is middle of the list.
mid
// \\
head tail
If left subtree is not empty, left.next = root, root.prev = left
If right subtree is not empty, root.next = right, right.prev = root
If both left and right subtrees are not empty, right.next = left, left.prev = right
O(n) time: each node is touched an average of O(1) times.
O(n) space: depth of call stack
"""
class BiNode:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def append(self, other):
self.right = other
other.left = self
@staticmethod
def as_circular_linked_list(root):
if root is None:
return None
lsub = BiNode.as_circular_linked_list(root.left)
rsub = BiNode.as_circular_linked_list(root.right)
if lsub is None and rsub is None:
root.left = root
root.right = root
return root
rsub_tail = None if rsub is None else rsub.left
# join left to root
if lsub is None:
rsub.left.append(root)
else:
lsub.left.append(root)
# join right to root
if rsub is None:
root.append(lsub)
else:
root.append(rsub)
# join right to left
if lsub is not None and rsub is not None:
rsub_tail.append(lsub)
return root if lsub is None else lsub
@staticmethod
def as_linked_list(root):
"""Takes the circular linked list and break the circular connection."""
head = BiNode.as_circular_linked_list(root)
if head is None:
return None
head.left.right = None
head.left = None
return head
|
def count_votes(reactions):
"""
takes in a string with reactions from discord
parses it and return a tuple of the toal votes on each alternative
"""
positive_vote = "๐"
negative_vote = "๐"
alternatives = [positive_vote, negative_vote]
results={}
for a in alternatives:
position = reactions.find(a) + 17
votes= reactions[position:position+2]
if votes[-1] == ">": votes = votes[:-1]
results[a] = votes
return (results[positive_vote], results[negative_vote])
def net_score(results):
"""
takes in a results tuple and returns net score after a substraction
"""
if type(results) != tuple: raise TypeError
return int(results[0]) - int(results[1]) |
class ParticleDataAccessor(object):
""" This class provides access to the underlying data model.
"""
LINE_STYLE_SOLID = 0
LINE_STYLE_DASH = 1
LINE_STYLE_WAVE = 2
LINE_STYLE_SPIRAL = 3
LINE_VERTEX = 4
def id(self, object):
""" Returns an id to identify given object.
Usually it is sufficient to identify python objects directly with themselves.
Overwrite this function if this is not true for your objects.
"""
return id(object)
def particleId(self, object):
raise NotImplementedError
def isQuark(self, object):
raise NotImplementedError
def isLepton(self, object):
raise NotImplementedError
def isGluon(self, object):
raise NotImplementedError
def isBoson(self, object):
raise NotImplementedError
def color(self, object):
raise NotImplementedError
def lineStyle(self, object):
raise NotImplementedError
def createParticle(self):
raise NotImplementedError
def charge(self, object):
raise NotImplementedError
def linkMother(self, object, mother):
raise NotImplementedError
def linkDaughter(self, object, daughter):
raise NotImplementedError
|
description = 'setup for the NICOS collector'
group = 'special'
devices = dict(
CacheKafka=device(
'nicos_ess.devices.cache_kafka_forwarder.CacheKafkaForwarder',
dev_ignore=['space', 'sample'],
brokers=configdata('config.KAFKA_BROKERS'),
output_topic="nicos_cache",
update_interval=10.
),
Collector=device('nicos.services.collector.Collector',
cache='localhost:14869',
forwarders=['CacheKafka'],
),
)
|
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
if 1 not in nums: return True
start, end = nums.index(1), nums.index(1)+1
while end < len(nums):
if nums[start] == 1 and nums[end] == 1 and end - start <= k:
return False
elif nums[start] == 1 and nums[end] == 1:
start = end
end += 1
else:
end += 1
return True |
""" This module contains all notification payload objects."""
class BaseMsg(dict):
"""The BaseClass of all objects in notification payload."""
apns_keys = []
def __init__(self, custom_fields={}, **apn_args):
super(BaseMsg, self).__init__(custom_fields, **apn_args)
if custom_fields:
self.update(custom_fields)
def update_keys(self, apn_args, msg_obj_keys):
"""Transform the input keys with '_' to apns format with '-'."""
for k, v in apn_args.iteritems():
formated_k = k.replace('_', '-')
if formated_k in msg_obj_keys:
del apn_args[k]
apn_args[formated_k] = v
class Alert(BaseMsg):
"""The alert piece in aps section."""
apns_keys = [
'title', 'body', 'title-loc-key', 'title-loc-key', 'action-loc-key',
'loc-key', 'loc-args', 'launch-image']
def __init__(self, body=None, **apn_args):
self.update_keys(apn_args, Alert.apns_keys)
self.__setitem__('body', body)
super(Alert, self).__init__(**apn_args)
class APS(BaseMsg):
"""The aps section in the payload."""
apns_keys = [
'mutable-content', 'alert', 'badge', 'sound', 'content-available',
'category', 'thread-id']
def __init__(self, **apn_args):
self.update_keys(apn_args, APS.apns_keys)
super(APS, self).__init__(**apn_args)
class Payload(BaseMsg):
"""The whole payload to send to APNs as the request body."""
def __init__(self, aps, **apn_args):
self.__setitem__('aps', aps)
super(Payload, self).__init__(**apn_args)
class Headers(BaseMsg):
"""The request headers to send to APNs."""
apns_keys = [
'authorization', 'apns-id', 'apns-expiration', 'apns-priority',
'apns-topic', 'apns-collapse-id']
def __init__(self, **apn_args):
self.update_keys(apn_args, Headers.apns_keys)
super(Headers, self).__init__(**apn_args)
|
# Copyright https://www.globaletraining.com/
# List comprehensions provide a concise way to create lists.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def main():
final_list = []
for n in my_list:
final_list.append(n + 10)
print(final_list)
# TODO: Using Comprehension
final_list_comp1 = [n + 10 for n in my_list]
print(final_list_comp1)
# TODO: Using Comprehension & condition
final_list_comp2 = [n + 10 for n in my_list if n % 2 == 0]
print(final_list_comp2)
if __name__ == '__main__':
main() |
"""Win animation frames for Mystery Mansion.
Animation from: http://www.angelfire.com/ca/mathcool/fireworks.html
"""
win_animation = [
"""
.|
| |
|'| ._____
___ | | |. |' .---"|
_ .-' '-. | | .--'| || | _| |
.-'| _.| | || '-__ | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.|
| |
|'| ' ._____
___ | | . |. |' .---"|
_ .-' '-. | | . .--'| || | _| |
.-'| _.| | || '-__ | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.| _\\/_
| | /\\
|'| ' ._____
___ | | . |. |' .---"|
_ .-' '-. | | . .--'| || | _| |
.-'| _.| | || '-__ | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
* *
.| *_\\/_*
| | * /\\ *
|'| * * ._____
___ | | |. |' .---"|
_ .-' '-. | | .--'| || | _| |
.-'| _.| | || '-__ | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
* *
.| * *
| | * * _\\/_
_\\/_ |'| * * /\\ ._____
/\\ ___ | | |. |' .---"|
_ .-' '-. | | .--'| || | _| |
.-'| _.| | || '-__ | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
* *
_\\/_ .| * * .::.
.''. /\\ | | * :_\\/_:
:_\\/_: |'| * * : /\\ :_____
: /\\ :___ | | o '::'|. |' .---"|
_ '..-' '-. | | .--'| || | _| |
.-'| _.| | || '-__ | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.''. *
:_\\/_: .| .::.
.''.: /\\ : | | : :
: :'..' |'| \\'/ : :_____
: :___ | | = o = '::'|. |' .---"|
_ '..-' '-. | | /.\\.--'| || | _| |
.-'| _.| | || '-__ | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
_\\)/_
.''. /(\\
: : .| _\\/_
.''.: : | | : /\\
: :'..' |'|'.\\'/.' ._____
: :___ | |-= o =- |. |' .---"|
_ '..-' '-. | |.'/.\\:--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.
_\\)/_
.''. /(\\ .''.
: : .| ' :_\\/_:
: : | | : : /\\ :
'..' |'|'. ' .' '..'._____
___ | |-= =- |. |' .---"|
_ .-' '-. | |.' . :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
_\\/_ .''.
/\\ .| : :
| | : :
|'| '..'._____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
\\'/
* * = o =
*_\\/_* /.\\ .''.
* /\\ * .| : :
* * | | : :
|'| '..'._____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
'.\\'/.'
* * -= o =-
* * .'/.\\'.
* * .| :
* * | |
|'| ._____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
'.\\'/.'
-= =-
o .'/.\\'.
o .| :
| | .:.
|'| ':' ._____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
'. ' .'
\\'/ - -
\\'/ = o = .' . '.
= o = /.\\ .| : .:::.
/.\\ | | :::::::
|'| ':::'_____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
:
: '.\\'/.'
'.\\'/.'-= o =- .:::.
-= o =-.'/.\\'..| :::::::
.'/.\\'. : | | :::::::
: |'| ':::'_____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
:
: '.\\'/.'
'.\\'/.'-= =- * .:::.
-= =-.'/.\\'..| ::' '::
.'/.\\'. : | | ::. .::
: |'| ':::'_____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
: .
: '. ' .' _\\)/_
'. ' .'- - /(\\ .'''.
- -.' . '..| ' : :
.' . '. : | | : :
: |'| '...'_____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.
_\\)/_ _\\/_
/(\\ _\\/_ /\\
.| ' /\\
| |
|'| ._____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
. .''.
_\\)/_ .''. :_\\/_:
/(\\ :_\\/_:: /\\ :
.| ' : /\\ : '..'
o | | '..'
|'| ._____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.''.
.''. : :
_\\/_ : :: :
\\'/ .| /\\ : : '..'
= o = | | _\\/_ '..'
/.\\ |'| /\\ ._____
___ | | |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.''.
: :_\\/_:
'.\\'/.' .| : /\\.:'.
-= o =- | | '.:_\\/_:
.'/.\\'. |'| : /\\ : ._____
:__ | | '..' |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.''.
: : :
'.\\'/.' .| : .:'.
-= =- | | '.: :
.'/.\\'. |'| : : ._____
:__ | | '..' |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""",
"""
.''.
: : :
'. ' .' .| : .:'.
- - | | '.: :
.' . '. |'| : : ._____
:__ | | '..' |. |' .---"|
_ .-' '-. | | :--'| || | _| |
.-'| _.| | || '-__: | | | || |
|' | |. | || | | | | || |
___| '-' ' "" '-' '-.' '` |____
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""]
|
#!/usr/local/bin/python3
def main():
for i in range(1, 8):
print("============================")
print("Towers of Hanoi: {} Disks".format(i))
towers_of_hanoi(i)
print("Number of moves: {}".format(2**i - 1))
print("============================")
return 0
def towers_of_hanoi(n, s="source", t="target", b="buffer"):
# n is number of disks, smaller disk must always be on top of larger one
assert n > 0
if n == 1:
print("Move {} to {}".format(s, t))
return
else:
# Recursively move n-1 disks from source to buffer
towers_of_hanoi(n-1, s, b, t)
# Move largest disk from source to target
towers_of_hanoi(1, s, t, b)
# Recursively move n-1 disks from buffer to target
towers_of_hanoi(n-1, b, t, s)
if __name__ == '__main__':
main()
|
def domino():
"""Imprime todas las fichas de domino"""
a = 0
b = 0
for k in range (0,7):
a = k
for i in range (a, 7):
b = i
print (a, b)
|
# -*- coding: utf-8 -*-
"""PACKAGE INFO
This module provides some basic information about the package.
"""
# Set the package release version
version_info = (0, 0, 0)
__version__ = '.'.join(str(c) for c in version_info)
# Set the package details
__author__ = 'Jonah Crawford'
__email__ = '[email protected]'
__year__ = '2019'
__url__ = 'https://github.com/minskmaz/dckrclstrpanic'
__description__ = 'Roll panic tests for https://gun.eco'
__requires__ = ['sh', 'zope.component'] # Your package dependencies
# Default package properties
__license__ = 'MIT'
__about__ = ('{} \n\n Author: {} \n Email: {} \n Year: {} \n {} \n\n'
''.format(__name__, __author__, __email__, __year__,
__description__))
__setup_requires__ = ['pytest-runner', ]
__tests_require__ = ['pytest', 'pytest-cov', 'pytest-pep8']
|
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/Dummy.msg;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/answer.msg"
services_str = ""
pkg_name = "meturone_egitim"
dependencies_str = "std_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = "meturone_egitim;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg;std_msgs;/opt/ros/noetic/share/std_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python3"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/noetic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
|
XK_Greek_ALPHAaccent = 0x7a1
XK_Greek_EPSILONaccent = 0x7a2
XK_Greek_ETAaccent = 0x7a3
XK_Greek_IOTAaccent = 0x7a4
XK_Greek_IOTAdiaeresis = 0x7a5
XK_Greek_OMICRONaccent = 0x7a7
XK_Greek_UPSILONaccent = 0x7a8
XK_Greek_UPSILONdieresis = 0x7a9
XK_Greek_OMEGAaccent = 0x7ab
XK_Greek_accentdieresis = 0x7ae
XK_Greek_horizbar = 0x7af
XK_Greek_alphaaccent = 0x7b1
XK_Greek_epsilonaccent = 0x7b2
XK_Greek_etaaccent = 0x7b3
XK_Greek_iotaaccent = 0x7b4
XK_Greek_iotadieresis = 0x7b5
XK_Greek_iotaaccentdieresis = 0x7b6
XK_Greek_omicronaccent = 0x7b7
XK_Greek_upsilonaccent = 0x7b8
XK_Greek_upsilondieresis = 0x7b9
XK_Greek_upsilonaccentdieresis = 0x7ba
XK_Greek_omegaaccent = 0x7bb
XK_Greek_ALPHA = 0x7c1
XK_Greek_BETA = 0x7c2
XK_Greek_GAMMA = 0x7c3
XK_Greek_DELTA = 0x7c4
XK_Greek_EPSILON = 0x7c5
XK_Greek_ZETA = 0x7c6
XK_Greek_ETA = 0x7c7
XK_Greek_THETA = 0x7c8
XK_Greek_IOTA = 0x7c9
XK_Greek_KAPPA = 0x7ca
XK_Greek_LAMDA = 0x7cb
XK_Greek_LAMBDA = 0x7cb
XK_Greek_MU = 0x7cc
XK_Greek_NU = 0x7cd
XK_Greek_XI = 0x7ce
XK_Greek_OMICRON = 0x7cf
XK_Greek_PI = 0x7d0
XK_Greek_RHO = 0x7d1
XK_Greek_SIGMA = 0x7d2
XK_Greek_TAU = 0x7d4
XK_Greek_UPSILON = 0x7d5
XK_Greek_PHI = 0x7d6
XK_Greek_CHI = 0x7d7
XK_Greek_PSI = 0x7d8
XK_Greek_OMEGA = 0x7d9
XK_Greek_alpha = 0x7e1
XK_Greek_beta = 0x7e2
XK_Greek_gamma = 0x7e3
XK_Greek_delta = 0x7e4
XK_Greek_epsilon = 0x7e5
XK_Greek_zeta = 0x7e6
XK_Greek_eta = 0x7e7
XK_Greek_theta = 0x7e8
XK_Greek_iota = 0x7e9
XK_Greek_kappa = 0x7ea
XK_Greek_lamda = 0x7eb
XK_Greek_lambda = 0x7eb
XK_Greek_mu = 0x7ec
XK_Greek_nu = 0x7ed
XK_Greek_xi = 0x7ee
XK_Greek_omicron = 0x7ef
XK_Greek_pi = 0x7f0
XK_Greek_rho = 0x7f1
XK_Greek_sigma = 0x7f2
XK_Greek_finalsmallsigma = 0x7f3
XK_Greek_tau = 0x7f4
XK_Greek_upsilon = 0x7f5
XK_Greek_phi = 0x7f6
XK_Greek_chi = 0x7f7
XK_Greek_psi = 0x7f8
XK_Greek_omega = 0x7f9
XK_Greek_switch = 0xFF7E
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.