content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#
# PySNMP MIB module ARUBA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARUBA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:25:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) ... |
def session_hist_tex(f, session_data,threshold_requests_per_session):
"""
Write session caracteristics in latex file
Parameters
----------
f: file
session_data: pandas dataframe of sessions
threshold_requests_per_session: int for f... | def session_hist_tex(f, session_data, threshold_requests_per_session):
"""
Write session caracteristics in latex file
Parameters
----------
f: file
session_data: pandas dataframe of sessions
threshold_requests_per_session: int for fi... |
def YesNo(message=None):
if message:
print(message + ' [y/N]')
else:
print('[y/N]')
choice = input()
if choice != 'y' and choice != 'Y':
return False
return True
def YesNoTwice():
if YesNo():
return YesNo("Are you really really sure?")
return False
def YesNoTrice():
if YesNo():
i... | def yes_no(message=None):
if message:
print(message + ' [y/N]')
else:
print('[y/N]')
choice = input()
if choice != 'y' and choice != 'Y':
return False
return True
def yes_no_twice():
if yes_no():
return yes_no('Are you really really sure?')
return False
def ... |
for i in range(int(input())):
n=int(input())
a=[int(x) for x in input().split()]
m=int(input())
my=[]
pf,c=0,0
q=[]
for i in range(n):
z=a[i]
if z not in my:
if len(my)<m:
my.append(z)
else:
my[my.index(q.pop(0))]=z
... | for i in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
m = int(input())
my = []
(pf, c) = (0, 0)
q = []
for i in range(n):
z = a[i]
if z not in my:
if len(my) < m:
my.append(z)
else:
my[my.i... |
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
for i in range(k-1):
nums.remove(max(nums))
return max(nums)
| class Solution:
def find_kth_largest(self, nums: List[int], k: int) -> int:
for i in range(k - 1):
nums.remove(max(nums))
return max(nums) |
# Garo9521
# https://codeforces.com/contest/1521/problem/B
# math
t = int(input())
for case in range(t):
n = int(input())
array = list(map(int, input().split()))
minpos = array.index(min(array))
print(n - 1)
for i in range(minpos):
print(i + 1, minpos + 1, array[minpos] + minpos - i, array[m... | t = int(input())
for case in range(t):
n = int(input())
array = list(map(int, input().split()))
minpos = array.index(min(array))
print(n - 1)
for i in range(minpos):
print(i + 1, minpos + 1, array[minpos] + minpos - i, array[minpos])
for i in range(minpos + 1, n):
print(minpos + ... |
class Encoder(tf.keras.layers.Layer):
def __init__(self, intermediate_dim):
super(Encoder, self).__init__()
self.hidden_layer = tf.keras.layers.Dense(
units=intermediate_dim,
activation=tf.nn.relu,
kernel_initializer='he_uniform'
)
self.output_layer = tf.keras.layers.Dense(
un... | class Encoder(tf.keras.layers.Layer):
def __init__(self, intermediate_dim):
super(Encoder, self).__init__()
self.hidden_layer = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu, kernel_initializer='he_uniform')
self.output_layer = tf.keras.layers.Dense(units=intermediate_... |
def main():
# input
S = input()
T = input()
U = input()
# compute
# output
print(U + T + S)
if __name__ == '__main__':
main()
| def main():
s = input()
t = input()
u = input()
print(U + T + S)
if __name__ == '__main__':
main() |
def chi_squared(k1, k2, xs, ys):
stats_x = [0 for _ in range(k1)]
stats_y = [0 for _ in range(k2)]
d = dict()
for x, y in zip(xs, ys):
if (x,y) in d:
d[(x, y)] += 1
else:
d[(x, y)] = 1
stats_x[x] += 1
stats_y[y] += 1
result = 0.
for ... | def chi_squared(k1, k2, xs, ys):
stats_x = [0 for _ in range(k1)]
stats_y = [0 for _ in range(k2)]
d = dict()
for (x, y) in zip(xs, ys):
if (x, y) in d:
d[x, y] += 1
else:
d[x, y] = 1
stats_x[x] += 1
stats_y[y] += 1
result = 0.0
for (x, y) ... |
class Solution:
def dfs(self, root):
if root is None:
return (float('inf'), float('-inf'), 0, 0) # min, max, largest, size
left, right = self.dfs(root.left), self.dfs(root.right)
new_min = min(root.val, left[0], right[0])
new_max = max(root.val, left[1], right[1])
... | class Solution:
def dfs(self, root):
if root is None:
return (float('inf'), float('-inf'), 0, 0)
(left, right) = (self.dfs(root.left), self.dfs(root.right))
new_min = min(root.val, left[0], right[0])
new_max = max(root.val, left[1], right[1])
new_largest = max(le... |
def count_substring(string, sub_string):
stringSequences = []
for i in range(len(string)):
stringSequences.append(string[i:i+len(sub_string)])
return stringSequences.count(sub_string)
| def count_substring(string, sub_string):
string_sequences = []
for i in range(len(string)):
stringSequences.append(string[i:i + len(sub_string)])
return stringSequences.count(sub_string) |
'''
Copyright 2019-2020 Secure Shed Project Dev Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | """
Copyright 2019-2020 Secure Shed Project Dev Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
'''configuration variables for use throughout the global scope'''
session = None
# --------------- Static Variables ------------------
APPLICATION_ID = 'amzn1.echo-sdk-ams.app.1a291230-7f25-48ed-b8b7-747205d072db'
APPLICATION_NAME = 'The Cyberpunk Dictionary'
APPLICATION_INVOCATION_NAME = 'the cyberpunk dictionary'
APP... | """configuration variables for use throughout the global scope"""
session = None
application_id = 'amzn1.echo-sdk-ams.app.1a291230-7f25-48ed-b8b7-747205d072db'
application_name = 'The Cyberpunk Dictionary'
application_invocation_name = 'the cyberpunk dictionary'
application_version = '0.1'
application_endpoint = 'arn:a... |
#!/usr/bin/env python3
# Print Welcome Message
print('Hello, World')
| print('Hello, World') |
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack = []
result = [0] * len(T)
for idx, t in enumerate(T):
while stack and T[stack[-1]] < t:
prev_idx = stack.pop()
result[prev_idx] = idx - prev_idx
stack.appe... | class Solution:
def daily_temperatures(self, T: List[int]) -> List[int]:
stack = []
result = [0] * len(T)
for (idx, t) in enumerate(T):
while stack and T[stack[-1]] < t:
prev_idx = stack.pop()
result[prev_idx] = idx - prev_idx
stack.ap... |
class RevitLinkType(ElementType,IDisposable):
"""
This class represents another Revit Document ("link") brought into
the current one ("host").
"""
@staticmethod
def Create(document,*__args):
"""
Create(document: Document,path: ModelPath,options: RevitLinkOptions) -> RevitLinkLoadResult
C... | class Revitlinktype(ElementType, IDisposable):
"""
This class represents another Revit Document ("link") brought into
the current one ("host").
"""
@staticmethod
def create(document, *__args):
"""
Create(document: Document,path: ModelPath,options: RevitLinkOptions) -> RevitLinkLoadResult
... |
def how_many_visited_houses(instructions):
visited = {'0:0' : True}
x = 0
y = 0
# ^y
# |
# |
# --------+---------->x
#
#
for step in instructions:
if step == '>':
x += 1
elif step == '<':
x -= 1... | def how_many_visited_houses(instructions):
visited = {'0:0': True}
x = 0
y = 0
for step in instructions:
if step == '>':
x += 1
elif step == '<':
x -= 1
elif step == 'v':
y -= 1
elif step == '^':
y += 1
else:
... |
for _ in range(int(input())):
a=input()
n=len(a)
if n%2==0 and a[0:n//2]==a[n//2:n]:
print("YES")
else:
print("NO")
| for _ in range(int(input())):
a = input()
n = len(a)
if n % 2 == 0 and a[0:n // 2] == a[n // 2:n]:
print('YES')
else:
print('NO') |
#class SVNRepo:
# @classmethod
# def isBadVersion(cls, id)
# # Run unit tests to check whether verison `id` is a bad version
# # return true if unit tests passed else false.
# You can use SVNRepo.isBadVersion(10) to check whether version 10 is a
# bad version.
class Solution:
"""
@param n: ... | class Solution:
"""
@param n: An integer
@return: An integer which is the first bad version.
"""
def find_first_bad_version(self, n):
low = 1
result = n
while low <= n:
mid = (low + n) // 2
if SVNRepo.isBadVersion(mid):
result = min(re... |
config = {}
def process_logic_message(message):
type = message.get("type", None)
if type == "initialize":
return __initialize__()
if type == "enable":
return __enable__()
if type == "disable":
return __disable__()
else:
return wirehome.response_creator.not_supporte... | config = {}
def process_logic_message(message):
type = message.get('type', None)
if type == 'initialize':
return __initialize__()
if type == 'enable':
return __enable__()
if type == 'disable':
return __disable__()
else:
return wirehome.response_creator.not_supported(... |
"""
8 / 8 test cases passed.
Runtime: 28 ms
Memory Usage: 15.2 MB
"""
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return ["FizzBuzz" if i % 3 == 0 and i % 5 == 0 else \
"Fizz" if i % 3 == 0 else \
"Buzz" if i % 5 == 0 else \
str(i) for i in range(... | """
8 / 8 test cases passed.
Runtime: 28 ms
Memory Usage: 15.2 MB
"""
class Solution:
def fizz_buzz(self, n: int) -> List[str]:
return ['FizzBuzz' if i % 3 == 0 and i % 5 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i) for i in range(1, n + 1)] |
class tooltips:
def __init__ (self, attr):
self.tips = dict()
self.ori_attr = attr
for i in attr:
self.tips[i] = True
if 'time_value' in self.tips:
self.tips['time_value'] = False
def set_attr(self, attr):
for i in self.tips:
self.tips[i] = False
for i in attr:
if i in self.tips:
self.... | class Tooltips:
def __init__(self, attr):
self.tips = dict()
self.ori_attr = attr
for i in attr:
self.tips[i] = True
if 'time_value' in self.tips:
self.tips['time_value'] = False
def set_attr(self, attr):
for i in self.tips:
self.tips... |
# -*- coding: utf-8 -*-
################################################
#
# URL:
# =====
# https://leetcode.com/problems/implement-trie-prefix-tree/
#
# DESC:
# =====
# Implement a trie with insert, search, and startsWith methods.
#
# Example:
# Trie trie = new Trie();
# trie.insert("apple");
# trie.search("apple"); ... | class Node:
def __init__(self):
self.word = False
self.children = {}
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = node()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
... |
def foo():
'''
>>> from mod import GoodFile as bad
'''
pass
| def foo():
"""
>>> from mod import GoodFile as bad
"""
pass |
print('program1.py')
a = 100000000
for x in range(1,9):
if (x>=1 and x<=2):
b=a*0
print('laba bulanan ke-',x,':',b)
if (x>=3 and x<=4):
c=a*0.1
print('laba bulanan ke-',x,':',c)
if (x>=5 and x<=7) :
d=a*0.5
print('laba bulanan ke-',x,':',d)
if (x==8) :
e=a*0.2
print('la... | print('program1.py')
a = 100000000
for x in range(1, 9):
if x >= 1 and x <= 2:
b = a * 0
print('laba bulanan ke-', x, ':', b)
if x >= 3 and x <= 4:
c = a * 0.1
print('laba bulanan ke-', x, ':', c)
if x >= 5 and x <= 7:
d = a * 0.5
print('laba bulanan ke-', x, ... |
def return_dict(list):
dict = {}
for plate in list:
if(plate in dict):
dict[plate] = dict[plate] + 1
else:
dict[plate] = 1
return dict
def isNumber(character):
return True if(character<='9' and character>='0') else False
def isLetter(character):
return True i... | def return_dict(list):
dict = {}
for plate in list:
if plate in dict:
dict[plate] = dict[plate] + 1
else:
dict[plate] = 1
return dict
def is_number(character):
return True if character <= '9' and character >= '0' else False
def is_letter(character):
return T... |
try:
a = 4 / 0
except Exception as ex:
print(str(ex))
finally:
print('Thats all Folks')
| try:
a = 4 / 0
except Exception as ex:
print(str(ex))
finally:
print('Thats all Folks') |
class Torus(object,IEpsilonComparable[Torus]):
""" Torus(basePlane: Plane,majorRadius: float,minorRadius: float) """
def EpsilonEquals(self,other,epsilon):
""" EpsilonEquals(self: Torus,other: Torus,epsilon: float) -> bool """
pass
def ToNurbsSurface(self):
""" ToNurbsSurface(self: Torus) -> NurbsSurface... | class Torus(object, IEpsilonComparable[Torus]):
""" Torus(basePlane: Plane,majorRadius: float,minorRadius: float) """
def epsilon_equals(self, other, epsilon):
""" EpsilonEquals(self: Torus,other: Torus,epsilon: float) -> bool """
pass
def to_nurbs_surface(self):
""" ToNurbsSurface... |
def bfs(graph, init):
visited = []
queue = [init]
while queue:
current = queue.pop(0)
if current not in visited:
visited.append(current)
adj = graph[current]
for neighbor in adj:
for k in neighbor.keys():
queue.append... | def bfs(graph, init):
visited = []
queue = [init]
while queue:
current = queue.pop(0)
if current not in visited:
visited.append(current)
adj = graph[current]
for neighbor in adj:
for k in neighbor.keys():
queue.append(k)... |
del_items(0x80118770)
SetType(0x80118770, "int NumOfMonsterListLevels")
del_items(0x800A7554)
SetType(0x800A7554, "struct MonstLevel AllLevels[16]")
del_items(0x8011846C)
SetType(0x8011846C, "unsigned char NumsLEV1M1A[4]")
del_items(0x80118470)
SetType(0x80118470, "unsigned char NumsLEV1M1B[4]")
del_items(0x80118474)
S... | del_items(2148632432)
set_type(2148632432, 'int NumOfMonsterListLevels')
del_items(2148169044)
set_type(2148169044, 'struct MonstLevel AllLevels[16]')
del_items(2148631660)
set_type(2148631660, 'unsigned char NumsLEV1M1A[4]')
del_items(2148631664)
set_type(2148631664, 'unsigned char NumsLEV1M1B[4]')
del_items(214863166... |
ls = []
with open('input.txt') as fh:
for line in fh.readlines():
if not line.strip():
continue
ls.append(int(line))
for i in range(len(ls)):
for j in range(i+1, len(ls)):
if ls[i] + ls[j] == 2020:
print("part1:")
print(ls[i], ls[j])
prin... | ls = []
with open('input.txt') as fh:
for line in fh.readlines():
if not line.strip():
continue
ls.append(int(line))
for i in range(len(ls)):
for j in range(i + 1, len(ls)):
if ls[i] + ls[j] == 2020:
print('part1:')
print(ls[i], ls[j])
prin... |
"""
Command parsing. :py:class:`CommandParser` breaks up the input, and tosses out
:py:class:`ParsedCommand` instance.
"""
class ParsedCommand(object):
"""
A parsed command, broken up into something the command handler can
muddle through.
:attr str command_str: The command that was passed.
:attr ... | """
Command parsing. :py:class:`CommandParser` breaks up the input, and tosses out
:py:class:`ParsedCommand` instance.
"""
class Parsedcommand(object):
"""
A parsed command, broken up into something the command handler can
muddle through.
:attr str command_str: The command that was passed.
:attr l... |
# test practice of the the collatz sequence(the simplest impossible maths problem
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number/2;
print(int(number))
else:
number = (number*3) + 1
print(int(number))
def main():
print("Enter number: ")
number = int(input())
colla... | def collatz(number):
while number != 1:
if number % 2 == 0:
number = number / 2
print(int(number))
else:
number = number * 3 + 1
print(int(number))
def main():
print('Enter number: ')
number = int(input())
collatz(number)
main() |
class Solution:
def countAndSay__iterative(self, n: int) -> str:
if n <= 0: return "" # EMPTY
if n == 1: return "1"
say_prev = "1"
for i in range(2, n + 1): # n included
say_curr = self.convert(say_prev)
say_prev = say_curr
return say_prev
# ... | class Solution:
def count_and_say__iterative(self, n: int) -> str:
if n <= 0:
return ''
if n == 1:
return '1'
say_prev = '1'
for i in range(2, n + 1):
say_curr = self.convert(say_prev)
say_prev = say_curr
return say_prev
d... |
"""
Question 7
Write code to calculate fibonacci numbers, create lists containing first 20 fibonacci numbers.
(Fib numbers made by sum of proceeding two.Series start at 0 1 1 2 3 5 8 13...)
"""
a = 0
b = 1
fib_num = list()
count = 0
user_input = input('Enter a number: ')
while not user_input.isdigit():
user_input =... | """
Question 7
Write code to calculate fibonacci numbers, create lists containing first 20 fibonacci numbers.
(Fib numbers made by sum of proceeding two.Series start at 0 1 1 2 3 5 8 13...)
"""
a = 0
b = 1
fib_num = list()
count = 0
user_input = input('Enter a number: ')
while not user_input.isdigit():
user_input =... |
"""TensorFlow Lite Support Library Helper Rules for iOS"""
# When the static framework is built with bazel, the all header files are moved
# to the "Headers" directory with no header path prefixes. This auxiliary rule
# is used for stripping the path prefix to the C API header files included by
# other C API header fi... | """TensorFlow Lite Support Library Helper Rules for iOS"""
def strip_c_api_include_path_prefix(name, hdr_labels, prefix=''):
"""Create modified header files with the common.h include path stripped out.
Args:
name: The name to be used as a prefix to the generated genrules.
hdr_labels: List of heade... |
class Bills:
"""A class that is used to build the Bills"""
def __init__(self, digest):
self.title = digest.get("title")
self.short_title = digest.get("shortTitle")
self.collection_code = digest.get("collectionCode")
self.collection_name = digest.get("collectionName")
self... | class Bills:
"""A class that is used to build the Bills"""
def __init__(self, digest):
self.title = digest.get('title')
self.short_title = digest.get('shortTitle')
self.collection_code = digest.get('collectionCode')
self.collection_name = digest.get('collectionName')
sel... |
count = 10
print("Hello!")
while count > 0:
print(count)
count -= 2 | count = 10
print('Hello!')
while count > 0:
print(count)
count -= 2 |
'''
Gui
___
Contains the Qt views and controllers.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
| """
Gui
___
Contains the Qt views and controllers.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
""" |
input = """
dir(e). dir(w). dir(n). dir(s).
inverse(e,w). inverse(w,e).
inverse(n,s). inverse(s,n).
row(X) :- field(X,Y).
col(Y) :- field(X,Y).
num_rows(X) :- row(X), not row(XX), XX = X+1.
num_cols(Y) :- col(Y), not col(YY), YY = Y+1.
goal(X,Y,0) :- goal_on(X,Y).
reach(X,Y,0) :- init_on(X,Y).
conn(X,Y,D,0) :- co... | input = '\ndir(e). dir(w). dir(n). dir(s).\ninverse(e,w). inverse(w,e).\ninverse(n,s). inverse(s,n).\n\nrow(X) :- field(X,Y).\ncol(Y) :- field(X,Y).\n\nnum_rows(X) :- row(X), not row(XX), XX = X+1.\nnum_cols(Y) :- col(Y), not col(YY), YY = Y+1.\n\ngoal(X,Y,0) :- goal_on(X,Y).\nreach(X,Y,0) :- init_on(X,Y).\nconn(X,Y... |
"""
44. How to select a specific column from a dataframe as a dataframe instead of a series?
"""
"""
Difficulty Level: L2
"""
"""
Get the first column (a) in df as a dataframe (rather than as a Series).
"""
"""
Input
"""
"""
df = pd.DataFrame(np.arange(20).reshape(-1, 5), columns=list('abcde'))
"""
# Input
df = pd.Dat... | """
44. How to select a specific column from a dataframe as a dataframe instead of a series?
"""
'\nDifficulty Level: L2\n'
'\nGet the first column (a) in df as a dataframe (rather than as a Series).\n'
'\nInput\n'
"\ndf = pd.DataFrame(np.arange(20).reshape(-1, 5), columns=list('abcde'))\n"
df = pd.DataFrame(np.arange(... |
numCasoTeste = int(input())
membros = ['Rolien', 'Naej', 'Elehcim', 'Odranoel']
for casoTeste in range(numCasoTeste):
numInput = int(input())
for _ in range(numInput):
recebido = int(input())
print(membros[recebido - 1]) | num_caso_teste = int(input())
membros = ['Rolien', 'Naej', 'Elehcim', 'Odranoel']
for caso_teste in range(numCasoTeste):
num_input = int(input())
for _ in range(numInput):
recebido = int(input())
print(membros[recebido - 1]) |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 8 13:44:47 2020
@author: celine.gross
"""
with open('input_day8.txt', 'r') as file:
puzzle = file.read().strip().split('\n')
# Part 1
def to_next(data, i=0, accumulator=0):
'''
Returns the next line index to look at (i) and the updated accumulator value
... | """
Created on Tue Dec 8 13:44:47 2020
@author: celine.gross
"""
with open('input_day8.txt', 'r') as file:
puzzle = file.read().strip().split('\n')
def to_next(data, i=0, accumulator=0):
"""
Returns the next line index to look at (i) and the updated accumulator value
"""
(action, increment) = dat... |
#
# PySNMP MIB module HP-SN-SW-L4-SWITCH-GROUP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-SN-MIBS
# Produced by pysmi-0.3.4 at Mon Apr 29 19:23:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
#!/usr/bin/env python3
# [rights] Copyright 2020 brianddk at github https://github.com/brianddk
# [license] Apache 2.0 License https://www.apache.org/licenses/LICENSE-2.0
# [repo] github.com/brianddk/reddit/blob/master/python/mining.py
# [btc] BTC-b32: bc1qwc2203uym96u0nmq04pcgqfs9ldqz9l3mz8fpj
# [tipjar] gith... | spot = 8939.9
hashrate = 110 * 10 ** 12
difficulty = float('16,104,807,485,529'.replace(',', '_'))
reward = 12.5
usd_per_day = spot * hashrate * reward * 60 * 60 * 24 / (difficulty * 2 ** 32)
print(usd_per_day) |
""" Supplies the internal functions for functools.py in the standard library """
# reduce() has moved to _functools in Python 2.6+.
reduce = reduce
class partial(object):
"""
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
"""
__slots_... | """ Supplies the internal functions for functools.py in the standard library """
reduce = reduce
class Partial(object):
"""
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
"""
__slots__ = ('_func', '_args', '_keywords', '__dict__')
... |
# Copyright 2019 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """CoreML related actions."""
load('@build_bazel_apple_support//lib:apple_support.bzl', 'apple_support')
load('@build_bazel_rules_apple//apple/internal/utils:xctoolrunner.bzl', 'xctoolrunner')
def compile_mlmodel(*, actions, input_file, output_bundle, output_plist, platform_prerequisites, resolved_xctoolrunner):
"... |
data = b""
data += b"\x7F\x45\x4C\x46" # ELF
data += b"\x02\x02\x02" # ELF64
data += b"\x20\x00" # ABI
data += b"\x00\x00\x00\x00\x00\x00\x00" # Pad
data += b"\x00\x00\x00\x00\x00\x00\x00\x00" # Type Machine Version
data += b"\x00\x00\x00\x00\x00\x00\x00\x00" # Start Address
data += b"\x00\x00\x00\x00\x00\x00\x00\x40"... | data = b''
data += b'\x7fELF'
data += b'\x02\x02\x02'
data += b' \x00'
data += b'\x00\x00\x00\x00\x00\x00\x00'
data += b'\x00\x00\x00\x00\x00\x00\x00\x00'
data += b'\x00\x00\x00\x00\x00\x00\x00\x00'
data += b'\x00\x00\x00\x00\x00\x00\x00@'
data += b'\x00\x00\x00\x00\x00\x00\x00x'
data += b'\x00\x00\x00\x00'
data += b'\... |
class User:
def __init__(self):
self.id = None
self.login = None
self.password = None
self.fullName = None
self.phone = None
self.email = None
self.imageUrl = ''
self.activated = False
self.langKey = 'en'
self.activationKey = None
... | class User:
def __init__(self):
self.id = None
self.login = None
self.password = None
self.fullName = None
self.phone = None
self.email = None
self.imageUrl = ''
self.activated = False
self.langKey = 'en'
self.activationKey = None
... |
row = int(input("How many rows you want? "))
column = int(input("How many columns you want? "))
if row==column:
for i in range(1,row+1):
for j in range(1,row+1):
if i==j:
print("1", end = " ")
else:
print("0", end= " ")
print("")
else:
pri... | row = int(input('How many rows you want? '))
column = int(input('How many columns you want? '))
if row == column:
for i in range(1, row + 1):
for j in range(1, row + 1):
if i == j:
print('1', end=' ')
else:
print('0', end=' ')
print('')
else:
... |
def arithmetic_progression(el_1, el_2, n):
"""Finds the nth element of Given the first two elements of
an arithmetic progression.
NOTE: nth term for arithmetic progression is a sub n = (n-1)*d + a
where n is the nth term, d is difference, a is the first element of
the arithmetic progression.
"""... | def arithmetic_progression(el_1, el_2, n):
"""Finds the nth element of Given the first two elements of
an arithmetic progression.
NOTE: nth term for arithmetic progression is a sub n = (n-1)*d + a
where n is the nth term, d is difference, a is the first element of
the arithmetic progression.
"""... |
patches = [
{
"op": "remove",
"path": "/PropertyTypes/AWS::S3::StorageLens.S3BucketDestination/Properties/Encryption/Type",
},
{
"op": "add",
"path": "/PropertyTypes/AWS::S3::StorageLens.S3BucketDestination/Properties/Encryption/PrimitiveType",
"value": "Json",
},... | patches = [{'op': 'remove', 'path': '/PropertyTypes/AWS::S3::StorageLens.S3BucketDestination/Properties/Encryption/Type'}, {'op': 'add', 'path': '/PropertyTypes/AWS::S3::StorageLens.S3BucketDestination/Properties/Encryption/PrimitiveType', 'value': 'Json'}, {'op': 'move', 'from': '/PropertyTypes/AWS::S3::StorageLens.Da... |
#
# PySNMP MIB module CISCO-COMMON-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-MGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) ... |
with open("input_16.txt", "r") as f:
lines = f.readlines()
names = []
restrictions = []
for line in lines:
if len(line.strip()) == 0:
break
names.append(line.strip().split(": ")[0])
values = line.strip().split(": ")[1]
ranges = values.split(" or ")
restrictions.append([
[int(x)... | with open('input_16.txt', 'r') as f:
lines = f.readlines()
names = []
restrictions = []
for line in lines:
if len(line.strip()) == 0:
break
names.append(line.strip().split(': ')[0])
values = line.strip().split(': ')[1]
ranges = values.split(' or ')
restrictions.append([[int(x) for x in r... |
#cigar_party
def cigar_party(cigars, is_weekend):
if 40<=cigars<=60:
return True
elif cigars>=60 and is_weekend:
return True
return False
#date_fashion
def date_fashion(you, date):
if you<=2 or date<=2:
return 0
elif you>=8 or date>=8:
return 2
elif 2<you<8 or 2<date<8:
r... | def cigar_party(cigars, is_weekend):
if 40 <= cigars <= 60:
return True
elif cigars >= 60 and is_weekend:
return True
return False
def date_fashion(you, date):
if you <= 2 or date <= 2:
return 0
elif you >= 8 or date >= 8:
return 2
elif 2 < you < 8 or 2 < date < ... |
#
# first solution:
#
class sample(object):
class one(object):
def __get__(self, obj, type=None):
print("computing ...")
obj.one = 1
return 1
one = one()
x=sample()
print(x.one)
print(x.one)
#
# other solution:
#
# lazy attribute descriptor
class lazyattr(objec... | class Sample(object):
class One(object):
def __get__(self, obj, type=None):
print('computing ...')
obj.one = 1
return 1
one = one()
x = sample()
print(x.one)
print(x.one)
class Lazyattr(object):
def __init__(self, fget, doc=''):
self.fget = fget
... |
"""About this package."""
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "jupyter-d3"
__summary__ = "Jupyter magic providing easy integration of d3 JavaScript visualization library."
__uri__ = "https://github.com/Cerma... | """About this package."""
__all__ = ['__title__', '__summary__', '__uri__', '__version__', '__author__', '__email__', '__license__', '__copyright__']
__title__ = 'jupyter-d3'
__summary__ = 'Jupyter magic providing easy integration of d3 JavaScript visualization library.'
__uri__ = 'https://github.com/CermakM/jupyter-d3... |
class Ball(object):
color = str()
circumference = float()
brand = str()
| class Ball(object):
color = str()
circumference = float()
brand = str() |
NAME = 'converter.py'
ORIGINAL_AUTHORS = [
'Angelo Giacco'
]
ABOUT = '''
Converts currencies
'''
COMMANDS = '''
>>> .convert <<base currency code>> <<target currency code>> <<amount>>
returns the conversion: amount argument is optional with a default of 1
.convert help
shows a list of currencies supported
'''
W... | name = 'converter.py'
original_authors = ['Angelo Giacco']
about = '\nConverts currencies\n'
commands = '\n>>> .convert <<base currency code>> <<target currency code>> <<amount>>\nreturns the conversion: amount argument is optional with a default of 1\n.convert help\nshows a list of currencies supported\n'
website = '' |
class Bar:
x = 1
print(Bar.x)
| class Bar:
x = 1
print(Bar.x) |
def find_min(array, i):
if i == len(array) - 1:
return array[i]
else:
tmp_min = array[i]
i = i + 1
min_frm = find_min(array, i)
return min(tmp_min, min_frm)
a = [2, 1, 3, 10, 53, 23, -1, 2, 5, 0, 34, 8]
#a = [x for x in range(1000)]
print (find_min(a, 0))
| def find_min(array, i):
if i == len(array) - 1:
return array[i]
else:
tmp_min = array[i]
i = i + 1
min_frm = find_min(array, i)
return min(tmp_min, min_frm)
a = [2, 1, 3, 10, 53, 23, -1, 2, 5, 0, 34, 8]
print(find_min(a, 0)) |
def solve(input):
print(sum(list(map(int, input))))
with open('input.txt', 'r') as f:
input = f.read().splitlines()
solve(input)
| def solve(input):
print(sum(list(map(int, input))))
with open('input.txt', 'r') as f:
input = f.read().splitlines()
solve(input) |
# Given a linked list, determine if it has a cycle in it.
# Follow up:
# Can you solve it without using extra space?
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boo... | class Solution:
def has_cycle(self, head):
if not head:
return False
walker = runner = head
while runner and runner.next:
walker = walker.next
runner = runner.next.next
if walker == runner:
return True
return False |
#1
# Time: O(n)
# Space: O(n)
# Given an array of integers, return indices of
# the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution,
# and you may not use the same element twice.
#
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Bec... | class Hashtablesol:
def two_sum(self, nums, target):
num_idx = {}
for (idx, num) in enumerate(nums):
if target - num in num_idx:
return [num_idx[target - num], idx]
else:
num_idx[num] = idx
return [] |
def get_length(dna):
''' (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
'''
return len(dna)
def is_longer(dna1, dna2):
''' (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
... | def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
... |
"""
Workflow module
"""
class Workflow:
"""
Base class for all workflows.
"""
def __init__(self, tasks, batch=100):
"""
Creates a new workflow. Workflows are lists of tasks to execute.
Args:
tasks: list of workflow tasks
batch: how many items to proces... | """
Workflow module
"""
class Workflow:
"""
Base class for all workflows.
"""
def __init__(self, tasks, batch=100):
"""
Creates a new workflow. Workflows are lists of tasks to execute.
Args:
tasks: list of workflow tasks
batch: how many items to process... |
"""Utility variables and functions for the TS3 API"""
# FROM OLD API
"""
Don't change the order in this map, otherwise it might break
"""
_ESCAPE_MAP = [
("\\", r"\\"),
("/", r"\/"),
(" ", r"\s"),
("|", r"\p"),
("\a", r"\a"),
("\b", r"\b"),
("\f", r"\f"),
("\n", r"\n"),
("\r", r"\r"... | """Utility variables and functions for the TS3 API"""
"\nDon't change the order in this map, otherwise it might break\n"
_escape_map = [('\\', '\\\\'), ('/', '\\/'), (' ', '\\s'), ('|', '\\p'), ('\x07', '\\a'), ('\x08', '\\b'), ('\x0c', '\\f'), ('\n', '\\n'), ('\r', '\\r'), ('\t', '\\t'), ('\x0b', '\\v')]
def escape(r... |
STREAM_ERROR_SOURCE_USER = "stream_error_source_user"
STREAM_ERROR_SOURCE_STREAM_PUMP = "stream_error_source_stream_pump"
STREAM_ERROR_SOURCE_SUBSCRIPTION_GAZE_DATA = "stream_error_source_subscription_gaze_data"
STREAM_ERROR_SOURCE_SUBSCRIPTION_USER_POSITION_GUIDE = "stream_error_source_subscription_user_position_guide... | stream_error_source_user = 'stream_error_source_user'
stream_error_source_stream_pump = 'stream_error_source_stream_pump'
stream_error_source_subscription_gaze_data = 'stream_error_source_subscription_gaze_data'
stream_error_source_subscription_user_position_guide = 'stream_error_source_subscription_user_position_guide... |
"""Filter Package
--------------
This package is the root module for spectral filtering utilities.
"""
| """Filter Package
--------------
This package is the root module for spectral filtering utilities.
""" |
def digit_sum(num: str):
res = 0
for c in num:
res += int(c)
return res
def digit_prod(num: str):
res = 1
for c in num:
res *= int(c)
return res
def main():
memo = {}
T = int(input())
for t in range(1, T + 1):
A, B = [int(x) for x in input().split(" ")]
... | def digit_sum(num: str):
res = 0
for c in num:
res += int(c)
return res
def digit_prod(num: str):
res = 1
for c in num:
res *= int(c)
return res
def main():
memo = {}
t = int(input())
for t in range(1, T + 1):
(a, b) = [int(x) for x in input().split(' ')]
... |
"""Organizations package.
Modules:
organizations
shortname_orgs
"""
| """Organizations package.
Modules:
organizations
shortname_orgs
""" |
BOT_TOKEN = "1910688339:AAG0t3dMaraOL9u31bkjMEbFcMPy-Pl6rA8"
RESULTS_COUNT = 4 # NOTE Number of results to show, 4 is better
SUDO_CHATS_ID = [1731097588, -1005456463651]
DRIVE_NAME = [
"Root", # folder 1 name
"Cartoon", # folder 2 name
"Course", # folder 3 name
"Movies", # ....
"Series", # .... | bot_token = '1910688339:AAG0t3dMaraOL9u31bkjMEbFcMPy-Pl6rA8'
results_count = 4
sudo_chats_id = [1731097588, -1005456463651]
drive_name = ['Root', 'Cartoon', 'Course', 'Movies', 'Series', 'Others']
drive_id = ['0AHQOFQWVW-LiUk9PVA', '0AKqQHy-eIErTUk9PVA', '0AITVP56KLmIIUk9PVA', '10_hTMK8HE8k144wOTth_3x1hC2kZL-LR', '1-oT... |
if __name__ == '__main__':
n = int(input())
i = 0
while n > 0:
print(i ** 2)
i = i + 1
n = n - 1
| if __name__ == '__main__':
n = int(input())
i = 0
while n > 0:
print(i ** 2)
i = i + 1
n = n - 1 |
"""
# LARGEST NUMBER
Given a list of non-negative integers nums, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2]
Output: "210"
Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"
E... | """
# LARGEST NUMBER
Given a list of non-negative integers nums, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2]
Output: "210"
Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"
E... |
#11. Find GCD of two given Numbers.
m = int(input("Enter the First Number: "))
n = int(input("Enter the Second Number: "))
r = m
while(m!=n):
if(m>n):
m=m-n
else:
n=n-m
print("G.C.D is ",m)
| m = int(input('Enter the First Number: '))
n = int(input('Enter the Second Number: '))
r = m
while m != n:
if m > n:
m = m - n
else:
n = n - m
print('G.C.D is ', m) |
############
## Solution
############
def e_step(Y, psi, A, L, dt):
"""
Args:
Y (numpy 3d array): tensor of recordings, has shape (n_trials, T, C)
psi (numpy vector): initial probabilities for each state
A (numpy matrix): transition matrix, A[i,j] represents the prob to switch from i to... | def e_step(Y, psi, A, L, dt):
"""
Args:
Y (numpy 3d array): tensor of recordings, has shape (n_trials, T, C)
psi (numpy vector): initial probabilities for each state
A (numpy matrix): transition matrix, A[i,j] represents the prob to switch from i to j. Has shape (K,K)
L (numpy ma... |
#Shipping Accounts App
#Define list of users
users = ['eramom', 'footea', 'davisv', 'papinukt', 'allenj', 'eliasro']
print("Welcome to the Shipping Accounts Program.")
#Get user input
username = input("\nHello, what is your username: ").lower().strip()
#User is in list....
if username in users:
#print a price ... | users = ['eramom', 'footea', 'davisv', 'papinukt', 'allenj', 'eliasro']
print('Welcome to the Shipping Accounts Program.')
username = input('\nHello, what is your username: ').lower().strip()
if username in users:
print('\nHello ' + username + '. Welcome back to your account.')
print('Current shipping prices ar... |
# A class to represent the adjacency list of the node
class AdjNode:
def __init__(self, data):
self.vertex = data
self.next = None
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [None] * self.V
self.verticeslist = []
def add_edge(self, ... | class Adjnode:
def __init__(self, data):
self.vertex = data
self.next = None
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [None] * self.V
self.verticeslist = []
def add_edge(self, src, dest):
self.verticeslist.append(src)
... |
"""
Contains configurations options so secret, that they may not even be
commited to git!
"""
ADMIN_PASSWORD = "secret"
SECRET_KEY = "secret key"
| """
Contains configurations options so secret, that they may not even be
commited to git!
"""
admin_password = 'secret'
secret_key = 'secret key' |
description = 'Vaccum sensors and temperature control'
devices = dict(
vacuum=device(
'nicos_ess.estia.devices.pfeiffer.PfeifferTPG261',
description='Pfeiffer TPG 261 vacuum gauge controller',
hostport='192.168.1.254:4002',
fmtstr='%.2E',
),
)
| description = 'Vaccum sensors and temperature control'
devices = dict(vacuum=device('nicos_ess.estia.devices.pfeiffer.PfeifferTPG261', description='Pfeiffer TPG 261 vacuum gauge controller', hostport='192.168.1.254:4002', fmtstr='%.2E')) |
#!/usr/bin/env python3
"""
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE.txt and README.txt files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent
"""
"""
Welcome message for ASCENT software
"... | """
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE.txt and README.txt files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent
"""
'\nWelcome message for ASCENT software\n'
def welcome():
prin... |
SECRET_KEY = "123"
INSTALLED_APPS = [
'sr'
]
SR = {
'test1': 'Test1',
'test2': {
'test3': 'Test3',
},
'test4': {
'test4': 'Test4 {0} {1}',
},
'test5': {
'test5': "<b>foo</b>",
}
}
| secret_key = '123'
installed_apps = ['sr']
sr = {'test1': 'Test1', 'test2': {'test3': 'Test3'}, 'test4': {'test4': 'Test4 {0} {1}'}, 'test5': {'test5': '<b>foo</b>'}} |
# coding=utf-8
"""
tests.functional.module
~~~~~~~~~~~~~~
Functional tests
"""
| """
tests.functional.module
~~~~~~~~~~~~~~
Functional tests
""" |
# -*- coding: utf-8 -*-
numero_empleado = int(input())
numero_hrs_mes = int(input())
pago_por_hora = float('%.2f' % ( float(input()) ))
pago_por_mes = pago_por_hora*numero_hrs_mes
pago_por_mes = '%.2f'%(float(pago_por_mes))
print ("NUMBER = " + str(numero_empleado))
print ("SALARY = U$ " + str(pago_por_mes)) | numero_empleado = int(input())
numero_hrs_mes = int(input())
pago_por_hora = float('%.2f' % float(input()))
pago_por_mes = pago_por_hora * numero_hrs_mes
pago_por_mes = '%.2f' % float(pago_por_mes)
print('NUMBER = ' + str(numero_empleado))
print('SALARY = U$ ' + str(pago_por_mes)) |
{
"targets": [
{
"target_name": "wiringpi",
"sources": [ "wiringpi.cc" ],
"include_dirs": [ "/usr/local/include" ],
"ldflags": [ "-lwiringPi" ]
}
]
}
| {'targets': [{'target_name': 'wiringpi', 'sources': ['wiringpi.cc'], 'include_dirs': ['/usr/local/include'], 'ldflags': ['-lwiringPi']}]} |
"""Core exceptions."""
class Unauthenticated(Exception):
"""Thrown when user is not authenticated."""
pass
class MalformedRequestData(Exception):
"""Thrown when request data is malformed."""
pass
class InputError(Exception):
"""Thrown on input error."""
pass
class FileTypeError(Except... | """Core exceptions."""
class Unauthenticated(Exception):
"""Thrown when user is not authenticated."""
pass
class Malformedrequestdata(Exception):
"""Thrown when request data is malformed."""
pass
class Inputerror(Exception):
"""Thrown on input error."""
pass
class Filetypeerror(Exception):
... |
bot_name = 'your_bot_username'
bot_token = 'your_bot_token'
redis_server = 'localhost'
redis_port = 6379
bot_master = 'your_userid_here'
| bot_name = 'your_bot_username'
bot_token = 'your_bot_token'
redis_server = 'localhost'
redis_port = 6379
bot_master = 'your_userid_here' |
class NavigationHelper:
def __init__(self, app):
self.app = app
def open_home_page(self):
wd = self.app.wd
wd.get(self.app.base_url)
def return_to_home_page(self):
wd = self.app.wd
wd.find_element_by_link_text("home").click()
| class Navigationhelper:
def __init__(self, app):
self.app = app
def open_home_page(self):
wd = self.app.wd
wd.get(self.app.base_url)
def return_to_home_page(self):
wd = self.app.wd
wd.find_element_by_link_text('home').click() |
_base_ = [
'./retina.py'
]
model= dict(
type='CustomRetinaNet',
#pretrained=None,
#backbone=dict( # Replacding R50 by OTE MV2
# _delete_=True,
# type='mobilenetv2_w1',
# out_indices=(2, 3, 4, 5),
# frozen_stages=-1,
# norm_eval=True, # False in OTE setting
# ... | _base_ = ['./retina.py']
model = dict(type='CustomRetinaNet') |
class BaseComponent(object):
def __init__(self):
self.version = self.__version__
def forward(self, tweet: str):
raise NotImplementedError
@property
def __version__(self):
raise NotImplementedError
| class Basecomponent(object):
def __init__(self):
self.version = self.__version__
def forward(self, tweet: str):
raise NotImplementedError
@property
def __version__(self):
raise NotImplementedError |
def create_spam_worker_name(user_id):
return f'user_{user_id}_spam_worker'
def create_email_worker_name(user_id):
return f'user_{user_id}_email_worker'
def create_worker_celery_name(worker_name):
return f"celery@{worker_name}"
def create_spam_worker_celery_name(user_id):
return create_worker_celer... | def create_spam_worker_name(user_id):
return f'user_{user_id}_spam_worker'
def create_email_worker_name(user_id):
return f'user_{user_id}_email_worker'
def create_worker_celery_name(worker_name):
return f'celery@{worker_name}'
def create_spam_worker_celery_name(user_id):
return create_worker_celery_n... |
def aditya():
return "aditya"
def shantanu(num):
if num>10:
return "shantanu"
else:
return "patankar" | def aditya():
return 'aditya'
def shantanu(num):
if num > 10:
return 'shantanu'
else:
return 'patankar' |
def personalData():
"""
Asks the user for their name and age.
Uses a try except block to cast their age to an int
prints out their name ad age.
:return:
"""
user_name = input("Enter your name: ")
user_age = input("Enter your age")
#use a try except block when casting to an int.
... | def personal_data():
"""
Asks the user for their name and age.
Uses a try except block to cast their age to an int
prints out their name ad age.
:return:
"""
user_name = input('Enter your name: ')
user_age = input('Enter your age')
try:
age = int(user_age)
print('Hell... |
# Define a Multiplication Function
def mul(num1, num2):
return num1 * num2
| def mul(num1, num2):
return num1 * num2 |
''' Write a Python program to accept a filename from the user and print the extension of that. '''
ext = input("Enter a file name: ")
files = ext.split('.')
print(files[1])
| """ Write a Python program to accept a filename from the user and print the extension of that. """
ext = input('Enter a file name: ')
files = ext.split('.')
print(files[1]) |
def kth_largest1(arr,k):
if k > len(arr):
return None
for i in range(k-1):
arr.remove(max(arr))
return max(arr)
def kth_largest2(arr,k):
if k > len(arr):
return None
n = len(arr)
arr.sort()
return(arr[n - k])
print(kth_largest2([4,2,8,9,5,6,7],2)) | def kth_largest1(arr, k):
if k > len(arr):
return None
for i in range(k - 1):
arr.remove(max(arr))
return max(arr)
def kth_largest2(arr, k):
if k > len(arr):
return None
n = len(arr)
arr.sort()
return arr[n - k]
print(kth_largest2([4, 2, 8, 9, 5, 6, 7], 2)) |
# the way currently the code is written it is possible to change the value accidently or it can be changed accidently
class Customer:
def __init__(self, cust_id, name, age, wallet_balance):
self.cust_id = cust_id
self.name = name
self.age = age
self.wallet_balance = wallet_balance
... | class Customer:
def __init__(self, cust_id, name, age, wallet_balance):
self.cust_id = cust_id
self.name = name
self.age = age
self.wallet_balance = wallet_balance
def update_balance(self, amount):
if amount < 1000 and amount > 0:
self.wallet_balance += amou... |
def match(output_file, input_file):
block = []
blocks = []
for line in open(input_file, encoding='utf8').readlines():
if line.startswith('#'):
block.append(line)
else:
if block:
blocks.append(block)
block = []
block1 = []
blocks1 =... | def match(output_file, input_file):
block = []
blocks = []
for line in open(input_file, encoding='utf8').readlines():
if line.startswith('#'):
block.append(line)
else:
if block:
blocks.append(block)
block = []
block1 = []
blocks1 = ... |
class MysqlDumpParser:
def __init__(self, table: str):
"""
:param: str table The name of the table to parse, in case there are multiple tables in the same file
"""
self.table = table
self.columns = []
@staticmethod
def is_create_statement(line):
return line.u... | class Mysqldumpparser:
def __init__(self, table: str):
"""
:param: str table The name of the table to parse, in case there are multiple tables in the same file
"""
self.table = table
self.columns = []
@staticmethod
def is_create_statement(line):
return line.... |
# quicksort
def partition(arr,low,high):
i = ( low-1 ) # index of smaller element
pivot = arr[high] # pivot
for j in range(low , high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of ... | def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i = i + 1
(arr[i], arr[j]) = (arr[j], arr[i])
(arr[i + 1], arr[high]) = (arr[high], arr[i + 1])
return i + 1
def quick_sort(arr, low, high):
if low < high:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.