content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
import pytest
import torch
import pytorch_lightning as pl
from torchphysics.solver import PINNModule
from torchphysics.setting import Setting
from torchphysics.models.fcn import SimpleFCN
from torchphysics.utils.plot import Plotter
from torchphysics.problem.condition import DirichletCondition
from torchphysics.pro... | """
import pytest
import torch
import pytorch_lightning as pl
from torchphysics.solver import PINNModule
from torchphysics.setting import Setting
from torchphysics.models.fcn import SimpleFCN
from torchphysics.utils.plot import Plotter
from torchphysics.problem.condition import DirichletCondition
from torchphysics.pro... |
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
t = -1
for i in range(len(tokens)):
if tokens[i] == '+':
tokens[t - 1] += tokens[t]
t -= 1
elif tokens[i] == '-':
tokens[t - 1] -= tokens[t]
t... | class Solution:
def eval_rpn(self, tokens: List[str]) -> int:
t = -1
for i in range(len(tokens)):
if tokens[i] == '+':
tokens[t - 1] += tokens[t]
t -= 1
elif tokens[i] == '-':
tokens[t - 1] -= tokens[t]
t -= 1
... |
def rotate(A, B, C):
return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0])
def jarvismarch(A):
points_count = len(A)
processing_indexes = range(points_count)
# start point
for i in range(1, points_count):
if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]:
... | def rotate(A, B, C):
return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0])
def jarvismarch(A):
points_count = len(A)
processing_indexes = range(points_count)
for i in range(1, points_count):
if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]:
(processing_ind... |
class NodoAST:
def __init__(self, contenido):
self._contenido = contenido
self._hijos = []
def getContenido(self):
return self._contenido
def getHijos(self):
return self._hijos
def setHijo(self, hijo):
self._hijos.append(hijo) | class Nodoast:
def __init__(self, contenido):
self._contenido = contenido
self._hijos = []
def get_contenido(self):
return self._contenido
def get_hijos(self):
return self._hijos
def set_hijo(self, hijo):
self._hijos.append(hijo) |
#This program displays a date in the form
#(Month day, Year like March 12, 2014
#ALGORITHM in pseudocode
#1. get a date string in the form mm/dd/yyyy from the user
#2. use the split method to remove the seperator('/')
# and assign the results to a variable.
#3. determine the month the user entered
# if month is 0... | def main():
date_string = input('Enter a date in the form "mm/dd/yyyy": ')
date_list = get_date_list(date_string)
def get_date_list(date_string):
date_list = date_string.split('/')
mm = date_list[0]
if mm == '01':
mm = 'January'
elif mm == '02':
mm = 'February'
elif mm == '0... |
# coding=utf-8
"""
Package used to unify the different constant values used in entire project
"""
class Consts(object):
"""
Class used to unify the different constant values used in entire project
"""
# BPMN 2.0 element attribute names
id = "id"
name = "name"
# Flow nodes cannot use "name" ... | """
Package used to unify the different constant values used in entire project
"""
class Consts(object):
"""
Class used to unify the different constant values used in entire project
"""
id = 'id'
name = 'name'
node_name = 'node_name'
gateway_direction = 'gatewayDirection'
default = 'def... |
"""
All exceptions that can be raised during handling of a weatherapi request.
"""
# Functions that make a request to weatherapi.com have the possibility
# of raising one of these errors depending on the response.
# We use these custom error classes to make the error code more readable
# and easier to handle.
__all__... | """
All exceptions that can be raised during handling of a weatherapi request.
"""
__all__ = ['WeatherApiError', 'NoApiKey', 'InvalidApiKey', 'QuotaExceeded', 'ApiKeyDisabled', 'QueryNotProvided', 'InvalidRequestUrl', 'InvalidLocation', 'InternalError']
class Weatherapierror(Exception):
"""
Raised when an unkn... |
n1 = float(input('Valor do produto (R$): '))
n2 = float(input('Desconto em porcentagem (%): '))
d = n2/100
d1 = n1*d
nv = n1-d1
print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2,nv))
| n1 = float(input('Valor do produto (R$): '))
n2 = float(input('Desconto em porcentagem (%): '))
d = n2 / 100
d1 = n1 * d
nv = n1 - d1
print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2, nv)) |
mem_key_cache = 'cache'
mem_key_metadata = 'meta'
mem_key_sponsor = 'sponsor'
mem_key_total_open_source_spaces = 'oss'
mem_key_creeps_by_role = 'roles_alive'
mem_key_work_parts_by_role = 'roles_work'
mem_key_carry_parts_by_role = 'roles_carry'
mem_key_creeps_by_role_and_replacement_time = 'rt_map'
mem_key_prepping_defe... | mem_key_cache = 'cache'
mem_key_metadata = 'meta'
mem_key_sponsor = 'sponsor'
mem_key_total_open_source_spaces = 'oss'
mem_key_creeps_by_role = 'roles_alive'
mem_key_work_parts_by_role = 'roles_work'
mem_key_carry_parts_by_role = 'roles_carry'
mem_key_creeps_by_role_and_replacement_time = 'rt_map'
mem_key_prepping_defe... |
# -*- coding: utf-8 -*-
# Scrapy settings for watches project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topic... | bot_name = 'watches'
spider_modules = ['watches.spiders']
newspider_module = 'watches.spiders'
redirect_enabled = False
retry_times = 10
retry_http_codes = [500, 503, 504, 400, 403, 404, 408]
robotstxt_obey = False
download_delay = 0.2
cookies_enabled = False |
#!/usr/bin/env python
#######################################
# Installation module for eyewitness
#######################################
# AUTHOR OF MODULE NAME
AUTHOR="Kirk Hayes (l0gan)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update EyeWitness."
# INSTALL TYPE GIT, SVN, FILE DOWNLOAD
#... | author = 'Kirk Hayes (l0gan)'
description = 'This module will install/update EyeWitness.'
install_type = 'GIT'
repository_location = 'https://github.com/FortyNorthSecurity/EyeWitness'
install_location = 'eyewitness'
debian = 'git,python-setuptools,libffi-dev,libssl-dev'
after_commands = 'cd {INSTALL_LOCATION}Python/set... |
users = {'email1': 'password1'}
links = [ # fake array of posts
{
'author': 'users',
'date' : "04-08-2017",
'description': 'cool information site',
'link': 'https://www.wikipedia.org',
'tags': None
},
{
'author': 'user',
'date' : "06-08-2017",
... | users = {'email1': 'password1'}
links = [{'author': 'users', 'date': '04-08-2017', 'description': 'cool information site', 'link': 'https://www.wikipedia.org', 'tags': None}, {'author': 'user', 'date': '06-08-2017', 'description': "worst site I've ever used", 'link': 'www.facebook.org', 'tags': None}, {'author': 'user'... |
# OAuth app keys
DROPBOX_BUSINESS_FILEACCESS_KEY = None
DROPBOX_BUSINESS_FILEACCESS_SECRET = None
DROPBOX_BUSINESS_MANAGEMENT_KEY = None
DROPBOX_BUSINESS_MANAGEMENT_SECRET = None
DROPBOX_BUSINESS_AUTH_CSRF_TOKEN = 'dropboxbusiness-auth-csrf-token'
TEAM_FOLDER_NAME_FORMAT = '{title}_GRDM_{guid}' # available: {title} ... | dropbox_business_fileaccess_key = None
dropbox_business_fileaccess_secret = None
dropbox_business_management_key = None
dropbox_business_management_secret = None
dropbox_business_auth_csrf_token = 'dropboxbusiness-auth-csrf-token'
team_folder_name_format = '{title}_GRDM_{guid}'
group_name_format = 'GRDM_{guid}'
admin_g... |
colors = {
'default': (0, 'WHITE', 'BLACK', 'NORMAL'),
'title': (1, 'YELLOW', 'BLUE', 'BOLD'),
'status': (2, 'YELLOW', 'BLUE', 'BOLD'),
'error': (3, 'RED', 'BLACK', 'BOLD'),
'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD'),
}
| colors = {'default': (0, 'WHITE', 'BLACK', 'NORMAL'), 'title': (1, 'YELLOW', 'BLUE', 'BOLD'), 'status': (2, 'YELLOW', 'BLUE', 'BOLD'), 'error': (3, 'RED', 'BLACK', 'BOLD'), 'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD')} |
#-----------------problem parameters-----------------------
depot = []
capacity = 120
time_dist_factor = 10 # time per job converted to distance
num_salesmen = 5
# ---------------------------------------------------------
population = 50
nodes = []
node_num = 0
gnd_truth_tsp = []
gnd_truth_dist_list... | depot = []
capacity = 120
time_dist_factor = 10
num_salesmen = 5
population = 50
nodes = []
node_num = 0
gnd_truth_tsp = []
gnd_truth_dist_list = []
gnd_truth_dist_from_depot = []
def print_error(msg):
print('ERROR: ' + msg)
exit() |
class MeuObjeto:
def __init__(self, id, nome, sobrenome):
self.id = id
self.nome = nome
self.sobrenome = sobrenome
| class Meuobjeto:
def __init__(self, id, nome, sobrenome):
self.id = id
self.nome = nome
self.sobrenome = sobrenome |
def retry_until(condition):
def retry(request):
try:
return request()
except Exception as exception:
if condition(exception):
return retry(request)
else:
raise exception
return retry
def retry(max_retries):
retries = [0]
... | def retry_until(condition):
def retry(request):
try:
return request()
except Exception as exception:
if condition(exception):
return retry(request)
else:
raise exception
return retry
def retry(max_retries):
retries = [0]
... |
def list__data_pt():
length = input("\nEnter the Number of Data Point(s) :\t")
try:
if not length.isnumeric() or int(length) <= 0:
raise Exception
except Exception:
print()
print(length)
print("ERROR !!!")
print("Enter a Natural Number Greater t... | def list__data_pt():
length = input('\nEnter the Number of Data Point(s) :\t')
try:
if not length.isnumeric() or int(length) <= 0:
raise Exception
except Exception:
print()
print(length)
print('ERROR !!!')
print('Enter a Natural Number Greater than 0 !!!')... |
fig, ax = plt.subplots()
ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue')
ax.set_xlabel('Zr [ppm]')
ax.set_ylabel('Likelihood of occurrence')
| (fig, ax) = plt.subplots()
ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue')
ax.set_xlabel('Zr [ppm]')
ax.set_ylabel('Likelihood of occurrence') |
# Found in https://leetcode.com/problems/two-sum/
#
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
haveSeenIt = {}
for idx, val... | class Solution(object):
def two_sum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
have_seen_it = {}
for (idx, val) in enumerate(nums):
if target - val in haveSeenIt:
return [haveSeenIt[targe... |
heights = [161, 164, 156, 144, 158, 170, 163, 163, 157]
can_ride_coaster = [can for can in heights if can > 161]
print(can_ride_coaster)
| heights = [161, 164, 156, 144, 158, 170, 163, 163, 157]
can_ride_coaster = [can for can in heights if can > 161]
print(can_ride_coaster) |
"""Common node-related functions
"""
def set_text_on_node(graph, current_node, errorstring, highlight_color, resize):
"""Sets an error string on the current_node in graph.
Also changes the color to red to highlight it.
The parameter current_node should come from the graph that was parsed from file,
... | """Common node-related functions
"""
def set_text_on_node(graph, current_node, errorstring, highlight_color, resize):
"""Sets an error string on the current_node in graph.
Also changes the color to red to highlight it.
The parameter current_node should come from the graph that was parsed from file,
... |
i = 1
while (i<=10):
print(i, end=" ")
i += 1
print()
| i = 1
while i <= 10:
print(i, end=' ')
i += 1
print() |
def my_function(*args, **kwargs):
for arg in args:
print('arg:', arg)
for key in kwargs.keys():
print('key:', key, 'has value: ', kwargs[key])
my_function('John', 'Denise', daughter='Phoebe', son='Adam')
print('-' * 50)
my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='Jame... | def my_function(*args, **kwargs):
for arg in args:
print('arg:', arg)
for key in kwargs.keys():
print('key:', key, 'has value: ', kwargs[key])
my_function('John', 'Denise', daughter='Phoebe', son='Adam')
print('-' * 50)
my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='James'... |
class A:
def __init__(self):
print("A")
super().__init__()
class B1(A):
def __init__(self):
print("B1")
super().__init__()
class B2(A):
def __init__(self):
print("B2")
super().__init__()
class C(B1, A):
def __init__(self):
print("C")
sup... | class A:
def __init__(self):
print('A')
super().__init__()
class B1(A):
def __init__(self):
print('B1')
super().__init__()
class B2(A):
def __init__(self):
print('B2')
super().__init__()
class C(B1, A):
def __init__(self):
print('C')
... |
props.bf_Shank_Dia = 10.0
#props.bf_Pitch = 1.5 # Coarse
props.bf_Pitch = 1.25 # Fine
props.bf_Crest_Percent = 10
props.bf_Root_Percent = 10
props.bf_Major_Dia = 10.0
props.bf_Minor_Dia = props.bf_Major_Dia - (1.082532 * props.bf_Pitch)
props.bf_Hex_Head_Flat_Distance = 17.0
props.bf_Hex_Head_Height = 6.4
props.bf_Cap... | props.bf_Shank_Dia = 10.0
props.bf_Pitch = 1.25
props.bf_Crest_Percent = 10
props.bf_Root_Percent = 10
props.bf_Major_Dia = 10.0
props.bf_Minor_Dia = props.bf_Major_Dia - 1.082532 * props.bf_Pitch
props.bf_Hex_Head_Flat_Distance = 17.0
props.bf_Hex_Head_Height = 6.4
props.bf_Cap_Head_Dia = 16.0
props.bf_Cap_Head_Height... |
def dividedtimes(x):
if not isinstance(x, int):
raise TypeError('x must be integer.')
elif x <= 2:
raise ValueError('x must be greater than 2.')
counter = 0
while x >= 2:
x = x / 2
counter += 1
return counter
| def dividedtimes(x):
if not isinstance(x, int):
raise type_error('x must be integer.')
elif x <= 2:
raise value_error('x must be greater than 2.')
counter = 0
while x >= 2:
x = x / 2
counter += 1
return counter |
def bubbleSort(list):
for i in range(0,len(list)-1):
for j in range(0,len(list)-i-1):
if list[j] > list[j+1]:
print("\n%d > %d"%(list[j],list[j+1]))
(list[j], list[j+1]) = (list[j+1], list[j])
print("\nNext Pass\n")
print("\nThe elements are now sorted in ascending order:\n")
for i i... | def bubble_sort(list):
for i in range(0, len(list) - 1):
for j in range(0, len(list) - i - 1):
if list[j] > list[j + 1]:
print('\n%d > %d' % (list[j], list[j + 1]))
(list[j], list[j + 1]) = (list[j + 1], list[j])
print('\nNext Pass\n')
print('\nThe ele... |
# pylint: disable=missing-docstring,redefined-builtin,unsubscriptable-object
# pylint: disable=invalid-name,too-few-public-methods,attribute-defined-outside-init
class Repository:
def _transfer(self, bytes=-1):
self._bytesTransfered = 0
bufff = True
while bufff and (bytes < 0 or self._bytesT... | class Repository:
def _transfer(self, bytes=-1):
self._bytesTransfered = 0
bufff = True
while bufff and (bytes < 0 or self._bytesTransfered < bytes):
bufff = bufff[:bytes - self._bytesTransfered]
self._bytesTransfered += len(bufff) |
# Copyright 2016 Check Point Software Technologies LTD
#
# 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 app... | uri = 'https://te-api.checkpoint.com/tecloud/api/v1/file/'
token_uri = 'https://cloudinfra-gw.portal.checkpoint.com/auth/external'
port = '18194'
remote_dir = 'tecloud/api/v1/file'
query = 'query'
upload = 'upload'
download = 'download'
query_selector = '%s%s' % (URI, QUERY)
upload_selector = '%s%s' % (URI, UPLOAD)
dow... |
g=[]
for a in range (1000):
if a%3==0 or a%5==0:
g.append(a)
print(sum(g))
| g = []
for a in range(1000):
if a % 3 == 0 or a % 5 == 0:
g.append(a)
print(sum(g)) |
#Strinping Names:
Person_name = " Chandler Bing "
print("Person Name with tab space :\t"+Person_name)
print("Person Name in new line :\n"+Person_name)
print("Person Name with space removed from left side :"+Person_name.lstrip())
print("Person Name with space removed from right side :"+Person_name.rstrip())
print("Pe... | person_name = ' Chandler Bing '
print('Person Name with tab space :\t' + Person_name)
print('Person Name in new line :\n' + Person_name)
print('Person Name with space removed from left side :' + Person_name.lstrip())
print('Person Name with space removed from right side :' + Person_name.rstrip())
print('Person Name wit... |
def divisibleSumPairs(n, k, ar):
count = 0
for i in range(len(ar)-1):
for j in range(i+1, len(ar)):
if (ar[i]+ar[j])%k == 0:
count += 1
return count
| def divisible_sum_pairs(n, k, ar):
count = 0
for i in range(len(ar) - 1):
for j in range(i + 1, len(ar)):
if (ar[i] + ar[j]) % k == 0:
count += 1
return count |
# Python3 Binary Tree to Doubly Linked List
# 10
# / \
# 12 15 ---> head ---> 25<->12<->30<->10<->36<->15
# / \ /
# 25 30 36
#
def tree2DLL(root, head):
if not root:
return
prev = None
tree2DLL(root.left)
if not prev:
head = prev
else:
root.left = prev
pr... | def tree2_dll(root, head):
if not root:
return
prev = None
tree2_dll(root.left)
if not prev:
head = prev
else:
root.left = prev
prev.right = root
prev = root |
class Synapse:
def __init__(self, label, input, weight, next_neurons):
self.label = label
self.input = input
self.weight = weight
self.next_neurons = next_neurons
| class Synapse:
def __init__(self, label, input, weight, next_neurons):
self.label = label
self.input = input
self.weight = weight
self.next_neurons = next_neurons |
'''
Created on 2020-09-10
@author: wf
'''
class Labels(object):
'''
NLTK labels
'''
default=['GPE','PERSON','ORGANIZATION']
geo=['GPE'] | """
Created on 2020-09-10
@author: wf
"""
class Labels(object):
"""
NLTK labels
"""
default = ['GPE', 'PERSON', 'ORGANIZATION']
geo = ['GPE'] |
'''
Substring Concatenation
Asked in: Facebook
https://www.interviewbit.com/problems/substring-concatenation/
You are given a string, S, and a list of words, L, that are all of the same length.
Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any inter... | """
Substring Concatenation
Asked in: Facebook
https://www.interviewbit.com/problems/substring-concatenation/
You are given a string, S, and a list of words, L, that are all of the same length.
Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any inter... |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
return [dic[nums[i]], i]
dic[target - nums[... | class Solution(object):
def two_sum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
return [dic[nums[i]], i]
dic[target - num... |
def trunk_1(arr_1, size_1):
result_1 = []
while arr:
pop_data = [arr_1.pop(0) for _ in range(size_1)]
result_1.append(pop_data)
return result_1
def trunk_2(arr_2, size_2):
arrs = []
while len(arr_2) > size_2:
pice = arr_2[:size_2]
arrs.append(pice)
arr_2 = ... | def trunk_1(arr_1, size_1):
result_1 = []
while arr:
pop_data = [arr_1.pop(0) for _ in range(size_1)]
result_1.append(pop_data)
return result_1
def trunk_2(arr_2, size_2):
arrs = []
while len(arr_2) > size_2:
pice = arr_2[:size_2]
arrs.append(pice)
arr_2 = ar... |
#!/usr/bin/env python
if __name__ == "__main__":
print("Hello world from copied executable")
| if __name__ == '__main__':
print('Hello world from copied executable') |
data = open("day3.txt", "r").read().splitlines()
openSquare = data[0][0]
tree = data[0][6]
def howManyTrees(right, down):
position = right
iterator = down
trees = 0
openSquares = 0
for rowIterator in range(0, int((len(data))/down) - 1):
row = data[iterator]
res_row = row * 100
obstacle = res_... | data = open('day3.txt', 'r').read().splitlines()
open_square = data[0][0]
tree = data[0][6]
def how_many_trees(right, down):
position = right
iterator = down
trees = 0
open_squares = 0
for row_iterator in range(0, int(len(data) / down) - 1):
row = data[iterator]
res_row = row * 100
... |
n = int(input())
d = [[0,0,0] for i in range(n + 1)]
for i in range(1, n + 1):
(r, g, b) = [int(i) for i in input().split()]
d[i][0] = r + min(d[i - 1][1], d[i - 1][2])
d[i][1] = g + min(d[i - 1][0], d[i - 1][2])
d[i][2] = b + min(d[i - 1][0], d[i - 1][1])
print(min(d[n])) | n = int(input())
d = [[0, 0, 0] for i in range(n + 1)]
for i in range(1, n + 1):
(r, g, b) = [int(i) for i in input().split()]
d[i][0] = r + min(d[i - 1][1], d[i - 1][2])
d[i][1] = g + min(d[i - 1][0], d[i - 1][2])
d[i][2] = b + min(d[i - 1][0], d[i - 1][1])
print(min(d[n])) |
x = [1,2,3]
def weird(num, default_ls=None):
default_ls = default_ls or []
default_ls.append(num)
print(default_ls)
return default_ls
weird(1)
weird(2)
weird(3)
ls = list()
ls = weird(99, ls) # [99]
print(ls)
weird(1000001, ls) # [99, 100001] [10000001]
"""
MacBook-Pro:random_python_stuff demous... | x = [1, 2, 3]
def weird(num, default_ls=None):
default_ls = default_ls or []
default_ls.append(num)
print(default_ls)
return default_ls
weird(1)
weird(2)
weird(3)
ls = list()
ls = weird(99, ls)
print(ls)
weird(1000001, ls)
'\n\nMacBook-Pro:random_python_stuff demouser$ python data_types.py\n[1]\n[1, 2]... |
# Test passwords are randomly hashed
def test_passwords_hashed_randomly(test_app, test_database, add_user):
user_one = add_user(
"test_user_one", "test_user_one@mail.com", "test_password"
)
user_two = add_user(
"test_user_two", "test_user_two@mail.com", "test_password"
)
assert user... | def test_passwords_hashed_randomly(test_app, test_database, add_user):
user_one = add_user('test_user_one', 'test_user_one@mail.com', 'test_password')
user_two = add_user('test_user_two', 'test_user_two@mail.com', 'test_password')
assert user_one.password != user_two.password
assert user_one.password !=... |
def karatsuba(x: int, y: int) -> int:
"""Multiply two numbers using the Karatsuba algorithm
Args:
x (int): the first integer to be multiplied
y (int): the second integer to be multiplied
Returns:
int: the result of the multiplication
"""
# Break the recursion written below... | def karatsuba(x: int, y: int) -> int:
"""Multiply two numbers using the Karatsuba algorithm
Args:
x (int): the first integer to be multiplied
y (int): the second integer to be multiplied
Returns:
int: the result of the multiplication
"""
if x < 10 or y < 10:
return ... |
# Defination for mathematical operation
def math(token_ip_stream,toko):
if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and token_ip_stream[2][1] == "=" and token_ip_stream[3][1] == toko[0][0] and token_ip_stream[5][1] == toko[1][0] and token_ip_stream[6][0] == "STATEMENT_END" :
... | def math(token_ip_stream, toko):
if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and (token_ip_stream[2][1] == '=') and (token_ip_stream[3][1] == toko[0][0]) and (token_ip_stream[5][1] == toko[1][0]) and (token_ip_stream[6][0] == 'STATEMENT_END'):
if token_ip_stream[4][1] == '+... |
# Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2.
# First way is brute force
def is_triplet(array):
# Base case, if array is under 3 elements, not possible
if len(array) < 3:
return False
# Iterate through first element... | def is_triplet(array):
if len(array) < 3:
return False
for i in range(len(array) - 2):
for j in range(i + 1, len(array) - 1):
for k in range(j, len(array)):
a = array[i] * array[i]
b = array[j] * array[j]
c = array[k] * array[k]
... |
climacell_yr_map = {
"6201": "48", # heavy freezing rain
"6001": "12", # freezing rain
"6200": "47", # light freezing rain
"6000": "47", # freeing drizzle
"7101": "48", # heavy ice pellets
"7000": "12", # ice pellets
"7102": "47", # light ice pellets
"5101": "50", # heavy snow
"5000... | climacell_yr_map = {'6201': '48', '6001': '12', '6200': '47', '6000': '47', '7101': '48', '7000': '12', '7102': '47', '5101': '50', '5000': '13', '5100': '49', '5001': '49', '8000': '11', '4201': '10', '4001': '09', '4200': '46', '4000': '46', '2100': '15', '2000': '15', '1001': '04', '1102': '03', '1101': '02', '1100'... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 14:49:25 2018
@author: User
"""
class Airlines():
def __init__(self, code, date, fare):
self.code = code
self.date = date
self.fare = int(fare)
def getDates(self):
print( self.date)
def getFares(self):
... | """
Created on Mon Jan 22 14:49:25 2018
@author: User
"""
class Airlines:
def __init__(self, code, date, fare):
self.code = code
self.date = date
self.fare = int(fare)
def get_dates(self):
print(self.date)
def get_fares(self):
return int(self.fare)
def descr... |
# read answer, context, question
# generate vocabulary file for elmo batcher
pre = ['dev', 'train']
fs = ['answer', 'context', 'question']
result = set()
for p in pre:
for f in fs:
print ('Processing ' + p + '.' +f)
with open('../../data/' + p + '.' + f) as ff:
content = ff.readlines()
... | pre = ['dev', 'train']
fs = ['answer', 'context', 'question']
result = set()
for p in pre:
for f in fs:
print('Processing ' + p + '.' + f)
with open('../../data/' + p + '.' + f) as ff:
content = ff.readlines()
for line in content:
for token in line.split():
... |
'''
Insert 5 numbers in the right position without using .sort()
Then show the list orderned
'''
my_list = []
for c in range(0, 5):
num = int(input('Type a number: '))
if c == 0 or num > my_list[-1]:
my_list.append(num)
print('Add this number at the end.')
else:
pos = 0
while... | """
Insert 5 numbers in the right position without using .sort()
Then show the list orderned
"""
my_list = []
for c in range(0, 5):
num = int(input('Type a number: '))
if c == 0 or num > my_list[-1]:
my_list.append(num)
print('Add this number at the end.')
else:
pos = 0
while... |
# Wi-Fi Diagnostic Tree
print(' Please reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Make sure the cables between t... | print(' Please reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Reboot your computer and try to connect.')
answer = input('Did that fix the problem? ')
if answer != 'yes':
print('Make sure the cables between the router and modem are p... |
class Dictionary:
def __init__(self):
self.words = set()
def check(self, word):
return word.lower() in self.words
def load(self, dictionary):
file = open(dictionary, 'r')
for line in file:
self.words.add(line.rstrip('\n'))
file.close()
return True
def size(self):
return len(self.words)
def un... | class Dictionary:
def __init__(self):
self.words = set()
def check(self, word):
return word.lower() in self.words
def load(self, dictionary):
file = open(dictionary, 'r')
for line in file:
self.words.add(line.rstrip('\n'))
file.close()
return Tr... |
class Map:
def __init__(self, x, y):
self.wall = False
self.small_dot = False
self.big_dot = False
self.eaten = False
self.x = x
self.y = y
#--- drawing on map ---#
def draw_dot(self):
if self.small_dot:
if not self.eaten:
... | class Map:
def __init__(self, x, y):
self.wall = False
self.small_dot = False
self.big_dot = False
self.eaten = False
self.x = x
self.y = y
def draw_dot(self):
if self.small_dot:
if not self.eaten:
fill(255, 255, 0)
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
### CONTROLS (non-tunable) ###
# general
TYPE_OF_RUN = train # train, test, test_episodes, render
LOAD_MODEL_FROM = None
SAVE_MODELS_TO = models/debugging_wmg_dynamic_state_Collins2018_train10_test15.pth
# worker.py
ENV = Collins2018_Env
EN... | type_of_run = train
load_model_from = None
save_models_to = models / debugging_wmg_dynamic_state_Collins2018_train10_test15.pth
env = Collins2018_Env
env_random_seed = 2
agent_random_seed = 1
reporting_interval = 5000
total_steps = 10000000
anneal_lr = False
num_episodes_to_test = 5
agent_net = WMG_State_Network
v2 = F... |
"""
# Startup script
Python script to set certain states at HA start and notify.
This unifies various automations and HA scripts in a simpler one.
"""
SWITCH_EXPERT_MODE = 'input_boolean.show_expert_mode'
# 'expert mode' for filtering groups and visibility control for ESP modules
last_state = hass.states.get(SWITCH... | """
# Startup script
Python script to set certain states at HA start and notify.
This unifies various automations and HA scripts in a simpler one.
"""
switch_expert_mode = 'input_boolean.show_expert_mode'
last_state = hass.states.get(SWITCH_EXPERT_MODE)
expert_mode_on = data.get('expert_mode_state', last_state.state)... |
class B:
pass
class A:
pass | class B:
pass
class A:
pass |
# ###############################
# Truthiness of an element:
# ###############################
def print_truthiness(msg, exp):
print(("TRUE" if exp else "FALSE") + " <-- " + msg)
print_truthiness("Testing True", True)
print_truthiness("Testing False", False)
# for sequences
seq = []
print_truthiness("Empty li... | def print_truthiness(msg, exp):
print(('TRUE' if exp else 'FALSE') + ' <-- ' + msg)
print_truthiness('Testing True', True)
print_truthiness('Testing False', False)
seq = []
print_truthiness('Empty list', seq)
seq.append('The cat')
print_truthiness('1 item list', seq)
print_truthiness('Zero', 0)
print_truthiness('El... |
class Solution:
def maxScore(self, cards, k):
pre = [0]
for card in cards:
pre.append(pre[-1] + card)
ans = 0
n = len(pre)
for i in range(k + 1):
ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans)
return ans
| class Solution:
def max_score(self, cards, k):
pre = [0]
for card in cards:
pre.append(pre[-1] + card)
ans = 0
n = len(pre)
for i in range(k + 1):
ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans)
return ans |
def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday):
#assert len(books) == len(L)
score = 0.
d = 0
for l in L:
d += L_signuptimes[l]
number_of_books = (D - d) * L_shipperday[l]
score += sum(books[l][:number_of_books])
return score
| def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday):
score = 0.0
d = 0
for l in L:
d += L_signuptimes[l]
number_of_books = (D - d) * L_shipperday[l]
score += sum(books[l][:number_of_books])
return score |
MESSAGE_PRIORITY = (
(-2, 'Stumm'),
(-1, 'Ruhig'),
(0, 'Normal'),
(1, 'Wichtig'),
(2, 'Emergency'),
) | message_priority = ((-2, 'Stumm'), (-1, 'Ruhig'), (0, 'Normal'), (1, 'Wichtig'), (2, 'Emergency')) |
class AsyncClass:
async def do_coroutine(self):
"""A documented coroutine function"""
attr_coro_result = await _other_coro_func() # NOQA
async def _other_coro_func():
return "run"
| class Asyncclass:
async def do_coroutine(self):
"""A documented coroutine function"""
attr_coro_result = await _other_coro_func()
async def _other_coro_func():
return 'run' |
class ProcessError(Exception):
"""Exception raised when a process exits with a non-zero exit code."""
def __init__(self, message):
self.message = message
| class Processerror(Exception):
"""Exception raised when a process exits with a non-zero exit code."""
def __init__(self, message):
self.message = message |
# Copyright 2016 Savoir-faire Linux
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Web No Bubble",
"version": "14.0.1.0.0",
"author": "Savoir-faire Linux, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"license": "AGPL-3",
"category": ... | {'name': 'Web No Bubble', 'version': '14.0.1.0.0', 'author': 'Savoir-faire Linux, Odoo Community Association (OCA)', 'website': 'https://github.com/OCA/web', 'license': 'AGPL-3', 'category': 'Web', 'summary': 'Remove the bubbles from the web interface', 'depends': ['web'], 'data': ['views/web_no_bubble.xml'], 'installa... |
# https://adventofcode.com/2019/day/5
#
# --- Day 2: 1202 Program Alarm ---
#
# --- Day 5: Sunny with a Chance of Asteroids ---
#
def loadintCode(fname='input'):
with open(fname, 'r') as f:
l = list(f.read().split(','))
p = [int(x) for x in l]
return p
def printIndexValue(L, pos=0):
... | def loadint_code(fname='input'):
with open(fname, 'r') as f:
l = list(f.read().split(','))
p = [int(x) for x in l]
return p
def print_index_value(L, pos=0):
longest = len(str(max(L)))
print('[', end='')
for (idx, val) in enumerate(L):
print('{:{width}d},'.format(val, wid... |
class Phone(object):
def __init__(self, phone_number):
phone_number = [char for char in phone_number if char.isdigit()]
if phone_number[:1] == ['1']:
phone_number = phone_number[1:]
if len(phone_number) != 10:
raise ValueError("Insufficient Digits")
if (int(ph... | class Phone(object):
def __init__(self, phone_number):
phone_number = [char for char in phone_number if char.isdigit()]
if phone_number[:1] == ['1']:
phone_number = phone_number[1:]
if len(phone_number) != 10:
raise value_error('Insufficient Digits')
if int(p... |
# -*- coding: utf-8 -*-
__title__ = u'django-flexisettings'
# semantic versioning, check http://semver.org/
__version__ = u'0.3.1'
__author__ = u'Stefan Berder <stefan.berder@ledapei.com>'
__copyright__ = u'Copyright 2012-2013, Heatwave fashion Ltd., ' \
u'all rights reserved'
| __title__ = u'django-flexisettings'
__version__ = u'0.3.1'
__author__ = u'Stefan Berder <stefan.berder@ledapei.com>'
__copyright__ = u'Copyright 2012-2013, Heatwave fashion Ltd., all rights reserved' |
def solution(p):
answer = p + 1
while(not isBeautifulYear(answer)):
answer += 1
return answer
def isBeautifulYear(year):
years = list(map(int, str(year)))
return len(set([x for x in years])) == len(years)
print(solution(1987)) | def solution(p):
answer = p + 1
while not is_beautiful_year(answer):
answer += 1
return answer
def is_beautiful_year(year):
years = list(map(int, str(year)))
return len(set([x for x in years])) == len(years)
print(solution(1987)) |
def split_and_add(numbers, n):
temp=[]
count=0
while count<n:
for i in range(0,len(numbers)//2):
temp.append(numbers[0])
numbers.pop(0)
if not temp:
return numbers
if len(temp)<len(numbers):
for i in range(0,len(temp)):
... | def split_and_add(numbers, n):
temp = []
count = 0
while count < n:
for i in range(0, len(numbers) // 2):
temp.append(numbers[0])
numbers.pop(0)
if not temp:
return numbers
if len(temp) < len(numbers):
for i in range(0, len(temp)):
... |
if __name__ == "__main__":
with open("file.txt", "r", encoding="utf-8") as f:
a = f.readlines()
for i in a:
if "," in i:
print(i)
| if __name__ == '__main__':
with open('file.txt', 'r', encoding='utf-8') as f:
a = f.readlines()
for i in a:
if ',' in i:
print(i) |
description='HRPT Graphit Filter via SPS-S5'
devices = dict(
graphit=device('nicos_sinq.amor.devices.sps_switch.SpsSwitch',
description='Graphit filter controlled by SPS',
epicstimeout=3.0,
readpv='SQ:HRPT:SPS1:DigitalInput',
... | description = 'HRPT Graphit Filter via SPS-S5'
devices = dict(graphit=device('nicos_sinq.amor.devices.sps_switch.SpsSwitch', description='Graphit filter controlled by SPS', epicstimeout=3.0, readpv='SQ:HRPT:SPS1:DigitalInput', commandpv='SQ:HRPT:SPS1:Push', commandstr='S0001', byte=4, bit=4, mapping={'OFF': False, 'ON'... |
"""
Notes:
This is more "find maximum profit" rather than finding best times to buy and sell stock.
"""
class Solution:
def max_profit(self, prices: [int]) -> int:
profit = 0
for stock in range(len(prices)-1):
if prices[stock+1] > prices[stock]:
profit += prices[stock+1... | """
Notes:
This is more "find maximum profit" rather than finding best times to buy and sell stock.
"""
class Solution:
def max_profit(self, prices: [int]) -> int:
profit = 0
for stock in range(len(prices) - 1):
if prices[stock + 1] > prices[stock]:
profit += prices[st... |
# BUILD FILE SYNTAX: SKYLARK
SE_VERSION = '3.11.0'
| se_version = '3.11.0' |
def main(filepath):
rows = []
#file load
with open(filepath) as file:
for line in file:
rows.append(line)
counter = 0
counter2 = 0
for entry in rows:
entry = entry.split(" ")
letter = entry[1][0]
entry[0] = entry[0].split("-")
low =... | def main(filepath):
rows = []
with open(filepath) as file:
for line in file:
rows.append(line)
counter = 0
counter2 = 0
for entry in rows:
entry = entry.split(' ')
letter = entry[1][0]
entry[0] = entry[0].split('-')
low = entry[0][0]
high =... |
class Solution:
def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
if not any(matrix):
return 0
m, n = len(matrix), len(matrix[0])
res = float('-inf')
for left in range(n):
... | class Solution:
def max_sum_submatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
if not any(matrix):
return 0
(m, n) = (len(matrix), len(matrix[0]))
res = float('-inf')
for left in range(n):
... |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* re... | """*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... |
x = range(1, 5, 9)
for n in x:
print(n)
| x = range(1, 5, 9)
for n in x:
print(n) |
class StudySeries(object):
def __init__(self, study_object, study_data=None):
'''
Takes study object
'''
assert hasattr(study_object, "__call__"), "invalid study object"
self.study = study_object
if study_data:
self.update(study... | class Studyseries(object):
def __init__(self, study_object, study_data=None):
"""
Takes study object
"""
assert hasattr(study_object, '__call__'), 'invalid study object'
self.study = study_object
if study_data:
self.update(study_data)
def up... |
TRPOconfig = {
'cg_damping': 1e-3,
'GAE_lambda': 0.,
'reward_decay': 0.98,
'max_kl_divergence': 2e-5,
'hidden_layers': [256, 256, 256],
'hidden_layers_v': [256, 256, 256],
'max_grad_norm': None,
'value_lr': 5e-4,
'train_v_iters': 20,
'lr_pi': 5e-4,
'steps_per_iter'... | trp_oconfig = {'cg_damping': 0.001, 'GAE_lambda': 0.0, 'reward_decay': 0.98, 'max_kl_divergence': 2e-05, 'hidden_layers': [256, 256, 256], 'hidden_layers_v': [256, 256, 256], 'max_grad_norm': None, 'value_lr': 0.0005, 'train_v_iters': 20, 'lr_pi': 0.0005, 'steps_per_iter': 3200, 'value_func_type': 'FC'}
TRPOconfig['mem... |
transverse_run5 = [
6165044,
6165046,
6165047,
6165055,
6165058,
6165059,
6165063,
6166051,
6166052,
6166054,
6166055,
6166056,
6166057,
6166059,
6166060,
6166061,
6166070,
6166071,
6166073,
6166074,
6166075,
6166076,
6166090,
6166091,
#6166101, ## no relative luminosities
6167079,
6167083,
6167088
]
## transverse run... | transverse_run5 = [6165044, 6165046, 6165047, 6165055, 6165058, 6165059, 6165063, 6166051, 6166052, 6166054, 6166055, 6166056, 6166057, 6166059, 6166060, 6166061, 6166070, 6166071, 6166073, 6166074, 6166075, 6166076, 6166090, 6166091, 6167079, 6167083, 6167088]
transverse_run6_iucf = [7098001, 7098002, 7098004, 7098006... |
class Details:
def __init__(self, details):
self.details = details
def __getattr__(self, attr):
if attr in self.details:
return self.details[attr]
else:
raise AttributeError('{attr} is not a valid attribute of Details'.format(attr))
@property
def all(se... | class Details:
def __init__(self, details):
self.details = details
def __getattr__(self, attr):
if attr in self.details:
return self.details[attr]
else:
raise attribute_error('{attr} is not a valid attribute of Details'.format(attr))
@property
def all(s... |
# Aula 18 - Listas (Parte 2)
teste = list()
teste.append('Marieliton')
teste.append(33)
galera = list()
#galera.append(teste) # fazer isso cria uma dependencia entre as listas
galera.append(teste[:]) # isso faz a copia da lista sem criar dependencia
print(galera)
teste[0] = 'Maria'
teste[1] = 22
print(teste)
galera.... | teste = list()
teste.append('Marieliton')
teste.append(33)
galera = list()
galera.append(teste[:])
print(galera)
teste[0] = 'Maria'
teste[1] = 22
print(teste)
galera.append(teste)
print(galera)
galera = [['Joao', 19], ['Ana', 31], ['Manoel', 42], ['Maria', 51]]
for pessoa in galera:
print(f'{pessoa[0]} tem {pessoa[... |
expected_output = {
"Ethernet1/1": {
"advertising_code": "Passive Cu",
"cable_attenuation": "0/0/0/0/0 dB for bands 5/7/12.9/25.8/56 " "GHz",
"cable_length": 2.0,
"cis_part_number": "37-1843-01",
"cis_product_id": "QDD-400-CU2M",
"cis_version_id": "V01",
"cisc... | expected_output = {'Ethernet1/1': {'advertising_code': 'Passive Cu', 'cable_attenuation': '0/0/0/0/0 dB for bands 5/7/12.9/25.8/56 GHz', 'cable_length': 2.0, 'cis_part_number': '37-1843-01', 'cis_product_id': 'QDD-400-CU2M', 'cis_version_id': 'V01', 'cisco_id': '0x18', 'clei': 'CMPQAGSCAA', 'cmis_ver': 4, 'date_code': ... |
a=input().split();r=5000
for i in a:
if i=='1':
r-=500
elif i=='2':
r-=800
else:
r-=1000
print(r)
| a = input().split()
r = 5000
for i in a:
if i == '1':
r -= 500
elif i == '2':
r -= 800
else:
r -= 1000
print(r) |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 16 14:25:12 2021
@author: ELCOT
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n == 1:
return x
if n == 2:
return x*x
... | """
Created on Fri Apr 16 14:25:12 2021
@author: ELCOT
"""
class Solution:
def my_pow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n == 1:
return x
if n == 2:
return x * x
is_neg = 0
if n < 0:
is_neg = 1
... |
# https://leetcode.com/problems/clone-graph/description/
#
# algorithms
# Medium (25.08%)
# Total Accepted: 180.2K
# Total Submissions: 718.5K
# beats 50.23% of python submissions
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# se... | class Solution:
def __init__(self):
self.hash_map = {}
def clone_graph(self, node):
if not node:
return node
new_node = undirected_graph_node(node.label)
self.hash_map[node.label] = new_node
for neighbor in node.neighbors:
if neighbor.label in se... |
class Preprocessor(object):
"""
Preprocessor: Apply simple preprocessing operations to real-valued numerical datasets (min-max normalization)
"""
def __init__(self, data):
"""
Initializes the Preprocessor according to the provided dataset
Arguments:
data {np.ndarray... | class Preprocessor(object):
"""
Preprocessor: Apply simple preprocessing operations to real-valued numerical datasets (min-max normalization)
"""
def __init__(self, data):
"""
Initializes the Preprocessor according to the provided dataset
Arguments:
data {np.ndarray... |
def preprocess_input(date, state_holiday):
day, month = (int(date.split(" ")[0]), int(date.split(" ")[1]))
if state_holiday == 'a':
state_holiday = 1
elif state_holiday == 'b':
state_holiday = 2
elif state_holiday == 'c':
state_holiday = 3
else:
state_holiday = 0
return day, month, state_holiday | def preprocess_input(date, state_holiday):
(day, month) = (int(date.split(' ')[0]), int(date.split(' ')[1]))
if state_holiday == 'a':
state_holiday = 1
elif state_holiday == 'b':
state_holiday = 2
elif state_holiday == 'c':
state_holiday = 3
else:
state_holiday = 0
... |
class dotDrawText_t(object):
# no doc
aText=None
Color=None
Location=None
| class Dotdrawtext_T(object):
a_text = None
color = None
location = None |
numeros = [-12, 84, 13, 20, -33, 101, 9]
def separar(lista):
pares = []
impares = []
for numero in lista:
if numero%2 == 0:
pares.append(numero)
else:
impares.append(numero)
return pares, impares
pares, impares = separar(numeros)
print(pares)
print(impares)
| numeros = [-12, 84, 13, 20, -33, 101, 9]
def separar(lista):
pares = []
impares = []
for numero in lista:
if numero % 2 == 0:
pares.append(numero)
else:
impares.append(numero)
return (pares, impares)
(pares, impares) = separar(numeros)
print(pares)
print(impares) |
# callback handlers: reloaded each time triggered
def message1(): # change me
print('spamSpamSPAM') # or could build a dialog...
def message2(self):
print('Ni! Ni!') # change me
self.method1() # access the 'Hello' instance...
| def message1():
print('spamSpamSPAM')
def message2(self):
print('Ni! Ni!')
self.method1() |
class DetailModel:
class Mesh:
def __init__(self):
self.vertices_count = None
self.indices_count = None
self.uv_map_name = 'Texture'
self.bpy_mesh = None
self.bpy_material = None
def __init__(self):
self.shader = None
self.tex... | class Detailmodel:
class Mesh:
def __init__(self):
self.vertices_count = None
self.indices_count = None
self.uv_map_name = 'Texture'
self.bpy_mesh = None
self.bpy_material = None
def __init__(self):
self.shader = None
self.te... |
def fibonacci_numbers(ul: int) -> int:
numbers: list = []
a: int = 0
b: int = 1
total: int = 0
while (total <= ul):
numbers.append(total)
a = b
b = total
total = a + b
return sum(filter(lambda x: not x % 2, numbers))
if __name__ == '__main__':
t: int = int(i... | def fibonacci_numbers(ul: int) -> int:
numbers: list = []
a: int = 0
b: int = 1
total: int = 0
while total <= ul:
numbers.append(total)
a = b
b = total
total = a + b
return sum(filter(lambda x: not x % 2, numbers))
if __name__ == '__main__':
t: int = int(input... |
nm = input().split()
n = int(nm[0])
m = int(nm[1])
mt = []
for _ in range(n):
matrix_item = input()
mt.append(matrix_item)
p=0
print(mt)
k = int(input())
for i in range(n):
for j in range(m):
if(mt[i][j]=="M"):
print(i,j)
for i in range(n):
for ... | nm = input().split()
n = int(nm[0])
m = int(nm[1])
mt = []
for _ in range(n):
matrix_item = input()
mt.append(matrix_item)
p = 0
print(mt)
k = int(input())
for i in range(n):
for j in range(m):
if mt[i][j] == 'M':
print(i, j)
for i in range(n):
for j in range(... |
class TwoSum:
def __init__(self):
self.numberCountMap = {}
"""
@param number: An integer
@return: nothing
"""
def add(self, number):
count = 1
if number in self.numberCountMap :
count = self.numberCountMap[number]+1
self.numberCountMap[number] = coun... | class Twosum:
def __init__(self):
self.numberCountMap = {}
'\n @param number: An integer\n @return: nothing\n '
def add(self, number):
count = 1
if number in self.numberCountMap:
count = self.numberCountMap[number] + 1
self.numberCountMap[number] = coun... |
class Formatter:
def __init__(self):
pass
def format(self, args, data):
if args.vba:
self.format_VBA(args,data)
elif args.csharp:
self.format_CSharp(args,data)
elif args.cpp:
self.format_CPP(args,data)
elif args.raw:
... | class Formatter:
def __init__(self):
pass
def format(self, args, data):
if args.vba:
self.format_VBA(args, data)
elif args.csharp:
self.format_CSharp(args, data)
elif args.cpp:
self.format_CPP(args, data)
elif args.raw:
pr... |
"""This module contains code for computing variant statistics and pedigree checks.
It provides similar functionality to Peddy but works with a database backend. Peddy is described in
Pedersen & Quinlan (2017).
"""
| """This module contains code for computing variant statistics and pedigree checks.
It provides similar functionality to Peddy but works with a database backend. Peddy is described in
Pedersen & Quinlan (2017).
""" |
"""The all pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest
path problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will
represent the minimum distance from any node to all other nodes in the graph. """
"""For bet... | """The all pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest
path problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will
represent the minimum distance from any node to all other nodes in the graph. """
'For better... |
M = int(input())
N = int(input())+1
numbers = []
for i in range(M,N):
c = 0
for j in range(1,i+1):
if i%j == 0:
c += 1
if c > 2:
break
if c == 2:
numbers.append(i)
if sum(numbers) == 0:
print(-1)
else:
print(sum(numbers),min(numbers),sep='\n') | m = int(input())
n = int(input()) + 1
numbers = []
for i in range(M, N):
c = 0
for j in range(1, i + 1):
if i % j == 0:
c += 1
if c > 2:
break
if c == 2:
numbers.append(i)
if sum(numbers) == 0:
print(-1)
else:
print(sum(numbers), min(numbers), sep='\n'... |
# Runtime: 176 ms
# Beats 77.94% of Python submissions
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution():
def constructMaximumBinaryTree(self, nums):
"""
:type n... | class Solution:
def construct_maximum_binary_tree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
if len(nums) == 1:
return tree_node(nums[0])
(curr_max, max_index) = self.max(nums)
root = t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.