content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
Author: Sam Gerendasy
This module returns a list of free and busy time blocks
from a given list of calendar entries, between a given
start and end date, and furthermore, between a given
start and end time.
'''
def freeBusyTimes(eSet, startingBounds, endingBounds):
'''
eSet is an array of entrie... | """
Author: Sam Gerendasy
This module returns a list of free and busy time blocks
from a given list of calendar entries, between a given
start and end date, and furthermore, between a given
start and end time.
"""
def free_busy_times(eSet, startingBounds, endingBounds):
"""
eSet is an array of entries.
sta... |
{
"targets": [
{
"target_name": "bmp183",
"sources": [ "SPIDevice.cpp", "DataManip.cpp", "Bmp183Drv.cpp", "Bmp183Node.cpp" ],
"cflags": ["-std=c++11", "-Wall"],
}
]
}
| {'targets': [{'target_name': 'bmp183', 'sources': ['SPIDevice.cpp', 'DataManip.cpp', 'Bmp183Drv.cpp', 'Bmp183Node.cpp'], 'cflags': ['-std=c++11', '-Wall']}]} |
# !/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Check if a string is numeric. #
# Program Author : Happi... | if __name__ == '__main__':
user_str = input('Enter sample string: ')
try:
data = float(user_str)
except (ValueError, TypeError) as error:
print(f'\nNot numeric:\n\n{error}') |
sys.stdout = open("1-num.txt", "w")
data = "1234567890"
for a in data:
print(a)
sys.stdout.close()
| sys.stdout = open('1-num.txt', 'w')
data = '1234567890'
for a in data:
print(a)
sys.stdout.close() |
mxsum = 0
count = 0
with open("17.txt", "r") as f:
l = f.readlines()
for i in range(len(l)-1):
if (int(l[i]) % 3 == 0) or (int(l[i+1]) % 3 == 0):
count += 1
mxsum = max(mxsum, int(l[i]) + int(l[i+1]))
print(count, mxsum)
| mxsum = 0
count = 0
with open('17.txt', 'r') as f:
l = f.readlines()
for i in range(len(l) - 1):
if int(l[i]) % 3 == 0 or int(l[i + 1]) % 3 == 0:
count += 1
mxsum = max(mxsum, int(l[i]) + int(l[i + 1]))
print(count, mxsum) |
def update_all(g, mpdfg, msg_params=(), reduce_params=(), update_params=()):
updated = mpdfg.forward(g.DGLGraph, g.ndata, g.edata, g.ntype_data,
g.etype_data, *msg_params, *reduce_params, *update_params)
for key in updated:
g.ndata[key] = updated[key]
| def update_all(g, mpdfg, msg_params=(), reduce_params=(), update_params=()):
updated = mpdfg.forward(g.DGLGraph, g.ndata, g.edata, g.ntype_data, g.etype_data, *msg_params, *reduce_params, *update_params)
for key in updated:
g.ndata[key] = updated[key] |
def linearSearch(array,value):
for i in range(len(array)):
if array[i]==value:
return i
return -1
arr=[20,30,40,50,90]
print(linearSearch(arr,30)) | def linear_search(array, value):
for i in range(len(array)):
if array[i] == value:
return i
return -1
arr = [20, 30, 40, 50, 90]
print(linear_search(arr, 30)) |
def generate_mysql_command(loginpath=None, user=None, password=None, host=None, port=None, socket=None, no_header=True):
mysqlcomm = "mysql "
if loginpath is not None:
mysqlcomm += " --login-path={}".format(loginpath)
else:
mysqlcomm += " --user={}".format(user)
if password is not N... | def generate_mysql_command(loginpath=None, user=None, password=None, host=None, port=None, socket=None, no_header=True):
mysqlcomm = 'mysql '
if loginpath is not None:
mysqlcomm += ' --login-path={}'.format(loginpath)
else:
mysqlcomm += ' --user={}'.format(user)
if password is not No... |
msg_0 = "Enter an equation"
msg_1 = "Do you even know what numbers are? Stay focused!"
msg_2 = "Yes ... an interesting math operation. You've slept through all classes, haven't you?"
msg_3 = "Yeah... division by zero. Smart move..."
msg_4 = "Do you want to store the result? (y / n):"
msg_5 = "Do you want to continue ca... | msg_0 = 'Enter an equation'
msg_1 = 'Do you even know what numbers are? Stay focused!'
msg_2 = "Yes ... an interesting math operation. You've slept through all classes, haven't you?"
msg_3 = 'Yeah... division by zero. Smart move...'
msg_4 = 'Do you want to store the result? (y / n):'
msg_5 = 'Do you want to continue ca... |
class Truth:
'''
The __bool__ method is prefered over __len__ in python.
'''
def __bool__(self):
return True
def __len__(self):
return 0
if __name__ == "__main__":
X = Truth()
if X: print("Yes!"); | class Truth:
"""
The __bool__ method is prefered over __len__ in python.
"""
def __bool__(self):
return True
def __len__(self):
return 0
if __name__ == '__main__':
x = truth()
if X:
print('Yes!') |
#!/usr/bin/env python
# coding: utf-8
# # Counting Inversions
#
# The number of *inversions* in a disordered list is the number of pairs of elements that are inverted (out of order) in the list.
#
# Here are some examples:
# - [0,1] has 0 inversions
# - [2,1] has 1 inversion (2,1)
# - [3, 1, 2, 4] has 2 inv... | def count_inversions(arr):
pass
def count_inversions(arr):
start_index = 0
end_index = len(arr) - 1
output = inversion_count_func(arr, start_index, end_index)
return output
def inversion_count_func(arr, start_index, end_index):
if start_index >= end_index:
return 0
mid_index = star... |
# -*- coding: utf-8 -*-
class InvalidFieldException(Exception):
pass
class PreconditionFailException(Exception):
pass
class ItemNotFoundException(Exception):
pass
class ProductAlreadyExistsException(Exception):
pass
| class Invalidfieldexception(Exception):
pass
class Preconditionfailexception(Exception):
pass
class Itemnotfoundexception(Exception):
pass
class Productalreadyexistsexception(Exception):
pass |
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def sum(self):
return self.a + self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
def sub(self):
return self.a - self.b
class Circle:
pi = 3.14... | class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def sum(self):
return self.a + self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
def sub(self):
return self.a - self.b
class Circle:
pi = 3.141... |
#!/usr/bin/env python3
def coord(x, y, x0, y0):
dx = x - x0
dy = y - y0
if dx == 0 or dy == 0:
return 'divisa'
if dx > 0 and dy > 0:
return 'NE'
if dx < 0 and dy > 0:
return 'NO'
if dx > 0 and dy < 0:
return 'SE'
if dx < 0 and dy < 0:
return 'SO'
d... | def coord(x, y, x0, y0):
dx = x - x0
dy = y - y0
if dx == 0 or dy == 0:
return 'divisa'
if dx > 0 and dy > 0:
return 'NE'
if dx < 0 and dy > 0:
return 'NO'
if dx > 0 and dy < 0:
return 'SE'
if dx < 0 and dy < 0:
return 'SO'
def main():
while True:... |
#!/usr/bin/env python3
def main():
for i in range(1, 11):
for j in range(1, 11):
print('{0:4d}'.format(i * j), end="")
print()
if __name__ == "__main__":
main()
| def main():
for i in range(1, 11):
for j in range(1, 11):
print('{0:4d}'.format(i * j), end='')
print()
if __name__ == '__main__':
main() |
scripted_localisation_functions = [
"GetName",
"GetNameDef",
"GetAdjective",
"GetAdjectiveCap",
"GetLeader",
"GetRulingParty",
"GetRulingIdeology",
"GetRulingIdeologyNoun",
"GetPartySupport",
"GetLastElection",
"GetManpower",
"GetFactionName",
"GetFlag",
"GetNameW... | scripted_localisation_functions = ['GetName', 'GetNameDef', 'GetAdjective', 'GetAdjectiveCap', 'GetLeader', 'GetRulingParty', 'GetRulingIdeology', 'GetRulingIdeologyNoun', 'GetPartySupport', 'GetLastElection', 'GetManpower', 'GetFactionName', 'GetFlag', 'GetNameWithFlag', 'GetCommunistParty', 'GetDemocraticParty', 'Get... |
#2.uzdevums
def get_common_elements(seq1,seq2,seq3):
return tuple(set(seq1) & set(seq2) & set(seq3))
print(get_common_elements("abcd",['a','b', 'd'],('b','c', 'd')))
### 2. Task with STAR
#### Common elements
def get_common_elements(*seq1):
if len(seq1) == 0:
return ()
common_set = set(... | def get_common_elements(seq1, seq2, seq3):
return tuple(set(seq1) & set(seq2) & set(seq3))
print(get_common_elements('abcd', ['a', 'b', 'd'], ('b', 'c', 'd')))
def get_common_elements(*seq1):
if len(seq1) == 0:
return ()
common_set = set(seq1[0])
for seq_n in seq1[1:]:
common_set = comm... |
try:
reversed
except:
print("SKIP")
raise SystemExit
# argument to fromkeys has no __len__
d = dict.fromkeys(reversed(range(1)))
#d = dict.fromkeys((x for x in range(1)))
print(d)
| try:
reversed
except:
print('SKIP')
raise SystemExit
d = dict.fromkeys(reversed(range(1)))
print(d) |
#
# @lc app=leetcode id=646 lang=python3
#
# [646] Maximum Length of Pair Chain
#
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
if not pairs:
return 0
pairs.sort(key=lambda x: x[1])
prev = - sys.maxsize - 1
count = 0
for idx in range... | class Solution:
def find_longest_chain(self, pairs: List[List[int]]) -> int:
if not pairs:
return 0
pairs.sort(key=lambda x: x[1])
prev = -sys.maxsize - 1
count = 0
for idx in range(len(pairs)):
if pairs[idx][0] > prev:
prev = pairs[id... |
whunparams = {
"NUM_FEATURES": 104,
"FOLDER": 'effort/',
"HUMAN_WEIGHT": 1.5,
"RECURSION_LIMIT": 5000,
"BUDGET": "zero",
}
| whunparams = {'NUM_FEATURES': 104, 'FOLDER': 'effort/', 'HUMAN_WEIGHT': 1.5, 'RECURSION_LIMIT': 5000, 'BUDGET': 'zero'} |
# Remote run directory [Default is abaverify_temp]
# Command line run directory will override the value specified here if both are provided
#remote_run_directory = 'abaverify_temp'
# Add files to copy to the remote [Default is empty list]
# Paths relative to /tests directory
local_files_to_copy_to_remote = ['CompDam.... | local_files_to_copy_to_remote = ['CompDam.parameters']
file_extensions_to_copy_to_local = ['.dat', '.inp', '.msg', '.odb', '.sta', '.py']
copy_results_to_local = True
environment_file_name = 'abaqus_v6.env' |
def search(arr, l, h, val):
if h < l:
return -1
m = int(l + (h - l) / 2)
if val < arr[m]:
return search(arr, l, m - 1, val)
elif arr[m] < val:
return search(arr, m + 1, h, val)
return m
arr = [ 2, 3, 4, 10, 40 ]
assert 3 == search(arr, 0, len(arr) - 1, 10)
assert 0 == search(arr, 0, len(arr) ... | def search(arr, l, h, val):
if h < l:
return -1
m = int(l + (h - l) / 2)
if val < arr[m]:
return search(arr, l, m - 1, val)
elif arr[m] < val:
return search(arr, m + 1, h, val)
return m
arr = [2, 3, 4, 10, 40]
assert 3 == search(arr, 0, len(arr) - 1, 10)
assert 0 == search(ar... |
number = int(input())
if number == int(1):
print ("Monday")
if number == int(2):
print ("Tuesday")
if number == int(3):
print ("Wednesday")
if number == int(4):
print ("Thursday")
if number == int(5):
print ("Friday")
if number == int(6):
print ("Saturday")
if number == int(7):
print ("Sunda... | number = int(input())
if number == int(1):
print('Monday')
if number == int(2):
print('Tuesday')
if number == int(3):
print('Wednesday')
if number == int(4):
print('Thursday')
if number == int(5):
print('Friday')
if number == int(6):
print('Saturday')
if number == int(7):
print('Sunday')
if ... |
N,M=map(int,input().split())
AB=[list(map(int,input().split())) for i in range(N)]
AB.sort()
ans=0
count=0
for i in range(N):
count=M-AB[i][1]
if count>=0:
ans+=AB[i][0]*AB[i][1]
M=count
else:
ans+=AB[i][0]*M
break
print(ans) | (n, m) = map(int, input().split())
ab = [list(map(int, input().split())) for i in range(N)]
AB.sort()
ans = 0
count = 0
for i in range(N):
count = M - AB[i][1]
if count >= 0:
ans += AB[i][0] * AB[i][1]
m = count
else:
ans += AB[i][0] * M
break
print(ans) |
#
# PySNMP MIB module ZYXEL-RADIUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-RADIUS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:45:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, constraints_union, single_value_constraint) ... |
# if , elif , else . ladder. in python
# enter use your age and check your age status.
#age = int(input("Enter your age\n"))
'''
if (age>=18):
print("You are young")
elif(age<18):
print("You are child")
'''
# logical operators.
'''
if(age<=18 and age<60):
print("You can drive")
elif(age<18 and age>16):... | """
if (age>=18):
print("You are young")
elif(age<18):
print("You are child")
"""
'\nif(age<=18 and age<60):\n print("You can drive")\nelif(age<18 and age>16):\n print("Apply after 18") \nelse:\n print("You are kid now") \n \nif (18>20 or 18>10):\n print(True)\n\n '
a = None
if a is None... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Explore": "00_explore.ipynb"}
modules = ["explore.py"]
doc_url = "https://aayushmnit.github.io/mlcookbooks/"
git_url = "https://github.com/aayushmnit/mlcookbooks/tree/master/"
def custom_doc_links(name):... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'Explore': '00_explore.ipynb'}
modules = ['explore.py']
doc_url = 'https://aayushmnit.github.io/mlcookbooks/'
git_url = 'https://github.com/aayushmnit/mlcookbooks/tree/master/'
def custom_doc_links(name):
return None |
class Solution:
def longestDecomposition(self, text: str) -> int:
if not text:
return 0
for k in range(1, 1 + len(text)//2):
if text[:k] == text[-k:]:
return 2 + self.longestDecomposition(text[k:-k])
return 1
text = "ghiabcdefhelloadamhelloabcdefghi"... | class Solution:
def longest_decomposition(self, text: str) -> int:
if not text:
return 0
for k in range(1, 1 + len(text) // 2):
if text[:k] == text[-k:]:
return 2 + self.longestDecomposition(text[k:-k])
return 1
text = 'ghiabcdefhelloadamhelloabcdefgh... |
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
rows = len(board)
cols = len(board[0])
def helper(board, visited, remaining, curr_x, curr_y):
visited.add((curr_x, curr_y))
if not r... | class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
rows = len(board)
cols = len(board[0])
def helper(board, visited, remaining, curr_x, curr_y):
visited.add((curr_x, curr_y))
if not rem... |
s = input()
mountains = []
prev = 0
for i in range(len(s) - 1):
if s[i:i + 2] == "><":
mountains.append(s[prev:i + 1])
prev = i + 1
mountains.append(s[prev:])
ans = 0
for m in mountains:
lt = m.count("<")
gt = m.count(">")
if lt > gt: lt, gt = gt, lt
ans += (1 + gt) * gt // 2 + (1... | s = input()
mountains = []
prev = 0
for i in range(len(s) - 1):
if s[i:i + 2] == '><':
mountains.append(s[prev:i + 1])
prev = i + 1
mountains.append(s[prev:])
ans = 0
for m in mountains:
lt = m.count('<')
gt = m.count('>')
if lt > gt:
(lt, gt) = (gt, lt)
ans += (1 + gt) * gt ... |
rules = {}
lines = [l.strip() for l in open('in', 'r').readlines()]
rule_lines = lines[:lines.index('')]
message_lines = lines[lines.index('') + 1:]
for line in rule_lines:
rule_id, rule = line.split(':')
rule = rule.strip()
rules[rule_id] = rule
rules['8'] = '42 | 42 8'
rules['11'] = '42 31 | 42 11 31'... | rules = {}
lines = [l.strip() for l in open('in', 'r').readlines()]
rule_lines = lines[:lines.index('')]
message_lines = lines[lines.index('') + 1:]
for line in rule_lines:
(rule_id, rule) = line.split(':')
rule = rule.strip()
rules[rule_id] = rule
rules['8'] = '42 | 42 8'
rules['11'] = '42 31 | 42 11 31'
... |
# Direction Game
locations = {
1: "Road",
2: "Hill",
3: "Building",
4: "Valley",
5: "Forest",
}
exits = [
{"Q": 0},
{"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
{"N": 5, "Q": 0},
{"W": 1, "Q": 0},
{"N": 1, "W": 2, "Q": 0},
{"W": 2, "S": 1, "Q": 0}
]
loc = 1
while True:
av... | locations = {1: 'Road', 2: 'Hill', 3: 'Building', 4: 'Valley', 5: 'Forest'}
exits = [{'Q': 0}, {'W': 2, 'E': 3, 'N': 5, 'S': 4, 'Q': 0}, {'N': 5, 'Q': 0}, {'W': 1, 'Q': 0}, {'N': 1, 'W': 2, 'Q': 0}, {'W': 2, 'S': 1, 'Q': 0}]
loc = 1
while True:
available_exits = ', '.join(exits[loc].keys())
print(locations[loc]... |
# hash state, action
def hash_state_action(state, action):
return state + "|" + str(action)
# reverse hashing state-action to state, action
def reverse_hashing_state_action(hashing_state_action):
state , action = hashing_state_action.split("|")
#state = reverse_hashing_state(state)
action = int(action... | def hash_state_action(state, action):
return state + '|' + str(action)
def reverse_hashing_state_action(hashing_state_action):
(state, action) = hashing_state_action.split('|')
action = int(action)
return (state, action)
def get_max_action(state, q_value_function, maze_env):
max_action = None
... |
url = 'https://docs.google.com/forms/d/e/1FAIpQLSd-qJkd_S-6zeEQZuHPE5qInuByzQzQsYtb4PG4NeqkTWUC-g'
user_agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36'
maps = 'maps_RU/'
log_path = 'logs/'
| url = 'https://docs.google.com/forms/d/e/1FAIpQLSd-qJkd_S-6zeEQZuHPE5qInuByzQzQsYtb4PG4NeqkTWUC-g'
user_agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36'
maps = 'maps_RU/'
log_path = 'logs/' |
operations = {
"average": lambda seq: sum(seq) / len(seq),
"total": sum, #lambda seq: sum(seq)
"top": max #lambda seq: max(seq)
}
students = [
{"name": "Kamran", "grades": (67, 90, 95, 100)},
{"name": "Ali", "grades": (56, 78, 80, 90)}
]
for student in students:
name = student["name"]
grades = student[... | operations = {'average': lambda seq: sum(seq) / len(seq), 'total': sum, 'top': max}
students = [{'name': 'Kamran', 'grades': (67, 90, 95, 100)}, {'name': 'Ali', 'grades': (56, 78, 80, 90)}]
for student in students:
name = student['name']
grades = student['grades']
operation = input("Enter 'average', 'total'... |
def add_native_methods(clazz):
def setOption__java_lang_String__java_lang_String__(a0, a1, a2):
raise NotImplementedError()
def getOption__java_lang_String__(a0, a1):
raise NotImplementedError()
clazz.setOption__java_lang_String__java_lang_String__ = setOption__java_lang_String__java_lang_... | def add_native_methods(clazz):
def set_option__java_lang__string__java_lang__string__(a0, a1, a2):
raise not_implemented_error()
def get_option__java_lang__string__(a0, a1):
raise not_implemented_error()
clazz.setOption__java_lang_String__java_lang_String__ = setOption__java_lang_String__j... |
def concat(s1,s2):
return s1 + " "+ s2
s = concat("John", "Doe")
print(s) | def concat(s1, s2):
return s1 + ' ' + s2
s = concat('John', 'Doe')
print(s) |
class Film:
def __init__(self, imdbid, title, year, duration, rating, format, known_as):
self.imdbid = imdbid
self.title = title
self.year = year
self.duration = duration
self.rating = rating
self.format = format
self.known_as = known_as | class Film:
def __init__(self, imdbid, title, year, duration, rating, format, known_as):
self.imdbid = imdbid
self.title = title
self.year = year
self.duration = duration
self.rating = rating
self.format = format
self.known_as = known_as |
# dict object with special methods
d = {}
d.__setitem__('2', 'two')
print(d.__getitem__('2'))
d.__delitem__('2')
print(d)
print("PASS") | d = {}
d.__setitem__('2', 'two')
print(d.__getitem__('2'))
d.__delitem__('2')
print(d)
print('PASS') |
i=0
sum=0
while i<1000:
if(i%3==0) or (i%5==0):
sum=sum+i;
i=i+1
print(sum); | i = 0
sum = 0
while i < 1000:
if i % 3 == 0 or i % 5 == 0:
sum = sum + i
i = i + 1
print(sum) |
class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
e=0
o=0
for i in position:
if i%2==0:
e=e+1
else:
o=o+1
return min(e,o)
| class Solution:
def min_cost_to_move_chips(self, position: List[int]) -> int:
e = 0
o = 0
for i in position:
if i % 2 == 0:
e = e + 1
else:
o = o + 1
return min(e, o) |
# Classes - Graph classes
'''
Graph class
Uses a distionary to store vertices in the format vertex_name
and vertex_object
To add a new vertex to the graph, we first check if the object
passed in is a vertex object, then ckeck if it already exists
in the graph. If both checks pass, then we add the vertex to the graph... | """
Graph class
Uses a distionary to store vertices in the format vertex_name
and vertex_object
To add a new vertex to the graph, we first check if the object
passed in is a vertex object, then ckeck if it already exists
in the graph. If both checks pass, then we add the vertex to the graph's vertices
dictionary.
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, target: int) -> bool:
if not root: return False
if not root.left and not root.right:... | class Solution:
def has_path_sum(self, root: TreeNode, target: int) -> bool:
if not root:
return False
if not root.left and (not root.right):
return root.val == target
return any((self.hasPathSum(child, target - root.val) for child in (root.left, root.right))) |
def enQueue(i):
lst.append(i)
def deQueue():
return lst.pop(0)
lst = ['a','b','c','d','e']
enQueue('t')
enQueue('g')
enQueue('h')
print(lst)
d = deQueue()
print(d)
d = deQueue()
print(d)
d = deQueue()
print(d)
d = deQueue()
print(d)
d = deQueue()
print(d)
print(lst) | def en_queue(i):
lst.append(i)
def de_queue():
return lst.pop(0)
lst = ['a', 'b', 'c', 'd', 'e']
en_queue('t')
en_queue('g')
en_queue('h')
print(lst)
d = de_queue()
print(d)
d = de_queue()
print(d)
d = de_queue()
print(d)
d = de_queue()
print(d)
d = de_queue()
print(d)
print(lst) |
def name(name_class, slug, name, desc="", order=0, **kwargs):
# create if it doesn't exist, set name and desc
obj, created = name_class.objects.get_or_create(slug=slug)
if created:
obj.name = name
obj.desc = desc
obj.order = order
for k, v in kwargs.iteritems():
s... | def name(name_class, slug, name, desc='', order=0, **kwargs):
(obj, created) = name_class.objects.get_or_create(slug=slug)
if created:
obj.name = name
obj.desc = desc
obj.order = order
for (k, v) in kwargs.iteritems():
setattr(obj, k, v)
obj.save()
return ... |
def reverse_string(s="hello"):
s_reverse = s[::-1]
return s_reverse
print(reverse_string())
| def reverse_string(s='hello'):
s_reverse = s[::-1]
return s_reverse
print(reverse_string()) |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/shams3049/catkin_ws/src/simtrack/interface/include".split(';') if "/home/shams3049/catkin_ws/src/simtrack/interface/include" != "" else []
PROJECT_CATKIN_DEPENDS = "low_level_vision;pose_estimati... | catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/shams3049/catkin_ws/src/simtrack/interface/include'.split(';') if '/home/shams3049/catkin_ws/src/simtrack/interface/include' != '' else []
project_catkin_depends = 'low_level_vision;pose_estimation;cv_bridge'.replace(';', ' ')
pkg_config_libraries_with... |
class PathDoesNotExist(Exception):
def __init__(self, name) -> None:
msg = f"The path '{name}' does not exist"
super().__init__(msg)
class ModuleDoesNotExist(Exception):
def __init__(self, name) -> None:
msg = f"The module '{name}' does not exist"
super().__init__(msg)
class ... | class Pathdoesnotexist(Exception):
def __init__(self, name) -> None:
msg = f"The path '{name}' does not exist"
super().__init__(msg)
class Moduledoesnotexist(Exception):
def __init__(self, name) -> None:
msg = f"The module '{name}' does not exist"
super().__init__(msg)
class ... |
class Node():
def __init__(self, value):
self.value = value
self.leftchild = None
self.rightchild = None
class Tree():
def __init__(self, value):
self.root = Node(value)
self.height = -1
self.values = [value]
self.element = 0
self.links = [self.r... | class Node:
def __init__(self, value):
self.value = value
self.leftchild = None
self.rightchild = None
class Tree:
def __init__(self, value):
self.root = node(value)
self.height = -1
self.values = [value]
self.element = 0
self.links = [self.root... |
#zip: zip(*iterables)
#built-in iterables (like: list, string, dict), or user-defined iterables
lang=['python','java','c']
creators=['guido','james','denis']
for lang,creators in zip(lang,creators):
print(lang,creators)
| lang = ['python', 'java', 'c']
creators = ['guido', 'james', 'denis']
for (lang, creators) in zip(lang, creators):
print(lang, creators) |
# -*- coding: utf-8 -*-
'''
In this config file the parameters for later use in all the scripts are stored
'''
CONFIG = {
'folder':'data/deviceX/', # set folder where calibration data will be stored
'filenameCalib':'dataE_calib', # name of file for calibration data aquisition
'filename... | """
In this config file the parameters for later use in all the scripts are stored
"""
config = {'folder': 'data/deviceX/', 'filenameCalib': 'dataE_calib', 'filenameTols': 'data_tols'} |
####### One More Day's Config File
####### Lytes - Laitanayoola@gmail.com
####### Add More Youtube Channels If You Want A Bigger Pool To Pick From
source = ['https://www.youtube.com/channel/UCa10nxShhzNrCE1o2ZOPztg',
'https://www.youtube.com/channel/UCCvVpbYRgYjMN7mG7qQN0Pg',
'https://www.youtube.com/channel/UCj_Y-x... | source = ['https://www.youtube.com/channel/UCa10nxShhzNrCE1o2ZOPztg', 'https://www.youtube.com/channel/UCCvVpbYRgYjMN7mG7qQN0Pg', 'https://www.youtube.com/channel/UCj_Y-xJ2DRDGP4ilfzplCOQ', 'https://www.youtube.com/channel/UCS34YVeqtFViWRB3jc3o2FQ', 'https://www.youtube.com/channel/UCRrCiR_F-olJgMClfsl7YAg', 'https://w... |
TASK_NORMALIZE = {
"cifar10": {
"mean": (0.49139968, 0.48215841, 0.44653091),
"std": (0.24703223, 0.24348513, 0.26158784),
},
"cifar100": {
"mean": (0.50707516, 0.48654887, 0.44091784),
"std": (0.26733429, 0.25643846, 0.27615047),
},
"mnist": {"mean": [0.1307], "std":... | task_normalize = {'cifar10': {'mean': (0.49139968, 0.48215841, 0.44653091), 'std': (0.24703223, 0.24348513, 0.26158784)}, 'cifar100': {'mean': (0.50707516, 0.48654887, 0.44091784), 'std': (0.26733429, 0.25643846, 0.27615047)}, 'mnist': {'mean': [0.1307], 'std': [0.3081]}}
task_num_class = {'cifar10': 10, 'cifar100': 10... |
def run_command():
response = '__Book of Spells__'
spells = {
'convert': 'Convert magic ore into mana.',
'teleport': 'Teleport up to 10 tiles away.',
'heal': 'Heal 10 health.',
}
response = '__Spell Book__'
for command, description in spells.items():
response += '\... | def run_command():
response = '__Book of Spells__'
spells = {'convert': 'Convert magic ore into mana.', 'teleport': 'Teleport up to 10 tiles away.', 'heal': 'Heal 10 health.'}
response = '__Spell Book__'
for (command, description) in spells.items():
response += '\n**{}**: `{}`'.format(command, d... |
def letter_queue(commands):
queue = []
for i in commands:
temp = i.split()
if temp[0].strip() == 'PUSH':
queue.append(temp[1].strip())
elif temp[0].strip() == 'POP':
queue = queue[1:]
return ''.join(queue)
if __name__ == '__main__':
# These "asserts" usi... | def letter_queue(commands):
queue = []
for i in commands:
temp = i.split()
if temp[0].strip() == 'PUSH':
queue.append(temp[1].strip())
elif temp[0].strip() == 'POP':
queue = queue[1:]
return ''.join(queue)
if __name__ == '__main__':
assert letter_queue(['P... |
combs = set()
for a in xrange(2,101):
for b in xrange(2,101):
combs.add(a**b)
print(len(combs)) # 9183 | combs = set()
for a in xrange(2, 101):
for b in xrange(2, 101):
combs.add(a ** b)
print(len(combs)) |
# ------------------------------
# 417. Pacific Atlantic Water Flow
#
# Description:
# Given an m x n matrix of non-negative integers representing the height of each unit cell in a
# continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic
# ocean" touches the right and bottom ed... | class Solution:
def pacific_atlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix or not matrix[0]:
return
res = []
n = len(matrix)
m = len(matrix[0])
pacific = [[False for _ in range(m)] for _ in range(n)]
atlantic = [[False for _ in ... |
class McostGrid():
default_value = 1
def __init__(self):
self.grid = []
self.terrain_types = []
self.unit_types = []
@property
def row_headers(self):
return self.terrain_types
@property
def column_headers(self):
return self.unit_types
def set(self,... | class Mcostgrid:
default_value = 1
def __init__(self):
self.grid = []
self.terrain_types = []
self.unit_types = []
@property
def row_headers(self):
return self.terrain_types
@property
def column_headers(self):
return self.unit_types
def set(self, c... |
def sort(arr, exp1):
n = len(arr)
output = [0] * (n)
count = [0] * (10)
for i in range(0, n):
index = (arr[i]/exp1)
count[int((index)%10)] += 1
for i in range(1,10):
count[i] += count[i-1]
i = n-1
while i>=0:
index = (arr[i]/exp1)
output[ count[ int((index)%10) ] - 1] = arr[i]
count[... | def sort(arr, exp1):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(0, n):
index = arr[i] / exp1
count[int(index % 10)] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] / exp1
output[count[int(i... |
'''
import flask as f # give name to flask mode]ule as f
print(f.__version__) # see version
import sys
print(sys.path)
import f33var
print(f33var.n)
'''
| """
import flask as f # give name to flask mode]ule as f
print(f.__version__) # see version
import sys
print(sys.path)
import f33var
print(f33var.n)
""" |
# Remove Duplicates from Sorted List
# https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list/
#
# Given a sorted linked list, delete all duplicates such that each element appear only once.
#
# For example,
# Given 1->1->2, return 1->2.
# Given 1->1->2->3->3, return 1->2->3.
#
# # # # # # # # # # # # ... | class Solution:
def delete_duplicates(self, A):
if A is None or A.next is None:
return A
(prev, tmp) = (A, A.next)
while tmp:
if prev.val == tmp.val:
prev.next = tmp.next
tmp = prev.next
else:
prev = tmp
... |
if __name__ == "__main__":
with open("12_04_01.txt", "r") as f:
rng = f.readline().split("-")
pwds = []
for pwd in range(int(rng[0]), int(rng[1])):
lpwd = [char for char in str(pwd)]
for num in lpwd:
num = int(num)
flag = 1
... | if __name__ == '__main__':
with open('12_04_01.txt', 'r') as f:
rng = f.readline().split('-')
pwds = []
for pwd in range(int(rng[0]), int(rng[1])):
lpwd = [char for char in str(pwd)]
for num in lpwd:
num = int(num)
flag = 1
for ... |
'''
Joe Walter
difficulty: 5%
run time: 0:00
answer: 9110846700
***
048 Self Powers
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
'''
def solve(n, num_digits = 10):
mod = 10**num_digits
sum = 0
for k in range(1, n+1):
sum += pow(k, k, mod)
return sum % mod
assert solve(10... | """
Joe Walter
difficulty: 5%
run time: 0:00
answer: 9110846700
***
048 Self Powers
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
"""
def solve(n, num_digits=10):
mod = 10 ** num_digits
sum = 0
for k in range(1, n + 1):
sum += pow(k, k, mod)
return sum % ... |
# Number of occurrences of 2 as a digit in numbers from 0 to n
# Count the number of 2s as digit in all numbers from 0 to n.
# Examples :
# Input : 22
# Output : 6
# Explanation: Total 2s that appear as digit
# from 0 to 22 are (2, 12, 20,
# 21, 22);
# Input : 100
# Output : 20
# Explanat... | def occurance_of_twos(n):
num = 0
two_count = 0
while num <= n:
two_count += list(str(num)).count('2')
num += 1
return twoCount
print(occurance_of_twos(22))
print(occurance_of_twos(100)) |
emojis = [{"id": 1, "emoji": "emoji1", "active": "y", "type": "Free", "type_num": 1},
{"id": 2, "emoji": "emoji2", "active": "y", "type": "Free", "type_num": 1},
{"id": 3, "emoji": "emoji3", "active": "y", "type": "Free", "type_num": 1},
{"id": 4, "emoji": "emoji4", "active": "y", "typ... | emojis = [{'id': 1, 'emoji': 'emoji1', 'active': 'y', 'type': 'Free', 'type_num': 1}, {'id': 2, 'emoji': 'emoji2', 'active': 'y', 'type': 'Free', 'type_num': 1}, {'id': 3, 'emoji': 'emoji3', 'active': 'y', 'type': 'Free', 'type_num': 1}, {'id': 4, 'emoji': 'emoji4', 'active': 'y', 'type': 'Free', 'type_num': 1}, {'id':... |
#-----------------------------------------------------------------------------
# Runtime: 56ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def permuteUnique(self, nums: [int]) -> [[int]]:
if len(nums) == 1:
return [ nu... | class Solution:
def permute_unique(self, nums: [int]) -> [[int]]:
if len(nums) == 1:
return [nums]
nums.sort()
visited = [False] * len(nums)
result = []
temp_result = []
def dfs(temp_result: [int]):
if len(nums) == len(temp_result):
... |
#1. Create a greeting for your program.
#2. Ask the user for the city that they grew up in.
#3. Ask the user for the name of a pet.
#4. Combine the name of their city and pet and show them their band name.
#5. Make sure the input cursor shows on a new line, see the example at:
# https://band-name-generator-end.ap... | print('Welcome to Band Name Generator')
city = input("What's name of the city you grew up in?\n")
pet = input("What is the name of your pet?(Let's have a pet's name if not a pet otherwise)\n")
print('Seems like ' + pet + ' ' + city + ' will be a good band name for you') |
mysql = {
'host': 'localhost',
'user': 'student',
'password': 'student',
'database': 'BeerDB'
}
| mysql = {'host': 'localhost', 'user': 'student', 'password': 'student', 'database': 'BeerDB'} |
# Adesh Gautam
def merge(arr, l, m, r):
L = arr[:m]
R = arr[m:]
n1 = len(L)
n2 = len(R)
i, j, k = 0, 0, 0
while i < n1 and j < n2 :
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
whi... | def merge(arr, l, m, r):
l = arr[:m]
r = arr[m:]
n1 = len(L)
n2 = len(R)
(i, j, k) = (0, 0, 0)
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k]... |
# python is a General Purpose High level Programming Language
# Dictionaries
''' Dictionaries are unordered changeable (muteable) indexed collections
in Python Dictionaries are Declared with {} and key value pairs
'''
thisDict = {
'Name':'Shinji Ikari',
'Father':'Gendo Ikari',
'Mother':'Yui Ikari',
... | """ Dictionaries are unordered changeable (muteable) indexed collections
in Python Dictionaries are Declared with {} and key value pairs
"""
this_dict = {'Name': 'Shinji Ikari', 'Father': 'Gendo Ikari', 'Mother': 'Yui Ikari', 'Guardian': 'Misato Kasturagi'}
print(thisDict)
thisDict['Father'] = 'Ikari Gendo'
print(... |
#!/usr/bin/env python
# encoding: utf-8
FILE = 'File'
ASSIGNMENT = 'Assignment'
DOWNLOAD_URL_EXTENSION = "?forcedownload=1"
| file = 'File'
assignment = 'Assignment'
download_url_extension = '?forcedownload=1' |
class Solution(object):
def numTilings(self, N):
H = [[0, 0] for _ in xrange(N+1)]
H[0][0] = 1
H[1][0] = 1
for i in xrange(2, N+1):
H[i][0] = (H[i-1][0] + H[i-2][0] + H[i-1][1]*2) % 1000000007
H[i][1] = (H[i-2][0] + H[i-1][1]) % 1000000007
... | class Solution(object):
def num_tilings(self, N):
h = [[0, 0] for _ in xrange(N + 1)]
H[0][0] = 1
H[1][0] = 1
for i in xrange(2, N + 1):
H[i][0] = (H[i - 1][0] + H[i - 2][0] + H[i - 1][1] * 2) % 1000000007
H[i][1] = (H[i - 2][0] + H[i - 1][1]) % 1000000007
... |
#dic.py
stu = {"203-2012-045":"John", "203-2012-037":"Peter"}
stu["202-2011-121"] = "Susan"
print(stu["202-2011-121"])
del stu["202-2011-121"]
for key in stu:
print(key+" : "+str(stu[key]))
for value in stu.values():
print(value)
for item in stu.items():
print(item)
print("203-2012-037" in stu)
print(tuple(stu.ke... | stu = {'203-2012-045': 'John', '203-2012-037': 'Peter'}
stu['202-2011-121'] = 'Susan'
print(stu['202-2011-121'])
del stu['202-2011-121']
for key in stu:
print(key + ' : ' + str(stu[key]))
for value in stu.values():
print(value)
for item in stu.items():
print(item)
print('203-2012-037' in stu)
print(tuple(st... |
class AttrDict(object):
def __init__(self, initializer=None):
self._data=dict()
self._initializer = initializer
self._is_initialized = False if initializer is not None else True
def _initialize(self):
if self._initializer:
self._initializer(self)
def get(self, ... | class Attrdict(object):
def __init__(self, initializer=None):
self._data = dict()
self._initializer = initializer
self._is_initialized = False if initializer is not None else True
def _initialize(self):
if self._initializer:
self._initializer(self)
def get(self... |
# integers
print(format(10, '+'))
print(format(15, 'b'))
print(format(15, 'x'))
print(format(15, 'X'))
# float
print(format(.2, '%'))
print(format(10.5, 'e'))
print(format(10.5, 'e'))
print(format(10.5345678, 'f'))
print(format(10.5, 'F'))
class Data:
id = 0
def __init__(self, i):
self.id = i
... | print(format(10, '+'))
print(format(15, 'b'))
print(format(15, 'x'))
print(format(15, 'X'))
print(format(0.2, '%'))
print(format(10.5, 'e'))
print(format(10.5, 'e'))
print(format(10.5345678, 'f'))
print(format(10.5, 'F'))
class Data:
id = 0
def __init__(self, i):
self.id = i
def __format__(self, ... |
class Man:
def __init__(self, name):
self.name = name
def hello(self):
print(self.name)
m = Man("Ken")
m.hello()
| class Man:
def __init__(self, name):
self.name = name
def hello(self):
print(self.name)
m = man('Ken')
m.hello() |
@frappe.whitelist(allow_guest=True)
def holdOrder(data):
try:
doc = data
if isinstance(doc, string_types):
doc = json.loads(doc)
if doc.get('hold_Id'):
cart = frappe.get_doc('Shopping Cart', doc.get('hold_Id'))
else:
cart = frappe.new_doc('Shopping Cart')
cart.cart_type = 'Pos Cart'
car... | @frappe.whitelist(allow_guest=True)
def hold_order(data):
try:
doc = data
if isinstance(doc, string_types):
doc = json.loads(doc)
if doc.get('hold_Id'):
cart = frappe.get_doc('Shopping Cart', doc.get('hold_Id'))
else:
cart = frappe.new_doc('Shoppin... |
class Solution:
def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
v = [i for i in nums1]
v.sort()
gap = float('-inf')
for ind, (i, j) in enumerate(zip(nums1, nums2)):
k = bisect.bisect_right(v, j)
if k < len(nums1):
gap =... | class Solution:
def min_absolute_sum_diff(self, nums1: List[int], nums2: List[int]) -> int:
v = [i for i in nums1]
v.sort()
gap = float('-inf')
for (ind, (i, j)) in enumerate(zip(nums1, nums2)):
k = bisect.bisect_right(v, j)
if k < len(nums1):
... |
def look():
for i in range (1,101):
if i%3==0:
print("Fizz")
elif i%5==0:
print("Buzz")
elif i%3==0 and i//5==0:
print("FizzBuzz")
else:
print(i)
look() | def look():
for i in range(1, 101):
if i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
elif i % 3 == 0 and i // 5 == 0:
print('FizzBuzz')
else:
print(i)
look() |
#!/usr/bin/env python3
N = 53
eps = 1.0
for i in range(N):
eps = eps /2
onepeps = 1.0 + eps
print('eps = ', eps, ' , one + eps = ', onepeps)
| n = 53
eps = 1.0
for i in range(N):
eps = eps / 2
onepeps = 1.0 + eps
print('eps = ', eps, ' , one + eps = ', onepeps) |
{'stack': {'backgrounds': [{'components': [{'label': 'Make Visible',
'name': 'Command4',
'position': (480, 16),
'size': (89, 25),
'type': 'VBBut... | {'stack': {'backgrounds': [{'components': [{'label': 'Make Visible', 'name': 'Command4', 'position': (480, 16), 'size': (89, 25), 'type': 'VBButton'}, {'label': 'Move ', 'name': 'Command5', 'position': (576, 16), 'size': (89, 25), 'type': 'VBButton'}, {'label': 'Size ', 'name': 'Command6', 'position': (672, 16), 'size'... |
def bit_add(bit, i, x):
i += 1
n = len(bit)
while i <= n:
bit[i - 1] += x
i += i & -i
def bit_sum(bit, i):
result = 0
i += 1
while i > 0:
result += bit[i - 1]
i -= i & -i
return result
def bit_query(bit, start, stop):
if start == 0:
return bit_... | def bit_add(bit, i, x):
i += 1
n = len(bit)
while i <= n:
bit[i - 1] += x
i += i & -i
def bit_sum(bit, i):
result = 0
i += 1
while i > 0:
result += bit[i - 1]
i -= i & -i
return result
def bit_query(bit, start, stop):
if start == 0:
return bit_su... |
#!phthon 2
ip = raw_input("please type ip :")
# print "{:<12} {:<12} {:<12} {:<12}".format(*ip.split('.'))
ip_addr = ip.split(".")
ip_addr[3]='0'
print (ip_addr[0],ip_addr[1],ip_addr[2],ip_addr[3])
print (bin(int(ip_addr[0])),bin(int(ip_addr[1])),bin(int(ip_addr[2])),bin(int(ip_addr[3])))
| ip = raw_input('please type ip :')
ip_addr = ip.split('.')
ip_addr[3] = '0'
print(ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3])
print(bin(int(ip_addr[0])), bin(int(ip_addr[1])), bin(int(ip_addr[2])), bin(int(ip_addr[3]))) |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Assignment 1 Day8
def getInput(calculate_arg_fun):
def Fibonacci(n):
if n<=0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==1:
return 0
# Second Fibonacci number is 1
elif n==2:
... | def get_input(calculate_arg_fun):
def fibonacci(n):
if n <= 0:
print('Incorrect input')
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
return calculate_arg_fun(a)
return Fibonac... |
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
if(hour == 12):
hour = 0
angle_h = hour * 30.0 + minutes / 2.0
angle_m = minutes * 6.0
ans = abs(angle_h - angle_m)
return ans if 360.0 - ans > ans else 360.0 - ans
| class Solution:
def angle_clock(self, hour: int, minutes: int) -> float:
if hour == 12:
hour = 0
angle_h = hour * 30.0 + minutes / 2.0
angle_m = minutes * 6.0
ans = abs(angle_h - angle_m)
return ans if 360.0 - ans > ans else 360.0 - ans |
graph = [
[],
[2, 6],
[1],
[4, 5, 6],
[3],
[3],
[1, 3]
]
def dfs1(v, visited, graph):
stack = [v]
while stack:
node = stack.pop()
visited[node] = True
print(node)
for nd in graph[node]:
if not visited[nd]:
stack.append(nd)... | graph = [[], [2, 6], [1], [4, 5, 6], [3], [3], [1, 3]]
def dfs1(v, visited, graph):
stack = [v]
while stack:
node = stack.pop()
visited[node] = True
print(node)
for nd in graph[node]:
if not visited[nd]:
stack.append(nd)
def dfs2(v, visited, graph):
... |
class Calculator:
def __init__(self, a: int, b: int) -> None:
self.a = a
self.b = b
def suma(self) -> int:
return self.a+self.b
def resta(self) -> int:
return self.a-self.b
def multi(self) -> int:
return self.a*self.b
def divi(self) -> int:... | class Calculator:
def __init__(self, a: int, b: int) -> None:
self.a = a
self.b = b
def suma(self) -> int:
return self.a + self.b
def resta(self) -> int:
return self.a - self.b
def multi(self) -> int:
return self.a * self.b
def divi(self) -> int:
... |
#Linear Search
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
n = int(input("Enter number: "))
arr = list(map(int, input().split()))
target = int(input("Enter target: "))
print(linear_search(arr, target))
| def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
n = int(input('Enter number: '))
arr = list(map(int, input().split()))
target = int(input('Enter target: '))
print(linear_search(arr, target)) |
# FLAKE8: NOQA
c = get_config()
c.TerminalIPythonApp.display_banner = True
c.InteractiveShellApp.log_level = 20
c.InteractiveShellApp.extensions = [
# 'myextension'
]
c.InteractiveShellApp.exec_lines = [
# '%load_ext pyflyby',
# 'import json',
# 'import requests',
# 'import pandas as pd',
]
c.Inte... | c = get_config()
c.TerminalIPythonApp.display_banner = True
c.InteractiveShellApp.log_level = 20
c.InteractiveShellApp.extensions = []
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_files = []
c.InteractiveShell.autoindent = True
c.InteractiveShell.colors = 'LightBG'
c.InteractiveShell.confirm_exit = ... |
# Selection structure
# conditional operators: if, else,elif
name = "Pedro"
if name:
print("The variable is not empty")
number1 = 20
number2 = 30
if number1 != number2:
print("Number 1 is lower than number 2")
else:
print("Number 2 is bigger than number 1")
color = "blue"
if color == "green":
pr... | name = 'Pedro'
if name:
print('The variable is not empty')
number1 = 20
number2 = 30
if number1 != number2:
print('Number 1 is lower than number 2')
else:
print('Number 2 is bigger than number 1')
color = 'blue'
if color == 'green':
print('Go ahead')
elif color == 'red':
print('Stop')
elif color == ... |
class TestModel_E2E_CNN:
def test_basic(self):
pass
# TODO
| class Testmodel_E2E_Cnn:
def test_basic(self):
pass |
# -*- coding: utf-8 -*-
def execute_rule(**kwargs):
sql = kwargs.get("sql")
bind_num = kwargs.get("or_num")
if sql.count(" or ") > bind_num:
return True
return False
| def execute_rule(**kwargs):
sql = kwargs.get('sql')
bind_num = kwargs.get('or_num')
if sql.count(' or ') > bind_num:
return True
return False |
def gen_mp4(src='pipe:0', dest='pipe:1'):
return [
'ffmpeg',
'-y',
'-i', src,
'-crf', '25',
'-preset', 'faster',
'-f', 'mp4',
'-movflags', 'frag_keyframe+empty_moov',
dest
]
def gen_mp3(src='pipe:0', dest='pipe:1', empty=False):
cmd = [
... | def gen_mp4(src='pipe:0', dest='pipe:1'):
return ['ffmpeg', '-y', '-i', src, '-crf', '25', '-preset', 'faster', '-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov', dest]
def gen_mp3(src='pipe:0', dest='pipe:1', empty=False):
cmd = ['ffmpeg', '-y', '-i', src, '-codec:a', 'libmp3lame', '-qscale:a', '2', dest]
... |
pink = 0xDEADBF
yellow = 0xFDDF86
blue = 0x6F90F5
red = 0xe74c3c
dark_red = 0x992d22
green = 0x1fb600
gold = 0xd4af3a
| pink = 14593471
yellow = 16637830
blue = 7311605
red = 15158332
dark_red = 10038562
green = 2078208
gold = 13938490 |
# Use this file to maintain resume data
# ======================================================
# ============= NAME AND CONTACT =======================
contact_info = {
'name':'Some Guy',
'street':'123 Fake St',
'city': 'Springfield',
'state':'OR',
'zip': '99700',
'phone':'555-555-5555',
'email':'som... | contact_info = {'name': 'Some Guy', 'street': '123 Fake St', 'city': 'Springfield', 'state': 'OR', 'zip': '99700', 'phone': '555-555-5555', 'email': 'someguy@somewebsite.example.com', 'title': 'All Around Great Guy'}
links = [{'url': 'http://www.google.com', 'label': 'Link'}]
about = 'Some Guy has over 20 years of expe... |
class Enum(object):
class __metaclass__(type):
def __getitem__(self, key):
return "Constants.{0}".format([item for item in self.__dict__ if key == self.__dict__[item]][0])
def get_name(self, key):
return "Constants.{0}".format([item for item in self.__dict__ if key == self.__... | class Enum(object):
class __Metaclass__(type):
def __getitem__(self, key):
return 'Constants.{0}'.format([item for item in self.__dict__ if key == self.__dict__[item]][0])
def get_name(self, key):
return 'Constants.{0}'.format([item for item in self.__dict__ if key == self... |
#create
dictionary1 = {1:"a", 2:"b", 3:"c"}
#access
print(dictionary1[1])
#updating
dictionary1[1]="hello"
print(dictionary1)
#delete
del dictionary1[1]
dictionary1.clear() # to clear it but keep the variable
print(dictionary1.keys())
print(dictionary1.values())
| dictionary1 = {1: 'a', 2: 'b', 3: 'c'}
print(dictionary1[1])
dictionary1[1] = 'hello'
print(dictionary1)
del dictionary1[1]
dictionary1.clear()
print(dictionary1.keys())
print(dictionary1.values()) |
# Adapted, with minor modifications, from stackoverflow:
# https://stackoverflow.com/questions/6752374/cube-root-modulo-p-how-do-i-do-this
# did not test fully, but it works for the NTTRU parameters we're using
def tonelli3(a,p,many=False):
def solution(p,root):
g=p-2
while pow(g,(p-1)//3,p)==1: ... | def tonelli3(a, p, many=False):
def solution(p, root):
g = p - 2
while pow(g, (p - 1) // 3, p) == 1:
g -= 1
g = pow(g, (p - 1) // 3, p)
return sorted([root % p, root * g % p, root * g ** 2 % p])
a = a % p
if p in [2, 3] or a == 0:
return a
if p % 3 ==... |
def localSant(numOfSiblings, numOfSweets) -> str:
try:
if numOfSweets == 0:
return 'no sweets left'
if numOfSweets % numOfSiblings == 0:
return 'give away'
else:
return 'eat them yourself'
except ZeroDivisionError:
return 'eat them yourself'
if __name__ == '__main__':
print(... | def local_sant(numOfSiblings, numOfSweets) -> str:
try:
if numOfSweets == 0:
return 'no sweets left'
if numOfSweets % numOfSiblings == 0:
return 'give away'
else:
return 'eat them yourself'
except ZeroDivisionError:
return 'eat them yourself'
i... |
def part1(s):
i = 0
while i < len(s) - 1:
react = abs(ord(s[i]) - ord(s[i+1])) == 32
if react:
if i == len(s) - 1:
s = s[:i]
else:
s = s[:i] + s[i+2:]
i = max(0, i-1)
else:
i += 1
return len(s)
def ... | def part1(s):
i = 0
while i < len(s) - 1:
react = abs(ord(s[i]) - ord(s[i + 1])) == 32
if react:
if i == len(s) - 1:
s = s[:i]
else:
s = s[:i] + s[i + 2:]
i = max(0, i - 1)
else:
i += 1
return len(s)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.