content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Implement an algorithm to find the kth to last element of a singly linked list.
1->3->5->7->9->0
"""
class Node:
def __init__(self, data, next_elem=None):
self.data = data
self.next_elem = next_elem
data = Node(1, Node(3, Node(5, Node(7, Node(9, Node(0))))))
curr = data
while curr is not N... | """
Implement an algorithm to find the kth to last element of a singly linked list.
1->3->5->7->9->0
"""
class Node:
def __init__(self, data, next_elem=None):
self.data = data
self.next_elem = next_elem
data = node(1, node(3, node(5, node(7, node(9, node(0))))))
curr = data
while curr is not None... |
def tram(m, n):
alfabet = "ABCDEFGHIJKLMNOPQRSTUVW"[:m]
przystanki = (alfabet + alfabet[1:-1][::-1]) * 2 * n
rozklad = ""
while przystanki:
curr = przystanki[n - 1]
#print(przystanki[:m * 2], " -- >", curr)
rozklad += curr
przystanki = popall(przystanki[n:], curr)
... | def tram(m, n):
alfabet = 'ABCDEFGHIJKLMNOPQRSTUVW'[:m]
przystanki = (alfabet + alfabet[1:-1][::-1]) * 2 * n
rozklad = ''
while przystanki:
curr = przystanki[n - 1]
rozklad += curr
przystanki = popall(przystanki[n:], curr)
return rozklad
def popall(slowo, x):
ret = ' '
... |
# Path for log. Make sure the files (if present, otherwise the containing directory) are writable by the user that will be running the daemon.
logPath = '/var/log/carillon/carillon.log'
logDebug = False
# Note, you can monitor the log in real time with tail -f [logPath]
# MIDI info
midiPort = 20 #Find with aplaymidi -... | log_path = '/var/log/carillon/carillon.log'
log_debug = False
midi_port = 20
midi_hw_port = 'hw:1'
midi_path = '/path/to/midifiles'
silent_hours = (22, 7)
striking_delay = 3 |
DATA = ''
MODEL_INIT = '$(pwd)/model_init'
MODEL_TRUE = '$(pwd)/model_true'
PRECOND = ''
SPECFEM_DATA = '$(pwd)/specfem2d/DATA'
SPECFEM_BIN = '$(pwd)/../../../specfem2d/bin'
| data = ''
model_init = '$(pwd)/model_init'
model_true = '$(pwd)/model_true'
precond = ''
specfem_data = '$(pwd)/specfem2d/DATA'
specfem_bin = '$(pwd)/../../../specfem2d/bin' |
def example():
return [1721, 979, 366, 299, 675, 1456]
def input_data():
with open( "input.txt" ) as fl:
nums = [ int(i) for i in fl.readlines() ]
return nums
def find_it(nums):
for idx in range(len(nums)):
for idy in range(len(nums))[idx+1:]:
if (nums[idx] + nums[idy] == ... | def example():
return [1721, 979, 366, 299, 675, 1456]
def input_data():
with open('input.txt') as fl:
nums = [int(i) for i in fl.readlines()]
return nums
def find_it(nums):
for idx in range(len(nums)):
for idy in range(len(nums))[idx + 1:]:
if nums[idx] + nums[idy] == 2020... |
# This is for the perso that i yearn
# i shall do a petty iterator
# it shall has a for cicle
# Dictionary
name = {
"Mayra":"love",
"Alejandra":"faith and hope",
"Arauz":" all my life",
"Mejia":"the best in civil engeenering"
}
# for Cicle
for maam in name:
print(f"She is {maam} and for me is {na... | name = {'Mayra': 'love', 'Alejandra': 'faith and hope', 'Arauz': ' all my life', 'Mejia': 'the best in civil engeenering'}
for maam in name:
print(f'She is {maam} and for me is {name[maam]}') |
#!/usr/bin/env python
'''The Goal of this script is to place the data in a
python dictionary of unique results.'''
# To accomplish this parsing we need a XML file that can be
# parsed so do scan your localhost using this command
# nmap -oX test 127.0.0.1
| """The Goal of this script is to place the data in a
python dictionary of unique results.""" |
"""
Write a function that takes in a string of lowercase English-alphabet letters
and returns the index of the string's first non-repeating character.
The first non-repeating character is the first character in a string that
occurs only once.
If the input string doesn't have any non-repeating charact... | """
Write a function that takes in a string of lowercase English-alphabet letters
and returns the index of the string's first non-repeating character.
The first non-repeating character is the first character in a string that
occurs only once.
If the input string doesn't have any non-repeating characte... |
"""
HPC Base image
Contents:
FFTW version 3.3.8
HDF5 version 1.10.6
Mellanox OFED version 5.0-2.1.8.0
NVIDIA HPC SDK version 20.7
OpenMPI version 4.0.4
Python 2 and 3 (upstream)
"""
# pylint: disable=invalid-name, undefined-variable, used-before-assignment
# The NVIDIA HPC SDK End-User License Agreement m... | """
HPC Base image
Contents:
FFTW version 3.3.8
HDF5 version 1.10.6
Mellanox OFED version 5.0-2.1.8.0
NVIDIA HPC SDK version 20.7
OpenMPI version 4.0.4
Python 2 and 3 (upstream)
"""
nvhpc_eula = False
if USERARG.get('nvhpc_eula_accept', False):
nvhpc_eula = True
else:
raise runtime_error('NVIDIA HP... |
"""
Copyright 2020, University Corporation for Atmospheric Research
See LICENSE.txt for details
"""
nlat = 19
nlon = 36
ntime = 10
nchar = 7
slices = ['input{0}.nc'.format(i) for i in range(5)]
scalars = ['scalar{0}'.format(i) for i in range(2)]
chvars = ['char{0}'.format(i) for i in range(1)]
timvars = ['tim{0}'.for... | """
Copyright 2020, University Corporation for Atmospheric Research
See LICENSE.txt for details
"""
nlat = 19
nlon = 36
ntime = 10
nchar = 7
slices = ['input{0}.nc'.format(i) for i in range(5)]
scalars = ['scalar{0}'.format(i) for i in range(2)]
chvars = ['char{0}'.format(i) for i in range(1)]
timvars = ['tim{0}'.forma... |
def main():
sequence = input().split(',')
programs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
program_string = ''.join(programs)
seen = [program_string]
for index in range(1000000000):
for command in sequence:
programs = run_comman... | def main():
sequence = input().split(',')
programs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
program_string = ''.join(programs)
seen = [program_string]
for index in range(1000000000):
for command in sequence:
programs = run_command(program... |
def rec_bin_search(arr, element):
if len(arr) == 0:
return False
else:
mid = len(arr) // 2
if arr[mid] == element:
return True
else:
if element < arr[mid]:
return rec_bin_search(arr[:mid], element)
else:
return... | def rec_bin_search(arr, element):
if len(arr) == 0:
return False
else:
mid = len(arr) // 2
if arr[mid] == element:
return True
elif element < arr[mid]:
return rec_bin_search(arr[:mid], element)
else:
return rec_bin_search(arr[mid + 1:],... |
class Dog:
def bark(self):
print("Bark")
d = Dog()
d.bark()
| class Dog:
def bark(self):
print('Bark')
d = dog()
d.bark() |
"""
Submodules for AST manipulation.
"""
def remove_implications(ast):
"""
@brief Removes implications in an AST.
@param ast The ast
@return another AST
"""
if len(ast) == 3:
op, oper1, oper2 = ast
oper1 = remove_implications(oper1)
oper2 = rem... | """
Submodules for AST manipulation.
"""
def remove_implications(ast):
"""
@brief Removes implications in an AST.
@param ast The ast
@return another AST
"""
if len(ast) == 3:
(op, oper1, oper2) = ast
oper1 = remove_implications(oper1)
oper2 = re... |
class ModelDot:
"""The ModelDot object can be used to access an actual MeshNode, ReferencePoint, or ConstrainedSketchVertex
object.
Notes
-----
This object can be accessed by:
"""
pass
| class Modeldot:
"""The ModelDot object can be used to access an actual MeshNode, ReferencePoint, or ConstrainedSketchVertex
object.
Notes
-----
This object can be accessed by:
"""
pass |
LONG_BLOG_POST = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget nibh ac purus euismod pharetra nec ac justo. Suspendisse fringilla tellus ipsum, quis vulputate leo eleifend pellentesque. Vivamus rhoncus augue justo, elementum commodo urna egestas in. Maecenas fermentum et orci sit amet egesta... | long_blog_post = '\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget nibh ac purus euismod pharetra nec ac justo. Suspendisse fringilla tellus ipsum, quis vulputate leo eleifend pellentesque. Vivamus rhoncus augue justo, elementum commodo urna egestas in. Maecenas fermentum et orci sit amet egestas... |
"""Example of Counting Permutations with Recursive Factorial Functions"""
# Data
n = 5
# The One-Liner
factorial = lambda n: n * factorial(n-1) if n > 1 else 1
# The Result
print(factorial(n)) | """Example of Counting Permutations with Recursive Factorial Functions"""
n = 5
factorial = lambda n: n * factorial(n - 1) if n > 1 else 1
print(factorial(n)) |
[
alg.createtemp (
"revenue",
alg.aggregation (
"l_suppkey",
[ ( Reduction.SUM, "revenue", "sum_revenue" ) ],
alg.map (
"revenue",
scal.MulExpr (
scal.AttrExpr ( "l_extendedprice" ),
scal.SubExpr (
scal.Const... | [alg.createtemp('revenue', alg.aggregation('l_suppkey', [(Reduction.SUM, 'revenue', 'sum_revenue')], alg.map('revenue', scal.MulExpr(scal.AttrExpr('l_extendedprice'), scal.SubExpr(scal.ConstExpr('1.0', Type.FLOAT), scal.AttrExpr('l_discount'))), alg.selection(scal.AndExpr(scal.LargerEqualExpr(scal.AttrExpr('l_shipdate'... |
#!/usr/bin/env python
__all__ = [
"osutils",
]
| __all__ = ['osutils'] |
def searchInsert(self, nums, target):
start = 0
end = len(nums) - 1
while start <= end:
middle = (start + end) // 2
if nums[middle] == target:
return middle
elif target > nums[middle]:
start = ... | def search_insert(self, nums, target):
start = 0
end = len(nums) - 1
while start <= end:
middle = (start + end) // 2
if nums[middle] == target:
return middle
elif target > nums[middle]:
start = middle + 1
elif target < nums[middle]:
end = m... |
#!/usr/bin/python3
RYD_TO_EV = 13.6056980659
class EnergyVals():
def __init__(self, **kwargs):
kwargs = {k.lower():v for k,v in kwargs.items()}
self._eqTol = 1e-5
self._e0Tot = kwargs.get("e0tot", None)
self._e0Coh = kwargs.get("e0coh", None)
self.e1 = kwargs.get("e1", None)
self.e2 = kwargs.get("e2", N... | ryd_to_ev = 13.6056980659
class Energyvals:
def __init__(self, **kwargs):
kwargs = {k.lower(): v for (k, v) in kwargs.items()}
self._eqTol = 1e-05
self._e0Tot = kwargs.get('e0tot', None)
self._e0Coh = kwargs.get('e0coh', None)
self.e1 = kwargs.get('e1', None)
self.e... |
f = open("input1.txt").readlines()
count = 0
for i in range(1,len(f)):
if int(f[i-1])<int(f[i]):
count+=1
print(count)
count = 0
for i in range(3,len(f)):
if int(f[i-3])<int(f[i]):
count+=1
print(count)
| f = open('input1.txt').readlines()
count = 0
for i in range(1, len(f)):
if int(f[i - 1]) < int(f[i]):
count += 1
print(count)
count = 0
for i in range(3, len(f)):
if int(f[i - 3]) < int(f[i]):
count += 1
print(count) |
_base_ = "soft_teacher_faster_rcnn_r50_caffe_fpn_coco_full_720k.py"
lr_config = dict(step=[120000 * 8, 160000 * 8])
runner = dict(_delete_=True, type="IterBasedRunner", max_iters=180000 * 8)
| _base_ = 'soft_teacher_faster_rcnn_r50_caffe_fpn_coco_full_720k.py'
lr_config = dict(step=[120000 * 8, 160000 * 8])
runner = dict(_delete_=True, type='IterBasedRunner', max_iters=180000 * 8) |
# melhora a performace do codigo
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ex1 = [variavel for variavel in l1]
ex2 = [v * 2 for v in l1] # multiplica cado elemento da lista 1 por 2
ex3 = [(v, v2) for v in l1 for v2 in range(3)]
print(ex3)
l2 = ['pedro', 'mauro', 'maria']
ex4 = [v.replace('a', '@').upper() for v in l2] # m... | l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ex1 = [variavel for variavel in l1]
ex2 = [v * 2 for v in l1]
ex3 = [(v, v2) for v in l1 for v2 in range(3)]
print(ex3)
l2 = ['pedro', 'mauro', 'maria']
ex4 = [v.replace('a', '@').upper() for v in l2]
print(ex4)
tupla = (('chave1', 'valor1'), ('chave2', 'valor2'))
ex5 = [(y, x) for (x, ... |
""" This module contains the functions to compare MISRA rules """
def misra_c2004_compare(rule):
""" compare misra C2004 rules """
return int(rule.split('.')[0])*100 + int(rule.split('.')[1])
def misra_c2012_compare(rule):
""" compare misra C2012 rules """
return int(rule.split('.')[0])*100 + int(r... | """ This module contains the functions to compare MISRA rules """
def misra_c2004_compare(rule):
""" compare misra C2004 rules """
return int(rule.split('.')[0]) * 100 + int(rule.split('.')[1])
def misra_c2012_compare(rule):
""" compare misra C2012 rules """
return int(rule.split('.')[0]) * 100 + int(... |
# defines a function that takes two arguments
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# prints a string with the first argument passed into the function inserted into the output
print(f"You have {cheese_count} cheeses!")
# prints a string with the second argument passed into the function i... | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f'You have {cheese_count} cheeses!')
print(f'You have {boxes_of_crackers} boxes of crackers!')
print("Man that's enough for a party!")
print('Get a blanket.\n')
print('We can just give the function numbers directly:')
cheese_and_crackers(20... |
def selection_sort(arr):
for i in range(len(arr)):
min = i # index of min elem
for j in range(i+1,len(arr)):
# arr[j] is smaller than the min elem
if arr[j] < arr[min]:
min = j
arr[i],arr[min] = arr[min],arr[i] # swap
# print... | def selection_sort(arr):
for i in range(len(arr)):
min = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min]:
min = j
(arr[i], arr[min]) = (arr[min], arr[i])
return arr |
class System_Status():
def __init__(self, plant_state=None):
if plant_state is None:
plant_state = [1, 1, 1]
self.plant_state = plant_state
def __str__(self):
return f"El estado de la planta es {self.plant_state}" | class System_Status:
def __init__(self, plant_state=None):
if plant_state is None:
plant_state = [1, 1, 1]
self.plant_state = plant_state
def __str__(self):
return f'El estado de la planta es {self.plant_state}' |
class IPVerify:
def __init__(self):
super(IPVerify, self).__init__()
# self.octetLst = []
# self.subnetMaskLst = []
# def __initializeIP(self, ip: str):
# self.octetLst.clear()
# [self.octetLst.append(i) for i in ip.split(".")]
# return self.octetLst
... | class Ipverify:
def __init__(self):
super(IPVerify, self).__init__()
def __initialize_ip(self, ip: str):
lst = []
[lst.append(i) for i in ip.split('.')]
if len(lst[0]) == 8:
lst = self.__binInput(lst)
return lst
@staticmethod
def __bin_input(lst):
... |
NODE_LIST = [
{
'name': 'syslog_source',
'type': 'syslog_file_monitor',
'outputs': [
'filter',
],
'params': {
'filename': 'testlog1.log',
}
},
{
'name': 'filter',
'type': 'rx_grouper',
'params': {
'gr... | node_list = [{'name': 'syslog_source', 'type': 'syslog_file_monitor', 'outputs': ['filter'], 'params': {'filename': 'testlog1.log'}}, {'name': 'filter', 'type': 'rx_grouper', 'params': {'groups': {'imap_auth': {'rx_list': ['.*hint.*', ('host', 'publicapi1')], 'outputs': ['writer']}}}}, {'name': 'writer', 'type': 'conso... |
def Convert(number,mode):
if mode.startswith("mili") and mode.endswith("meter") == True:
Milimeter = number
Centimeter = number / 10
Meter = Centimeter / 100
Kilometer = Meter / 1000
Result1 = f"Milimeters : {Milimeter}"
Result2 =f"Centimeters : {Centimeter}"... | def convert(number, mode):
if mode.startswith('mili') and mode.endswith('meter') == True:
milimeter = number
centimeter = number / 10
meter = Centimeter / 100
kilometer = Meter / 1000
result1 = f'Milimeters : {Milimeter}'
result2 = f'Centimeters : {Centimeter}'
... |
pt = int(input('digite o primeiro termo da PA '))
r = int(input('digite a razao '))
termos = 1
total=0
total2=0
contador = 10
print('{} -> '.format(pt),end='')
while contador > 1 :
if contador == 10:
total=pt+r
print('{} -> '.format(total),end='')
contador=contador-1
else:
total= total+r
pr... | pt = int(input('digite o primeiro termo da PA '))
r = int(input('digite a razao '))
termos = 1
total = 0
total2 = 0
contador = 10
print('{} -> '.format(pt), end='')
while contador > 1:
if contador == 10:
total = pt + r
print('{} -> '.format(total), end='')
contador = contador - 1
else:
... |
def analysis(sliceno, job):
job.save('this_is_the_data_analysis ' + str(sliceno), 'myfile1', sliceno=sliceno)
def synthesis(job):
job.save('this_is_the_data_2', 'myfile2')
| def analysis(sliceno, job):
job.save('this_is_the_data_analysis ' + str(sliceno), 'myfile1', sliceno=sliceno)
def synthesis(job):
job.save('this_is_the_data_2', 'myfile2') |
"""Common configuration constants
"""
PROJECTNAME = 'rendereasy.cnawhatsapp'
ADD_PERMISSIONS = {
# -*- extra stuff goes here -*-
'Envio': 'rendereasy.cnawhatsapp: Add Envio',
'Grupo': 'rendereasy.cnawhatsapp: Add Grupo',
}
| """Common configuration constants
"""
projectname = 'rendereasy.cnawhatsapp'
add_permissions = {'Envio': 'rendereasy.cnawhatsapp: Add Envio', 'Grupo': 'rendereasy.cnawhatsapp: Add Grupo'} |
class IIIF_Photo(object):
def __init__(self, iiif, country):
self.iiif = iiif
self.country = country
def get_photo_link(self):
return self.iiif["images"][0]["resource"]["@id"]
| class Iiif_Photo(object):
def __init__(self, iiif, country):
self.iiif = iiif
self.country = country
def get_photo_link(self):
return self.iiif['images'][0]['resource']['@id'] |
birth_year = input('Birth year: ')
print(type(birth_year))
age = 2019 - int(birth_year)
print(type(age))
print(age)
#exercise
weight_in_lbs = input('What is your weight (in pounds)? ')
weight_in_kg = float(weight_in_lbs) * 0.454
print('Your weight is (in kg): ' + str(weight_in_kg))
| birth_year = input('Birth year: ')
print(type(birth_year))
age = 2019 - int(birth_year)
print(type(age))
print(age)
weight_in_lbs = input('What is your weight (in pounds)? ')
weight_in_kg = float(weight_in_lbs) * 0.454
print('Your weight is (in kg): ' + str(weight_in_kg)) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Michael Eaton <meaton@iforium.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
ANSIBLE_METADATA = {'metadata... | ansible_metadata = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'}
documentation = "\n---\nmodule: win_firewall\nversion_added: '2.4'\nshort_description: Enable or disable the Windows Firewall\ndescription:\n- Enable or Disable Windows Firewall profiles.\nrequirements:\n - This module r... |
{
'targets': [
{
'target_name': 'pointer',
'sources': ['pointer.cc'],
'include_dirs': ['<!(node -e \'require("nan")\')'],
'link_settings': {
'libraries': [
'-lX11',
]
},
'cflags': [
... | {'targets': [{'target_name': 'pointer', 'sources': ['pointer.cc'], 'include_dirs': ['<!(node -e \'require("nan")\')'], 'link_settings': {'libraries': ['-lX11']}, 'cflags': []}]} |
#
# PySNMP MIB module CLEARTRAC7-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CLEARTRAC7-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:09:07 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, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_range_constraint, value_size_constraint) ... |
# Author: Stephen Mugisha
# FSM exceptions
class InitializationError(Exception):
"""
State Machine InitializationError
exception raised.
"""
def __init__(self, message, payload=None):
self.message = message
self.payload = payload #more exception args
... | class Initializationerror(Exception):
"""
State Machine InitializationError
exception raised.
"""
def __init__(self, message, payload=None):
self.message = message
self.payload = payload
def __str__(self):
return str(self.message) |
def generate_associated_dt_annotation(
associations, orig_col, primary_time=False, description="", qualifies=None
):
"""if associated with another col through dt also annotate that col"""
cols = [associations[x] for x in associations.keys() if x.find("_format") == -1]
entry = {}
for col in cols:
... | def generate_associated_dt_annotation(associations, orig_col, primary_time=False, description='', qualifies=None):
"""if associated with another col through dt also annotate that col"""
cols = [associations[x] for x in associations.keys() if x.find('_format') == -1]
entry = {}
for col in cols:
f... |
# -*- coding: utf-8 -*-
print ("Hello World!")
print ("Hello Again")
print ("I like Typing this.")
print ("This is fun.")
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.') | print('Hello World!')
print('Hello Again')
print('I like Typing this.')
print('This is fun.')
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.') |
#!/usr/bin/env python
polyCorners = 4
poly_1_x = [22.017965, 22.017852, 22.016992, 22.017187]
poly_1_y = [85.432761, 85.433074, 85.432577, 85.432243]
poly_2_x = [22.017187, 22.016992, 22.015849, 22.015982]
poly_2_y = [85.432243, 85.432577, 85.431865, 85.431574]
poly_3_x = [22.015850, 22.015636, 22.015874, 22.016053]... | poly_corners = 4
poly_1_x = [22.017965, 22.017852, 22.016992, 22.017187]
poly_1_y = [85.432761, 85.433074, 85.432577, 85.432243]
poly_2_x = [22.017187, 22.016992, 22.015849, 22.015982]
poly_2_y = [85.432243, 85.432577, 85.431865, 85.431574]
poly_3_x = [22.01585, 22.015636, 22.015874, 22.016053]
poly_3_y = [85.431406, 8... |
print (True and True)
print (True and False)
print (False and True)
print (False and False)
print (True or True)
print (True or False)
print (False or True)
print (False or False)
| print(True and True)
print(True and False)
print(False and True)
print(False and False)
print(True or True)
print(True or False)
print(False or True)
print(False or False) |
#!/usr/bin/env python3
print("hello")
f = open('python file.txt', 'a+')
f.write("Hello")
f.close() | print('hello')
f = open('python file.txt', 'a+')
f.write('Hello')
f.close() |
class Person(dict):
def __init__(self, person_id, sex, phenotype, studies):
self.person_id = str(person_id)
self.sex = sex
self.phenotype = phenotype
self.studies = studies
def __repr__(self):
return f'Person("{self.person_id}", "{self.sex}", {self.phenotype}, ... | class Person(dict):
def __init__(self, person_id, sex, phenotype, studies):
self.person_id = str(person_id)
self.sex = sex
self.phenotype = phenotype
self.studies = studies
def __repr__(self):
return f'Person("{self.person_id}", "{self.sex}", {self.phenotype}, {self.stu... |
""" A file designed to have lines of similarity when compared to similar_lines_b
We use lorm-ipsum to generate 'random' code. """
# Copyright (c) 2020 Frank Harrison <frank@doublethefish.com>
def adipiscing(elit):
etiam = "id"
dictum = "purus,"
vitae = "pretium"
neque = "Vivamus"
nec = "ornare"
... | """ A file designed to have lines of similarity when compared to similar_lines_b
We use lorm-ipsum to generate 'random' code. """
def adipiscing(elit):
etiam = 'id'
dictum = 'purus,'
vitae = 'pretium'
neque = 'Vivamus'
nec = 'ornare'
tortor = 'sit'
return (etiam, dictum, vitae, neque, nec,... |
"""
Configuration variables
"""
start_test_items_map = {
'first': 0,
'second': 1,
'third': 2,
'fourth': 3,
'fifth': 4,
'sixth': 5,
'seventh': 6,
'eighth': 7,
'ninth': 8,
'tenth': 9,
}
end_test_items_map = {
'tenth_to_last': 0,
'ninth_to_last': 1,
'eighth_to_last': 2... | """
Configuration variables
"""
start_test_items_map = {'first': 0, 'second': 1, 'third': 2, 'fourth': 3, 'fifth': 4, 'sixth': 5, 'seventh': 6, 'eighth': 7, 'ninth': 8, 'tenth': 9}
end_test_items_map = {'tenth_to_last': 0, 'ninth_to_last': 1, 'eighth_to_last': 2, 'seventh_to_last': 3, 'sixth_to_last': 4, 'fifth_to_last... |
A,B = map(int,input().split())
if A >= 13:
print(B)
elif A >= 6:
print(B//2)
else:
print(0)
| (a, b) = map(int, input().split())
if A >= 13:
print(B)
elif A >= 6:
print(B // 2)
else:
print(0) |
#SQL Server details
SQL_HOST = 'localhost'
SQL_USERNAME = 'root'
SQL_PASSWORD = ''
#Cache details - whether to call a URL once an ingestion script is finished
RESET_CACHE = False
RESET_CACHE_URL = 'http://example.com/visualization_reload/'
#Fab - configuration for deploying to a remote server
FAB_HOSTS = []
FAB_GITHUB_... | sql_host = 'localhost'
sql_username = 'root'
sql_password = ''
reset_cache = False
reset_cache_url = 'http://example.com/visualization_reload/'
fab_hosts = []
fab_github_url = 'https://github.com/UQ-UQx/injestor.git'
fab_remote_path = '/file/to/your/deployment/location'
ignore_services = ['extractsample', 'personcourse... |
__description__ = 'Wordpress Two-Factor Authentication Brute-forcer'
__title__ = 'WPBiff'
__version_info__ = ('0', '1', '1')
__version__ = '.'.join(__version_info__)
__author__ = 'Gabor Szathmari'
__credits__ = ['Gabor Szathmari']
__maintainer__ = 'Gabor Szathmari'
__email__ = 'gszathmari@gmail.com'
__status__ = 'beta'... | __description__ = 'Wordpress Two-Factor Authentication Brute-forcer'
__title__ = 'WPBiff'
__version_info__ = ('0', '1', '1')
__version__ = '.'.join(__version_info__)
__author__ = 'Gabor Szathmari'
__credits__ = ['Gabor Szathmari']
__maintainer__ = 'Gabor Szathmari'
__email__ = 'gszathmari@gmail.com'
__status__ = 'beta'... |
"""
Link:
Language: Python
Written by: Mostofa Adib Shakib
Time complexity: O(n)
Space Complexity: O(1)
"""
T = int(input())
for x in range(1, T + 1):
N, M, Q = map(int, input().split())
min1 = (M-Q) + (N-Q+1) + (M-1)
min2 = (M-1) + 1 + N
y = min(min1, min2)
print("Case #{}: {}".f... | """
Link:
Language: Python
Written by: Mostofa Adib Shakib
Time complexity: O(n)
Space Complexity: O(1)
"""
t = int(input())
for x in range(1, T + 1):
(n, m, q) = map(int, input().split())
min1 = M - Q + (N - Q + 1) + (M - 1)
min2 = M - 1 + 1 + N
y = min(min1, min2)
print('Case #{}: {}'.format(x, ... |
N = int(input())
NG = set([int(input()) for _ in range(3)])
if N in NG:
print("NO")
exit(0)
for _ in range(100):
if 0 <= N <= 3:
print("YES")
break
if N - 3 not in NG:
N -= 3
elif N - 2 not in NG:
N -= 2
elif N - 1 not in NG:
N -= 1
else:
print("NO")
| n = int(input())
ng = set([int(input()) for _ in range(3)])
if N in NG:
print('NO')
exit(0)
for _ in range(100):
if 0 <= N <= 3:
print('YES')
break
if N - 3 not in NG:
n -= 3
elif N - 2 not in NG:
n -= 2
elif N - 1 not in NG:
n -= 1
else:
print('NO') |
def master_plan():
yield from bps.mvr(giantxy.x,x_range/2)
yield from bps.mvr(giantxy.y,y_range/2)
for _ in range(6):
yield from bps.mvr(giantxy.x,-x_range)
yield from bps.mvr(giantxy.y,-1)
yield from bps.mvr(giantxy.x,+x_range)
yield from bps.mvr(giantxy.y,-1)
yield from... | def master_plan():
yield from bps.mvr(giantxy.x, x_range / 2)
yield from bps.mvr(giantxy.y, y_range / 2)
for _ in range(6):
yield from bps.mvr(giantxy.x, -x_range)
yield from bps.mvr(giantxy.y, -1)
yield from bps.mvr(giantxy.x, +x_range)
yield from bps.mvr(giantxy.y, -1)
... |
def extractAquaScans(item):
"""
"""
if 'Manga' in item['tags']:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
bad_tags = [
'Majo no Shinzou',
'Kanata no Togabito ga Tatakau Riyuu',
... | def extract_aqua_scans(item):
"""
"""
if 'Manga' in item['tags']:
return None
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
bad_tags = ['Majo no Shinzou', 'Kanata no Tog... |
number =int(raw_input("enter number:"))
word =str(raw_input("enter word:"))
if number == 0 or number > 1:
print ("%s %ss." % (number,word))
else:
print("%s %s." % (number,word))
if word[-3:] == "ife":
print( word[:-3] + "ives")
elif word[-2:] == "sh":
print(word[:-2] + "shes" )
elif word[-2:] == "ch... | number = int(raw_input('enter number:'))
word = str(raw_input('enter word:'))
if number == 0 or number > 1:
print('%s %ss.' % (number, word))
else:
print('%s %s.' % (number, word))
if word[-3:] == 'ife':
print(word[:-3] + 'ives')
elif word[-2:] == 'sh':
print(word[:-2] + 'shes')
elif word[-2:] == 'ch':
... |
FIELDS_EN = {
'title': lambda **kwargs: ' renamed project from "{from}" to "{to}"'.format(**kwargs),
'short': lambda **kwargs: ' changed short name of project from "{from}" to "{to}"'.format(**kwargs),
'description': lambda **kwargs: ' changed description of project from "{from}" to "{to}"'.format(**kwargs)... | fields_en = {'title': lambda **kwargs: ' renamed project from "{from}" to "{to}"'.format(**kwargs), 'short': lambda **kwargs: ' changed short name of project from "{from}" to "{to}"'.format(**kwargs), 'description': lambda **kwargs: ' changed description of project from "{from}" to "{to}"'.format(**kwargs), 'creator': ... |
# -*- coding: utf-8 -*-
class PeekableGenerator(object):
def __init__(self, generator):
self.__generator = generator
self.__element = None
self.__isset = False
self.__more = False
try:
self.__element = generator.next()
self.__more = True
... | class Peekablegenerator(object):
def __init__(self, generator):
self.__generator = generator
self.__element = None
self.__isset = False
self.__more = False
try:
self.__element = generator.next()
self.__more = True
self.__isset = True
... |
def get_member_guaranteed(ctx, lookup):
if len(ctx.message.mentions) > 0:
return ctx.message.mentions[0]
if lookup.isdigit():
result = ctx.guild.get_member(int(lookup))
if result:
return result
if "#" in lookup:
result = ctx.guild.get_member_named(lookup)
... | def get_member_guaranteed(ctx, lookup):
if len(ctx.message.mentions) > 0:
return ctx.message.mentions[0]
if lookup.isdigit():
result = ctx.guild.get_member(int(lookup))
if result:
return result
if '#' in lookup:
result = ctx.guild.get_member_named(lookup)
... |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_t_dic = {}
t_s_dic = {}
n = len(s)
for i in range(n):
if (s[i] not in s_t_dic) and (t[i] not in t_s_dic):
s_t_dic[s[i]] = t[i]
... | class Solution:
def is_isomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_t_dic = {}
t_s_dic = {}
n = len(s)
for i in range(n):
if s[i] not in s_t_dic and t[i] not in t_s_dic:
s_t_dic[s[i]] = t[i]
... |
class RandomListNode():
def __init__(self, x: int):
self.label = x
self.next = None
self.random = None
class Solution():
def copy_random_list(self, root: RandomListNode) -> RandomListNode:
head = None
if root is not None:
pointers = {}
new_root =... | class Randomlistnode:
def __init__(self, x: int):
self.label = x
self.next = None
self.random = None
class Solution:
def copy_random_list(self, root: RandomListNode) -> RandomListNode:
head = None
if root is not None:
pointers = {}
new_root = ra... |
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# These devices are ina3221 (3-channels/i2c address) devices
inas = [('0x40:0', 'pp3300_edp_dx', 3.30, 0.020, 'rem', True), #R367
('0x40:1', '... | inas = [('0x40:0', 'pp3300_edp_dx', 3.3, 0.02, 'rem', True), ('0x40:1', 'pp3300_a', 3.3, 0.002, 'rem', True), ('0x40:2', 'pp1800_a', 1.8, 0.02, 'rem', True), ('0x41:0', 'pp1240_a', 1.24, 0.02, 'rem', True), ('0x41:1', 'pp1800_dram_u', 1.8, 0.02, 'rem', True), ('0x41:2', 'pp1050_s', 1.05, 0.01, 'rem', True), ('0x42:0', ... |
class _PortfolioMemberships:
"""This object determines if a user is a member of a portfolio.
"""
def __init__(self, client=None):
self.client = client
def find_all(self, params={}, **options):
"""Returns the compact portfolio membership records for the portfolio. You must
s... | class _Portfoliomemberships:
"""This object determines if a user is a member of a portfolio.
"""
def __init__(self, client=None):
self.client = client
def find_all(self, params={}, **options):
"""Returns the compact portfolio membership records for the portfolio. You must
speci... |
n = int(input())
lst = []
for _ in range(n):
a, b = [int(i) for i in input().split()]
lst.append((a,b))
lst.sort(key = lambda x: x[1])
index = 0
coordinates = []
while index < n:
curr = lst[index]
while index < n-1 and curr[1]>=lst[index+1][0]:
index += 1
coordinates.append(curr[1])
... | n = int(input())
lst = []
for _ in range(n):
(a, b) = [int(i) for i in input().split()]
lst.append((a, b))
lst.sort(key=lambda x: x[1])
index = 0
coordinates = []
while index < n:
curr = lst[index]
while index < n - 1 and curr[1] >= lst[index + 1][0]:
index += 1
coordinates.append(curr[1])
... |
# -*- coding: utf-8 -*-
class Solution:
def numDifferentIntegers(self, word: str) -> int:
result = set()
number = None
for char in word:
if char.isdigit() and number is None:
number = int(char)
elif char.isdigit() and number is not None:
... | class Solution:
def num_different_integers(self, word: str) -> int:
result = set()
number = None
for char in word:
if char.isdigit() and number is None:
number = int(char)
elif char.isdigit() and number is not None:
number = 10 * numbe... |
def fibo(n):
return n if n <= 1 else (fibo(n-1) + fibo(n-2))
nums = [1,2,3,4,5,6]
[fibo(x) for x in nums]
# [1, 1, 2 ,3 ,5, 8]
[y for x in nums if (y:= fibo(x)) % 2 == 0]
# [2, 8]
| def fibo(n):
return n if n <= 1 else fibo(n - 1) + fibo(n - 2)
nums = [1, 2, 3, 4, 5, 6]
[fibo(x) for x in nums]
[y for x in nums if (y := fibo(x)) % 2 == 0] |
#!/usr/bin/env python
# encoding: utf-8
name = "Singlet_Carbene_Intra_Disproportionation/rules"
shortDesc = u"Convert a singlet carbene to a closed-shell molecule through a concerted 1,2-H shift + 1,2-bond formation"
longDesc = u"""
Reaction site *1 should always be a singlet in this family.
"""
| name = 'Singlet_Carbene_Intra_Disproportionation/rules'
short_desc = u'Convert a singlet carbene to a closed-shell molecule through a concerted 1,2-H shift + 1,2-bond formation'
long_desc = u'\nReaction site *1 should always be a singlet in this family.\n' |
BUTTON_LEFT = 0
BUTTON_MIDDLE = 1
BUTTON_RIGHT = 2
| button_left = 0
button_middle = 1
button_right = 2 |
def main():
file_log = open("hostapd.log",'r').read()
address = file_log.find("AP-STA-CONNECTED")
mac = set()
while address >= 0:
mac.add(file_log[address+17:address+34])
address=file_log.find("AP-STA-CONNECTED",address+1)
for addr in mac:
print(addr)
# For ... | def main():
file_log = open('hostapd.log', 'r').read()
address = file_log.find('AP-STA-CONNECTED')
mac = set()
while address >= 0:
mac.add(file_log[address + 17:address + 34])
address = file_log.find('AP-STA-CONNECTED', address + 1)
for addr in mac:
print(addr)
if __name__ ==... |
COURSE = "Python for Everybody"
def which_course_is_this():
print("The course is:", COURSE)
| course = 'Python for Everybody'
def which_course_is_this():
print('The course is:', COURSE) |
DATASOURCE_NAME = "Coderepos"
GITHUB_DATASOURCE_NAME = "github"
| datasource_name = 'Coderepos'
github_datasource_name = 'github' |
def readDataIntoMatrix(fileName):
f = open(fileName, 'r')
i = 0
data = []
for line in f.readlines():
j = 0
row = []
values = line.split()
for value in values:
row.append(int(value))
j += 1
data.append(row)
i += 1
return data | def read_data_into_matrix(fileName):
f = open(fileName, 'r')
i = 0
data = []
for line in f.readlines():
j = 0
row = []
values = line.split()
for value in values:
row.append(int(value))
j += 1
data.append(row)
i += 1
return data |
# -*- coding: UTF-8 -*-
logger.info("Loading 2 objects to table invoicing_tariff...")
# fields: id, designation, number_of_events, min_asset, max_asset
loader.save(create_invoicing_tariff(1,['By presence', 'Pro Anwesenheit', 'By presence'],1,None,None))
loader.save(create_invoicing_tariff(2,['Maximum 10', 'Maximum 10',... | logger.info('Loading 2 objects to table invoicing_tariff...')
loader.save(create_invoicing_tariff(1, ['By presence', 'Pro Anwesenheit', 'By presence'], 1, None, None))
loader.save(create_invoicing_tariff(2, ['Maximum 10', 'Maximum 10', 'Maximum 10'], 1, None, 10))
loader.flush_deferred_objects() |
#!/usr/bin/env python3
# Write a program that computes the GC% of a DNA sequence
# Format the output for 2 decimal places
# Use all three formatting methods
print('Method 1: printf()')
seq = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change
gc_count = 0
for i in range(0, len(seq)):
if seq[i] == 'G' or seq[i]... | print('Method 1: printf()')
seq = 'ACAGAGCCAGCAGATATACAGCAGATACTAT'
gc_count = 0
for i in range(0, len(seq)):
if seq[i] == 'G' or seq[i] == 'C':
gc_count += 1
print('%.2f' % (gc_count / len(seq)))
print('-----')
print('Method 2: str.format()')
gc_count = 0
for i in range(0, len(seq)):
if seq[i] == 'G' o... |
'''
solve amazing problem:
Given a 2D array of mines, replace the question mark with the number of mines that immediately surround it.
This includes the diagonals, meaning it is possible for it to be surrounded by 8 mines maximum.
The key is as follows:
An empty space: "-"
A mine: "#"
Number showing number of mines... | """
solve amazing problem:
Given a 2D array of mines, replace the question mark with the number of mines that immediately surround it.
This includes the diagonals, meaning it is possible for it to be surrounded by 8 mines maximum.
The key is as follows:
An empty space: "-"
A mine: "#"
Number showing number of mines... |
#when many condition fullfil use all.
subs = 1000
likes = 400
comments = 500
condition = [subs>150,likes>150,comments>50]
if all(condition):
print('Great Content') | subs = 1000
likes = 400
comments = 500
condition = [subs > 150, likes > 150, comments > 50]
if all(condition):
print('Great Content') |
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
tmp = nums1 + nums2
tmp.sort()
if len(tmp)%2 == 0:
# print(tmp[len(tmp)//2 - 1] + tmp[len(tmp)//2] / 2)
... | class Solution:
def find_median_sorted_arrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
tmp = nums1 + nums2
tmp.sort()
if len(tmp) % 2 == 0:
return (tmp[len(tmp) // 2 - 1] + tmp[len(tmp) // 2]... |
def write_to(filename:str,text:str):
with open(f'{filename}.txt','w') as file1:
file1.write(text)
write_to('players','zarinaemirbaizak')
| def write_to(filename: str, text: str):
with open(f'{filename}.txt', 'w') as file1:
file1.write(text)
write_to('players', 'zarinaemirbaizak') |
def main():
# input
S = input()
N, M = map(int, input().split())
# compute
# output
print(S[:N-1] + S[M-1] + S[N:M-1] + S[N-1] + S[M:])
if __name__ == '__main__':
main()
| def main():
s = input()
(n, m) = map(int, input().split())
print(S[:N - 1] + S[M - 1] + S[N:M - 1] + S[N - 1] + S[M:])
if __name__ == '__main__':
main() |
class PropertyMonitor(object):
__slots__ = (
'_lock', # concurrency control
'_state', # currently active state
'_pool', # MsgRecord deque to hold temporary records
'witness', # MsgRecord list of observed events
'on_enter_scope', # callback upo... | class Propertymonitor(object):
__slots__ = ('_lock', '_state', '_pool', 'witness', 'on_enter_scope', 'on_exit_scope', 'on_violation', 'on_success', 'time_launch', 'time_shutdown', 'time_state', 'cb_map')
prop_id = 'None'
prop_title = 'None'
prop_desc = 'None'
hpl_property = 'globally: /a { True } fo... |
le = 0
notas = 0
while le != 2:
n = float(input())
if 0 <= n <= 10:
notas = notas+n
le += 1
else:
print('nota invalida')
print('media = {:.2f}'.format((notas/2)))
| le = 0
notas = 0
while le != 2:
n = float(input())
if 0 <= n <= 10:
notas = notas + n
le += 1
else:
print('nota invalida')
print('media = {:.2f}'.format(notas / 2)) |
class CustomHandling:
"""
A decorator that wraps the passed in function. Will push exceptions to
a queue.
"""
def __init__(self, queue):
self.queue = queue
def __call__(self, func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
... | class Customhandling:
"""
A decorator that wraps the passed in function. Will push exceptions to
a queue.
"""
def __init__(self, queue):
self.queue = queue
def __call__(self, func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
... |
def ipaddr(interface=None):
'''
Returns the IP address for a given interface
CLI Example::
salt '*' network.ipaddr eth0
'''
iflist = interfaces()
out = None
if interface:
data = iflist.get(interface) or dict()
if data.get('inet'):
return data.get('inet'... | def ipaddr(interface=None):
"""
Returns the IP address for a given interface
CLI Example::
salt '*' network.ipaddr eth0
"""
iflist = interfaces()
out = None
if interface:
data = iflist.get(interface) or dict()
if data.get('inet'):
return data.get('inet')... |
def generate(env, **kw):
if not kw.get('depsOnly',0):
env.Tool('addLibrary', library=['astro'], package = 'astro')
if env['PLATFORM'] == 'win32'and env.get('CONTAINERNAME','')=='GlastRelease':
env.Tool('findPkgPath', package = 'astro')
env.Tool('facilitiesLib')
env.Tool('tipLib')
env.Tool('addLibrary', libr... | def generate(env, **kw):
if not kw.get('depsOnly', 0):
env.Tool('addLibrary', library=['astro'], package='astro')
if env['PLATFORM'] == 'win32' and env.get('CONTAINERNAME', '') == 'GlastRelease':
env.Tool('findPkgPath', package='astro')
env.Tool('facilitiesLib')
env.Tool('tipLib'... |
def cvt(s):
if isinstance(s, str):
return unicode(s)
return s
class GWTCanvasImplDefault:
def createElement(self):
e = DOM.createElement("CANVAS")
try:
# This results occasionally in an error:
# AttributeError: XPCOM component '<unknown>' has no attribute 'M... | def cvt(s):
if isinstance(s, str):
return unicode(s)
return s
class Gwtcanvasimpldefault:
def create_element(self):
e = DOM.createElement('CANVAS')
try:
self.setCanvasContext(e.MozGetIPCContext(u'2d'))
except AttributeError:
self.setCanvasContext(e.g... |
def create_category(base_cls):
class Category(base_cls):
__tablename__ = 'category'
__table_args__ = {'autoload': True}
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'Category_name'... | def create_category(base_cls):
class Category(base_cls):
__tablename__ = 'category'
__table_args__ = {'autoload': True}
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {'Category_name': self.name, 'Category_id': ... |
"""
File: boggle.py
Name:
----------------------------------------
TODO:
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
lst = []
enter_lst = []
d = {} # A dict contain the alphabets in boggle games
ans_lst = [... | """
File: boggle.py
Name:
----------------------------------------
TODO:
"""
file = 'dictionary.txt'
lst = []
enter_lst = []
d = {}
ans_lst = []
found_words = 0
def main():
"""
TODO:
# """
global lst, enter_lst, d
read_dictionary()
row_num = 1
while True:
if row_num <= 4:
ente... |
# DSAME prob #40
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def get_josephus_pos():
q = p = Node()
n = int(input("Enter no of players: "))
m = int(input("Enter which player needs to be eliminated each time:"))
# create cll containing a... | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def get_josephus_pos():
q = p = node()
n = int(input('Enter no of players: '))
m = int(input('Enter which player needs to be eliminated each time:'))
p.data = 1
p.next = node()
for i in ... |
'''LC459:Repeated Substr pattern
https://leetcode.com/problems/repeated-substring-pattern/
Given a non-empty string check if it can be constructed by
taking a substring of it and appending multiple copies of the
substring together. You may assume the given string consists
of lowercase English letters only and its lengt... | """LC459:Repeated Substr pattern
https://leetcode.com/problems/repeated-substring-pattern/
Given a non-empty string check if it can be constructed by
taking a substring of it and appending multiple copies of the
substring together. You may assume the given string consists
of lowercase English letters only and its lengt... |
a=float(input())
b=float(input())
if a<b:
print(a)
else:
print(b) | a = float(input())
b = float(input())
if a < b:
print(a)
else:
print(b) |
def grammar():
return [
'progStructure',
'name',
'body',
'instruction',
'moreInstruction',
'functionCall',
'parameter',
'moreParameter',
'parameterType'
]
def progStructure(self):
self.name()
self.match( ('reserved_word', 'INICIO')... | def grammar():
return ['progStructure', 'name', 'body', 'instruction', 'moreInstruction', 'functionCall', 'parameter', 'moreParameter', 'parameterType']
def prog_structure(self):
self.name()
self.match(('reserved_word', 'INICIO'))
self.body()
self.match(('reserved_word', 'FIN'))
def name(self):
... |
class GeneratorCache(object):
"""Cache for cached_generator to store SharedGenerators and exception info.
"""
# Private attributes:
# list<dict> _shared_generators - A list of the SharedGenerator and
# exception info maps stored in this GeneratorCache.
def __init__(self):
self._sha... | class Generatorcache(object):
"""Cache for cached_generator to store SharedGenerators and exception info.
"""
def __init__(self):
self._shared_generators = []
def clear(self):
"""Clear the SharedGenerators from all functions using this.
Clear the SharedGenerators and exception... |
n,m=map(int,input().split())
l1=list(map(int,input().split()))
minindex=l1.index(min(l1))
l2=list(map(int,input().split()))
maxindex=l2.index(max(l2))
for i in range(0,m):
print(minindex,i)
for j in range(0,minindex):
print(j,maxindex)
for j in range(minindex+1,n):
print(j,maxindex)
| (n, m) = map(int, input().split())
l1 = list(map(int, input().split()))
minindex = l1.index(min(l1))
l2 = list(map(int, input().split()))
maxindex = l2.index(max(l2))
for i in range(0, m):
print(minindex, i)
for j in range(0, minindex):
print(j, maxindex)
for j in range(minindex + 1, n):
print(j, maxindex) |
class TempSensor:
__sensor_path = '/sys/bus/w1/devices/28-00000652b8e4/w1_slave'
def __init__(self):
self.__recent_values = []
def read(self):
data = self.__read_sensor_file()
temp_value = self.__parse_sensor_data(data)
fahrenheit_value = self.__convert_to_fahrenheit(temp_... | class Tempsensor:
__sensor_path = '/sys/bus/w1/devices/28-00000652b8e4/w1_slave'
def __init__(self):
self.__recent_values = []
def read(self):
data = self.__read_sensor_file()
temp_value = self.__parse_sensor_data(data)
fahrenheit_value = self.__convert_to_fahrenheit(temp_v... |
#Question 14
power = int(input('Enter power:'))
number = 2**power
print('Two last digits:', number%100)
| power = int(input('Enter power:'))
number = 2 ** power
print('Two last digits:', number % 100) |
def distance(strand_a, strand_b):
if len(strand_a) != len(strand_b):
raise ValueError('strands are not of equal length')
count = 0
for i in range(len(strand_a)):
if strand_a[i] != strand_b[i]:
count += 1
return count
| def distance(strand_a, strand_b):
if len(strand_a) != len(strand_b):
raise value_error('strands are not of equal length')
count = 0
for i in range(len(strand_a)):
if strand_a[i] != strand_b[i]:
count += 1
return count |
# 367. Valid Perfect Square
class Solution:
# Binary Search
def isPerfectSquare(self, num: int) -> bool:
if num < 2:
return True
left, right = 2, num // 2
while left <= right:
mid = left + (right - left) // 2
sqr = mid ** 2
if sqr == num... | class Solution:
def is_perfect_square(self, num: int) -> bool:
if num < 2:
return True
(left, right) = (2, num // 2)
while left <= right:
mid = left + (right - left) // 2
sqr = mid ** 2
if sqr == num:
return True
el... |
class BuySellEnum:
BUY_SELL_UNSET = 0
BUY = 1
SELL = 2
| class Buysellenum:
buy_sell_unset = 0
buy = 1
sell = 2 |
# -*- coding: utf-8 -*-
"""
logbook._termcolors
~~~~~~~~~~~~~~~~~~~
Provides terminal color mappings.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
esc = "\x1b["
codes = {"": "", "reset": esc + "39;49;00m"}
dark_colors = ["black", "darkre... | """
logbook._termcolors
~~~~~~~~~~~~~~~~~~~
Provides terminal color mappings.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
esc = '\x1b['
codes = {'': '', 'reset': esc + '39;49;00m'}
dark_colors = ['black', 'darkred', 'darkgreen', 'brown', '... |
STATS = [
{
"num_node_expansions": 653,
"plan_length": 167,
"search_time": 0.49,
"total_time": 0.49
},
{
"num_node_expansions": 978,
"plan_length": 167,
"search_time": 0.72,
"total_time": 0.72
},
{
"num_node_expansions": 1087,
... | stats = [{'num_node_expansions': 653, 'plan_length': 167, 'search_time': 0.49, 'total_time': 0.49}, {'num_node_expansions': 978, 'plan_length': 167, 'search_time': 0.72, 'total_time': 0.72}, {'num_node_expansions': 1087, 'plan_length': 194, 'search_time': 17.44, 'total_time': 17.44}, {'num_node_expansions': 923, 'plan_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.