content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def printSet(set):
sorted(set)
print('{', end=" ")
for x in set :
print(x, end=" ")
print('}')
def main():
a = set("Hi There, Raghuram")
b = set("Hello, Nice to Meet you")
x = set('hello')
y = set('world')
printSet(a)
printSet(b)
printSet(x - y )
if __name__ == "__... | def print_set(set):
sorted(set)
print('{', end=' ')
for x in set:
print(x, end=' ')
print('}')
def main():
a = set('Hi There, Raghuram')
b = set('Hello, Nice to Meet you')
x = set('hello')
y = set('world')
print_set(a)
print_set(b)
print_set(x - y)
if __name__ == '__... |
with open('input.txt') as f:
lines = [int(i) for i in f.readlines()]
depth_increased = 0
for i in range(0, len(lines) - 3):
last_sum = sum(lines[i-1:i+2])
current_sum = sum(lines[i:i+3])
if (current_sum > last_sum):
depth_increased = depth_increased + ... | with open('input.txt') as f:
lines = [int(i) for i in f.readlines()]
depth_increased = 0
for i in range(0, len(lines) - 3):
last_sum = sum(lines[i - 1:i + 2])
current_sum = sum(lines[i:i + 3])
if current_sum > last_sum:
depth_increased = depth_increased + 1
print(dept... |
# https://leetcode.com/problems/missing-number/description/
# Time: O(n) ~ O(n^2)
# Space: O(n)
# Given a string array words, find the maximum value of
# length(word[i]) * length(word[j]) where the two words
# do not share common letters. You may assume that each
# word will contain only lower case letters. If no such... | class Solution:
def max_product(self, words):
"""
:type words: List[str]
:rtype: int
"""
word_dict = dict()
for word in words:
word_dict[word] = set(word)
max_len = 0
for (i1, w1) in enumerate(words):
for i2 in range(i1 + 1, le... |
class Bye:
def __init__(self):
self.foo = 'bar'
def is_hello(self):
return type(self) == Hello
class Hello:
def __init__(self):
self.value = 'foobar'
print(Bye().is_hello())
| class Bye:
def __init__(self):
self.foo = 'bar'
def is_hello(self):
return type(self) == Hello
class Hello:
def __init__(self):
self.value = 'foobar'
print(bye().is_hello()) |
# Leetcode 70. Climbing Stairs
#
# Link: https://leetcode.com/problems/climbing-stairs/
# Difficulty: Easy
# Solution using DP
# Complexity:
# O(N) time | where N represent the number of steps of the staircase
# O(1) space
class Solution:
def climbStairs(self, n: int) -> int:
one, two = 1, 1
... | class Solution:
def climb_stairs(self, n: int) -> int:
(one, two) = (1, 1)
for i in range(n - 1):
(one, two) = (one + two, one)
return one |
## Set to display confirmation dialog on exit. You can always use 'exit' or
# 'quit', to force a direct exit without any confirmation.
c.JupyterConsoleApp.confirm_exit = False
## Whether to display a banner upon starting the QtConsole.
c.JupyterQtConsoleApp.display_banner = False
## Start the console window with the... | c.JupyterConsoleApp.confirm_exit = False
c.JupyterQtConsoleApp.display_banner = False
c.JupyterQtConsoleApp.hide_menubar = True |
#66: Compute a Grade Point Average
a={'A+':4.0,'A':4.0,'A-':3.7,'B+':3.3,'B':3.0,'B-':2.7,'C+':2.3,'C':2.0,'C-':1.7,'D+':1.3,'D':1.0,'F':0}
add=lambda x,y:x+y
c=0
d=0
while True:
b=input("Enter the grade:")
if b=="":
break
c=add(c,a[b])
d+=1
print("Average grade point:",c/d)
| a = {'A+': 4.0, 'A': 4.0, 'A-': 3.7, 'B+': 3.3, 'B': 3.0, 'B-': 2.7, 'C+': 2.3, 'C': 2.0, 'C-': 1.7, 'D+': 1.3, 'D': 1.0, 'F': 0}
add = lambda x, y: x + y
c = 0
d = 0
while True:
b = input('Enter the grade:')
if b == '':
break
c = add(c, a[b])
d += 1
print('Average grade point:', c / d) |
"""
Given two arrays, write a function to compute their intersection.
Note:
- Each element in the result must be unique.
- The result can be in any order.
link: https://leetcode.com/problems/intersection-of-two-arrays/
"""
class Solution(object):
def intersection(self, nums1, nums2):
"""
F... | """
Given two arrays, write a function to compute their intersection.
Note:
- Each element in the result must be unique.
- The result can be in any order.
link: https://leetcode.com/problems/intersection-of-two-arrays/
"""
class Solution(object):
def intersection(self, nums1, nums2):
"""
F... |
def test_mining_property_tester(web3_tester):
web3 = web3_tester
assert web3.eth.mining is False
def test_mining_property_ipc_and_rpc(web3_empty, wait_for_miner_start,
skip_if_testrpc):
web3 = web3_empty
skip_if_testrpc(web3)
wait_for_miner_start(web3)
a... | def test_mining_property_tester(web3_tester):
web3 = web3_tester
assert web3.eth.mining is False
def test_mining_property_ipc_and_rpc(web3_empty, wait_for_miner_start, skip_if_testrpc):
web3 = web3_empty
skip_if_testrpc(web3)
wait_for_miner_start(web3)
assert web3.eth.mining is True |
class Solution:
def checkIfExist(self, arr):
exists = {}
for num in arr:
if (num * 2) in exists or ((num / 2) in exists and num % 2 == 0):
return True
exists[num] = True
return False | class Solution:
def check_if_exist(self, arr):
exists = {}
for num in arr:
if num * 2 in exists or (num / 2 in exists and num % 2 == 0):
return True
exists[num] = True
return False |
#input
# 637 3371 327 67 924 968 2 6 6 77 5464 21813 70 5 67 74225 46 2 310 6156 50 4 623 87675 1702 3947 4927 9628 7 510 31 65 3321 23993 8406 88 -1
array = [int(x) for x in input().split()]
array.remove(-1)
swaps = 0
for i in range(0, len(array) - 1):
if array[i] > array[i+1]:
swaps += 1
t = array[i]
... | array = [int(x) for x in input().split()]
array.remove(-1)
swaps = 0
for i in range(0, len(array) - 1):
if array[i] > array[i + 1]:
swaps += 1
t = array[i]
array[i] = array[i + 1]
array[i + 1] = t
checksum = 0
for num in array:
checksum += num
checksum *= 113
checksum %= 1000... |
DEBUG = True
| debug = True |
# Write a program that reads a word and prints the number of syllables in the word.
# For this exercise, assume that syllables are determined as follows: Each sequence of
# adjacent vowels a e i o u y , except for the last e in a word, is a syllable. However, if
# that algorithm yields a count of 0, change it to 1. F... | input_word = str(input('Enter a word: '))
vowels = ('a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y')
last_vowel = False
last_cons = False
curr_vowel = False
curr_cons = False
syllables_count = 0
for i in range(len(inputWord)):
letter = inputWord[i]
if letter in vowels:
curr_vowel = True
... |
# Maximum number of images to keep in the database
MAX_FILES = 20
# Size of a JPEG minimum coded unit (MCU)
BLOCK_SIZE = 16
# Images will be resized to this width
IMAGE_WIDTH = 1200
# Image aspect ratio
ASPECT_RATIO = 3
| max_files = 20
block_size = 16
image_width = 1200
aspect_ratio = 3 |
# Source: https://leetcode.com/problems/contains-duplicate-iii/
# Better approach; Current time complexity: O(n * k)
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
if t == 0 and len(set(nums)) == len(nums):
return False
for i i... | class Solution:
def contains_nearby_almost_duplicate(self, nums: List[int], k: int, t: int) -> bool:
if t == 0 and len(set(nums)) == len(nums):
return False
for i in range(len(nums)):
for j in range(i + 1, min(i + k + 1, len(nums))):
if abs(nums[i] - nums[j])... |
response = sm.sendAskYesNo("Are you sure you want to leave?")
# sm.sendSay("Response was " + str(response) + "\r\rAnswer was " + str(answer))
if response:
sm.clearPartyInfo(401060000)
sm.dispose()
| response = sm.sendAskYesNo('Are you sure you want to leave?')
if response:
sm.clearPartyInfo(401060000)
sm.dispose() |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class IndexingPolicy(object):
"""Implementation of the 'IndexingPolicy' model.
Specifies settings for indexing files found in an Object
(such as a VM) so these files can be searched and recovered.
This also specifies inclusion and exclusion rule... | class Indexingpolicy(object):
"""Implementation of the 'IndexingPolicy' model.
Specifies settings for indexing files found in an Object
(such as a VM) so these files can be searched and recovered.
This also specifies inclusion and exclusion rules that determine
the directories to index.
Attrib... |
VISIT_DETAIL_FORM_CONSTANTS = {
'visit_date':{
'max_length': 100,
"data-dojo-type": "dijit.form.DateTextBox",
"data-dojo-props": r"'required' :true"
},
'op_surgeon':{
'max_length': 100,
"data-dojo-type": "dijit.form.Select",
... | visit_detail_form_constants = {'visit_date': {'max_length': 100, 'data-dojo-type': 'dijit.form.DateTextBox', 'data-dojo-props': "'required' :true"}, 'op_surgeon': {'max_length': 100, 'data-dojo-type': 'dijit.form.Select', 'data-dojo-props': "'required' : true"}, 'referring_doctor': {'max_length': 100, 'data-dojo-type':... |
def _merge_mro(seqs):
res = []
i = 0
while 1:
nonemptyseqs = [seq for seq in seqs if seq]
if not nonemptyseqs:
return res
i += 1
for seq in nonemptyseqs:
cand = seq[0]
nothead = [s for s in nonemptyseqs if cand in s[1:]]
if nothead:
cand = None
else:
break
if not ca... | def _merge_mro(seqs):
res = []
i = 0
while 1:
nonemptyseqs = [seq for seq in seqs if seq]
if not nonemptyseqs:
return res
i += 1
for seq in nonemptyseqs:
cand = seq[0]
nothead = [s for s in nonemptyseqs if cand in s[1:]]
if noth... |
def Skew(Genome):
res = [0]
for nuc in Genome:
to_app = res[-1]
if nuc == 'C':
to_app -= 1
elif nuc == 'G':
to_app += 1
res.append(to_app)
return res
def MinimumSkew(Genome):
min_val = 0
current_val = 0
min_pos = [0]
for i, nuc in enumerate(Genome):
if nuc == 'C':
current_val -= 1
elif nuc ... | def skew(Genome):
res = [0]
for nuc in Genome:
to_app = res[-1]
if nuc == 'C':
to_app -= 1
elif nuc == 'G':
to_app += 1
res.append(to_app)
return res
def minimum_skew(Genome):
min_val = 0
current_val = 0
min_pos = [0]
for (i, nuc) in e... |
load("@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "tool_path", "action_config", "tool")
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
def _impl(ctx):
tool_paths = [
tool_path(
name = "gcc",
path = "wrapper_cc.sh",
),
tool_path(
... | load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'tool_path', 'action_config', 'tool')
load('@bazel_tools//tools/build_defs/cc:action_names.bzl', 'ACTION_NAMES')
def _impl(ctx):
tool_paths = [tool_path(name='gcc', path='wrapper_cc.sh'), tool_path(name='g++', path='wrapper_cxx.sh'), tool_path(name='ld', ... |
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \t Distance from source")
for node in range(self.V):
print(node, "\t", dist[node])
... | class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
def print_solution(self, dist):
print('Vertex \t Distance from source')
for node in range(self.V):
print(node, '\t', dist[node])
... |
def setup_animation():
init_figure()
for line in lines:
self.line = self.mplCanvas.canvas.ax.plot([], [], [])
self.stopped = False | def setup_animation():
init_figure()
for line in lines:
self.line = self.mplCanvas.canvas.ax.plot([], [], [])
self.stopped = False |
def count_substring(string, sub_string):
# Init counter
counter = 0
# Find first index
ind = string.find(sub_string)
# Iterate over string
for i in string:
# If not found, return counter
if ind == -1:
return counter
else:
# Increment counter
... | def count_substring(string, sub_string):
counter = 0
ind = string.find(sub_string)
for i in string:
if ind == -1:
return counter
else:
counter += 1
string = string[ind + 1:]
ind = string.find(sub_string)
if __name__ == '__main__':
string = ... |
# MIT License
#
# Copyright (c) 2021 [FacuFalcone]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | def factorial(number: int):
"""
Calculate the factorial of a positive integer
https://en.wikipedia.org/wiki/Factorial
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(20))
True
>>> factorial(0.1)
Traceback (most recent call last):
...
ValueError: facto... |
def main() :
lstFriends = ("sharjeel", "GOPESH PANDEY", "Rupak")
print(lstFriends)
#Return the item in position 1
print(lstFriends[1])
#Tuples are unchangeabl: Once a tuple is created, you cannot change its values.
#lstFriends[1] = "AFFAN"
# The values will remain the same:
print(lstFriends)
#Use For l... | def main():
lst_friends = ('sharjeel', 'GOPESH PANDEY', 'Rupak')
print(lstFriends)
print(lstFriends[1])
print(lstFriends)
for frnd in lstFriends:
print(frnd)
print(len(lstFriends))
'Add Items\n\t#Once a tuple is created, you cannot add items to it. Tuples are unchangeable.\n\t\n\tlst... |
s = input()
if s[0:3] == 'KIH':
s = 'A'+s
elif s[0:4] != 'AKIH':
print('NO')
exit(0)
if s[4:5] == 'B':
s = s[0:4]+'A'+s[4:]
elif s[4:6] != 'AB':
print('NO')
exit(0)
if s[5:7] == 'BR':
s = s[0:6]+'A'+s[6:]
elif s[5:7] != 'BA':
print('NO')
exit(0)
if (s[7:9] == 'RA' and len(s) == 9... | s = input()
if s[0:3] == 'KIH':
s = 'A' + s
elif s[0:4] != 'AKIH':
print('NO')
exit(0)
if s[4:5] == 'B':
s = s[0:4] + 'A' + s[4:]
elif s[4:6] != 'AB':
print('NO')
exit(0)
if s[5:7] == 'BR':
s = s[0:6] + 'A' + s[6:]
elif s[5:7] != 'BA':
print('NO')
exit(0)
if s[7:9] == 'RA' and len(s)... |
def main():
file = open('6.txt')
banks = []
for line in file:
cells = [int(i) for i in line.split()]
banks.extend(cells)
all_banks = []
while banks not in all_banks:
all_banks.append(banks.copy())
i, m = max(enumerate(banks), key=lambda x: x[1])
banks[i] = 0
... | def main():
file = open('6.txt')
banks = []
for line in file:
cells = [int(i) for i in line.split()]
banks.extend(cells)
all_banks = []
while banks not in all_banks:
all_banks.append(banks.copy())
(i, m) = max(enumerate(banks), key=lambda x: x[1])
banks[i] = 0... |
def get_key(x, y):
return str(x)+"-"+str(y)
#input_line = input("Enter input:\n")
filename = "..\inputs\day_three_input.txt"
f = open(filename)
input_line = f.readline()
x = 0
y = 0
present_locations = {}
present_locations[get_key(x,y)]=1
for c in input_line:
if c == ">":
x += 1
elif c == "<":
x -= 1
elif c ==... | def get_key(x, y):
return str(x) + '-' + str(y)
filename = '..\\inputs\\day_three_input.txt'
f = open(filename)
input_line = f.readline()
x = 0
y = 0
present_locations = {}
present_locations[get_key(x, y)] = 1
for c in input_line:
if c == '>':
x += 1
elif c == '<':
x -= 1
elif c == '^':
... |
class PersegiPanjang(object) :
def __init__(self,p,l) :
self.panjang = p
self.lebar = l
def hitungLuas(self) :
return self.panjang * self.lebar
def cetakLuas(self) :
print('Panjang : ',self.panjang)
print('Lebar : ',self.lebar)
print('Luas : ',self.hitungLuas())
def main() :
test = Per... | class Persegipanjang(object):
def __init__(self, p, l):
self.panjang = p
self.lebar = l
def hitung_luas(self):
return self.panjang * self.lebar
def cetak_luas(self):
print('Panjang : ', self.panjang)
print('Lebar : ', self.lebar)
print('Luas : ', self.hitun... |
#this code gives the numbers of integers, floats, and strings present in the list
a= ['Hello',35,'b',45.5,'world',60]
i=f=s=0
for j in a:
if isinstance(j,int):
i=i+1
elif isinstance(j,float):
f=f+1
else:
s=s+1
print('Number of integers are:',i)
print('Number of Floats are:',f)
prin... | a = ['Hello', 35, 'b', 45.5, 'world', 60]
i = f = s = 0
for j in a:
if isinstance(j, int):
i = i + 1
elif isinstance(j, float):
f = f + 1
else:
s = s + 1
print('Number of integers are:', i)
print('Number of Floats are:', f)
print('numbers of strings are:', s) |
while True:
a, b = map(int, input().split())
if a == 0 and b == 0: break
print("Yes" if (a > b) else "No")
| while True:
(a, b) = map(int, input().split())
if a == 0 and b == 0:
break
print('Yes' if a > b else 'No') |
# initialize the compass points
NORTH, EAST, SOUTH, WEST = range(4)
class CompassPoints(object):
"""
initialize the class to have a default compass bearing of NORTH
left method subtracts a 'co-ordinate' point from the x axis
right method moves the robot +1 co-ordinate along the x-axis
"""
com... | (north, east, south, west) = range(4)
class Compasspoints(object):
"""
initialize the class to have a default compass bearing of NORTH
left method subtracts a 'co-ordinate' point from the x axis
right method moves the robot +1 co-ordinate along the x-axis
"""
compass_points = [NORTH, EAST, SOUT... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 21:10:52 2019
@author: felix
"""
def minimum_skew(genome):
"""
GC-skew such a useful tool for identifying the location of ori
"""
val = [0]
j = 0
_min = 0
for i in genome:
if i == 'C':
j -= 1
... | """
Created on Tue Jan 29 21:10:52 2019
@author: felix
"""
def minimum_skew(genome):
"""
GC-skew such a useful tool for identifying the location of ori
"""
val = [0]
j = 0
_min = 0
for i in genome:
if i == 'C':
j -= 1
if i == 'G':
j += 1
val.... |
class ComplexNumber(object):
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return ComplexNumber(self.real+other.real, self.imag+other.imag)
def __sub__(self, other):
return ComplexNumber(self.real-other.real, self.imag-other.ima... | class Complexnumber(object):
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return complex_number(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return complex_number(self.real - other.real, self.imag ... |
# https://leetcode.com/problems/first-bad-version/
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return an integer
# def isBadVersion(version):
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
if isBadVersio... | class Solution:
def first_bad_version(self, n):
"""
:type n: int
:rtype: int
"""
if is_bad_version(1):
return 1
low = 2
high = n
while low <= high:
middle = (low + high) // 2
if is_bad_version(middle) and (not is_ba... |
"""# Providers
Defines providers and related types used throughout the rules in this
repository.
Most users will not need to use these providers to simply create Xcode projects,
but if you want to write your own custom rules that interact with these
rules, then you will use these providers to communicate between them... | """# Providers
Defines providers and related types used throughout the rules in this
repository.
Most users will not need to use these providers to simply create Xcode projects,
but if you want to write your own custom rules that interact with these
rules, then you will use these providers to communicate between them... |
"""
Utilities for visualization plugins.
"""
# =============================================================================
class OpenObject(dict):
# note: not a Bunch
# TODO: move to util.data_structures
"""
A dict that allows assignment and attribute retrieval using the dot
operator.
If an... | """
Utilities for visualization plugins.
"""
class Openobject(dict):
"""
A dict that allows assignment and attribute retrieval using the dot
operator.
If an attribute isn't contained in the dict `None` is returned (no
KeyError).
JSON-serializable.
"""
def __getitem__(self, key):
... |
rec3 = 0
rec4 = 0
def hanoi3num(n, origem, destino, trabalho):
global rec3
rec3 += 1
if n == 1:
return rec3
hanoi3num(n-1, origem, trabalho, destino)
hanoi3num(n-1, trabalho, destino, origem)
return rec3
def hanoi4num(n, origem, destino, trabalho1, trabalho2):
global rec4
i... | rec3 = 0
rec4 = 0
def hanoi3num(n, origem, destino, trabalho):
global rec3
rec3 += 1
if n == 1:
return rec3
hanoi3num(n - 1, origem, trabalho, destino)
hanoi3num(n - 1, trabalho, destino, origem)
return rec3
def hanoi4num(n, origem, destino, trabalho1, trabalho2):
global rec4
i... |
class Solution:
def strMultiply(self, s, char):
bonus = 0
n = int(char)
newStr = ''
for i in range(len(s) - 1, -1, -1):
m = int(s[i])
result = n * m + bonus
newChar, bonus = str(result % 10), result // 10
newStr = newChar + newStr
... | class Solution:
def str_multiply(self, s, char):
bonus = 0
n = int(char)
new_str = ''
for i in range(len(s) - 1, -1, -1):
m = int(s[i])
result = n * m + bonus
(new_char, bonus) = (str(result % 10), result // 10)
new_str = newChar + new... |
# These commands are the saved state of coot. You can evaluate them
# using "Calculate->Run Script...".
#;;molecule-info: 0_PO4b.pdb
#;;molecule-info: 1_PO4b.pdb
#;;molecule-info: 2_PO4b.pdb
#;;molecule-info: PO4.pdb
#;;molecule-info: PO4_O.pdb
#;;molecule-info: 0_PO4e.pdb
#;;molecule-info: 1_PO4e.pdb
#;;molecule-info... | set_graphics_window_size(1309, 1017)
set_graphics_window_position(20, 20)
set_display_control_dialog_position(1491, 37)
vt_surface(2)
set_clipping_front(-10.0)
set_clipping_back(-10.0)
set_map_radius(10.0)
set_iso_level_increment(0.05)
set_diff_map_iso_level_increment(0.005)
set_colour_map_rotation_on_read_pdb(21.0)
se... |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Find the length of the longest substring with at most k disti... | class Solution(object):
def longest_substr(self, string, k):
if string is None:
raise type_error('string cannot be None')
if k is None:
raise type_error('k cannot be None')
low_index = 0
max_length = 0
chars_to_index_map = {}
for (index, char)... |
class DBPrefix:
DATA_Block = b'\x01'
DATA_Transaction = b'\x02'
ST_Account = b'\x40'
ST_Coin = b'\x44'
ST_SpentCoin = b'\x45'
ST_Validator = b'\x48'
ST_Asset = b'\x4c'
ST_Contract = b'\x50'
ST_Storage = b'\x70'
IX_HeaderHashList = b'\x80'
SYS_CurrentBlock = b'\xc0'
SY... | class Dbprefix:
data__block = b'\x01'
data__transaction = b'\x02'
st__account = b'@'
st__coin = b'D'
st__spent_coin = b'E'
st__validator = b'H'
st__asset = b'L'
st__contract = b'P'
st__storage = b'p'
ix__header_hash_list = b'\x80'
sys__current_block = b'\xc0'
sys__current... |
"""
The constants.py namespace contains constants used throughout the repo
These values are assigned at the start of analysis using the "metadata.MetaData" class
Set the values by populating the .xml or .xlsx file as per documentation
"""
# === runtime arguments ===
EXTRACT_OD = None
ANALYZE_OD = None
INPUT_FOL... | """
The constants.py namespace contains constants used throughout the repo
These values are assigned at the start of analysis using the "metadata.MetaData" class
Set the values by populating the .xml or .xlsx file as per documentation
"""
extract_od = None
analyze_od = None
input_folder = None
output_folder = N... |
#!/usr/bin/env python3
_DEFAULT_DEPENDENCIES = [
"packages/data/**/*",
"packages/common/**/*",
"packages/course-landing/**/*",
"packages/{{site}}/**/*",
"yarn.lock",
]
_COURSE_LANDING_DEPENDENCIES = [
"packages/data/training/sessions.yml",
"packages/data/training/recommendations/**/*",
... | _default_dependencies = ['packages/data/**/*', 'packages/common/**/*', 'packages/course-landing/**/*', 'packages/{{site}}/**/*', 'yarn.lock']
_course_landing_dependencies = ['packages/data/training/sessions.yml', 'packages/data/training/recommendations/**/*', 'packages/data/training/recommendations/**/*', 'packages/dat... |
class Board:
"""
Author: MBoss
Date: Jan 17, 2018.
Board class.
Board data:
1=white, -1=black, 0=empty
first dim is column , 2nd is row:
pieces[1][7] is the square in column 2,
at the opposite end of the board in row 8.
Squares are stored and manipulated as (x,y) tu... | class Board:
"""
Author: MBoss
Date: Jan 17, 2018.
Board class.
Board data:
1=white, -1=black, 0=empty
first dim is column , 2nd is row:
pieces[1][7] is the square in column 2,
at the opposite end of the board in row 8.
Squares are stored and manipulated as (x,y) tu... |
class EthTokenTransferV2(object):
def __init__(self):
self.contract_address = None
self.from_address = None
self.to_address = None
self.token_type = None
self.token_id = None
self.amount = None
self.transaction_hash = None
self.log_index = None
... | class Ethtokentransferv2(object):
def __init__(self):
self.contract_address = None
self.from_address = None
self.to_address = None
self.token_type = None
self.token_id = None
self.amount = None
self.transaction_hash = None
self.log_index = None
... |
""" tests module for the FIX-specific modules for the fixtest tool.
Copyright (c) 2014 Kenn Takara
See LICENSE for details
"""
| """ tests module for the FIX-specific modules for the fixtest tool.
Copyright (c) 2014 Kenn Takara
See LICENSE for details
""" |
class PlasterError(Exception):
"""
A base exception for any error generated by plaster.
"""
class InvalidURI(PlasterError, ValueError):
"""
Raised by :func:`plaster.parse_uri` when failing to parse a ``config_uri``.
:ivar uri: The user-supplied ``config_uri`` string.
"""
def __init__... | class Plastererror(Exception):
"""
A base exception for any error generated by plaster.
"""
class Invaliduri(PlasterError, ValueError):
"""
Raised by :func:`plaster.parse_uri` when failing to parse a ``config_uri``.
:ivar uri: The user-supplied ``config_uri`` string.
"""
def __init__... |
class Node(object):
def __init__(self, value=None, pointer=None):
self.value = value
self.pointer = None
class Queue(object):
def __init__(self):
self.head = None
self.tail = None
def isEmpty(self):
return not bool(self.head)
def enqueue(self, value):
nod... | class Node(object):
def __init__(self, value=None, pointer=None):
self.value = value
self.pointer = None
class Queue(object):
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return not bool(self.head)
def enqueue(self, value):
... |
def reverseList(self, head: ListNode) -> ListNode:
# begin with temporary node
cur = ListNode(-1)
# continue while list exists
while head is not None:
# create temp and make temp the new cur
temp = ListNode(-1)
cur.val = head.val
temp.next = cur
cur = temp
... | def reverse_list(self, head: ListNode) -> ListNode:
cur = list_node(-1)
while head is not None:
temp = list_node(-1)
cur.val = head.val
temp.next = cur
cur = temp
head = head.next
return cur.next |
# terrascript/data/hashicorp/random.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:25:40 UTC)
__all__ = []
| __all__ = [] |
class CommonRescale():
def get_factor(self, a):
raise NotImplementedError
def __call__(self, init, mask):
init_copy = init.clone()
init_copy[~mask] = 1e-12
return self.get_factor(init) / self.get_factor(init_copy)
class L1GlobalRescale(CommonRescale):
def get_factor(self, ... | class Commonrescale:
def get_factor(self, a):
raise NotImplementedError
def __call__(self, init, mask):
init_copy = init.clone()
init_copy[~mask] = 1e-12
return self.get_factor(init) / self.get_factor(init_copy)
class L1Globalrescale(CommonRescale):
def get_factor(self, a... |
#
# PySNMP MIB module BEGEMOT-WIRELESS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-WIRELESS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:20:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) ... |
epochs = 7
tau = 1.0
dropout = 0.2
validation_split = None
batch_size = 32
lengthscale = 0.01
| epochs = 7
tau = 1.0
dropout = 0.2
validation_split = None
batch_size = 32
lengthscale = 0.01 |
# MEDIUM
# TLE if decrement divisor only
# Bit manipulation.
# input: 100 / 3
# times = 0
# 3 << 0 = 3
# 3 << 1 = 6
# 3 << 2 = 12
# 3 << 3 = 24
# 3 << 4 = 48
# 3 << 5 = 96
# 3 << 6 = 192 => greater than dividend 100 => stop here
# times -=1 becaus... | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend == -2 ** 31 and divisor == -1:
return 2 ** 31 - 1
if dividend == 0:
return 0
sign = dividend >= 0 and divisor >= 0 or (dividend < 0 and divisor < 0)
(left, right) = (abs(dividen... |
def parse_data(data, objects_format, separator=" "):
"""
Takes a list of strings and a list of objects format and returns a list of objects formatted according to the objects format.
Example:
parse_data(['forward 10', 'left 90', 'right 90'], [{'key': 'command, 'format': str}, {'key': 'value', 'forma... | def parse_data(data, objects_format, separator=' '):
"""
Takes a list of strings and a list of objects format and returns a list of objects formatted according to the objects format.
Example:
parse_data(['forward 10', 'left 90', 'right 90'], [{'key': 'command, 'format': str}, {'key': 'value', 'forma... |
class Test:
def __init__(self):
self.prop1 = None
raise Exception('Interrupt init')
def __del__(self):
print('instance deleted')
print(self.prop1)
class Test2(Test):
pass
Test2()
| class Test:
def __init__(self):
self.prop1 = None
raise exception('Interrupt init')
def __del__(self):
print('instance deleted')
print(self.prop1)
class Test2(Test):
pass
test2() |
def compress_image(image, n_colors=64):
"""Compress an image
Parameters
==========
image : numpy array
array of shape (height, width, 3) with integer values between 0 and 255
n_colors : integer
the number of colors in the final compressed image
(i.e. the number of KMeans clu... | def compress_image(image, n_colors=64):
"""Compress an image
Parameters
==========
image : numpy array
array of shape (height, width, 3) with integer values between 0 and 255
n_colors : integer
the number of colors in the final compressed image
(i.e. the number of KMeans clu... |
def custom_filter(record):
info = record.INFO
support = info['SU'][0]
paired_end_support = info['PE'][0]
split_read_support = info['SR'][0]
if support > 10 and paired_end_support > 5 and split_read_support > 5:
yield record
| def custom_filter(record):
info = record.INFO
support = info['SU'][0]
paired_end_support = info['PE'][0]
split_read_support = info['SR'][0]
if support > 10 and paired_end_support > 5 and (split_read_support > 5):
yield record |
def from_socket(node, socket):
pass
| def from_socket(node, socket):
pass |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Blackbox Hardware Driver',
'version': '1.0',
'category': 'Hardware Drivers',
'sequence': 6,
'summary': 'Hardware Driver for Belgian Fiscal Data Modules',
'website': 'https://www.odoo.com... | {'name': 'Blackbox Hardware Driver', 'version': '1.0', 'category': 'Hardware Drivers', 'sequence': 6, 'summary': 'Hardware Driver for Belgian Fiscal Data Modules', 'website': 'https://www.odoo.com/page/point-of-sale', 'description': '\nFiscal Data Module Hardware Driver\n==================================\n\nThis modul... |
"""
---> Longest Consecutive Sequence
---> Medium
"""
class Solution:
def longestConsecutive(self, nums) -> int:
nums = set(nums)
ans = 0
for num in nums:
if num - 1 not in nums:
curr = num
while curr in nums:
ans = max(ans,... | """
---> Longest Consecutive Sequence
---> Medium
"""
class Solution:
def longest_consecutive(self, nums) -> int:
nums = set(nums)
ans = 0
for num in nums:
if num - 1 not in nums:
curr = num
while curr in nums:
ans = max(ans... |
def append_helper(initial_list, append_this):
if type(initial_list) is not list:
raise TypeError("initial_list must be a list")
if type(append_this) == list:
return initial_list + append_this
else:
initial_list.append(append_this)
return initial_list
| def append_helper(initial_list, append_this):
if type(initial_list) is not list:
raise type_error('initial_list must be a list')
if type(append_this) == list:
return initial_list + append_this
else:
initial_list.append(append_this)
return initial_list |
def imageF():
image = imread(r"E:\Python Working\png")
if __name__ =="__main__":
imageF() | def image_f():
image = imread('E:\\Python Working\\png')
if __name__ == '__main__':
image_f() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" This file will contain the webui endpoints for the web Application
Too small so moved for now.
"""
| """ This file will contain the webui endpoints for the web Application
Too small so moved for now.
""" |
# Time: O(n)
# Space: O(1)
# We have two integer sequences A and B of the same non-zero length.
#
# We are allowed to swap elements A[i] and B[i].
# Note that both elements are in the same index position in their respective sequences.
#
# At the end of some number of swaps, A and B are both strictly increasing.
# (A ... | class Solution(object):
def min_swap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
(dp_no_swap, dp_swap) = ([0] * 2, [1] * 2)
for i in xrange(1, len(A)):
(dp_no_swap[i % 2], dp_swap[i % 2]) = (float('inf'), float('inf'))
... |
class IGetCurrencies:
def __init__(self, data):
self.success = data.get('success')
self.message = data.get('message', '')
self.currencies_raw = data.get('currencies', {})
self.earbuds = Currency(self.currencies_raw.get('earbuds', {}))
self.keys = Currency(self.currencies_raw... | class Igetcurrencies:
def __init__(self, data):
self.success = data.get('success')
self.message = data.get('message', '')
self.currencies_raw = data.get('currencies', {})
self.earbuds = currency(self.currencies_raw.get('earbuds', {}))
self.keys = currency(self.currencies_raw... |
def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort):
"""
To have custom time scaling do something like this:
.. sourcecode:: python
def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort):
if unit == 'seconds':
prefix = ''
... | def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort):
"""
To have custom time scaling do something like this:
.. sourcecode:: python
def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort):
if unit == 'seconds':
prefix = ''
... |
class TestFile():
test = temp
def temp_method():
print('temp_method')
| class Testfile:
test = temp
def temp_method():
print('temp_method') |
"""
Vulnerabilities are divided into 2 main categories.
MITRE Category
--------------
Vulnerability that correlates to a method in the official MITRE ATT&CK matrix for kubernetes
CVE Category
-------------
"General" category definition. The category is usually determined by the severity of the CVE
"""
class MITRECa... | """
Vulnerabilities are divided into 2 main categories.
MITRE Category
--------------
Vulnerability that correlates to a method in the official MITRE ATT&CK matrix for kubernetes
CVE Category
-------------
"General" category definition. The category is usually determined by the severity of the CVE
"""
class Mitrecat... |
WORKER_THREAD = 'thread'
WORKER_GREENLET = 'greenlet'
WORKER_PROCESS = 'process'
WORKER_TYPES = (WORKER_THREAD, WORKER_GREENLET, WORKER_PROCESS)
class EmptyData(object):
pass
| worker_thread = 'thread'
worker_greenlet = 'greenlet'
worker_process = 'process'
worker_types = (WORKER_THREAD, WORKER_GREENLET, WORKER_PROCESS)
class Emptydata(object):
pass |
description = 'RESI NICOS startup setup'
group = 'basic'
includes = ['system'] #, 'lakeshore', 'cascade', 'detector']
modules = ['nicos_mlz.resi.scan']
devices = dict(
resi = device('nicos_mlz.resi.devices.residevice.ResiDevice',
description = 'main RESI device',
unit = 'special',
),
theta ... | description = 'RESI NICOS startup setup'
group = 'basic'
includes = ['system']
modules = ['nicos_mlz.resi.scan']
devices = dict(resi=device('nicos_mlz.resi.devices.residevice.ResiDevice', description='main RESI device', unit='special'), theta=device('nicos_mlz.resi.devices.residevice.ResiVAxis', description='theta axis... |
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
if letter.isupper():
translation = translation + "M"
else:
translation = translation + "m"
else:
translation = translation + letter
ret... | def translate(phrase):
translation = ''
for letter in phrase:
if letter in 'AEIOUaeiou':
if letter.isupper():
translation = translation + 'M'
else:
translation = translation + 'm'
else:
translation = translation + letter
ret... |
class Quote(object):
def __init__(self, root, **kwargs):
self._data = kwargs
self._root = root
def __getattr__(self, item):
return self._data.get(item, None)
def to_primitive(self):
return self._data
@staticmethod
def from_primitive(root, primitive):
if pri... | class Quote(object):
def __init__(self, root, **kwargs):
self._data = kwargs
self._root = root
def __getattr__(self, item):
return self._data.get(item, None)
def to_primitive(self):
return self._data
@staticmethod
def from_primitive(root, primitive):
if pr... |
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = [
'django_nose',
'tests.testapp',
]
ROOT_URLCONF = 'tests.urls'
SECRET_KEY = "shh...it's a seakret"
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION... | debug = True
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
installed_apps = ['django_nose', 'tests.testapp']
root_urlconf = 'tests.urls'
secret_key = "shh...it's a seakret"
caches = {'default': {'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '127.0.0.1:6381', 'OPTIONS': {'DB': 15, 'PASSWORD': 'yad... |
# Example test module for nose
# run with: nosetests -v
# or: nosetests -s
# Simple test functions first:
def test_ok():
print("test_ok")
# def fail_test():
# print "fail_test: will always fail"
# assert False
# Private functions are however not recognized:
def _test_notseen():
print("_test_notseen")
... | def test_ok():
print('test_ok')
def _test_notseen():
print('_test_notseen')
assert False
def _notseen_test():
print('_notseen_test')
assert False
def test_evens():
for i in range(0, 5, 2):
yield (check_even, i)
def check_even(n):
assert n % 2 == 0
def setup_func():
"""set up... |
#!/usr/bin/env python3
num = int(input())
if num % 3 == 0 and num % 5 == 0:
print('fizzbuzz')
elif num % 3 == 0:
print("fizz")
elif num % 5 == 0:
print("buzz")
else:
print('you are wrong kiddo')
# the point of fizzbuzz is to see if a number is divisible by 3 and 5, or just one, or neither.
# for more info c... | num = int(input())
if num % 3 == 0 and num % 5 == 0:
print('fizzbuzz')
elif num % 3 == 0:
print('fizz')
elif num % 5 == 0:
print('buzz')
else:
print('you are wrong kiddo') |
class BuildError(Exception):
def __init__(self, message: str):
super().__init__(message)
class MissedRequiredParamError(BuildError):
def __init__(self, param_name: str):
message = f'Required param "{param_name}" is missed'
super().__init__(message)
class FunctionNotExistError(BuildEr... | class Builderror(Exception):
def __init__(self, message: str):
super().__init__(message)
class Missedrequiredparamerror(BuildError):
def __init__(self, param_name: str):
message = f'Required param "{param_name}" is missed'
super().__init__(message)
class Functionnotexisterror(BuildEr... |
def func(arg, opt=1, *args, **kwargs):
print(arg, opt, args, kwargs)
func(0)
func(0, 10)
func(0, 10, 20)
func(0, 10, 20, 30)
func(0, 10, 20, 30, key='value')
func(0, 10, 20, 30, key='value', key2='v2')
| def func(arg, opt=1, *args, **kwargs):
print(arg, opt, args, kwargs)
func(0)
func(0, 10)
func(0, 10, 20)
func(0, 10, 20, 30)
func(0, 10, 20, 30, key='value')
func(0, 10, 20, 30, key='value', key2='v2') |
# class definition
class MyClass:
pass
# The __init__() Method
# attributes
# methods
class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
def sayhi(self):
print("Hi, my name is %s, and I'm %s" % (self.__name, self.__age))
def get_age(self):
... | class Myclass:
pass
class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
def sayhi(self):
print("Hi, my name is %s, and I'm %s" % (self.__name, self.__age))
def get_age(self):
return self.__age
def set_age(self, num):
if isinst... |
print('Opening dummy.txt')
#open dummy.txt to read it as "in_stream" (in_stream is the variable)
with open('dummy.txt', 'r') as in_stream:
print('Opening output.txt')
#open output.txt to write in it, call it "out_stream"
with open('output.txt', 'w') as out_stream:
#for every line in the dummy.txt input file
#en... | print('Opening dummy.txt')
with open('dummy.txt', 'r') as in_stream:
print('Opening output.txt')
with open('output.txt', 'w') as out_stream:
for (line_index, line) in enumerate(in_stream):
line = line.strip()
word_list = line.split()
word_list.sort()
for w... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This module defines input/output functions.
Text
----
.. automodule:: tunacell.io.text
:members:
Sniff
-----
.. automodule:: tunacell.io.sniff
:members:
HDF5
----
.. automodule:: tunacell.io.h5
:members:
"""
| """
This module defines input/output functions.
Text
----
.. automodule:: tunacell.io.text
:members:
Sniff
-----
.. automodule:: tunacell.io.sniff
:members:
HDF5
----
.. automodule:: tunacell.io.h5
:members:
""" |
count = int(input())
numbers_list = []
for _x in range(count):
numbers_list.append(int(input()))
sum_numbers = 0
count_numbers = len(numbers_list)
for x in numbers_list:
sum_numbers += x
mean = sum_numbers / count_numbers
print(mean)
| count = int(input())
numbers_list = []
for _x in range(count):
numbers_list.append(int(input()))
sum_numbers = 0
count_numbers = len(numbers_list)
for x in numbers_list:
sum_numbers += x
mean = sum_numbers / count_numbers
print(mean) |
#! /usr/bin/env python3
AsciiBinFmt, AsciiGrayFmt, AsciiPixelFmt = range(1, 4)
BinBinFmt, BinGrayFmt, BinPixelFmt = range(4, 7)
ext = ["", "pbm", "pgm", "ppm", "pbm", "pgm", "ppm"]
def isBinFmt(fmt):
return fmt % 3 == 1
def isGrayFmt(fmt):
return fmt % 3 == 2
def isPixelFmt(fmt):
return fmt % 3 == 0
c... | (ascii_bin_fmt, ascii_gray_fmt, ascii_pixel_fmt) = range(1, 4)
(bin_bin_fmt, bin_gray_fmt, bin_pixel_fmt) = range(4, 7)
ext = ['', 'pbm', 'pgm', 'ppm', 'pbm', 'pgm', 'ppm']
def is_bin_fmt(fmt):
return fmt % 3 == 1
def is_gray_fmt(fmt):
return fmt % 3 == 2
def is_pixel_fmt(fmt):
return fmt % 3 == 0
class... |
'''
The function has been made even more general by parameterizing the size of one sub box.
'''
def drawBox(length, cellSize):
for i in range(length):
printBoxLines(length, cellSize, "*", "---", 1)
printBoxLines(length, cellSize, "|", " ", cellSize)
printBoxLines(length, cellSize, "*", "---"... | """
The function has been made even more general by parameterizing the size of one sub box.
"""
def draw_box(length, cellSize):
for i in range(length):
print_box_lines(length, cellSize, '*', '---', 1)
print_box_lines(length, cellSize, '|', ' ', cellSize)
print_box_lines(length, cellSize, '*',... |
GRID_SIZE = 5
# Bingo numbers and grids.
def get_b_and_g(lines):
bingo_numbers = []
grids = []
is_first = True
for line in lines:
if is_first:
bingo_numbers = [int(s) for s in line.split(",") if s.isdigit()]
is_first = False
continue
if line == "":
... | grid_size = 5
def get_b_and_g(lines):
bingo_numbers = []
grids = []
is_first = True
for line in lines:
if is_first:
bingo_numbers = [int(s) for s in line.split(',') if s.isdigit()]
is_first = False
continue
if line == '':
grids.append([])
... |
# Even Fibonacci numbers
# Each new term in the Fibonacci sequence is generated
# by adding the previous two terms. By starting with
# 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence
# whose values do not exceed four million, find th... | upper_bound = 4000000
def run():
even_fib_sum = 0
fib_last = 1
fib_current = 1
while fib_current <= UPPER_BOUND:
if fib_current % 2 == 0:
even_fib_sum += fib_current
fib_new = fib_last + fib_current
fib_last = fib_current
fib_current = fib_new
print('The ... |
""" Lab 05: Mutable Sequences and Trees """
# Q1
def acorn_finder(t):
"""Returns True if t contains a node with the value 'acorn' and
False otherwise.
>>> scrat = tree('acorn')
>>> acorn_finder(scrat)
True
>>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('acorn')]), tree('branch... | """ Lab 05: Mutable Sequences and Trees """
def acorn_finder(t):
"""Returns True if t contains a node with the value 'acorn' and
False otherwise.
>>> scrat = tree('acorn')
>>> acorn_finder(scrat)
True
>>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('acorn')]), tree('branch2')])... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def f1(a,b,c=0,*args,**kwargs):
print('a=',a,'b=',b,'c=',c,'args=',args,'kwargs=',kwargs)
def f2(a,b,c=0,*,d,**kw):
print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
#f1(1,2,3,'a','b',x=99)
#f2(1,2,d=99,ext=None)
args=(1,2,3,4)
kw={'d':99,'x':'#'}
f1(*args,**kw)
args=(... | def f1(a, b, c=0, *args, **kwargs):
print('a=', a, 'b=', b, 'c=', c, 'args=', args, 'kwargs=', kwargs)
def f2(a, b, c=0, *, d, **kw):
print('a=', a, 'b=', b, 'c=', c, 'd=', d, 'kw=', kw)
args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, **kw)
args = (1, 2, 3)
kw = {'d': 88, '*': '#'}
f2(*args, **kw) |
#!/usr/bin/env python3
#
# Copyright 2019 Vojtech Horky
#
# 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 o... | """
Unit conversion utilities.
"""
class Smartunit:
"""
Holds arbitrary value but formats it in a reasonable unit.
"""
def __init__(self, value, size, unit=''):
self.value = value
self.size = size
self.unit = unit
def get_reasonable_value_with_unit_(self):
""" Does... |
# Copyright 2015 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... | """Rust rules for Bazel"""
rust_filetype = file_type(['.rs'])
a_filetype = file_type(['.a'])
library_crate_types = ['lib', 'rlib', 'dylib', 'staticlib']
html_md_filetype = file_type(['.html', '.md'])
css_filetype = file_type(['.css'])
zip_path = '/usr/bin/zip'
def _relative(src_path, dest_path):
"""Returns the rel... |
# Robot variable file using Python syntax
# Installed browser selection
# BROWSER = "chrome"
# BROWSER = "firefox"
BROWSER = "headlessfirefox"
# Helmi login credentials:
# replace <helmiurl> with your area specific value https://alue.helmi.fi
# replace <user> and <pass> with your Helmi username and password
HELMI_LO... | browser = 'headlessfirefox'
helmi_login_page = '<helmiurl>'
helmi_username = '<user>'
helmi_password = '<pass>'
gmail_userid = '<email>'
helmi_target_email = '<email>' |
class Solution:
"""
@param: s: A string
@return: A string
"""
def reverseWords(self, s):
return " ".join(list(filter(lambda x: x != "", s.split(" ")))[::-1]) | class Solution:
"""
@param: s: A string
@return: A string
"""
def reverse_words(self, s):
return ' '.join(list(filter(lambda x: x != '', s.split(' ')))[::-1]) |
class Solution:
def printMinNumberForPattern(ob, S):
# code here
count = 1
stack = []
ans = ""
for i in S:
if i == "D":
stack.append(count)
count += 1
else:
stack.append(count)
coun... | class Solution:
def print_min_number_for_pattern(ob, S):
count = 1
stack = []
ans = ''
for i in S:
if i == 'D':
stack.append(count)
count += 1
else:
stack.append(count)
count += 1
... |
class Solution:
def removeDuplicates(self, nums):
if len(nums) == 0:
return 0
nextAvail = 1
for i in range(1, len(nums)):
if nums[i] == nums[nextAvail-1]:
i += 1
else:
nums[nextAvail] = nums[i]
nextAvail += 1... | class Solution:
def remove_duplicates(self, nums):
if len(nums) == 0:
return 0
next_avail = 1
for i in range(1, len(nums)):
if nums[i] == nums[nextAvail - 1]:
i += 1
else:
nums[nextAvail] = nums[i]
next_avai... |
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
dp = 0
ans = 0
n = len(nums)
for i in range(2, n):
pre = nums[i - 1] - nums[i - 2]
now = nums[i] - nums[i - 1]
if now == pre:
dp += 1
ans +=... | class Solution:
def number_of_arithmetic_slices(self, nums: List[int]) -> int:
dp = 0
ans = 0
n = len(nums)
for i in range(2, n):
pre = nums[i - 1] - nums[i - 2]
now = nums[i] - nums[i - 1]
if now == pre:
dp += 1
an... |
def findMax(some_dict):
positions = set() # output variable
max_value = -1
for k, v in some_dict.items():
if v == max_value:
positions.add(k)
if v > max_value:
max_value = v
positions = set() # output variable
positions.add(k)
return positions, max_value
def getChangeTimes(cowL... | def find_max(some_dict):
positions = set()
max_value = -1
for (k, v) in some_dict.items():
if v == max_value:
positions.add(k)
if v > max_value:
max_value = v
positions = set()
positions.add(k)
return (positions, max_value)
def get_change_... |
"""
Test all functionality related to authorization, e.g. logging in, logging out, registering etc.
"""
def test_nonexisting_account(client):
response = client.get('/v0/whoami')
assert response.status_code == 401
response = client.post('/v0/login', json={
'username': 'a',
'password': 'a'
... | """
Test all functionality related to authorization, e.g. logging in, logging out, registering etc.
"""
def test_nonexisting_account(client):
response = client.get('/v0/whoami')
assert response.status_code == 401
response = client.post('/v0/login', json={'username': 'a', 'password': 'a'})
assert respon... |
def mdc(a,b):
if a<b:
return mdc(b,a)
else:
if b==0:
return a
else:
return mdc(b, a % b)
print(mdc(12,8))
print(mdc(12,10))
| def mdc(a, b):
if a < b:
return mdc(b, a)
elif b == 0:
return a
else:
return mdc(b, a % b)
print(mdc(12, 8))
print(mdc(12, 10)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.