content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
person_1 = {
'first_name': 'Tony',
'last_name': 'Macaroni',
'age': 26,
'state': 'PA',
}
person_2 = {
'first_name': 'Betsy',
'last_name': 'Bolognese',
'age': 34,
'state': 'KS',
}
person_3 = {
'first_name': 'Peter',
'last_name': 'Pepperoni',
'age': 24,
'state': 'NY',
}
f... | person_1 = {'first_name': 'Tony', 'last_name': 'Macaroni', 'age': 26, 'state': 'PA'}
person_2 = {'first_name': 'Betsy', 'last_name': 'Bolognese', 'age': 34, 'state': 'KS'}
person_3 = {'first_name': 'Peter', 'last_name': 'Pepperoni', 'age': 24, 'state': 'NY'}
friends = {person_1['first_name']: person_1, person_2['first_... |
input_ = [int(element) for element in input().split(" ")]
# print(input_)
n = input_[0]
acceptable_lengths = input_[1:]
#print(n)
#print(acceptable_lengths)
acceptable_lengths.sort()
max_possible_pieces = n // acceptable_lengths[0]
print(max_possible_pieces) | input_ = [int(element) for element in input().split(' ')]
n = input_[0]
acceptable_lengths = input_[1:]
acceptable_lengths.sort()
max_possible_pieces = n // acceptable_lengths[0]
print(max_possible_pieces) |
class ApplicationError(Exception):
"""Base class for all application errors."""
class NotFoundError(ApplicationError):
"""Raised when an entity does not exists."""
| class Applicationerror(Exception):
"""Base class for all application errors."""
class Notfounderror(ApplicationError):
"""Raised when an entity does not exists.""" |
## The modelling for generations
# define bus types
AC = 1 # Critical AC generators
UAC = 2 # Non-critical AC generators
DC = 3 # Critical DC generators
UDC = 4 # Critical DC generators
# define the indices
GEN_BUS = 0 # bus number
GEN_TYPE = 1 # type of generators
PG = 2 # Pg, real power output (W)
QG = 3 # ... | ac = 1
uac = 2
dc = 3
udc = 4
gen_bus = 0
gen_type = 1
pg = 2
qg = 3
rg = 4
qmax = 5
qmin = 6
smax = 7
vg = 8
mbase = 9
gen_status = 10
pmax = 11
pmin = 12
pc1 = 13
pc2 = 14
qc1_min = 15
qc1_max = 16
qc2_min = 17
qc2_max = 18
ramp_agc = 19
ramp_10 = 20
ramp_30 = 21
ramp_q = 22
apf = 23
mu_pmax = 24
mu_pmin = 25
mu_qmax... |
def addition (a,b):
return a + b
def substraction (a,b):
return a - b
def multiplication (a,b):
return a * b
def division (a,b):
return a / b
first_number=int(input("Enter the first number: "))
second_number=int(input("Enter the second number: "))
print("The sum of your two numbers is: " + str(... | def addition(a, b):
return a + b
def substraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
first_number = int(input('Enter the first number: '))
second_number = int(input('Enter the second number: '))
print('The sum of your two numbers is: ' + str(ad... |
#!/usr/bin/env python
# coding: utf-8
"""
Exception classes used in smtplibaio package.
The exhaustive hierarchy of exceptions that might be raised in the smtplibaio
package is as follows:
BaseException
|
+ Exception
|
+ SMTPException
| |
| + SMTPCommandNot... | """
Exception classes used in smtplibaio package.
The exhaustive hierarchy of exceptions that might be raised in the smtplibaio
package is as follows:
BaseException
|
+ Exception
|
+ SMTPException
| |
| + SMTPCommandNotSupportedError
| + SMTPLogi... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
else:
... | class Solution:
def delete_duplicates(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
else:
node_list = []
last_node = head
is_duplicate = False
head = head.next
while True:
... |
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for main_index in range(1, len(arr)):
reference_value = arr[main_index]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position... | def insertion_sort(arr):
for main_index in range(1, len(arr)):
reference_value = arr[main_index]
working_index = main_index - 1
while working_index >= 0:
if arr[working_index + 1] < arr[working_index]:
(arr[working_index + 1], arr[working_index]) = (arr[working_in... |
def broken_function_with_message(error):
a_message = ""
try:
raise error("A message ?")
except error as err:
a_message += str(err)
finally:
a_message += "All good"
a_message += "I continue running !"
return a_message
def broken_function_without_message(error):
a_me... | def broken_function_with_message(error):
a_message = ''
try:
raise error('A message ?')
except error as err:
a_message += str(err)
finally:
a_message += 'All good'
a_message += 'I continue running !'
return a_message
def broken_function_without_message(error):
a_mess... |
"""
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
====
Assume we are dealing with an environment which could only hold integers within the 32-bit signed
integer ra... | """
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
====
Assume we are dealing with an environment which could only hold integers within the 32-bit signed
integer ra... |
#TEMA:IF
###########################################################################
def evalucion(nota):
valoracion = "Aprobado"
if nota<5:
valoracion="Suspenso"
return valoracion
###########################################################################
#Llamada de la funcion
print("Ejemplo #1")
print(4)
p... | def evalucion(nota):
valoracion = 'Aprobado'
if nota < 5:
valoracion = 'Suspenso'
return valoracion
print('Ejemplo #1')
print(4)
print()
print()
print()
print('Ejemplo #2')
nota_alumno = input('Introduce la nota del alumno: ')
nota_alumno = int(notaAlumno)
print(evalucion(notaAlumno))
print()
print(... |
# Excepciones => try ... except ... finally
try:
numero = int(input("Ingrese un numero"))
# numero/0
except ValueError :
print('Tiene que ser un numero')
# except ZeroDivisionError:
# print('No se puede hacer la division entre cero')
except:
print('Hubo un error')
# else => solamente va a funcionar ... | try:
numero = int(input('Ingrese un numero'))
except ValueError:
print('Tiene que ser un numero')
except:
print('Hubo un error')
else:
print('Todo fue bien')
finally:
print('Yo siempre me ejecuto')
print('Yo soy otra linea de codigo') |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 19 16:14:38 2016
@author: zhengzhang
"""
def run(self):
for i in range(self.num_steps):
direction = self.dice.roll()
if direction == 0:
self.x_pos += 1
elif direction == 1:
self.x_pos -= 1
elif direction ==... | """
Created on Sat Mar 19 16:14:38 2016
@author: zhengzhang
"""
def run(self):
for i in range(self.num_steps):
direction = self.dice.roll()
if direction == 0:
self.x_pos += 1
elif direction == 1:
self.x_pos -= 1
elif direction == 2:
self.y_pos +=... |
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
DB_NAME = 'ugc_db'
BENCHMARK_ITERATIONS = 10
| mongo_host = 'localhost'
mongo_port = 27017
db_name = 'ugc_db'
benchmark_iterations = 10 |
data = input().split("\\")
name, extension = data[-1].split(".")
print(f"File name: {name}")
print(f"File extension: {extension}")
| data = input().split('\\')
(name, extension) = data[-1].split('.')
print(f'File name: {name}')
print(f'File extension: {extension}') |
"""Shared configuration flags."""
HIDDEN_TRACEBACK = True
HOOKS_ENABLED = True
MINIMAL_DIFFS = True
WRITE_DELAY = 0.0 # seconds
| """Shared configuration flags."""
hidden_traceback = True
hooks_enabled = True
minimal_diffs = True
write_delay = 0.0 |
WIN_SIZE = 25
def valid_number(window, number):
for n in window:
dif = abs(number-n)
if n != dif and dif in window:
return True
return False
def find_wrong(input):
window = input[:WIN_SIZE]
i = 1
for number in input[WIN_SIZE:]:
if not valid_number(window, numb... | win_size = 25
def valid_number(window, number):
for n in window:
dif = abs(number - n)
if n != dif and dif in window:
return True
return False
def find_wrong(input):
window = input[:WIN_SIZE]
i = 1
for number in input[WIN_SIZE:]:
if not valid_number(window, numb... |
class CustomTextSummarizer(BaseTextSummarizer):
def __init__ (self, model_key, language):
self._tokenizer = AutoTokenizer.from_pretrained(model_key)
self._language = language
self._model = AutoModelForSeq2SeqLM.from_pretrained(model_key)
self._device = 'cuda' if bool(strtobool(os.... | class Customtextsummarizer(BaseTextSummarizer):
def __init__(self, model_key, language):
self._tokenizer = AutoTokenizer.from_pretrained(model_key)
self._language = language
self._model = AutoModelForSeq2SeqLM.from_pretrained(model_key)
self._device = 'cuda' if bool(strtobool(os.get... |
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
queue = collections.deque()
for i, row in enumerate(matrix):
for j, val in enumerate(row):
if val:
matrix[i][j] = math.inf
... | class Solution:
def update_matrix(self, matrix: List[List[int]]) -> List[List[int]]:
(m, n) = (len(matrix), len(matrix[0]))
queue = collections.deque()
for (i, row) in enumerate(matrix):
for (j, val) in enumerate(row):
if val:
matrix[i][j] = m... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'depot_tools/bot_update',
'depot_tools/gclient',
'depot_tools/git',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/prope... | deps = ['depot_tools/bot_update', 'depot_tools/gclient', 'depot_tools/git', 'recipe_engine/context', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/raw_io', 'recipe_engine/step', 'webrtc']
def run_steps(api):
api.gclient.set_config('webrtc')
for os in ['linux', 'androi... |
"""Mobjects used to display Text using Pango or LaTeX.
Modules
=======
.. autosummary::
:toctree: ../reference
~code_mobject
~numbers
~tex_mobject
~text_mobject
"""
| """Mobjects used to display Text using Pango or LaTeX.
Modules
=======
.. autosummary::
:toctree: ../reference
~code_mobject
~numbers
~tex_mobject
~text_mobject
""" |
MODEL_BUCKET = 'clothing-08-04-2019'
MODEL_PATH = 'classifier/net.p'
PATH_DATA = 'data'
PORT = 8080
LABELS = ('back', 'front', 'other', 'packshot', 'side') | model_bucket = 'clothing-08-04-2019'
model_path = 'classifier/net.p'
path_data = 'data'
port = 8080
labels = ('back', 'front', 'other', 'packshot', 'side') |
class Entity(dict):
identity: int = 0
def __repr__(self):
return f"<Entity-{self.identity}:{super().__repr__()}>"
| class Entity(dict):
identity: int = 0
def __repr__(self):
return f'<Entity-{self.identity}:{super().__repr__()}>' |
# odc module, used to simulate the C++ functions exported by PyPort
# "LIs:log"
def log(guid, level, message):
print("Log - Guid - {} - Level {} - Message - {}".format(guid, level, message))
return
# "LsIss:PublishEvent"
# Same format as Event
def PublishEvent(guid, EventType, ODCIndex, Quality, PayLoad ):
... | def log(guid, level, message):
print('Log - Guid - {} - Level {} - Message - {}'.format(guid, level, message))
return
def publish_event(guid, EventType, ODCIndex, Quality, PayLoad):
print('Publish Event - Guid - {} - {} {} {}'.format(guid, EventType, ODCIndex, Quality, PayLoad))
return True
def set_ti... |
"""Module containing the `AnalysisError` exception class."""
class AnalysisError(Exception):
"""
Exception representing an error during a repository analysis.
Attributes:
message {string} -- Message explaining what went wrong.
"""
def __init__(self, message):
"""
Initial... | """Module containing the `AnalysisError` exception class."""
class Analysiserror(Exception):
"""
Exception representing an error during a repository analysis.
Attributes:
message {string} -- Message explaining what went wrong.
"""
def __init__(self, message):
"""
Initiali... |
class Solution:
def transformArray(self, arr: List[int]) -> List[int]:
diff = True
while diff:
curr = arr[:]
diff = False
for i in range(1, len(arr) - 1):
if arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
curr[i] += 1
... | class Solution:
def transform_array(self, arr: List[int]) -> List[int]:
diff = True
while diff:
curr = arr[:]
diff = False
for i in range(1, len(arr) - 1):
if arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
curr[i] += 1
... |
class Solution:
def threeSum(self, nums) :
ans=[]
nums.sort()
if nums==[]:
return []
for i in range(len(nums)-1):
j=i+1
k=len(nums)-1
while j<k:
x = nums[i]+nums[j]+nums[k]
if x==0:
y=... | class Solution:
def three_sum(self, nums):
ans = []
nums.sort()
if nums == []:
return []
for i in range(len(nums) - 1):
j = i + 1
k = len(nums) - 1
while j < k:
x = nums[i] + nums[j] + nums[k]
if x == 0:... |
class DomainException(Exception):
pass
class DomainIdError(DomainException):
pass
class DomainNotFoundError(DomainException):
pass
def domain_id_error(domainname, id):
if (id == None):
return get_id_error(domainname, "None", "ID is missing!")
else:
return get_id_error(domainname, ... | class Domainexception(Exception):
pass
class Domainiderror(DomainException):
pass
class Domainnotfounderror(DomainException):
pass
def domain_id_error(domainname, id):
if id == None:
return get_id_error(domainname, 'None', 'ID is missing!')
else:
return get_id_error(domainname, id... |
# Python Resources
# The purpose of this document is to direct you to resources that you may find useful if you decide to do a deeper dive into Python.
# This course is not meant to be an introduction to programming, nor an introduction to Python, but if you find yourself interested
# in exploring Python further, or fe... | result = []
for x in range(10):
for y in range(5):
if x * y > 10:
result.append((x, y))
print(result)
result = []
for x in range(10):
for y in range(5):
if x * y > 10:
result.append((x, y))
print(result)
for x in range(10):
print(x)
for x in range(10):
print(x)
fo... |
#while loop
# while [condition]:
# [statements]
#else:
count =1
sum = 0
while count <=20:
sum=sum + count
count=count+1
print(sum)
sum1=0
for value in range(1,21):
pass
| count = 1
sum = 0
while count <= 20:
sum = sum + count
count = count + 1
print(sum)
sum1 = 0
for value in range(1, 21):
pass |
"""
This is the docstring for an empty init file, to support testing packages besides PyTest such as Nose that may look for
such a file
"""
| """
This is the docstring for an empty init file, to support testing packages besides PyTest such as Nose that may look for
such a file
""" |
def allow_tags(func):
"""Allows HTML tags to be returned from resource without escaping"""
if isinstance(func, property):
func = func.fget
func.allow_tags = True
return func
def humanized(humanized_func, **humanized_func_kwargs):
"""Sets 'humanized' function to method or property."""
d... | def allow_tags(func):
"""Allows HTML tags to be returned from resource without escaping"""
if isinstance(func, property):
func = func.fget
func.allow_tags = True
return func
def humanized(humanized_func, **humanized_func_kwargs):
"""Sets 'humanized' function to method or property."""
d... |
class NewsStyleUriParser(UriParser):
"""
A customizable parser based on the news scheme using the Network News Transfer Protocol (NNTP).
NewsStyleUriParser()
"""
| class Newsstyleuriparser(UriParser):
"""
A customizable parser based on the news scheme using the Network News Transfer Protocol (NNTP).
NewsStyleUriParser()
""" |
class Blueberry (object):
app_volume = 1.0
break_loop = False
@staticmethod
def sel_local_vol(new_vol):
Blueberry.app_volume = new_vol
@staticmethod
def gel_local_vol():
return Blueberry.app_volume
@staticmethod
def set_break_status(new_status):
Blueberry.br... | class Blueberry(object):
app_volume = 1.0
break_loop = False
@staticmethod
def sel_local_vol(new_vol):
Blueberry.app_volume = new_vol
@staticmethod
def gel_local_vol():
return Blueberry.app_volume
@staticmethod
def set_break_status(new_status):
Blueberry.break_... |
# Contains many tic tac toe positions to test the solver
x_move_1 = [['X', '_', '_'],
['_', '_', '_'],
['_', '_', '_']]
x_move_2 = [['_', 'X', '_'],
['_', '_', '_'],
['_', '_', '_']]
x_move_3 = [['_', '_', '_'],
['_', 'X', '_'],
... | x_move_1 = [['X', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
x_move_2 = [['_', 'X', '_'], ['_', '_', '_'], ['_', '_', '_']]
x_move_3 = [['_', '_', '_'], ['_', 'X', '_'], ['_', '_', '_']]
x_wins_1 = [['X', 'O', '_'], ['_', '_', '_'], ['_', '_', '_']]
x_wins_2 = [['X', '_', 'O'], ['_', '_', '_'], ['_', '_', '_']]
x_win... |
class Solution:
circle_id = 0
def next_circle_id(self):
self.circle_id += 1
return self.circle_id
def findCircleNum(self, M):
"""
:type M:list[list[int]]
:rtype: int0
"""
m_length = len(M)
circle_map = [-1 for i in range(m_length)] # type: ... | class Solution:
circle_id = 0
def next_circle_id(self):
self.circle_id += 1
return self.circle_id
def find_circle_num(self, M):
"""
:type M:list[list[int]]
:rtype: int0
"""
m_length = len(M)
circle_map = [-1 for i in range(m_length)]
... |
''' IMPLEMENTATION METHOD 2 (less common but easier)
HEAD TAIL
________ ________ ________ ________
| | | | | | | | | | | |
| None | |--->| a | |--->| b | |--->| c | |--->None
|______|_| |______|_| |______|_| |___... | """ IMPLEMENTATION METHOD 2 (less common but easier)
HEAD TAIL
________ ________ ________ ________
| | | | | | | | | | | |
| None | |--->| a | |--->| b | |--->| c | |--->None
|______|_| |______|_| |______|_| |___... |
"Talk."
# https://www.jetbrains.com/help/pycharm/part-1-debugging-python-code.html#7bf477d0 - IDE
# https://wiki.python.org/moin/PythonDebuggingTools - debug
print('sds') | """Talk."""
print('sds') |
def obtener_ganadores(lista_ganadores):
lista_unica=[]
for i in lista_ganadores:
if i not in lista_unica:
lista_unica.append(i)
return lista_unica
def obtener_posiciones_premio_doble(lista_carreras_con_premio,lista_ganadores,caballo ):
lista_final_premio=[]
c=0
for i in lista_carreras_con_premio:... | def obtener_ganadores(lista_ganadores):
lista_unica = []
for i in lista_ganadores:
if i not in lista_unica:
lista_unica.append(i)
return lista_unica
def obtener_posiciones_premio_doble(lista_carreras_con_premio, lista_ganadores, caballo):
lista_final_premio = []
c = 0
for i ... |
#
# PySNMP MIB module CHIPDOT1D-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHIPDOT1D-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:48:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ... |
"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should
be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 +... | """
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should
be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 +... |
class Memory():
def __init__(self):
#Depricate
self.stack = {}
self.heap = {}
#Depricate
self.variableNames = []
self.Env = [{}]
def malloc(self,x,v):
l = len(self.Env)
(self.Env[l-1])[x] = v
def requestVar(self,x):
l = len(se... | class Memory:
def __init__(self):
self.stack = {}
self.heap = {}
self.variableNames = []
self.Env = [{}]
def malloc(self, x, v):
l = len(self.Env)
self.Env[l - 1][x] = v
def request_var(self, x):
l = len(self.Env)
i = l - 1
stk = sel... |
name = "David"
if name == "David":
print(name)
elif name == "Artur":
print(name)
else:
print("Nothing found") | name = 'David'
if name == 'David':
print(name)
elif name == 'Artur':
print(name)
else:
print('Nothing found') |
a = 15
# print(1 & 15)
# print(2 & 15)
# print(4 & 15)
| a = 15 |
def extractKoreanNovelTrans(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag):
return False
if 'Novel: Kill the Lights' in item['tags']:
return buildReleaseMessageWithType(item, 'Kill the Lights', vol, chp, frag=frag, postfix=postfix)
if 'Nov... | def extract_korean_novel_trans(item):
"""
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol or frag):
return False
if 'Novel: Kill the Lights' in item['tags']:
return build_release_message_with_type(item, 'Kill the Lights', vol, chp,... |
class float_range(object):
def __init__(self, start, stop=None, step=1):
if stop is None:
start, stop = 0, start
if not step:
raise ValueError
(self.start, self.stop, self.step) = (start, stop, step)
def __iter__(self):
i = self.start
if self.step... | class Float_Range(object):
def __init__(self, start, stop=None, step=1):
if stop is None:
(start, stop) = (0, start)
if not step:
raise ValueError
(self.start, self.stop, self.step) = (start, stop, step)
def __iter__(self):
i = self.start
if self... |
class ThreeIncreasing:
def minEaten(self, a, b, c):
candies_eaten = 0
while(c <= b):
b -= 1
candies_eaten += 1
while(b <= a):
a -= 1
candies_eaten += 1
if(a <= 0 or b <= 0 or c <= 0):
return -1
el... | class Threeincreasing:
def min_eaten(self, a, b, c):
candies_eaten = 0
while c <= b:
b -= 1
candies_eaten += 1
while b <= a:
a -= 1
candies_eaten += 1
if a <= 0 or b <= 0 or c <= 0:
return -1
else:
retur... |
#!/usr/bin/env python3
# Copyright (C) Alibaba Group Holding Limited.
""" Registry class. """
class Registry(object):
"""
The Registry class provides a registry for all things
To initialize:
REGISTRY = Registry()
To register a tracker:
@REGISTRY.register()
class Model():
... | """ Registry class. """
class Registry(object):
"""
The Registry class provides a registry for all things
To initialize:
REGISTRY = Registry()
To register a tracker:
@REGISTRY.register()
class Model():
...
"""
def __init__(self, table_name=''):
... |
# ------------------------------
# 777. Swap Adjacent in LR String
#
# Description:
# In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the endi... | class Solution:
def can_transform(self, start, end):
"""
:type start: str
:type end: str
:rtype: bool
"""
if start.replace('X', '') != end.replace('X', ''):
return False
t = 0
for i in range(len(start)):
if start[i] == 'L':
... |
type = 'SMPLify'
verbose = True
body_model = dict(
type='SMPL',
gender='neutral',
num_betas=10,
keypoint_src='smpl_45',
# keypoint_dst='smpl_45',
keypoint_dst='smpl',
model_path='data/body_models/smpl',
batch_size=1)
stages = [
# stage 0: optimize `betas`
dict(
num_iter... | type = 'SMPLify'
verbose = True
body_model = dict(type='SMPL', gender='neutral', num_betas=10, keypoint_src='smpl_45', keypoint_dst='smpl', model_path='data/body_models/smpl', batch_size=1)
stages = [dict(num_iter=10, ftol=0.0001, fit_global_orient=False, fit_transl=False, fit_body_pose=False, fit_betas=True, keypoints... |
def sum_integer(a, b):
sum_no = a + b
if (sum_no >= 15) and (sum_no <= 20):
sum_no = 20
return sum_no
print (sum_integer(23, 5)) | def sum_integer(a, b):
sum_no = a + b
if sum_no >= 15 and sum_no <= 20:
sum_no = 20
return sum_no
print(sum_integer(23, 5)) |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/aref/test/q3at/install/include;/usr/include".split(';') if "/home/aref/test/q3at/install/include;/usr/include" != "" else []
PROJECT_CATKIN_DEPENDS = "geometry_msgs;hector_uav_msgs;roscpp".replac... | catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/aref/test/q3at/install/include;/usr/include'.split(';') if '/home/aref/test/q3at/install/include;/usr/include' != '' else []
project_catkin_depends = 'geometry_msgs;hector_uav_msgs;roscpp'.replace(';', ' ')
pkg_config_libraries_with_prefix = '-lhector_... |
# convert a supplied string to a usable integer
def string_to_num(str : str):
return sum([ord(str[index]) for index in range(len(str))])
def xor(n1, n2):
# remove the 0b string from the beggining of the binary string
n1_binary, n2_binary = bin(n1)[2:], bin(n2)[2:]
# make sure both strings are the same... | def string_to_num(str: str):
return sum([ord(str[index]) for index in range(len(str))])
def xor(n1, n2):
(n1_binary, n2_binary) = (bin(n1)[2:], bin(n2)[2:])
extra_zeros = len(n1_binary) - len(n2_binary)
if extra_zeros > 0:
for i in range(0, extra_zeros, 1):
n2_binary = '0' + n2_bina... |
default_configs = [{'type': 'integer', 'name': 'num_clones', 'value': 1, 'description': 'Number of clones to deploy.'},
{'type': 'boolean', 'name': 'clone_on_cpu', 'value': False,
'description': 'Use CPUs to deploy clones.'},
{'type': 'integer', 'name': 'num_rep... | default_configs = [{'type': 'integer', 'name': 'num_clones', 'value': 1, 'description': 'Number of clones to deploy.'}, {'type': 'boolean', 'name': 'clone_on_cpu', 'value': False, 'description': 'Use CPUs to deploy clones.'}, {'type': 'integer', 'name': 'num_replicas', 'value': 1, 'description': 'Number of worker repli... |
alien_0 = {
'color':'green',
'points':'5'
}
print(alien_0)
print(alien_0['color'])
new_points = alien_0['points']
print(f"You just earned {new_points} points")
alien_0['x_position'] = 0
alien_0['y_position'] = 35
alien_0['my_name'] = 'Mareedu' # adding
alien_0['color'] = 'blue' # modify
del alien_0['my_name']... | alien_0 = {'color': 'green', 'points': '5'}
print(alien_0)
print(alien_0['color'])
new_points = alien_0['points']
print(f'You just earned {new_points} points')
alien_0['x_position'] = 0
alien_0['y_position'] = 35
alien_0['my_name'] = 'Mareedu'
alien_0['color'] = 'blue'
del alien_0['my_name']
print(alien_0)
user_0 = {'u... |
class graph:
def __init__(self):
self.graph={}
self.visited=set()
def dfs(self,node):
if node not in self.visited:
print(node)
self.visited.add(n... | class Graph:
def __init__(self):
self.graph = {}
self.visited = set()
def dfs(self, node):
if node not in self.visited:
print(node)
self.visited.add(node)
for neighbour in self.graph[node]:
self.dfs(neighbour)
def graph_input(sel... |
secret_word = "fart"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Guess a word: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of gu... | secret_word = 'fart'
guess = ''
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and (not out_of_guesses):
if guess_count < guess_limit:
guess = input('Guess a word: ')
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print('Out of gues... |
def transfer_money(from_addr, to_addr, value):
"""
A simple stub to show that money is being transferred
"""
print("Transferring {} UNITS From {} TO {}".format(value, from_addr, to_addr))
| def transfer_money(from_addr, to_addr, value):
"""
A simple stub to show that money is being transferred
"""
print('Transferring {} UNITS From {} TO {}'.format(value, from_addr, to_addr)) |
class payload:
__payload = ''
def __init__(self, version, sender_name, session_id, country_code,
ip_type, domain, ip_address, media_type, protocol_id,
media_transfer_type, protocol, port, modulation_type,
modulation_port, session_name='SESSION SDP'):
s... | class Payload:
__payload = ''
def __init__(self, version, sender_name, session_id, country_code, ip_type, domain, ip_address, media_type, protocol_id, media_transfer_type, protocol, port, modulation_type, modulation_port, session_name='SESSION SDP'):
self.__make_payload(version, sender_name, session_id... |
# Indexing dan subset string di python
a = "Hello, World!"
H = a[0] #dalam python indexing dimulai dari 0
o = a[4]
Hello = a[0:5]
print(Hello)
Hello_ = a[:5]
print(Hello_)
World = a[7:12]
print(World)
World_ = a[-6:-1]
print(World_)
# Merge string
b = "I'm ready for python!"
c = a+b
print(c)
c = a+ " " +b
prin... | a = 'Hello, World!'
h = a[0]
o = a[4]
hello = a[0:5]
print(Hello)
hello_ = a[:5]
print(Hello_)
world = a[7:12]
print(World)
world_ = a[-6:-1]
print(World_)
b = "I'm ready for python!"
c = a + b
print(c)
c = a + ' ' + b
print(c) |
"""
@no 46
@name Permutations
"""
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0:
return []
if len(nums) == 1:
return [[nums[0]]]
ans = []
for i in range(len(nums... | """
@no 46
@name Permutations
"""
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0:
return []
if len(nums) == 1:
return [[nums[0]]]
ans = []
for i in range(len(nu... |
__author__ = 'Owais Lone'
__version__ = '0.6.0'
default_app_config = 'webpack_loader.apps.WebpackLoaderConfig'
| __author__ = 'Owais Lone'
__version__ = '0.6.0'
default_app_config = 'webpack_loader.apps.WebpackLoaderConfig' |
# https://stackoverflow.com/questions/443885/python-callbacks-delegates-what-is-common
# Listeners, callbacks, delegates
class Foo(object):
def __init__(self):
self._bar_observers = []
def add_bar_observer(self, observer):
self._bar_observers.append(observer)
def notify_bar(self, param):... | class Foo(object):
def __init__(self):
self._bar_observers = []
def add_bar_observer(self, observer):
self._bar_observers.append(observer)
def notify_bar(self, param):
for observer in self._bar_observers:
observer(param)
def observer(param):
print('observer(%s)' %... |
for i in range(int(input())):
word=input()
if word==word[::-1]:
print(f"#{i+1} 1")
else :
print(f"#{i+1} 0") | for i in range(int(input())):
word = input()
if word == word[::-1]:
print(f'#{i + 1} 1')
else:
print(f'#{i + 1} 0') |
def teste (b):
a=8
b+=4
c=2
print(f'A dentro vale {a}')
print(f'B dentro vale {b}')
print(f'C dentro vale {c}')
a=5
teste(a)
print(f'A fora vale {a}')
| def teste(b):
a = 8
b += 4
c = 2
print(f'A dentro vale {a}')
print(f'B dentro vale {b}')
print(f'C dentro vale {c}')
a = 5
teste(a)
print(f'A fora vale {a}') |
# This is day22 - works for part 1, minor change needed for day 2
spells = {
"missile": 53, # It instantly does 4 damage.
"drain": 73, # It instantly does 2 damage and heals you for 2 hit points.
"shield": 113, # Effect: 6 turns. While it is active, your armor is increased by 7.
"poison": 173, # Effect... | spells = {'missile': 53, 'drain': 73, 'shield': 113, 'poison': 173, 'recharge': 229}
class Unit:
def __init__(self, hp, attack, armor, mana, effects):
self.hp = hp
self.att = attack
self.arm = armor
self.mana = mana
self.ef = effects
def basic_attack(self, other):
... |
X, Y = [int(x) for x in input().split()]
if 2 * X <= Y <= 4 * X and Y % 2 == 0:
print("Yes")
else:
print("No")
| (x, y) = [int(x) for x in input().split()]
if 2 * X <= Y <= 4 * X and Y % 2 == 0:
print('Yes')
else:
print('No') |
#Empty List to contain user input
UserChoice = []
#Goes through C Branch options
def Cdecision(RootChoice):
opsC = True #variable was global, but made it local due to "UnboundLocalError"
while opsC:
choice = input("You can choose 'c': ")
if choice == "c":
UserChoice.append(choice)
... | user_choice = []
def cdecision(RootChoice):
ops_c = True
while opsC:
choice = input("You can choose 'c': ")
if choice == 'c':
UserChoice.append(choice)
print(UserChoice)
if UserChoice[-1] == 'c':
choice = input("You can choose 'c1': ")
... |
test = { 'name': 'q1a',
'points': 11,
'suites': [ { 'cases': [ { 'code': '>>> '
'round(get_mape(pd.Series(np.linspace(1, '
'3, 4)), '
'pd.Series(np.linspace(1, 1... | test = {'name': 'q1a', 'points': 11, 'suites': [{'cases': [{'code': '>>> round(get_mape(pd.Series(np.linspace(1, 3, 4)), pd.Series(np.linspace(1, 1, 4))),5) == 0.40952\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]} |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
slow, fast = head, head
if not slow and not fast: return True
while fast and ... | class Solution:
def is_palindrome(self, head: ListNode) -> bool:
(slow, fast) = (head, head)
if not slow and (not fast):
return True
while fast and fast.next:
slow = slow.next
fast = fast.next.next
n_head = slow
prev = None
while n... |
#
# PySNMP MIB module NOVELL-IPX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOVELL-IPX-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:14:30 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')
(constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) ... |
# -*- coding: utf-8 -*-
# @Time : 2019-08-06 18:20
# @Author : Kai Zhang
# @Email : kai.zhang@lizhiweike.com
# @File : ex4-circularDeque.py
# @Software: PyCharm
class MyCircularDeque:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the deque to be k.
... | class Mycirculardeque:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the deque to be k.
"""
self.data = []
self.size = k
def insert_front(self, value: int) -> bool:
"""
Adds an item at the front of Deque. Return tru... |
async def issue_opened_event(event, gh, *args, **kwargs):
"""
Whenever an issue is opened, greet the author and say thanks.
"""
url = event.data["issue"]["comments_url"]
author = event.data["issue"]["user"]["login"]
message = f"Thanks for the report @{author}! I will look into it ASAP! (... | async def issue_opened_event(event, gh, *args, **kwargs):
"""
Whenever an issue is opened, greet the author and say thanks.
"""
url = event.data['issue']['comments_url']
author = event.data['issue']['user']['login']
message = f"Thanks for the report @{author}! I will look into it ASAP! (I'm a bo... |
def ShoeStoreThingy(PairOfShoes, PairOfSocks, Money, time):
#shoes#
shoeBuy1 = int(input("How many Pairs of Shoe Would you like to buy, 1 pair of shoes = $800 ??? >>"))
countshoe = PairOfShoes + shoeBuy1
sureshoes = int(input("How Many shoes would you like to remove???, 0 for none >>"))
countshoe =... | def shoe_store_thingy(PairOfShoes, PairOfSocks, Money, time):
shoe_buy1 = int(input('How many Pairs of Shoe Would you like to buy, 1 pair of shoes = $800 ??? >>'))
countshoe = PairOfShoes + shoeBuy1
sureshoes = int(input('How Many shoes would you like to remove???, 0 for none >>'))
countshoe = countshoe... |
FNAME = 'submit'
def main():
output = ''
for p, problem in enumerate(load_input(), 1):
output += 'Case #%d: %s\n' % (p, solve(problem))
with open('%sOutput.txt' % FNAME, 'w', encoding='utf-8') as fp:
fp.write(output)
def load_input():
with open('%sInput.txt' % FNAME, 'r', encoding='utf-8') as fp:
problems =... | fname = 'submit'
def main():
output = ''
for (p, problem) in enumerate(load_input(), 1):
output += 'Case #%d: %s\n' % (p, solve(problem))
with open('%sOutput.txt' % FNAME, 'w', encoding='utf-8') as fp:
fp.write(output)
def load_input():
with open('%sInput.txt' % FNAME, 'r', encoding='u... |
__author__ = 'Matt'
class PathSelection:
def __init__(self):
return
def drawPath(self, canvas, x, y, size):
ARENA_WIDTH = 100
ARENA_HEIGHT = 300
TRANSPORT_WIDTH = 10
TRANSPORT_HEIGHT = 15
EXCAVATOR_WIDTH = 10
EXCAVATOR_HEIGHT = 10
return | __author__ = 'Matt'
class Pathselection:
def __init__(self):
return
def draw_path(self, canvas, x, y, size):
arena_width = 100
arena_height = 300
transport_width = 10
transport_height = 15
excavator_width = 10
excavator_height = 10
return |
"""
Check if Two Rectangles Overlap
Given two rectangles, find if the given two rectangles overlap or not.
Note that a rectangle can be represented by two coordinates, top left and bottom right.
So mainly we are given following four coordinates (min X and Y and max X and Y).
- l1: Bottom Left coordinate of first r... | """
Check if Two Rectangles Overlap
Given two rectangles, find if the given two rectangles overlap or not.
Note that a rectangle can be represented by two coordinates, top left and bottom right.
So mainly we are given following four coordinates (min X and Y and max X and Y).
- l1: Bottom Left coordinate of first r... |
version = '1.6.4'
version_cmd = 'haproxy -v'
depends = ['build-essential', 'libpcre3-dev', 'zlib1g-dev', 'libssl-dev']
download_url = 'http://www.haproxy.org/download/1.6/src/haproxy-VERSION.tar.gz'
upstart = """
start on runlevel [2345]
stop on runlevel [016]
expect fork
pre-start exec haproxy -t
pre-stop exec hapr... | version = '1.6.4'
version_cmd = 'haproxy -v'
depends = ['build-essential', 'libpcre3-dev', 'zlib1g-dev', 'libssl-dev']
download_url = 'http://www.haproxy.org/download/1.6/src/haproxy-VERSION.tar.gz'
upstart = '\nstart on runlevel [2345]\nstop on runlevel [016]\n\nexpect fork\n\npre-start exec haproxy -t\npre-stop exec ... |
"""
.. currentmodule:: cockatoo.exception
.. autosummary::
:nosignatures:
CockatooException
CockatooImportException
RhinoNotPresentError
SystemNotPresentError
NetworkXNotPresentError
NetworkXVersionError
KnitNetworkError
KnitNetworkGeometryError
MappingNetworkError
KnitNetw... | """
.. currentmodule:: cockatoo.exception
.. autosummary::
:nosignatures:
CockatooException
CockatooImportException
RhinoNotPresentError
SystemNotPresentError
NetworkXNotPresentError
NetworkXVersionError
KnitNetworkError
KnitNetworkGeometryError
MappingNetworkError
KnitNetw... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Hao Luo at 2019-06-20
"""io.py
:description : script
:param :
:returns:
:rtype:
"""
def solution2txt(solution,model,outfile):
need_fluxes =solution.fluxes[abs(solution.fluxes)>1e-10]
with open(outfile,'w') as outf:
for need_id in need_flux... | """io.py
:description : script
:param :
:returns:
:rtype:
"""
def solution2txt(solution, model, outfile):
need_fluxes = solution.fluxes[abs(solution.fluxes) > 1e-10]
with open(outfile, 'w') as outf:
for need_id in need_fluxes.index:
rea = model.reactions.get_by_id(need_id)
ou... |
class DBRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'extoon':
return 'extoon'
if model._meta.app_label == 'emmdx':
return 'emmdx'
return 'default'
def db_for_write(self, model, **hints):
if model._meta.app_label == '... | class Dbrouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'extoon':
return 'extoon'
if model._meta.app_label == 'emmdx':
return 'emmdx'
return 'default'
def db_for_write(self, model, **hints):
if model._meta.app_label == ... |
# -*- coding: utf-8 -*-
{
'name': "api_for_download_attachment_directly",
'summary': """ Attachment Download """,
'description': """
Api For Downloading Attachment Directly Without Login Odoo
""",
'author': "Roger",
'website': "http://www.yourcompany.com",
# Categories can be use... | {'name': 'api_for_download_attachment_directly', 'summary': ' Attachment Download ', 'description': '\n Api For Downloading Attachment Directly Without Login Odoo\n ', 'author': 'Roger', 'website': 'http://www.yourcompany.com', 'category': 'Uncategorized', 'version': '0.1', 'depends': ['base'], 'data': ['secu... |
def binary_search(array , target):
first = 0
last = len(array) - 1
while first <= last:
midpoint = (first+last)//2
if array[midpoint] == target:
return midpoint
elif array[midpoint] > target:
last = midpoint - 1
else:
first = ... | def binary_search(array, target):
first = 0
last = len(array) - 1
while first <= last:
midpoint = (first + last) // 2
if array[midpoint] == target:
return midpoint
elif array[midpoint] > target:
last = midpoint - 1
else:
first = midpoint + ... |
class Skill:
def __init__(self):
self.max_cooldown = 0
self.cooldown = 0
self.damage_multiplier = 0
self.damage_cap = 0
self.ally_buffs = []
self.ally_debuffs = []
self.foe_buffs = []
self.foe_debuffs = []
def use(self, attack):
self.coold... | class Skill:
def __init__(self):
self.max_cooldown = 0
self.cooldown = 0
self.damage_multiplier = 0
self.damage_cap = 0
self.ally_buffs = []
self.ally_debuffs = []
self.foe_buffs = []
self.foe_debuffs = []
def use(self, attack):
self.cool... |
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.values = []
self.positions = {} # store corresponding positions of values in set
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set... | class Randomizedset:
def __init__(self):
"""
Initialize your data structure here.
"""
self.values = []
self.positions = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
... |
# Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this par... | def get_permutations(sequence):
"""
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutatio... |
'''
Problem Name: HCF and LCM
Problem Code: FDGHLM
Problem Link: https://www.codechef.com/problems/FDGHLM
Solution Link: https://www.codechef.com/viewsolution/47003480
'''
def gcd(m, n):
if n == 0:
return m
return gcd(n, m%n)
def lcm(m, n):
prod = m*n
return prod//gcd(m, n)
... | """
Problem Name: HCF and LCM
Problem Code: FDGHLM
Problem Link: https://www.codechef.com/problems/FDGHLM
Solution Link: https://www.codechef.com/viewsolution/47003480
"""
def gcd(m, n):
if n == 0:
return m
return gcd(n, m % n)
def lcm(m, n):
prod = m * n
return prod // gcd(m,... |
# -*- coding: utf-8 -*-
"""Algoritmo de Ordenamiento
Se puede definir un algoritmo de ordenamiento de datos
en una lista con estos datos de forma ascendente o
descendente
Recuerda que en Python podemos intercambiar variables
de forma sencilla: a, b = b, a
"""
def bubble_sort(list_data):
# Obtenemos la longitud... | """Algoritmo de Ordenamiento
Se puede definir un algoritmo de ordenamiento de datos
en una lista con estos datos de forma ascendente o
descendente
Recuerda que en Python podemos intercambiar variables
de forma sencilla: a, b = b, a
"""
def bubble_sort(list_data):
list_size = len(list_data)
for i in range(lis... |
# Author: b1tank
# Email: b1tank@outlook.com
#=================================
'''
720_Longest_Word_in_Dictionary on LeetCode
Solution:
- Trie: TrieNode has a value and a hashmap of child nodes
- Depth First Search (DFS) implemented using both stack and recursive
'''
class TrieNode():
... | """
720_Longest_Word_in_Dictionary on LeetCode
Solution:
- Trie: TrieNode has a value and a hashmap of child nodes
- Depth First Search (DFS) implemented using both stack and recursive
"""
class Trienode:
def __init__(self, c):
self.c = c
self.next = {}
class Trie(TrieNode):
def __... |
COLLECTION = "user"
blog_collection = "blogs"
blogs_comments = "comments"
Activities ="requests"
| collection = 'user'
blog_collection = 'blogs'
blogs_comments = 'comments'
activities = 'requests' |
array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
def insertion(array, g):
for i in range(g, len(array)):
v = array[i]
j = i-g
while j >= 0 and array[j] > v:
array[j + g] = array[j]
j = j - g
array[j+g] = v
def shellsort(arra... | array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
def insertion(array, g):
for i in range(g, len(array)):
v = array[i]
j = i - g
while j >= 0 and array[j] > v:
array[j + g] = array[j]
j = j - g
array[j + g] = v
def shellsort(arr... |
class A:
def foo(self):
print('a')
class B:
def foo(self):
print('b')
class C:
def foo(self):
print('c')
class D:
def foo2(self):
print('d')
class E(A, B, C):
def __init__(self):
super()
class F(D, C, B):
def __init__(self):
super()
class G(A, B, C):
def foo(self):
super(G, self).foo()
e = E... | class A:
def foo(self):
print('a')
class B:
def foo(self):
print('b')
class C:
def foo(self):
print('c')
class D:
def foo2(self):
print('d')
class E(A, B, C):
def __init__(self):
super()
class F(D, C, B):
def __init__(self):
super()
cla... |
print("Wellcome to the Multiplication/Exponent Tabel App\n")
name = str(input("What is your name: ")).title()
number = float(input("What number would you like to work with: "))
print(f"\nMultiplication Table For {number}\n")
print(f"\t1.0 * {number} = {number * 1}")
print(f"\t2.0 * {number} = {number * 2}")
print(f"... | print('Wellcome to the Multiplication/Exponent Tabel App\n')
name = str(input('What is your name: ')).title()
number = float(input('What number would you like to work with: '))
print(f'\nMultiplication Table For {number}\n')
print(f'\t1.0 * {number} = {number * 1}')
print(f'\t2.0 * {number} = {number * 2}')
print(f'\t3... |
n = 6
a = [0] * n
result = []
def recur(s, n, was, result):
if len(s) == n:
result.append(s)
return
for i in range(0, n):
if was[i] == 0:
was[i] = 1
recur(s + str(i + 1), n, was, result)
was[i] = 0
recur("", n, a, result)
print(result)
| n = 6
a = [0] * n
result = []
def recur(s, n, was, result):
if len(s) == n:
result.append(s)
return
for i in range(0, n):
if was[i] == 0:
was[i] = 1
recur(s + str(i + 1), n, was, result)
was[i] = 0
recur('', n, a, result)
print(result) |
"""
Function use to convert assembly in graph
"""
def asm2gfa(input_path, output_path, k):
"""
Convert bcalm assemblie in gfa format
"""
with open(input_path) as input_file:
# name stores the id of the unitig
# optional is a list which stores all the optional tags of a segment
... | """
Function use to convert assembly in graph
"""
def asm2gfa(input_path, output_path, k):
"""
Convert bcalm assemblie in gfa format
"""
with open(input_path) as input_file:
name = ''
optional = []
links = []
graph = open(output_path, 'w')
graph.write('H\tVN:Z:1.... |
def calculate_price_change(curr_state: dict, new_state: dict):
curr_price = curr_state["coinbase_btcusd_close"]
next_price = new_state["coinbase_btcusd_close"]
return curr_price - next_price
def buy(curr_state: dict, prev_interps, new_state: dict, new_interps):
return calculate_price_change(curr_state... | def calculate_price_change(curr_state: dict, new_state: dict):
curr_price = curr_state['coinbase_btcusd_close']
next_price = new_state['coinbase_btcusd_close']
return curr_price - next_price
def buy(curr_state: dict, prev_interps, new_state: dict, new_interps):
return calculate_price_change(curr_state=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Artificially cap how fast we can launch our probe.
# Select this value carefully, or else we might lose valid
# shot selections.
MAX_Y_VELOCITY = 1000
def tick(pos, vel):
# On each step, these changes occur in the following order:
#
# The probe's x position increases... | max_y_velocity = 1000
def tick(pos, vel):
pos = (pos[0] + vel[0], pos[1] + vel[1])
if vel[0] > 0:
vel = (vel[0] - 1, vel[1])
elif vel[0] < 0:
vel = (vel[0] + 1, vel[1])
vel = (vel[0], vel[1] - 1)
return (pos, vel)
with open('day17_input.txt') as f:
for line in f:
(x, y) ... |
# -*- coding: utf-8 -*-
class ClassifyBar:
def polarity(self,a,b):
return a <= b
pass
class RetrieveData:
def init():
pass
class FormatData:
def init():
pass
class ConsolidateBar:
def init():
pass
# Test Class for Simple Calculator functi... | class Classifybar:
def polarity(self, a, b):
return a <= b
pass
class Retrievedata:
def init():
pass
class Formatdata:
def init():
pass
class Consolidatebar:
def init():
pass
class Simplecalculator:
def add(self, *args):
return sum(args)
... |
#
# PySNMP MIB module A3COM-HUAWEI-IPV6-ADDRESS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-IPV6-ADDRESS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:05:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... | (h3c_common,) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'h3cCommon')
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_co... |
class Solution(object):
def strStr(self, haystack, needle):
i = 0
j = 0
m = len(needle)
n = len(haystack)
if m ==0:
return 0
while i<n and n-i+1>=m:
if haystack[i] == needle[j]:
temp = i
while j<m and i<n and needle[j]==haystack[i]:
... | class Solution(object):
def str_str(self, haystack, needle):
i = 0
j = 0
m = len(needle)
n = len(haystack)
if m == 0:
return 0
while i < n and n - i + 1 >= m:
if haystack[i] == needle[j]:
temp = i
while j < m an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.