content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def parse_commands(lines):
commands = []
for l in lines:
c, offset = l.split()
commands.append([c, int(offset)])
return commands
def run_command(command, idx, acc):
c, offset = command
if c == 'acc':
acc += offset
idx += 1
elif c == 'jmp':
idx += offset
... | def parse_commands(lines):
commands = []
for l in lines:
(c, offset) = l.split()
commands.append([c, int(offset)])
return commands
def run_command(command, idx, acc):
(c, offset) = command
if c == 'acc':
acc += offset
idx += 1
elif c == 'jmp':
idx += offs... |
languages = ["Python", "Perl", "Ruby", "Go", "Java", "C"]
lengths = [len(language) for language in languages]
print(lengths)
z = [x for x in range(0,101) if x%3 ==0]
print(z)
| languages = ['Python', 'Perl', 'Ruby', 'Go', 'Java', 'C']
lengths = [len(language) for language in languages]
print(lengths)
z = [x for x in range(0, 101) if x % 3 == 0]
print(z) |
class RGB:
def __init__(self, r: int, g: int, b: int):
self.r = r
self.g = g
self.b = b | class Rgb:
def __init__(self, r: int, g: int, b: int):
self.r = r
self.g = g
self.b = b |
N = int(input())
if N % 2 == 0:
print(N)
else:
print(2 * N)
| n = int(input())
if N % 2 == 0:
print(N)
else:
print(2 * N) |
# Class which represents the university object and its data
class University:
def __init__(self, world_rank, name, national_rank, education_quality, alumni_employment, faculty_quality,
publications, influence, citations, impact, patents, aggregate_rank):
self.id = world_rank
self.... | class University:
def __init__(self, world_rank, name, national_rank, education_quality, alumni_employment, faculty_quality, publications, influence, citations, impact, patents, aggregate_rank):
self.id = world_rank
self.name = name
self.national_rank = national_rank
self.education_... |
"""
761. Smallest Subset
https://www.lintcode.com/problem/smallest-subset/description
first sort, then calculate prefix sum.
"""
class Solution:
"""
@param arr: an array of non-negative integers
@return: minimum number of elements
"""
def minElements(self, arr):
# write your code here
... | """
761. Smallest Subset
https://www.lintcode.com/problem/smallest-subset/description
first sort, then calculate prefix sum.
"""
class Solution:
"""
@param arr: an array of non-negative integers
@return: minimum number of elements
"""
def min_elements(self, arr):
if not arr:
... |
"""shaarli-client"""
__title__ = 'shaarli_client'
__brief__ = 'CLI to interact with a Shaarli instance'
__version__ = '0.4.0'
__author__ = 'The Shaarli Community'
| """shaarli-client"""
__title__ = 'shaarli_client'
__brief__ = 'CLI to interact with a Shaarli instance'
__version__ = '0.4.0'
__author__ = 'The Shaarli Community' |
'''
Since 1926, the Belmont Stakes is a 1.5 mile-long race of 3-year old thoroughbred horses. Secretariat ran the fastest Belmont Stakes in history in 1973. While that was the fastest year, 1970 was the slowest because of unusually wet and sloppy conditions. With these two outliers removed from the data set, compute th... | """
Since 1926, the Belmont Stakes is a 1.5 mile-long race of 3-year old thoroughbred horses. Secretariat ran the fastest Belmont Stakes in history in 1973. While that was the fastest year, 1970 was the slowest because of unusually wet and sloppy conditions. With these two outliers removed from the data set, compute th... |
# Test for existing rows
def check_row_number(cur, tables):
"""
Check number of rows greater one for sql tables
Args:
cur (object): PostgreSQL curser object
tables (list): List of string of table names
"""
for table in tables:
cur.execute(f"SELECT COUNT(*) FROM {table}... | def check_row_number(cur, tables):
"""
Check number of rows greater one for sql tables
Args:
cur (object): PostgreSQL curser object
tables (list): List of string of table names
"""
for table in tables:
cur.execute(f'SELECT COUNT(*) FROM {table}')
if cur.rowcount... |
#if else can be done as
a=int(input())
b=int(input())
c=a%2
if a>b:
print("{} is greater than {}".format(a,b))
elif a==b:
print("{} and {} are equal".format(a,b))
else:
print("{} is greater than {}".format(b,a))
#if can be done in single line as
if a>b: print("{} is greater".format(a))
print("{} is even"... | a = int(input())
b = int(input())
c = a % 2
if a > b:
print('{} is greater than {}'.format(a, b))
elif a == b:
print('{} and {} are equal'.format(a, b))
else:
print('{} is greater than {}'.format(b, a))
if a > b:
print('{} is greater'.format(a))
print('{} is even'.format(a)) if c == 0 else print('{} is ... |
# Reading first input, not used anywhere in the program
first_input = input()
# Reading the input->split->parse to int->elements to set
set1 = set(map(int, input().split()))
# Same as second_input
second_input = input()
# Same as set2
set2 = set(map(int, input().split()))
# Union of set1 and set2 returns the set of all... | first_input = input()
set1 = set(map(int, input().split()))
second_input = input()
set2 = set(map(int, input().split()))
set3 = set1.union(set2)
print(len(set3)) |
self.description = "Remove a no longer needed package (multiple provision)"
lp1 = pmpkg("pkg1")
lp1.provides = ["imaginary"]
self.addpkg2db("local", lp1)
lp2 = pmpkg("pkg2")
lp2.provides = ["imaginary"]
self.addpkg2db("local", lp2)
lp3 = pmpkg("pkg3")
lp3.depends = ["imaginary"]
self.addpkg2db("local", lp3)
self.ar... | self.description = 'Remove a no longer needed package (multiple provision)'
lp1 = pmpkg('pkg1')
lp1.provides = ['imaginary']
self.addpkg2db('local', lp1)
lp2 = pmpkg('pkg2')
lp2.provides = ['imaginary']
self.addpkg2db('local', lp2)
lp3 = pmpkg('pkg3')
lp3.depends = ['imaginary']
self.addpkg2db('local', lp3)
self.args =... |
def multiple(first,second):
return first * second * 3
def add(x,y):
return x+y
| def multiple(first, second):
return first * second * 3
def add(x, y):
return x + y |
config = {
'max_length' : 512,
'class_names' : ['O', 'B-C', 'B-P', 'I-C', 'I-P'],
'ft_data_folders' : ['/content/change-my-view-modes/v2.0/data/'],
'max_tree_size' : 10,
'max_labelled_users_per_tree':10,
'batch_size' : 4,
'd_model': 512,
'init_alphas': [0.0, 0.0, 0.0, -10000., -1000... | config = {'max_length': 512, 'class_names': ['O', 'B-C', 'B-P', 'I-C', 'I-P'], 'ft_data_folders': ['/content/change-my-view-modes/v2.0/data/'], 'max_tree_size': 10, 'max_labelled_users_per_tree': 10, 'batch_size': 4, 'd_model': 512, 'init_alphas': [0.0, 0.0, 0.0, -10000.0, -10000.0], 'transition_init': [[0.01, -10000.0... |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "commons_lang_commons_lang",
artifact = "commons-lang:commons-lang:2.6",
jar_sha256 = "50f11b09f877c294d56f24463f47d28f929cf5044f648661c0f0cfbae9a2f49c",
srcja... | load('//:import_external.bzl', import_external='safe_wix_scala_maven_import_external')
def dependencies():
import_external(name='commons_lang_commons_lang', artifact='commons-lang:commons-lang:2.6', jar_sha256='50f11b09f877c294d56f24463f47d28f929cf5044f648661c0f0cfbae9a2f49c', srcjar_sha256='66c2760945cec226f26286... |
## Class responsible for representing a Sonobouy within Hunting the Plark
class Sonobuoy():
def __init__(self, active_range):
self.type = "SONOBUOY"
self.col = None
self.row = None
self.range = active_range
self.state = "COLD"
self.size = 1
## Setstate allows the change of state which will happen when... | class Sonobuoy:
def __init__(self, active_range):
self.type = 'SONOBUOY'
self.col = None
self.row = None
self.range = active_range
self.state = 'COLD'
self.size = 1
def set_state(self, state):
self.state = state
def get_state(self):
return s... |
def clamp(a, b):
if (b < 0 and a >= b) or (b > 0 and a <= b):
return a
def field(a, b, then):
val = clamp(a, b)
if val is not None:
return round(then(val), 3)
def sign_and_magnitude(intg, fract):
if fract > 100:
return None
val = (intg & 0x7F) + fract * 0.01
if int... | def clamp(a, b):
if b < 0 and a >= b or (b > 0 and a <= b):
return a
def field(a, b, then):
val = clamp(a, b)
if val is not None:
return round(then(val), 3)
def sign_and_magnitude(intg, fract):
if fract > 100:
return None
val = (intg & 127) + fract * 0.01
if intg & 128 ... |
def countfreq(input):
freq={}
for i in input:
freq[i]=input.count(i)
for key,value in freq.items():
print("%d:%d"%(key,value))
input=[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
countfreq(input)
| def countfreq(input):
freq = {}
for i in input:
freq[i] = input.count(i)
for (key, value) in freq.items():
print('%d:%d' % (key, value))
input = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
countfreq(input) |
"""
28. How to find all the local maxima (or peaks) in a numeric series?
"""
"""
Difficiulty Level: L3
"""
"""
Get the positions of peaks (values surrounded by smaller values on both sides) in ser.
"""
"""
Input
"""
"""
ser = pd.Series([2, 10, 3, 4, 9, 10, 2, 7, 3])
"""
"""
Desired output
"""
"""
array([1, 5, 7])
"""
| """
28. How to find all the local maxima (or peaks) in a numeric series?
"""
'\nDifficiulty Level: L3\n'
'\nGet the positions of peaks (values surrounded by smaller values on both sides) in ser.\n'
'\nInput\n'
'\nser = pd.Series([2, 10, 3, 4, 9, 10, 2, 7, 3])\n'
'\nDesired output\n'
'\narray([1, 5, 7])\n' |
#
# @lc app=leetcode.cn id=66 lang=python3
#
# [66] plus-one
#
None
# @lc code=end | None |
class Solution:
"""
@param n: a positive integer
@return: An integer
"""
def numSquares(self, n):
def issq(n):
x = int(n**.5)
return x * x == n
if issq(n):
return 1
dp = [0, 1]
for i in xrange(2, n + 1):
if issq(i):
... | class Solution:
"""
@param n: a positive integer
@return: An integer
"""
def num_squares(self, n):
def issq(n):
x = int(n ** 0.5)
return x * x == n
if issq(n):
return 1
dp = [0, 1]
for i in xrange(2, n + 1):
if issq(i)... |
class ZipDataLoader:
"""
A data loader that zips together two underlying data loaders. The data loaders must be
sampling the same batch size and :code:`drop_last` must be set to `True` on data loaders that
sample from a fixed-size dataset. Whenever one of the data loaders has a fixed size, this data
... | class Zipdataloader:
"""
A data loader that zips together two underlying data loaders. The data loaders must be
sampling the same batch size and :code:`drop_last` must be set to `True` on data loaders that
sample from a fixed-size dataset. Whenever one of the data loaders has a fixed size, this data
... |
for i in range(1,5):
for j in range(i,5):
print(j," " ,end="")
print()
str1 = "ABCD"
str2 = "PQR"
for i in range(4):
print(str1[:i+1]+str2[i:]) | for i in range(1, 5):
for j in range(i, 5):
print(j, ' ', end='')
print()
str1 = 'ABCD'
str2 = 'PQR'
for i in range(4):
print(str1[:i + 1] + str2[i:]) |
def new(a,b):
return a - b
def x(a,b):
return a
def y(z,t):
return z(*t)
def inModule2(a,b):
return a+b
def outerMethod(a,b):
def innerMethod(a,b):
if a < b:
return a+b
else:
return a-b
return innerMethod(a+2, b+4)
| def new(a, b):
return a - b
def x(a, b):
return a
def y(z, t):
return z(*t)
def in_module2(a, b):
return a + b
def outer_method(a, b):
def inner_method(a, b):
if a < b:
return a + b
else:
return a - b
return inner_method(a + 2, b + 4) |
"""
:testcase_name greet
:author Sriteja Kummita
:script_type Class
:description __getattr__ is called when a property/method of a class is used. This class allows three functions which
are not defined in the class but can be called using reflection
"""
class Greet:
def __init__(self, name):
self.name = n... | """
:testcase_name greet
:author Sriteja Kummita
:script_type Class
:description __getattr__ is called when a property/method of a class is used. This class allows three functions which
are not defined in the class but can be called using reflection
"""
class Greet:
def __init__(self, name):
self.name = n... |
#!/usr/bin/env python3
class Observer:
"""
Objects that are interested in a subject should
inherit from this class.
"""
def notify(self, sender: object):
pass
| class Observer:
"""
Objects that are interested in a subject should
inherit from this class.
"""
def notify(self, sender: object):
pass |
# This function takes a single parameter and prints it.
def print_value(x):
print(x)
print_value(12)
print_value("dog") | def print_value(x):
print(x)
print_value(12)
print_value('dog') |
__version__ = '1.3.0'
__url__ = 'https://github.com/mdawar/rq-exporter'
__description__ = 'Prometheus exporter for Python RQ (Redis Queue)'
__author__ = 'Pierre Mdawar'
__author_email__ = 'pierre@mdawar.dev'
__license__ = 'MIT'
| __version__ = '1.3.0'
__url__ = 'https://github.com/mdawar/rq-exporter'
__description__ = 'Prometheus exporter for Python RQ (Redis Queue)'
__author__ = 'Pierre Mdawar'
__author_email__ = 'pierre@mdawar.dev'
__license__ = 'MIT' |
class ArgErrorType(Exception):
"""Raised when provided argument is of unsupported type."""
pass
class UnreadableFileError(Exception):
"""Raised when pydicom cannot read provided file."""
pass | class Argerrortype(Exception):
"""Raised when provided argument is of unsupported type."""
pass
class Unreadablefileerror(Exception):
"""Raised when pydicom cannot read provided file."""
pass |
# All possible values that should be constant through the entire script
ERR_CODE_NON_EXISTING_FILE = 404
ERR_CODE_CREATING_XML = 406
ERR_CODE_COMMAND_LINE_ARGS = 407
ERR_CODE_NON_EXISTING_DIRECTORY = 408
ERR_CODE_NON_EXISTING_W_E = 409
WARNING_CODE_INVALID_FORMAT = 405
WARNING_CODE_NO_PAIR_FOUND = 406
WARNING_NOT_A_... | err_code_non_existing_file = 404
err_code_creating_xml = 406
err_code_command_line_args = 407
err_code_non_existing_directory = 408
err_code_non_existing_w_e = 409
warning_code_invalid_format = 405
warning_code_no_pair_found = 406
warning_not_a_tmx_file = 407
command_line_min_args = 2
command_line_command_name_position... |
'''
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
'''
... | """
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
"""
... |
# -*- coding: utf-8 -*-
class wcstr(str):
def __new__(*args, **kwargs):
return str.__new__(*args, **kwargs)
def __init__(self, *args, **kwargs):
self._update()
def _update(self):
self.bitindex = []
for i,j in zip(str(self), range(len(str(self)))):
iwidth = 1 if... | class Wcstr(str):
def __new__(*args, **kwargs):
return str.__new__(*args, **kwargs)
def __init__(self, *args, **kwargs):
self._update()
def _update(self):
self.bitindex = []
for (i, j) in zip(str(self), range(len(str(self)))):
iwidth = 1 if len(i.encode('utf8')... |
def twenty_twenty():
"""Come up with the most creative expression that evaluates to 2020,
using only numbers and the +, *, and - operators.
>>> twenty_twenty()
2020
"""
return 2019+1 | def twenty_twenty():
"""Come up with the most creative expression that evaluates to 2020,
using only numbers and the +, *, and - operators.
>>> twenty_twenty()
2020
"""
return 2019 + 1 |
T = (1,) + (2,3)
print(T)
print(type(T)) #<class 'tuple'>
T = T[0], T[1:2], T * 3 # (1, (2,), (1, 2, 3, 1, 2, 3, 1, 2, 3))
print(T)
# sorting is not available
T = ('aa', 'cc', 'dd', 'bb')
tmp = list(T)
tmp.sort()
T = tuple(tmp)
print(T)
# or sorted(T)
T = ('aa', 'cc', 'dd', 'bb')
T = sorted(T) # ['aa', 'bb', 'cc... | t = (1,) + (2, 3)
print(T)
print(type(T))
t = (T[0], T[1:2], T * 3)
print(T)
t = ('aa', 'cc', 'dd', 'bb')
tmp = list(T)
tmp.sort()
t = tuple(tmp)
print(T)
t = ('aa', 'cc', 'dd', 'bb')
t = sorted(T)
print(T)
t = (1, 2, 3, 4, 5)
l = [x + 100 for x in T]
print(L)
t = (1, 2, 2, 3, 4, 2, 5)
print(T.count(2))
print(T.index(2... |
class Solution:
def exist(self, board, word):
m, n, o = len(board), len(board and board[0]), len(word)
def explore(i, j, k, q):
for x, y in ((i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)):
if k>=o or (0<=x<m and 0<=y<n and board[x][y]==word[k] and (x,y) not in q and expl... | class Solution:
def exist(self, board, word):
(m, n, o) = (len(board), len(board and board[0]), len(word))
def explore(i, j, k, q):
for (x, y) in ((i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)):
if k >= o or (0 <= x < m and 0 <= y < n and (board[x][y] == word[k]) and (... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class RHdrcde(RPackage):
"""Computation of highest density regions in one and two
dimensions, kernel estimation o... | class Rhdrcde(RPackage):
"""Computation of highest density regions in one and two
dimensions, kernel estimation of univariate density functions
conditional on one covariate,and multimodal regression."""
cran = 'hdrcde'
version('3.4', sha256='4341c6a021da46dcae3b1ef6d580e84dcf625c2b2139f537d0c26ec908... |
f=open("input.txt")
Input=sorted(map(int, f.read().split("\n")))
Input = [0] + Input
f.close()
print(Input)
combinationCounts = [1] + [0] * (len(Input) - 1)
for i, value in enumerate(Input):
for j, adapterValue in enumerate(Input[i+1:], start=i+1):
if(adapterValue > value + 3):
break
c... | f = open('input.txt')
input = sorted(map(int, f.read().split('\n')))
input = [0] + Input
f.close()
print(Input)
combination_counts = [1] + [0] * (len(Input) - 1)
for (i, value) in enumerate(Input):
for (j, adapter_value) in enumerate(Input[i + 1:], start=i + 1):
if adapterValue > value + 3:
brea... |
# coding: utf-8
country = {
'ARG': 'Argentina',
'BOL': 'Bolivia',
'CHI': 'Chile',
'COL': 'Colombia',
'COS': 'Costa Rica',
'CUB': 'Cuba',
'EQU': 'Ecuador',
'SPA': 'Spain',
'MEX': 'Mexico',
'PER': 'Peru',
'POR': 'Portugal',
'BRA': 'Brazil',
'SOU': 'South Africa',
'... | country = {'ARG': 'Argentina', 'BOL': 'Bolivia', 'CHI': 'Chile', 'COL': 'Colombia', 'COS': 'Costa Rica', 'CUB': 'Cuba', 'EQU': 'Ecuador', 'SPA': 'Spain', 'MEX': 'Mexico', 'PER': 'Peru', 'POR': 'Portugal', 'BRA': 'Brazil', 'SOU': 'South Africa', 'URY': 'Uruguay', 'VEN': 'Venezuela', 'BUL': 'Switzerland', 'ANN': 'Italy',... |
class Solution:
def subsets(self, nums):
count = len(nums)
result = [[]]
for i in range(1, 2 ** count):
result.append([nums[j] for j in range(count) if i & (2 ** j)])
return result
| class Solution:
def subsets(self, nums):
count = len(nums)
result = [[]]
for i in range(1, 2 ** count):
result.append([nums[j] for j in range(count) if i & 2 ** j])
return result |
class Solution:
def maximumTime(self, time: str) -> str:
hour = time.split(':')[0]
minite = time.split(':')[1]
if hour[0] == '?':
if hour[1] == '?':
res_hour = '23'
elif hour[1] <= '3':
res_hour = str(2)+str(hour[1])
else:
... | class Solution:
def maximum_time(self, time: str) -> str:
hour = time.split(':')[0]
minite = time.split(':')[1]
if hour[0] == '?':
if hour[1] == '?':
res_hour = '23'
elif hour[1] <= '3':
res_hour = str(2) + str(hour[1])
els... |
texto = 'python'
for l in texto:
if l == 't':
l += 't'.upper()
print(l,end='')
else:
print(l,end='') | texto = 'python'
for l in texto:
if l == 't':
l += 't'.upper()
print(l, end='')
else:
print(l, end='') |
# ------------------------------
# 722. Remove Comments
#
# Description:
#
# Too long description. Check https://leetcode.com/problems/remove-comments/description/
#
# Example 2:
# Input:
# source = ["a/*comment", "line", "more_comment*/b"]
# Output: ["ab"]
# Explanation: The original source string is "a/*comment\n... | class Solution(object):
def remove_comments(self, source):
"""
:type source: List[str]
:rtype: List[str]
"""
in_comment_block = False
res = []
for line in source:
if not inCommentBlock:
newline = []
i = 0
wh... |
def flatten(lst_of_lst: list) -> list:
return [item for sublist in lst_of_lst for item in sublist]
def tests() -> None:
print(flatten([[1, 2], [3, 4], [5, 6]]))
print(flatten([[1, 4], [5, 4], [5, 6]]))
if __name__ == "__main__":
tests()
| def flatten(lst_of_lst: list) -> list:
return [item for sublist in lst_of_lst for item in sublist]
def tests() -> None:
print(flatten([[1, 2], [3, 4], [5, 6]]))
print(flatten([[1, 4], [5, 4], [5, 6]]))
if __name__ == '__main__':
tests() |
class OceanProviders:
"""Ocean assets class."""
def __init__(self, keeper, did_resolver, config):
self._keeper = keeper
self._did_resolver = did_resolver
self._config = config
def add(self, did, provider_address, account):
return self._keeper.did_registry.add_provider(did, ... | class Oceanproviders:
"""Ocean assets class."""
def __init__(self, keeper, did_resolver, config):
self._keeper = keeper
self._did_resolver = did_resolver
self._config = config
def add(self, did, provider_address, account):
return self._keeper.did_registry.add_provider(did, ... |
class Solution(object):
def removeOuterParentheses(self, s):
"""
:type s: str
:rtype: str
"""
new_string = ''
tmp_string = ''
left = 0
right = 0
for s_ in s:
tmp_string += s_
if s_ == '(':
left += 1
... | class Solution(object):
def remove_outer_parentheses(self, s):
"""
:type s: str
:rtype: str
"""
new_string = ''
tmp_string = ''
left = 0
right = 0
for s_ in s:
tmp_string += s_
if s_ == '(':
left += 1
... |
__version__ = "0.19.0-dev"
__libnetwork_plugin_version__ = "v0.8.0-dev"
__libcalico_version__ = "v0.14.0-dev"
__felix_version__ = "1.4.0b1-dev"
| __version__ = '0.19.0-dev'
__libnetwork_plugin_version__ = 'v0.8.0-dev'
__libcalico_version__ = 'v0.14.0-dev'
__felix_version__ = '1.4.0b1-dev' |
#
# Created on Mon Jun 14 2021
#
# The MIT License (MIT)
# Copyright (c) 2021 Vishnu Suresh
#
# 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... | class Righthandtree:
def __init__(self):
self.left = None
self.right = None
self.data = None
def insert_node(self, value):
if self.data == None:
self.data = value
elif '$' in self.data:
temp = self.data
self.data = value
s... |
class Attachment(object):
def __init__(self, name, data, length, content_type, origin):
self.name = name
self.data = data
self.length = length
self.content_type = content_type
self.origin = origin
def __str__(self):
return f"[{self.length} byte; {self.content_ty... | class Attachment(object):
def __init__(self, name, data, length, content_type, origin):
self.name = name
self.data = data
self.length = length
self.content_type = content_type
self.origin = origin
def __str__(self):
return f'[{self.length} byte; {self.content_ty... |
#!/usr/bin/env python
NAME = 'Wallarm (Wallarm Inc.)'
def is_waf(self):
if self.matchheader(('Server', r"nginx\-wallarm")):
return True
return False
| name = 'Wallarm (Wallarm Inc.)'
def is_waf(self):
if self.matchheader(('Server', 'nginx\\-wallarm')):
return True
return False |
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 124 - Ordered radicals
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
Modified sieve of Eratosthenes that records the product of prime factors. This
list is then sorted and the 10000ths entry is returned.
"""
def run():
N = ... | """
Solution to Project Euler problem 124 - Ordered radicals
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
Modified sieve of Eratosthenes that records the product of prime factors. This
list is then sorted and the 10000ths entry is returned.
"""
def run():
n = 100000
rad = {i: 1 for... |
class Point:
def __init__(self, new_x=0, new_y=0):
self.x = new_x
self.y = new_y
def set_point(self, point):
(self.x, self.y) = (point.x, point.y)
| class Point:
def __init__(self, new_x=0, new_y=0):
self.x = new_x
self.y = new_y
def set_point(self, point):
(self.x, self.y) = (point.x, point.y) |
test = { 'name': 'q7b',
'points': 1,
'suites': [ { 'cases': [ { 'code': '>>> '
"movies.head(1)['plots'][0]=='Two "
'imprisoned men bond over a '
'number of years... | test = {'name': 'q7b', 'points': 1, 'suites': [{'cases': [{'code': ">>> movies.head(1)['plots'][0]=='Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.'\nTrue", 'hidden': False, 'locked': False}, {'code': ">>> movies['plots'][23]=='An undercover cop an... |
csp = {
'default-src': [
'\'self\''
],
'script-src': [
'https://kit.fontawesome.com/4b9ba14b0f.js',
'http://localhost:5500/livereload.js',
'https://use.fontawesome.com/releases/v5.3.1/js/all.js',
'http://localhost:5000/static/js/base.js',
'http://localhost:550... | csp = {'default-src': ["'self'"], 'script-src': ['https://kit.fontawesome.com/4b9ba14b0f.js', 'http://localhost:5500/livereload.js', 'https://use.fontawesome.com/releases/v5.3.1/js/all.js', 'http://localhost:5000/static/js/base.js', 'http://localhost:5500/static/js/base.js', "'sha256-MclZcNa5vMtp/wzxRW6+KS3i8mRUf6thpmj... |
#encoding:utf-8
subreddit = 'pics'
t_channel = '@r_pics_redux'
def send_post(submission, r2t):
return r2t.send_simple(submission,
text=False,
gif=False,
img='{title}\n{short_link}',
album=False,
other=False
)
| subreddit = 'pics'
t_channel = '@r_pics_redux'
def send_post(submission, r2t):
return r2t.send_simple(submission, text=False, gif=False, img='{title}\n{short_link}', album=False, other=False) |
# Lesson3: while loop
# source: code/while.py
text = ''
while text != 'stop':
text = input('Tell me something:\n')
print('you told me:', text)
print('... and I\'m stopping')
| text = ''
while text != 'stop':
text = input('Tell me something:\n')
print('you told me:', text)
print("... and I'm stopping") |
workers = 1
worker_class = 'gevent'
bind = '0.0.0.0:5000'
pidfile = '/tmp/gunicorn-inspector.pid'
debug = True
reload = True
loglevel = 'info'
errorlog = '/tmp/gunicorn_inspector_error.log'
accesslog = '/tmp/gunicorn_inspector_access.log'
daemon = False
| workers = 1
worker_class = 'gevent'
bind = '0.0.0.0:5000'
pidfile = '/tmp/gunicorn-inspector.pid'
debug = True
reload = True
loglevel = 'info'
errorlog = '/tmp/gunicorn_inspector_error.log'
accesslog = '/tmp/gunicorn_inspector_access.log'
daemon = False |
"""
author : Ali Emre SAVAS
Link : https://www.hackerrank.com/challenges/text-wrap/problem
"""
def wrap(string, max_width):
newString = ""
for i in range(0, len(string), max_width):
newString += string[i:(i+max_width)] + "\n" # \n for new line.
# newString = newString[:(len(newString)-1)]... | """
author : Ali Emre SAVAS
Link : https://www.hackerrank.com/challenges/text-wrap/problem
"""
def wrap(string, max_width):
new_string = ''
for i in range(0, len(string), max_width):
new_string += string[i:i + max_width] + '\n'
return newString
if __name__ == '__main__':
(string, max_wi... |
# -*- coding: utf8 -*-
########################################################################################
# This file is part of exhale. Copyright (c) 2017-2019, Stephen McDowell. #
# Full BSD 3-Clause license available here: #
# ... | """
The ``tests`` package contains all of the test classes / functions.
""" |
# (User) Problem
# We know / We have: 3 number: win draw lose
# We need / We don't have: points for team
# We must: use: 3 points for win, 1 for draw, 0 for loss
# name of function must be: football_points
#
# Solution (Product)
# function with 3 inputs
def football_points(wins, draws, losses):
return wins * 3 + dr... | def football_points(wins, draws, losses):
return wins * 3 + draws |
users = [
{ "id": 0, "name": "Hero" },
{ "id": 1, "name": "Dunn" },
{ "id": 2, "name": "Sue" },
{ "id": 3, "name": "Chi" },
{ "id": 4, "name": "Thor" },
{ "id": 5, "name": "Clive" },
{ "id": 6, "name": "Hicks" },
{ "id": 7, "name": "Devin" },
{ "id": 8, "name": "Kate" },
{ "id": ... | users = [{'id': 0, 'name': 'Hero'}, {'id': 1, 'name': 'Dunn'}, {'id': 2, 'name': 'Sue'}, {'id': 3, 'name': 'Chi'}, {'id': 4, 'name': 'Thor'}, {'id': 5, 'name': 'Clive'}, {'id': 6, 'name': 'Hicks'}, {'id': 7, 'name': 'Devin'}, {'id': 8, 'name': 'Kate'}, {'id': 9, 'name': 'Klein'}]
friendships = [(0, 1), (0, 2), (1, 2), ... |
# Constants
Background = 'FF111111'
BackgroundDark = 'FF0A0A0A'
# OverlayVeryDark = GetAlpha(FF000000, 90),
# OverlayDark = GetAlpha(FF000000, 70),
# OverlayMed = GetAlpha(FF000000, 50),
# OverlayLht = GetAlpha(FF000000, 35),
Border = 'FF1F1F1F'
Empty = 'FF1F1F1F'
Card = 'FF1F1F1F'
Button = 'FF1F1F1F'
ButtonDark ... | background = 'FF111111'
background_dark = 'FF0A0A0A'
border = 'FF1F1F1F'
empty = 'FF1F1F1F'
card = 'FF1F1F1F'
button = 'FF1F1F1F'
button_dark = 'FF171717'
button_lht = 'FF555555'
button_med = 'FF2D2D2D'
indicator = 'FF999999'
text = 'FFFFFFFF'
subtitle = 'FF999999'
transparent = '00000000'
black = 'FF000000'
blue = 'FF... |
API_KEY = "PK3OA9F3DZ47286MDM81"
SECRET_KEY = "oJxGYAqcrIrhpLyXGJyIb3wsCrh2cR3xwaO662yp"
HEADERS = {
'APCA-API-KEY-ID': API_KEY,
'APCA-API-SECRET-KEY': SECRET_KEY
}
BARS_URL = 'https://data.alpaca.markets/v1/bars'
| api_key = 'PK3OA9F3DZ47286MDM81'
secret_key = 'oJxGYAqcrIrhpLyXGJyIb3wsCrh2cR3xwaO662yp'
headers = {'APCA-API-KEY-ID': API_KEY, 'APCA-API-SECRET-KEY': SECRET_KEY}
bars_url = 'https://data.alpaca.markets/v1/bars' |
n=int(input())
a=[int(i) for i in input().split()]
d=[a[0]]
for i in range(1,n):
x=a[i]
if x>d[-1]: d+=[x]
elif d[0]>=x: d[0]=x
else:
l,r=0,len(d)
while(r>l+1):
m=(l+r)//2
if(d[m]<x): l=m
else: r=m
d[r]=x
print(len(d)) ... | n = int(input())
a = [int(i) for i in input().split()]
d = [a[0]]
for i in range(1, n):
x = a[i]
if x > d[-1]:
d += [x]
elif d[0] >= x:
d[0] = x
else:
(l, r) = (0, len(d))
while r > l + 1:
m = (l + r) // 2
if d[m] < x:
l = m
... |
#!/usr/bin/env python3
# Write a program that prints out the position, frame, and letter of the DNA
# Try coding this with a single loop
# Try coding this with nested loops
dna = 'ATGGCCTTT'
"""
0 0 A
1 1 T
2 2 G
3 0 G
4 1 C
5 2 C
6 0 T
7 1 T
8 2 T
"""
#Frame is index modulo 3...
print("single loop")
for index in... | dna = 'ATGGCCTTT'
'\n0 0 A\n1 1 T\n2 2 G\n3 0 G\n4 1 C\n5 2 C\n6 0 T\n7 1 T\n8 2 T\n'
print('single loop')
for index in range(0, len(dna)):
print(index, index % 3, dna[index])
print('\nnested loops')
framesize = 3
for index in range(0, len(dna), framesize):
for frame_offset in range(0, framesize):
print... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 26 20:22:25 2020
@author: xianbingu
"""
def maximum(A):
#delete the following line and insert your code
#the built-in max() is not allowed to use here
pass
##---test---##
##You can comment out them when you write and test your code... | """
Created on Mon Oct 26 20:22:25 2020
@author: xianbingu
"""
def maximum(A):
pass
if __name__ == '__main__':
a = [8]
print(maximum(A))
a = [3, 2, 5, 7, 9, 10]
print(maximum(A)) |
# Copyright 2016 Twitter. 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 law or agree... | config_opts = dict()
verbose_flag = False
trace_execution_flag = False
def get_heron_config():
opt_list = []
for (k, v) in config_opts.items():
opt_list.append('%s=%s' % (k, v))
all_opts = '-Dheron.options=' + ','.join(opt_list).replace(' ', '%%%%')
return all_opts
def get_config(k):
globa... |
ENABLE_EXTERNAL_PATHS = False
SOURCE_DEFINITION = ['Landroid/telephony/TelephonyManager;->getDeviceId(',
'Landroid/telephony/TelephonyManager;->getSubscriberId(',
'Landroid/telephony/TelephonyManager;->getSimSerialNumber(',
'Landroid/telephony/TelephonyManager;->getLine1Number(']
#[
# 'Landroid/accounts/AccountMana... | enable_external_paths = False
source_definition = ['Landroid/telephony/TelephonyManager;->getDeviceId(', 'Landroid/telephony/TelephonyManager;->getSubscriberId(', 'Landroid/telephony/TelephonyManager;->getSimSerialNumber(', 'Landroid/telephony/TelephonyManager;->getLine1Number(']
sink_definition = ['Landroid/util/Log;-... |
weather = []
for i in range(4):
x = input().split()
| weather = []
for i in range(4):
x = input().split() |
def sol(preorder,inorder):
ret = []
def print_postorder(preorder, inorder):
n = len(preorder)
if n == 0:
return
root = preorder[0]
i = inorder.index(root)
print_postorder(preorder[1 : i + 1], inorder[:i])
print_postorder(preorder[i + 1 :], inorder[i ... | def sol(preorder, inorder):
ret = []
def print_postorder(preorder, inorder):
n = len(preorder)
if n == 0:
return
root = preorder[0]
i = inorder.index(root)
print_postorder(preorder[1:i + 1], inorder[:i])
print_postorder(preorder[i + 1:], inorder[i + 1... |
__version__ = '0.2.0'
__pdoc__ = {
'__version__': "The version of the installed nflfan module.",
}
| __version__ = '0.2.0'
__pdoc__ = {'__version__': 'The version of the installed nflfan module.'} |
{
"targets": [
{
"target_name": "math",
"sources": [ "math.cc" ],
"libraries": [
"<(module_root_dir)/libmath.a"
]
}
]
} | {'targets': [{'target_name': 'math', 'sources': ['math.cc'], 'libraries': ['<(module_root_dir)/libmath.a']}]} |
{
'target_defaults': {
'default_configuration': 'Release'
},
"targets": [
{
'configurations': {
'Debug': {
'cflags': ['-g3', '-O0'],
'msvs_settings': {
'VCCLCompilerTool': {
'BasicRuntimeChecks': 3, # /RTC1
'ExceptionHand... | {'target_defaults': {'default_configuration': 'Release'}, 'targets': [{'configurations': {'Debug': {'cflags': ['-g3', '-O0'], 'msvs_settings': {'VCCLCompilerTool': {'BasicRuntimeChecks': 3, 'ExceptionHandling': 1, 'Optimization': '0', 'WarningLevel': 4}, 'VCLinkerTool': {'GenerateDebugInformation': 'true', 'LinkIncreme... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,md,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Jonathan Date-Chong
# *... | def question_1(answer):
answers = {'A': 'Monday morning', 'B': 'Sunday night', 'C': 'Monday evening', 'D': "I don't know"}
try:
return answers[answer]
except:
return 'Not a valid answer'
answer_question_1 = lambda : question_1('C')
def question_2(answer):
answers = {'A': 'No', 'B': 'May... |
for i in range(1, 10+1):
if i%3 == 0:
print('hello')
elif i%5 == 0:
print('world')
else:
print(i)
| for i in range(1, 10 + 1):
if i % 3 == 0:
print('hello')
elif i % 5 == 0:
print('world')
else:
print(i) |
def place(arr, mask, vals):
# TODO(beam2d): Implement it
raise NotImplementedError
def put(a, ind, v, mode='raise'):
# TODO(beam2d): Implement it
raise NotImplementedError
def putmask(a, mask, values):
# TODO(beam2d): Implement it
raise NotImplementedError
def fill_diagonal(a, val, wrap=Fa... | def place(arr, mask, vals):
raise NotImplementedError
def put(a, ind, v, mode='raise'):
raise NotImplementedError
def putmask(a, mask, values):
raise NotImplementedError
def fill_diagonal(a, val, wrap=False):
raise NotImplementedError |
# maps biome IDs to supported biomes
biome_map = {
"Plains": [1, 129],
"Forest": [4, 18, 132],
"Birch Forest": [27, 28, 155, 156],
"Dark Forest": [29, 157],
"Swamp": [6, 134],
"Jungle": [21, 22, 23, 149, 151],
"River Beach": [7, 11, 16, 25],
"Taiga": [5, 19, 133, 30, 31, 158, 32, 33, 160... | biome_map = {'Plains': [1, 129], 'Forest': [4, 18, 132], 'Birch Forest': [27, 28, 155, 156], 'Dark Forest': [29, 157], 'Swamp': [6, 134], 'Jungle': [21, 22, 23, 149, 151], 'River Beach': [7, 11, 16, 25], 'Taiga': [5, 19, 133, 30, 31, 158, 32, 33, 160, 161], 'Ice': [12, 140, 26], 'Mountains': [3, 13, 34, 131, 162, 20], ... |
def pprint(obj):
return repr(obj)
def to_hex_str(data):
return ''.join("{0:x}".format(b) for b in data)
| def pprint(obj):
return repr(obj)
def to_hex_str(data):
return ''.join(('{0:x}'.format(b) for b in data)) |
# -*- coding: utf-8 -*-
class PluginException(Exception):
pass
class PluginTypeNotFound(PluginException):
pass
| class Pluginexception(Exception):
pass
class Plugintypenotfound(PluginException):
pass |
class gr():
def __init__(self):
age = 28
def stop(self):
return 1+1
if __name__ == "__main__":
print("hello")
pass | class Gr:
def __init__(self):
age = 28
def stop(self):
return 1 + 1
if __name__ == '__main__':
print('hello')
pass |
# Kata url: https://www.codewars.com/kata/574b1916a3ebd6e4fa0012e7.
def is_opposite(s1: str, s2: str) -> bool:
return len(s1) and s1 == s2.swapcase()
| def is_opposite(s1: str, s2: str) -> bool:
return len(s1) and s1 == s2.swapcase() |
def sectrails(domain,requests,api):
print("[+] Consultando securitytrails")
url = "https://api.securitytrails.com/v1/domain/"+domain+"/subdomains"
querystring = {"children_only":"false","include_inactive":"true"}
headers = {"Accept": "application/json","APIKEY": api}
subs = []
# Insira sua chav... | def sectrails(domain, requests, api):
print('[+] Consultando securitytrails')
url = 'https://api.securitytrails.com/v1/domain/' + domain + '/subdomains'
querystring = {'children_only': 'false', 'include_inactive': 'true'}
headers = {'Accept': 'application/json', 'APIKEY': api}
subs = []
try:
... |
"""
mimetypes
~~~~~~~~~
Define some constants for different mimetypes
"""
CSV_MIMETYPE = 'text/csv'
FILEUPLOAD_MIMETYPE = 'multipart/form-data'
FORMURL_MIMETYPE = 'application/x-www-form-urlencoded'
JSON_MIMETYPE = 'application/json'
JSONAPI_MIMETYPE = 'application/vnd.api+json'
| """
mimetypes
~~~~~~~~~
Define some constants for different mimetypes
"""
csv_mimetype = 'text/csv'
fileupload_mimetype = 'multipart/form-data'
formurl_mimetype = 'application/x-www-form-urlencoded'
json_mimetype = 'application/json'
jsonapi_mimetype = 'application/vnd.api+json' |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.reminder
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Reminder(object):
"""Implementation of the 'Reminder' enum.
TODO: type enum description here.
Attributes:
OFF: T... | """
idfy_rest_client.models.reminder
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Reminder(object):
"""Implementation of the 'Reminder' enum.
TODO: type enum description here.
Attributes:
OFF: TODO: type description here.
SENDS... |
class Node:
def __init__(self, data):
self.data = data
self.right_child = None
self.left_child = None
| class Node:
def __init__(self, data):
self.data = data
self.right_child = None
self.left_child = None |
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess any no. from 1-10: "))
guess_count+=1
if guess == secret_number:
print("You won")
break
else:
print("Better luck next time")
| secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('Guess any no. from 1-10: '))
guess_count += 1
if guess == secret_number:
print('You won')
break
else:
print('Better luck next time') |
# Linear Search Implementation
def linear_search(arr, search):
# Iterate over the array
for _, ele in enumerate(arr):
# Check for search element
if ele == search:
return True
return False
if __name__ == "__main__":
# Read input array from stdin
arr = list(map(int, input().strip().split()))
# Read sear... | def linear_search(arr, search):
for (_, ele) in enumerate(arr):
if ele == search:
return True
return False
if __name__ == '__main__':
arr = list(map(int, input().strip().split()))
search = list(map(int, input().strip().split()))
for s in search:
print(f'Searching for {s} ... |
#!/usr/bin/env python
"""
Copyright 2014-2020 by Taxamo
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 applic... | """
Copyright 2014-2020 by Taxamo
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 ... |
BASE_URL = "https://www.zhixue.com"
class Url:
SERVICE_URL = f"{BASE_URL}:443/ssoservice.jsp"
SSO_URL = f"https://sso.zhixue.com/sso_alpha/login?service={SERVICE_URL}"
TEST_PASSWORD_URL = f"{BASE_URL}/weakPwdLogin/?from=web_login"
TEST_URL = f"{BASE_URL}/container/container/teacher/teacherAccountNew"
... | base_url = 'https://www.zhixue.com'
class Url:
service_url = f'{BASE_URL}:443/ssoservice.jsp'
sso_url = f'https://sso.zhixue.com/sso_alpha/login?service={SERVICE_URL}'
test_password_url = f'{BASE_URL}/weakPwdLogin/?from=web_login'
test_url = f'{BASE_URL}/container/container/teacher/teacherAccountNew'
... |
class Solution:
def isRectangleOverlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
# [x1, y1, x2, y2]
return not (rec2[2] <= rec1[0] or rec1[2] <= rec2[0] or rec2[3] <= rec1[1] or rec1[3] <= rec2[1]) | class Solution:
def is_rectangle_overlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
return not (rec2[2] <= rec1[0] or rec1[2] <= rec2[0] or rec2[3] <= rec1[1] or (rec1[3] <= rec2[1])) |
#!/usr/bin/env python2.7
# Copyright (c) 2014 Franco Fichtner <franco@packetwerk.com>
# Copyright (c) 2014 Tobias Boertitz <tobias@packetwerk.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and th... | countries = []
with open('contrib/tzdata/iso3166.tab', 'r') as lines:
for line in lines:
country = line.strip().split('\t')
if country[0][0] == '#' or len(country) != 2:
continue
country[0] = country[0].upper()
countries.append(country)
if len(countries) == 0:
exit(0)... |
#
# PySNMP MIB module HPN-ICF-LI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-LI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:27:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_size_constraint, value_range_constraint) ... |
def inorder(root):
res = []
if not root:
return res
stack = []
while root and stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
res.add(root.val)
root = root.right
return res
| def inorder(root):
res = []
if not root:
return res
stack = []
while root and stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
res.add(root.val)
root = root.right
return res |
class Solution:
def partition(self, s: str) -> list[list[str]]:
# TODO: add explanation, make clearer
if len(s) == 0:
return [[]]
result = []
def backtrack(current: list[str], prefix: str) -> None:
if len(prefix) == 0:
result.append(current)
... | class Solution:
def partition(self, s: str) -> list[list[str]]:
if len(s) == 0:
return [[]]
result = []
def backtrack(current: list[str], prefix: str) -> None:
if len(prefix) == 0:
result.append(current)
return
for index i... |
def geobox2rect(geobox):
x, y, w, h = geobox
return x - int(w / 2), y - int(h / 2), w, h
def geobox2ptrect(geobox):
x, y, w, h = geobox2rect(geobox)
return x, y, x + w, y + h
def rect2geobox(x, y, w, h):
return x + int(w / 2), y + int(h / 2), w, h
def ptrect2geobox(x1, y1, x2, y2... | def geobox2rect(geobox):
(x, y, w, h) = geobox
return (x - int(w / 2), y - int(h / 2), w, h)
def geobox2ptrect(geobox):
(x, y, w, h) = geobox2rect(geobox)
return (x, y, x + w, y + h)
def rect2geobox(x, y, w, h):
return (x + int(w / 2), y + int(h / 2), w, h)
def ptrect2geobox(x1, y1, x2, y2):
... |
def pythag_triple(n):
for a in range(1, n // 2):
b = (n**2/2 - n*a)/(n - a)
if b.is_integer():
return int(a*b*(n - a - b))
return None
print(pythag_triple(1000))
# Copyright Junipyr. All rights reserved.
# https://github.com/Junipyr | def pythag_triple(n):
for a in range(1, n // 2):
b = (n ** 2 / 2 - n * a) / (n - a)
if b.is_integer():
return int(a * b * (n - a - b))
return None
print(pythag_triple(1000)) |
mylitta = [1, 2, 3, 4, 5]
l2 = list([1, 2, 3, 4, 5])
l3 = list("casa de papel")
l4 = "alberto torres".split()
l5 = "alberto torres,carolina torres,mauricio torres".split(",")
cadena = " - ".join(l5)
mylitta = mylitta + [12, 13]
mylitta += [15, 16]
mylitta.append(9)
mylitta.extend([10, 11])
print(mylitta)
print(... | mylitta = [1, 2, 3, 4, 5]
l2 = list([1, 2, 3, 4, 5])
l3 = list('casa de papel')
l4 = 'alberto torres'.split()
l5 = 'alberto torres,carolina torres,mauricio torres'.split(',')
cadena = ' - '.join(l5)
mylitta = mylitta + [12, 13]
mylitta += [15, 16]
mylitta.append(9)
mylitta.extend([10, 11])
print(mylitta)
print(l2)
prin... |
# open the fil2.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt", "r")
# stores all the data of the file into the variable content
content = fileptr.readlines()
# prints the content of the file
print(content)
# closes the opened file
fileptr.close() | fileptr = open('file2.txt', 'r')
content = fileptr.readlines()
print(content)
fileptr.close() |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class TypeSqlProtectionSourceEnum(object):
"""Implementation of the 'Type_SqlProtectionSource' enum.
Specifies the type of the managed Object in a SQL Protection Source.
Examples of SQL Objects include 'kInstance' and 'kDatabase'.
'kInstance' ind... | class Typesqlprotectionsourceenum(object):
"""Implementation of the 'Type_SqlProtectionSource' enum.
Specifies the type of the managed Object in a SQL Protection Source.
Examples of SQL Objects include 'kInstance' and 'kDatabase'.
'kInstance' indicates that SQL server instance is being protected.
'... |
# Advent of Code 2017
#
# From https://adventofcode.com/2017/day/4
#
passwords = [row.strip().split() for row in open('../inputs/Advent2017_04.txt', 'r')]
print(sum(len(row) == len(set(row)) for row in passwords))
print(sum(len(row) == len(set("".join(sorted(x)) for x in row)) for row in passwords))
| passwords = [row.strip().split() for row in open('../inputs/Advent2017_04.txt', 'r')]
print(sum((len(row) == len(set(row)) for row in passwords)))
print(sum((len(row) == len(set((''.join(sorted(x)) for x in row))) for row in passwords))) |
'''
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an integer... | """
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an integer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.