content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
SUCCESS_RESPONSE_CODE = 'Success'
METHOD_NOT_ALLOWED = 'Failure'
UNAUTHORIZED = 'Warning'
SUCCESS_RESPONSE_CREATED = 'Success'
PAGE_NOT_FOUND = 'Error'
INTERNAL_SERVER_ERROR = 'Error'
BAD_REQUEST_CODE = 'Error'
SUCCESS_MESSAGE = 'Success'
FAILURE_MESSAGE = 'Failure' | success_response_code = 'Success'
method_not_allowed = 'Failure'
unauthorized = 'Warning'
success_response_created = 'Success'
page_not_found = 'Error'
internal_server_error = 'Error'
bad_request_code = 'Error'
success_message = 'Success'
failure_message = 'Failure' |
class Stream(MarshalByRefObject):
""" Provides a generic view of a sequence of bytes. """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return Stream()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def BeginRead(self,buffer,offset,count,callback,state):
"""
BeginRead(... | class Stream(MarshalByRefObject):
""" Provides a generic view of a sequence of bytes. """
def zzz(self):
"""hardcoded/mock instance of the class"""
return stream()
instance = zzz()
'hardcoded/returns an instance of the class'
def begin_read(self, buffer, offset, count, callback, st... |
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
roman = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M', 5000: ''}
ret = ''
for i, s in enumerate(str(num)[::-1]):
if s in ['4', '9']:
... | class Solution(object):
def int_to_roman(self, num):
"""
:type num: int
:rtype: str
"""
roman = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M', 5000: ''}
ret = ''
for (i, s) in enumerate(str(num)[::-1]):
if s in ['4', '9']:
... |
#!/usr/bin/env python
"""Docstring"""
__author__ = "Petar Stoyanov"
def main():
"""Docstring"""
text = input().lower()
search_term = input().lower()
counter = 0
index = 0
while True:
if text.find(search_term, index) == -1:
break
else:
counter += 1
... | """Docstring"""
__author__ = 'Petar Stoyanov'
def main():
"""Docstring"""
text = input().lower()
search_term = input().lower()
counter = 0
index = 0
while True:
if text.find(search_term, index) == -1:
break
else:
counter += 1
index = text.find... |
"""Test data files."""
def test():
pass
| """Test data files."""
def test():
pass |
#!/usr/bin/env python
"""
https://leetcode.com/problems/implement-strstr/description/
Created on 2018-11-13
@author: 'Jiezhi.G@gmail.com'
Reference:
"""
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
... | """
https://leetcode.com/problems/implement-strstr/description/
Created on 2018-11-13
@author: 'Jiezhi.G@gmail.com'
Reference:
"""
class Solution:
def str_str(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle or hays... |
def phonehome():
relax()
sleep(1)
i01.setHeadSpeed(1.0,1.0,1.0,1.0,1.0)
i01.setArmSpeed("left",1.0,1.0,1.0,1.0)
i01.setArmSpeed("right",1.0,1.0,1.0,1.0)
i01.setHandSpeed("left",1.0,1.0,1.0,1.0,1.0,1.0)
i01.setHandSpeed("right",1.0,1.0,1.0,1.0,1.0,1.0)
i01.setTorsoSpeed(1.0,1.0,1.0)
i01.moveHead(160,68... | def phonehome():
relax()
sleep(1)
i01.setHeadSpeed(1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed('left', 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed('right', 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed('left', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed('right', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setTorso... |
n1 = int(input('Digite um Valor: '))
n2 = int(input('Digite outro valor: '))
n = n1 + n2
print('A soma entre {} e {} resulta em: {} !'.format(n1,n2,n))
print(type(n1))
| n1 = int(input('Digite um Valor: '))
n2 = int(input('Digite outro valor: '))
n = n1 + n2
print('A soma entre {} e {} resulta em: {} !'.format(n1, n2, n))
print(type(n1)) |
class JUMP_GE:
def __init__(self, stack):
self.phase = 0
self.ip = 0
self.stack = stack
self.a = 0
def exec(self, ip, data):
if (self.phase == 0):
self.ip = ip + 1
self.a = self.stack.pop()
self.phase = 1
return False
... | class Jump_Ge:
def __init__(self, stack):
self.phase = 0
self.ip = 0
self.stack = stack
self.a = 0
def exec(self, ip, data):
if self.phase == 0:
self.ip = ip + 1
self.a = self.stack.pop()
self.phase = 1
return False
... |
class TriggerListener(object):
def __init__(self, state_machine, **kwargs):
self._state_machine = state_machine
def __call__(self, msg):
self._state_machine.trigger(msg.data)
| class Triggerlistener(object):
def __init__(self, state_machine, **kwargs):
self._state_machine = state_machine
def __call__(self, msg):
self._state_machine.trigger(msg.data) |
# 78. Subsets
# Runtime: 32 ms, faster than 85.43% of Python3 online submissions for Subsets.
# Memory Usage: 14.3 MB, less than 78.59% of Python3 online submissions for Subsets.
class Solution:
# Cascading
def subsets(self, nums: list[int]) -> list[list[int]]:
res = [[]]
for n in nums:
... | class Solution:
def subsets(self, nums: list[int]) -> list[list[int]]:
res = [[]]
for n in nums:
res += [curr + [n] for curr in res]
return res |
def on_enter(event_data):
""" """
pocs = event_data.model
# Clear any current observation
pocs.observatory.current_observation = None
pocs.observatory.current_offset_info = None
pocs.next_state = 'parked'
if pocs.observatory.has_dome:
pocs.say('Closing dome')
if not pocs.o... | def on_enter(event_data):
""" """
pocs = event_data.model
pocs.observatory.current_observation = None
pocs.observatory.current_offset_info = None
pocs.next_state = 'parked'
if pocs.observatory.has_dome:
pocs.say('Closing dome')
if not pocs.observatory.close_dome():
po... |
"""
Nothing, but in a friendly way. Good for filling in for objects you want to
hide. If $form.f1 is a RecursiveNull object, then
$form.f1.anything["you"].might("use") will resolve to the empty string.
This module was contributed by Ian Bicking.
"""
class RecursiveNull(object):
def __getattr__(self, attr):
... | """
Nothing, but in a friendly way. Good for filling in for objects you want to
hide. If $form.f1 is a RecursiveNull object, then
$form.f1.anything["you"].might("use") will resolve to the empty string.
This module was contributed by Ian Bicking.
"""
class Recursivenull(object):
def __getattr__(self, attr):
... |
class BitVector(object):
"""docstring for BitVector"""
"""infinite array of bits is present in bitvector"""
def __init__(self):
self.BitNum=0
self.length=0
def set(self,i):
self.BitNum=self.BitNum | 1 << i
self.length=self.BitNum.bit_length()
def reset(self,i):
resetValue=1<<i
self.BitNum=self.BitNum ... | class Bitvector(object):
"""docstring for BitVector"""
'infinite array of bits is present in bitvector'
def __init__(self):
self.BitNum = 0
self.length = 0
def set(self, i):
self.BitNum = self.BitNum | 1 << i
self.length = self.BitNum.bit_length()
def reset(self, i... |
class Constand_Hs:
HEADERSIZE=1024
Dangkyvantay=str('FDK')
Dangkythetu=str('CDK')
Van_tay_mo_tu_F=str('Fopen\n')
Van_tay_dong_tu_F=str('Fclose\n')
Van_Tay_Su_Dung_Tu=str('Fused\n')
The_Tu_Su_Dung_Tu=str('Cused\n')
Van_tay_mo_tu_C=str('Copen')
Van_tay_dong_tu_C=str('Cclose')
Serve... | class Constand_Hs:
headersize = 1024
dangkyvantay = str('FDK')
dangkythetu = str('CDK')
van_tay_mo_tu_f = str('Fopen\n')
van_tay_dong_tu_f = str('Fclose\n')
van__tay__su__dung__tu = str('Fused\n')
the__tu__su__dung__tu = str('Cused\n')
van_tay_mo_tu_c = str('Copen')
van_tay_dong_tu_c... |
list1 = ['phisics','chemistry',1997,2000]
print("Value available at index 2 is ", list1[2])
list1[2] = 2003
print("New Value available at index 2 is ", list1[2]) | list1 = ['phisics', 'chemistry', 1997, 2000]
print('Value available at index 2 is ', list1[2])
list1[2] = 2003
print('New Value available at index 2 is ', list1[2]) |
expected_output = {
'mst_instances': {
6: {
'bridge_address': '5897.bdff.3b3a',
'bridge_priority': 20486,
'interfaces': {
'GigabitEthernet1/7': {
'cost': 20000,
'counters': {
'bpdu_received': ... | expected_output = {'mst_instances': {6: {'bridge_address': '5897.bdff.3b3a', 'bridge_priority': 20486, 'interfaces': {'GigabitEthernet1/7': {'cost': 20000, 'counters': {'bpdu_received': 0, 'bpdu_sent': 836828}, 'designated_bridge_address': '5897.bdff.3b3a', 'designated_bridge_port_id': '128.7', 'designated_bridge_prior... |
#It is highly recommended that you check your code first in IDLE first for syntax errors and then Test it here.
#If your code has syntax errors ,Open-Palm will freeze. You have to restart it in that case
def check_even(n):
if n%2 == 0:
return True
else:
return False
| def check_even(n):
if n % 2 == 0:
return True
else:
return False |
def expand(maze, fill):
length=len(maze)
res=[[fill]*(length*2) for i in range(length*2)]
for i in range(length//2, length//2+length):
for j in range(length//2, length//2+length):
res[i][j]=maze[i-length//2][j-length//2]
return res | def expand(maze, fill):
length = len(maze)
res = [[fill] * (length * 2) for i in range(length * 2)]
for i in range(length // 2, length // 2 + length):
for j in range(length // 2, length // 2 + length):
res[i][j] = maze[i - length // 2][j - length // 2]
return res |
# -*- coding: utf-8 -*-
"""
Branca plugins
--------------
Add different objects/effects in a branca webpage.
"""
__all__ = []
| """
Branca plugins
--------------
Add different objects/effects in a branca webpage.
"""
__all__ = [] |
number = int(input())
if any(number % int(i) for i in input().split()):
print('not divisible by all')
else:
print('divisible by all')
| number = int(input())
if any((number % int(i) for i in input().split())):
print('not divisible by all')
else:
print('divisible by all') |
#
# PySNMP MIB module ALTIGA-MULTILINK-STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTIGA-MULTILINK-STATS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:05:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (al_multi_link_mib_module,) = mibBuilder.importSymbols('ALTIGA-GLOBAL-REG', 'alMultiLinkMibModule')
(al_multi_link_group, al_stats_multi_link) = mibBuilder.importSymbols('ALTIGA-MIB', 'alMultiLinkGroup', 'alStatsMultiLink')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier'... |
class Solution:
def isPalindrome(self, s: str) -> bool:
l,r = 0, len(s)-1
while l<r:
if not s[l].isalnum():
l+=1
elif not s[r].isalnum():
r-=1
elif s[l].lower() == s[r].lower():
l+=1
... | class Solution:
def is_palindrome(self, s: str) -> bool:
(l, r) = (0, len(s) - 1)
while l < r:
if not s[l].isalnum():
l += 1
elif not s[r].isalnum():
r -= 1
elif s[l].lower() == s[r].lower():
l += 1
... |
"""
Entrez is an API that provides access to many databases, with most databases
dealing with the biomedical and molecular fields.
In this project we are concerned with the PubMed and the PubMed Central
databases that hold biomedical literature.
See:
- Links to API documentation & examples: https://www.ncbi.nlm.nih.g... | """
Entrez is an API that provides access to many databases, with most databases
dealing with the biomedical and molecular fields.
In this project we are concerned with the PubMed and the PubMed Central
databases that hold biomedical literature.
See:
- Links to API documentation & examples: https://www.ncbi.nlm.nih.g... |
class Solution:
def rankTeams(self, votes: List[str]) -> str:
# Create 2D data structure A : 0, 0, 0, 'A', C: 0, 0, 0, 'B'
rnk = {v:[0] * len(votes[0]) + [v] for v in votes[0]}
# Tally votes in reverse because sort defaults ascending
for v in votes:
for i, c in enumerate... | class Solution:
def rank_teams(self, votes: List[str]) -> str:
rnk = {v: [0] * len(votes[0]) + [v] for v in votes[0]}
for v in votes:
for (i, c) in enumerate(v):
rnk[c][i] -= 1
return ''.join(sorted(rnk, key=lambda x: rnk[x])) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
if not root:
return
dic = {}
def record(node):
... | class Solution:
def find_mode(self, root: TreeNode) -> List[int]:
if not root:
return
dic = {}
def record(node):
if not node:
return
if node.val not in dic:
dic[node.val] = 1
else:
dic[node.val]... |
#
# PySNMP MIB module TPT-DDOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-DDOS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:26:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) ... |
#
# PySNMP MIB module CNT251-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNT251-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:09:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, single_value_constraint, constraints_intersection) ... |
# Time: O(n)
# Space: O(h)
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def btreeGameWinningMove(self, root, n, x):
"""
:type root: TreeNode
:type n:... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def btree_game_winning_move(self, root, n, x):
"""
:type root: TreeNode
:type n: int
:type x: int
:rtype: bool
"""
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
... | class Solution(object):
def sum_numbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.dfs(root, 0)
def dfs(self, root, sum):
if not root:
return 0
sum = sum * 10 + root.val
if not root.left and (not root.right):
... |
"""
Open511 Orlando
"""
# List of attribute keys which correspond to event descriptions
DESC = ('Closure', 'Location')
mapping = (
('event_type', 'type'),
('geometry', 'geometry')
)
class Event(object):
def __init__(self, data, source: str = 'cityoforlando.net'):
self.data = data
self.so... | """
Open511 Orlando
"""
desc = ('Closure', 'Location')
mapping = (('event_type', 'type'), ('geometry', 'geometry'))
class Event(object):
def __init__(self, data, source: str='cityoforlando.net'):
self.data = data
self.source = source
def dynamic(self) -> dict:
"""Returns dynamic data ... |
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins, secs) = time_string.split(splitter)
return(mins + '.' + secs)
with open('james.txt') as jaf:
data = jaf.readline()
james = data.stri... | def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return mins + '.' + secs
with open('james.txt') as jaf:
data = jaf.readline()
james = data.strip().... |
def top3(products, amounts, prices):
revenue_index_product = [ (amo*pri,-idx,pro) for (pro,amo,pri,idx) in zip(products,amounts,prices,range(len(prices))) ]
revenue_index_product = sorted(revenue_index_product, reverse=True )
return [ pro for (rev,idx,pro) in revenue_index_product[0:3] ]
| def top3(products, amounts, prices):
revenue_index_product = [(amo * pri, -idx, pro) for (pro, amo, pri, idx) in zip(products, amounts, prices, range(len(prices)))]
revenue_index_product = sorted(revenue_index_product, reverse=True)
return [pro for (rev, idx, pro) in revenue_index_product[0:3]] |
__all__ = [ 'XDict' ]
class XDict(dict):
__slots__ = ()
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
__getitem__ = dict.get
__getattr__ = dict.get
__getnewargs__ = lambda self: getattr(dict,self).__getnewargs__(self)
__repr__ = lambda self: '<XDict %s>' % dict.__repr__(sel... | __all__ = ['XDict']
class Xdict(dict):
__slots__ = ()
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
__getitem__ = dict.get
__getattr__ = dict.get
__getnewargs__ = lambda self: getattr(dict, self).__getnewargs__(self)
__repr__ = lambda self: '<XDict %s>' % dict.__repr__(self)... |
class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
def setNext(self,next):
self.next=next
def setData(self, data):
self.data=data
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
if ... | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def set_next(self, next):
self.next = next
def set_data(self, data):
self.data = data
class Linkedlist:
def __init__(self):
self.head = None
def add(self, data):
... |
class cached_property(object):
"""
Decorator that creates converts a method with a single
self argument into a property cached on the instance.
"""
def __init__(self, func):
self.func = func
self.__doc__ = getattr(func, '__doc__')
def __get__(self, instance, type):
res =... | class Cached_Property(object):
"""
Decorator that creates converts a method with a single
self argument into a property cached on the instance.
"""
def __init__(self, func):
self.func = func
self.__doc__ = getattr(func, '__doc__')
def __get__(self, instance, type):
res ... |
AddrSize = 8
Out = open("Template.txt", "w")
Out.write(">->+\n[>\n" + ">" * AddrSize + "+" + "<" * AddrSize + "\n\n")
def Mark(C, L):
if C == L:
Out.write("\t" * 0 + "[-\n")
Out.write("\t" * 0 + "#\n")
Out.write("\t" * 0 + "]\n")
return
Out.write("\t" * 0 + "[>\n")
Ma... | addr_size = 8
out = open('Template.txt', 'w')
Out.write('>->+\n[>\n' + '>' * AddrSize + '+' + '<' * AddrSize + '\n\n')
def mark(C, L):
if C == L:
Out.write('\t' * 0 + '[-\n')
Out.write('\t' * 0 + '#\n')
Out.write('\t' * 0 + ']\n')
return
Out.write('\t' * 0 + '[>\n')
mark(C +... |
length = int(input())
width = int(input())
height = int(input())
occupied = float(input())
occupied_percent = occupied / 100
full_capacity = length * width * height
occupied_total = occupied_percent * full_capacity
remaining = full_capacity - occupied_total
capacity_in_dm = remaining / 1000
water = capacity_in_dm
print... | length = int(input())
width = int(input())
height = int(input())
occupied = float(input())
occupied_percent = occupied / 100
full_capacity = length * width * height
occupied_total = occupied_percent * full_capacity
remaining = full_capacity - occupied_total
capacity_in_dm = remaining / 1000
water = capacity_in_dm
print... |
module_id = 'gl'
report_name = 'tb_bf_maj'
table_name = 'gl_totals'
report_type = 'bf_cf'
groups = []
groups.append([
'code', # dim
['code_maj', []], # grp_name, filter
])
include_zeros = True
# allow_select_loc_fun = True
expand_subledg = True
columns = [
['op_date', 'op_date', 'Op date', 'DTE', 8... | module_id = 'gl'
report_name = 'tb_bf_maj'
table_name = 'gl_totals'
report_type = 'bf_cf'
groups = []
groups.append(['code', ['code_maj', []]])
include_zeros = True
expand_subledg = True
columns = [['op_date', 'op_date', 'Op date', 'DTE', 85, None, 'Total:'], ['cl_date', 'cl_date', 'Cl date', 'DTE', 85, None, False], [... |
"""
class TestNewOffsets(unittest.TestCase):
def test_yearoffset(self):
off = lib.YearOffset(dayoffset=0, biz=0, anchor=datetime(2002,1,1))
for i in range(500):
t = lib.Timestamp(off.ts)
self.assert_(t.day == 1)
self.assert_(t.month == 1)
self.asse... | """
class TestNewOffsets(unittest.TestCase):
def test_yearoffset(self):
off = lib.YearOffset(dayoffset=0, biz=0, anchor=datetime(2002,1,1))
for i in range(500):
t = lib.Timestamp(off.ts)
self.assert_(t.day == 1)
self.assert_(t.month == 1)
self.asser... |
class Calculator:
def __init__(self):
self.result = 0
def adder(self, num):
self.result += num
return self.result
cal1 = Calculator()
cal2 = Calculator()
print(cal1.adder(3)) # 3
print(cal1.adder(5)) # 8
print(cal2.adder(3)) # 3
print(cal2.adder(7)) # 10
# Empty ... | class Calculator:
def __init__(self):
self.result = 0
def adder(self, num):
self.result += num
return self.result
cal1 = calculator()
cal2 = calculator()
print(cal1.adder(3))
print(cal1.adder(5))
print(cal2.adder(3))
print(cal2.adder(7))
class Simple:
pass
class Service:
text... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-09-03 16:21:08
# Description:
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return node
m = {node: Node(node.val)}
stack = [node]
while stack:
n = sta... | class Solution:
def clone_graph(self, node: 'Node') -> 'Node':
if not node:
return node
m = {node: node(node.val)}
stack = [node]
while stack:
n = stack.pop()
for neigh in n.neighbors:
if neigh not in m:
stack.a... |
N=int(input())
A=[int(input()) for i in range(N)]
B={a:i for (i,a) in enumerate(sorted(set(A)))}
for a in A:
print(B[a]) | n = int(input())
a = [int(input()) for i in range(N)]
b = {a: i for (i, a) in enumerate(sorted(set(A)))}
for a in A:
print(B[a]) |
# List of strings/words
words = input().split()
word_one = words[0]
word_two = words[1]
total_sum = 0
shorter_word_length = min(len(word_one), len(word_two))
# Process shorter string
for i in range(shorter_word_length):
word_one_current = word_one[i]
word_two_current = word_two[i]
ch_multiplication = ord... | words = input().split()
word_one = words[0]
word_two = words[1]
total_sum = 0
shorter_word_length = min(len(word_one), len(word_two))
for i in range(shorter_word_length):
word_one_current = word_one[i]
word_two_current = word_two[i]
ch_multiplication = ord(word_one_current) * ord(word_two_current)
total... |
def solution(n: int):
answer = 0
i = 1
while i * i < n + 1:
if n % i == 0:
if i == n // i:
answer += i
else:
answer += i + n // i
i += 1
return answer
if __name__ == "__main__":
i = 25
print(solution(i))
| def solution(n: int):
answer = 0
i = 1
while i * i < n + 1:
if n % i == 0:
if i == n // i:
answer += i
else:
answer += i + n // i
i += 1
return answer
if __name__ == '__main__':
i = 25
print(solution(i)) |
"""
Entradas
Horas trabajadas-->float-->ht
Pago por hora-->float-->ph
Salidas
Pago junto con la horas-->float-->pa=ht*ph
Descuento por los impuestos-->float-->des1=pa*0.20 y des2=pa-des1
"""
ht=float(input("Digite las horas que ha trabajado: "))
ph=float(input("Digite el pago por hora: "))
pa=ht*ph
des1=pa*0.20
des2=p... | """
Entradas
Horas trabajadas-->float-->ht
Pago por hora-->float-->ph
Salidas
Pago junto con la horas-->float-->pa=ht*ph
Descuento por los impuestos-->float-->des1=pa*0.20 y des2=pa-des1
"""
ht = float(input('Digite las horas que ha trabajado: '))
ph = float(input('Digite el pago por hora: '))
pa = ht * ph
des1 = pa * ... |
qst_deliver_message = 0
qst_deliver_message_to_enemy_lord = 1
qst_raise_troops = 2
qst_escort_lady = 3
qst_deal_with_bandits_at_lords_village = 4
qst_collect_taxes = 5
qst_hunt_down_fugitive = 6
qst_kill_local_merchant = 7
qst_bring_back_runaway_serfs = 8
qst_follow_spy = 9
qst_capture_enemy_hero = 10
qst_lend_companio... | qst_deliver_message = 0
qst_deliver_message_to_enemy_lord = 1
qst_raise_troops = 2
qst_escort_lady = 3
qst_deal_with_bandits_at_lords_village = 4
qst_collect_taxes = 5
qst_hunt_down_fugitive = 6
qst_kill_local_merchant = 7
qst_bring_back_runaway_serfs = 8
qst_follow_spy = 9
qst_capture_enemy_hero = 10
qst_lend_companio... |
class Chair:
"""Create a chair
Parameters
----------
chair_name : str
The name of the chair
professor: str
The name of the professor
employees : {array-like of shape (n,), []}, default=[]
List of all employees of the chair
See A... | class Chair:
"""Create a chair
Parameters
----------
chair_name : str
The name of the chair
professor: str
The name of the professor
employees : {array-like of shape (n,), []}, default=[]
List of all employees of the chair
See Als... |
# Aluguel de carros
k= (float(input('Total kilometragem percorrida: ')))
a= (int(input('Total de dias alugado: ')))
kr= (float(input('Valor por kilometro rodado: R$ ')))
ad = (float(input('Valor do dia de aluguel: R$ ')))
tk = k*kr # total de kilometros rodados
ta = a * ad # total dias de aluguel
total = tk + ta
prin... | k = float(input('Total kilometragem percorrida: '))
a = int(input('Total de dias alugado: '))
kr = float(input('Valor por kilometro rodado: R$ '))
ad = float(input('Valor do dia de aluguel: R$ '))
tk = k * kr
ta = a * ad
total = tk + ta
print(f'Total a pagar por {k:.2f} kilometros rodados + {a} dias de aluguel: R$ {to... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"dimension": "00_core.ipynb",
"reshaped": "00_core.ipynb",
"show": "00_core.ipynb",
"makeThreatenedSquares": "00_core.ipynb",
"defence": "00_core.ipynb",
"attack":... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'dimension': '00_core.ipynb', 'reshaped': '00_core.ipynb', 'show': '00_core.ipynb', 'makeThreatenedSquares': '00_core.ipynb', 'defence': '00_core.ipynb', 'attack': '00_core.ipynb', 'fetch': '01_data.ipynb', 'Game': '01_data.ipynb', 'fromGame': '01_d... |
# This file was generated by the "capture_real_responses.py" script.
# On Wed, 20 Nov 2019 19:34:18 +0000.
#
# To update it run:
# python -m tests.providers.capture_real_responses
captured_responses = [
{
"request": {
"full_url": "https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService... | captured_responses = [{'request': {'full_url': 'https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente', 'method': 'POST', 'headers': {}, 'data': bytearray(b'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cli="http://cliente.bean.master.sigep.bsb.correios.com.b... |
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
l = 0
r = len(s)-1
while l<r:
s[l],s[r]=s[r],s[l]
l+=1
r-=1
| class Solution:
def reverse_string(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
l = 0
r = len(s) - 1
while l < r:
(s[l], s[r]) = (s[r], s[l])
l += 1
r -= 1 |
def check(params):
"Check input parameters"
attrs = []
for attr in attrs:
if attr not in params:
raise Exception('key {} not in {}'.format(attr, json.dumps(params)))
def execute(cur, stmt, bindings, verbose=None):
"Helper function to execute statement"
if verbose:
print(... | def check(params):
"""Check input parameters"""
attrs = []
for attr in attrs:
if attr not in params:
raise exception('key {} not in {}'.format(attr, json.dumps(params)))
def execute(cur, stmt, bindings, verbose=None):
"""Helper function to execute statement"""
if verbose:
... |
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left, right = 0, len(numbers) - 1
while left < right:
curSum = numbers[left] + numbers[right]
if curSum == target:
return[left + 1, right + 1]
if curSum > target:
... | class Solution:
def two_sum(self, numbers: List[int], target: int) -> List[int]:
(left, right) = (0, len(numbers) - 1)
while left < right:
cur_sum = numbers[left] + numbers[right]
if curSum == target:
return [left + 1, right + 1]
if curSum > targe... |
'''
A collection of optional backends. You must manually select and
install the backend you want. If the backend is not installed,
then trying to import the module for that backend will cause
an :class:`ImportError`.
See :ref:`Choose a hashing backend` for more.
'''
SUPPORTED_BACKENDS = [
'pycryptodomex', # pref... | """
A collection of optional backends. You must manually select and
install the backend you want. If the backend is not installed,
then trying to import the module for that backend will cause
an :class:`ImportError`.
See :ref:`Choose a hashing backend` for more.
"""
supported_backends = ['pycryptodomex', 'pysha3'] |
class linkedList(object):
"""
custom implementation of a linked list
We need a custom implementation because in the tableMethod class we need to refere
to individual items in the linked list to quickly remove and update them.
"""
first = None
last = None
lenght = 0
def... | class Linkedlist(object):
"""
custom implementation of a linked list
We need a custom implementation because in the tableMethod class we need to refere
to individual items in the linked list to quickly remove and update them.
"""
first = None
last = None
lenght = 0
def _... |
"""
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
print "line = %d " % line_count
current_file = open(input_file)
print "First let's print the whole file: "
print_all(current_file)
#print... | """
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
print "line = %d " % line_count
current_file = open(input_file)
print "First let's print the whole file: "
print_all(current_file)
#print... |
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.stack = []
self.pushLeftsUntilNull_(root)
def next(self) -> int:
root = self.stack.pop()
self.pushLeftsUntilNull_(root.right)
return root.val
def hasNext(self) -> bool:
return self.stack
def pushLeftsUntilNull_(self... | class Bstiterator:
def __init__(self, root: Optional[TreeNode]):
self.stack = []
self.pushLeftsUntilNull_(root)
def next(self) -> int:
root = self.stack.pop()
self.pushLeftsUntilNull_(root.right)
return root.val
def has_next(self) -> bool:
return self.stack... |
class Cache:
def __init__(self, function, limit=1000):
self.function = function
self.limit = limit
self.purge()
def get(self, key):
value = self.store.get(key)
if value is None:
value = self.function(key)
self.set(key, value)
return value
... | class Cache:
def __init__(self, function, limit=1000):
self.function = function
self.limit = limit
self.purge()
def get(self, key):
value = self.store.get(key)
if value is None:
value = self.function(key)
self.set(key, value)
return value... |
'''10. Write a Python program to use double quotes to display strings.'''
def double_quote_string(string):
ans = f"\"{string}\""
return ans
print(double_quote_string('This is working already')) | """10. Write a Python program to use double quotes to display strings."""
def double_quote_string(string):
ans = f'"{string}"'
return ans
print(double_quote_string('This is working already')) |
# noqa
class CustomSerializer:
"""Custom serializer implementation to test the injection of different serialization strategies to an input."""
@property
def extension(self) -> str: # noqa
return "ext"
def serialize(self, value: str) -> bytes: # noqa
return b"serialized"
def de... | class Customserializer:
"""Custom serializer implementation to test the injection of different serialization strategies to an input."""
@property
def extension(self) -> str:
return 'ext'
def serialize(self, value: str) -> bytes:
return b'serialized'
def deserialize(self, serialize... |
"""
.. module:: __init__
:synopsis: finvizfinance package general information
.. moduleauthor:: Tianning Li <ltianningli@gmail.com>
"""
__version__ = "0.10"
__author__ = "Tianning Li"
| """
.. module:: __init__
:synopsis: finvizfinance package general information
.. moduleauthor:: Tianning Li <ltianningli@gmail.com>
"""
__version__ = '0.10'
__author__ = 'Tianning Li' |
# URI Online Judge 1176
N = 62
n1 = 0
n2 = 1
string = '0 1'
for i in range(N-2):
new = n1 + n2
string += (' ') + str(new)
n1 = n2
n2 = new
fib = [int(item) for item in string.split()]
T = -1
while (T<0) or (T>60):
T = int(input())
for t in range(T):
entrada = int(input())... | n = 62
n1 = 0
n2 = 1
string = '0 1'
for i in range(N - 2):
new = n1 + n2
string += ' ' + str(new)
n1 = n2
n2 = new
fib = [int(item) for item in string.split()]
t = -1
while T < 0 or T > 60:
t = int(input())
for t in range(T):
entrada = int(input())
print('Fib({}) = {}'.format(entrada, fib[en... |
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
res = ListNode(None)
output = res
while list1 and list2:
if list1.val <= list2.val:
output.next = list1
list1 = list1.next... | class Solution:
def merge_two_lists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
res = list_node(None)
output = res
while list1 and list2:
if list1.val <= list2.val:
output.next = list1
list1 = list1.next
... |
line = input().split('\\')
line_length = len(line) -1
splitted = line[line_length].split('.')
file_name = splitted[0]
ext = splitted[1]
print(f'File name: {file_name}')
print(f'File extension: {ext}')
| line = input().split('\\')
line_length = len(line) - 1
splitted = line[line_length].split('.')
file_name = splitted[0]
ext = splitted[1]
print(f'File name: {file_name}')
print(f'File extension: {ext}') |
#
# PySNMP MIB module Wellfleet-CCT-NAME-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-CCT-NAME-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:32:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, single_value_constraint, constraints_intersection) ... |
word_size = 9
num_words = 256
words_per_row = 4
local_array_size = 15
output_extended_config = True
output_datasheet_info = True
netlist_only = True
nominal_corner_only = True
| word_size = 9
num_words = 256
words_per_row = 4
local_array_size = 15
output_extended_config = True
output_datasheet_info = True
netlist_only = True
nominal_corner_only = True |
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
if len(numbers) <= 1:
return [None, None]
idx2 = len(numbers)-1
idx1 = 0
while idx1 < idx2:
if numbers[idx1] + numbers[idx2] == target:
return [id... | class Solution:
def two_sum(self, numbers: List[int], target: int) -> List[int]:
if len(numbers) <= 1:
return [None, None]
idx2 = len(numbers) - 1
idx1 = 0
while idx1 < idx2:
if numbers[idx1] + numbers[idx2] == target:
return [idx1 + 1, idx2 +... |
class SumUpException(Exception):
pass
class SumUpNoAccessCode(SumUpException):
pass
class SumUpAccessCodeExpired(SumUpException):
pass
| class Sumupexception(Exception):
pass
class Sumupnoaccesscode(SumUpException):
pass
class Sumupaccesscodeexpired(SumUpException):
pass |
# flake8: noqa
test_train_config = {"training_parameters": {"EPOCHS": 50}}
test_model_config = {"model_parameters": {"model_save_path": "modeloutput1"}}
test_test_data = {
"text": "what Homeowners Warranty Program means,what it applies to, what is its purpose?"
}
test_entities = [
{"text": "homeowners warra... | test_train_config = {'training_parameters': {'EPOCHS': 50}}
test_model_config = {'model_parameters': {'model_save_path': 'modeloutput1'}}
test_test_data = {'text': 'what Homeowners Warranty Program means,what it applies to, what is its purpose?'}
test_entities = [{'text': 'homeowners warranty program', 'entity': 'Fin_C... |
# -*- coding: utf-8 -*-
"""Modulo helpers.url"""
def split_query_string(items):
"""dividir un query string"""
params = {'filter': {}, 'fields': [], 'pagination': {}, 'sort': {}, 'filter_in': {}}
for key, value in items:
sub_keys = key.split('.')
if 'fields' in sub_keys:
params['... | """Modulo helpers.url"""
def split_query_string(items):
"""dividir un query string"""
params = {'filter': {}, 'fields': [], 'pagination': {}, 'sort': {}, 'filter_in': {}}
for (key, value) in items:
sub_keys = key.split('.')
if 'fields' in sub_keys:
params['fields'] = [value] if ... |
def entrance():
'''This is the initial room the player will begin their adventure.'''
pass
def orange_rm_1():
'''Todo:
red key(hidden in desk drawer)
health(desk top)
desk
rat (24% damage)
red door
'''
pass
def red_rm_2():
'''locked entrance- requires red key
to do:
... | def entrance():
"""This is the initial room the player will begin their adventure."""
pass
def orange_rm_1():
"""Todo:
red key(hidden in desk drawer)
health(desk top)
desk
rat (24% damage)
red door
"""
pass
def red_rm_2():
"""locked entrance- requires red key
to do:
... |
def main(request, response):
headers = [("Content-Type", "text/javascript")]
milk = request.cookies.first("milk", None)
if milk is None:
return headers, "var included = false;"
elif milk.value == "yes":
return headers, "var included = true;"
return headers, "var included = false;"
| def main(request, response):
headers = [('Content-Type', 'text/javascript')]
milk = request.cookies.first('milk', None)
if milk is None:
return (headers, 'var included = false;')
elif milk.value == 'yes':
return (headers, 'var included = true;')
return (headers, 'var included = false... |
"""
Tema: Algoritmo de aproximacion.
Curso: Pensamiento computacional.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
objetivo = int(input('Escoge un numero: '))
epsilon = 0.0001
paso = epsilon**2
respuesta = 0.0
while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo:
... | """
Tema: Algoritmo de aproximacion.
Curso: Pensamiento computacional.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
objetivo = int(input('Escoge un numero: '))
epsilon = 0.0001
paso = epsilon ** 2
respuesta = 0.0
while abs(respuesta ** 2 - objetivo) >= epsilon and respuesta <= objetivo:
... |
#!/usr/bin/python3.8
def nics_menu():
FILENAME = "nics.yaml"
SWITCHES = "-n/--nics"
DESCRIPTION = "YAML file that contains the configuration for the interfaces to use"
REQUIRED = "always"
TEMPLATE = """nics: # number of nics needs to equal to 2
"""
NIC_TEMPLATE = """ - name: "{}" # name of t... | def nics_menu():
filename = 'nics.yaml'
switches = '-n/--nics'
description = 'YAML file that contains the configuration for the interfaces to use'
required = 'always'
template = 'nics: # number of nics needs to equal to 2\n'
nic_template = ' - name: "{}" # name of the interface\n subnet: "{}... |
"""Amazon Product Advertising API wrapper for Python"""
__version__ = '3.2.0'
__author__ = 'Sergio Abad'
| """Amazon Product Advertising API wrapper for Python"""
__version__ = '3.2.0'
__author__ = 'Sergio Abad' |
"""
My first Python script
- this is a multiline comment
"""
# My second comment
'''
This is also a multiline comment
'''
statement = 0
if statement !=False:
print(4)
counter = 1000
count = 0
sum = 0
while count < counter:
if count%3 ==0:
sum = sum+count
elif count%5 ==0:
sum = sum+cou... | """
My first Python script
- this is a multiline comment
"""
'\nThis is also a multiline comment\n'
statement = 0
if statement != False:
print(4)
counter = 1000
count = 0
sum = 0
while count < counter:
if count % 3 == 0:
sum = sum + count
elif count % 5 == 0:
sum = sum + count
count = ... |
CORRECT_PIN = "1234"
MAX_TRIES = 3
tries_left = MAX_TRIES
pin = input(f"Insert your pni ({tries_left} tries left): ")
while tries_left > 1 and pin != CORRECT_PIN:
tries_left -= 1
print("Your PIN is incorrect.")
pin = input(f"Insert your pni ({tries_left} tries left): ")
if pin == CORRECT_PIN:
print("... | correct_pin = '1234'
max_tries = 3
tries_left = MAX_TRIES
pin = input(f'Insert your pni ({tries_left} tries left): ')
while tries_left > 1 and pin != CORRECT_PIN:
tries_left -= 1
print('Your PIN is incorrect.')
pin = input(f'Insert your pni ({tries_left} tries left): ')
if pin == CORRECT_PIN:
print('You... |
#
# Solution to Project Euler problem 73
# Copyright (c) Project Nayuki. All rights reserved.
#
# https://www.nayuki.io/page/project-euler-solutions
# https://github.com/nayuki/Project-Euler-solutions
#
# The Stern-Brocot tree is an infinite binary search tree of all positive rational numbers,
# where each number ... | def compute():
ans = 0
stack = [(1, 3, 1, 2)]
while len(stack) > 0:
(leftn, leftd, rightn, rightd) = stack.pop()
d = leftd + rightd
if d <= 12000:
n = leftn + rightn
ans += 1
stack.append((n, d, rightn, rightd))
stack.append((leftn, lef... |
"""
Contains the Artist class
"""
__all__ = [
'Artist',
]
class Artist(object):
"""
Represents an artist
"""
def __init__(self):
"""
Initiate properties
"""
self.identifier = 0
self.name = ''
self.other_names = ''
self.group_name = ''
... | """
Contains the Artist class
"""
__all__ = ['Artist']
class Artist(object):
"""
Represents an artist
"""
def __init__(self):
"""
Initiate properties
"""
self.identifier = 0
self.name = ''
self.other_names = ''
self.group_name = ''
self.u... |
class BaseSiteCheckerException(Exception):
pass
class ErrorStopMsgLimit(BaseSiteCheckerException):
pass
| class Basesitecheckerexception(Exception):
pass
class Errorstopmsglimit(BaseSiteCheckerException):
pass |
def get_safe_balanced_split(target, train_ratio=0.8, get_test_indices=True, shuffle=False, seed=None):
classes, counts = np.unique(target, return_counts=True)
num_per_class = float(len(target))*float(train_ratio)/float(len(classes))
if num_per_class > np.min(counts):
print("Insufficient data to produce a bala... | def get_safe_balanced_split(target, train_ratio=0.8, get_test_indices=True, shuffle=False, seed=None):
(classes, counts) = np.unique(target, return_counts=True)
num_per_class = float(len(target)) * float(train_ratio) / float(len(classes))
if num_per_class > np.min(counts):
print('Insufficient data t... |
print("Welcome to the Multiplication/Exponent Table App")
print()
name = input("Hello, What is your name: ")
number = float(input("What number would you like to work with: "))
name = name.strip()
print("Multiplication Table For {}".format(number))
print()
print("\t\t1.0 * {} = {:.2f}".format(number, number*1.0))
print... | print('Welcome to the Multiplication/Exponent Table App')
print()
name = input('Hello, What is your name: ')
number = float(input('What number would you like to work with: '))
name = name.strip()
print('Multiplication Table For {}'.format(number))
print()
print('\t\t1.0 * {} = {:.2f}'.format(number, number * 1.0))
prin... |
# Live preview Markdown and reStructuredText files as HTML in a web browser.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: April 12, 2018
# URL: https://github.com/xolox/python-preview-markup
__version__ = '0.3.3'
| __version__ = '0.3.3' |
class DockablePaneState(object,IDisposable):
"""
Describes where a dockable pane window should appear in the Revit user interface.
DockablePaneState(other: DockablePaneState)
DockablePaneState()
"""
def Dispose(self):
""" Dispose(self: DockablePaneState) """
pass
def ReleaseUnmanagedResources(... | class Dockablepanestate(object, IDisposable):
"""
Describes where a dockable pane window should appear in the Revit user interface.
DockablePaneState(other: DockablePaneState)
DockablePaneState()
"""
def dispose(self):
""" Dispose(self: DockablePaneState) """
pass
def release_unma... |
class Solution:
"""
@param n: an integer
@return: if n is a power of two
"""
def isPowerOfTwo(self, n):
# Write your code here
while n>1:
n=n/2
if n ==1:
return True
else:
return False | class Solution:
"""
@param n: an integer
@return: if n is a power of two
"""
def is_power_of_two(self, n):
while n > 1:
n = n / 2
if n == 1:
return True
else:
return False |
#
# These methods are working on multiple processors
# that can be located remotely
#
class Bridges:
@staticmethod
def create(master=None, workers=None, name=None):
raise NotImplementedError
@staticmethod
def set(master=None, workers=None, name=None):
raise NotImplementedError
@s... | class Bridges:
@staticmethod
def create(master=None, workers=None, name=None):
raise NotImplementedError
@staticmethod
def set(master=None, workers=None, name=None):
raise NotImplementedError
@staticmethod
def list(hosts=None):
raise NotImplementedError
@staticmet... |
"""Simple touch utility."""
def touch(filename: str) -> None:
"""Mimics the "touch filename" utility.
:param filename: filename to touch
"""
with open(filename, "a"):
pass
| """Simple touch utility."""
def touch(filename: str) -> None:
"""Mimics the "touch filename" utility.
:param filename: filename to touch
"""
with open(filename, 'a'):
pass |
for index in range(1,101):
# if index % 15 == 0:
# print("fifteen")
if index % 3 == 0 and index % 5 == 0 :
print("fifteen")
elif index % 3 == 0:
print("three")
elif index % 5 == 0:
print("five")
else:
print(index)
| for index in range(1, 101):
if index % 3 == 0 and index % 5 == 0:
print('fifteen')
elif index % 3 == 0:
print('three')
elif index % 5 == 0:
print('five')
else:
print(index) |
class Solution:
def rob(self, nums):
if not nums:
return 0
values = [0] * len(nums)
for i in range(len(nums)):
if i == 0:
values[i] = max(values[i], nums[i])
elif i == 1:
values[i] = max(values[i-1], nums[i])
els... | class Solution:
def rob(self, nums):
if not nums:
return 0
values = [0] * len(nums)
for i in range(len(nums)):
if i == 0:
values[i] = max(values[i], nums[i])
elif i == 1:
values[i] = max(values[i - 1], nums[i])
... |
# Copyright 2018 The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | """Postprocessing utility function for CLIF."""
def value_error_on_false(ok, *output_args):
"""Raises ValueError if not ok, otherwise returns the output arguments."""
n_outputs = len(output_args)
if n_outputs < 2:
raise value_error('Expected 2 or more output_args. Got: %d' % n_outputs)
if not o... |
MASTER_PROCESS_RANK = 0 # Only meaningful if webscraper is run with multiple processes. Here we use rank = 0 for master process; however we can set it to any value in [0, nprocs-1].
READING_RATIO_FOR_INPUT_CSVs = 1 # It represents how much of the input files (in csv format for now) we should process.... | master_process_rank = 0
reading_ratio_for_input_cs_vs = 1
number_of_repeats_timeit = 1
create_word_cloud = True
create_bag_of_words = True
create_sentiment_analysis_results = True |
#
# @lc app=leetcode.cn id=1689 lang=python3
#
# [1689] detect-pattern-of-length-m-repeated-k-or-more-times
#
None
# @lc code=end | None |
print("Raadsel 1:",
"\n Wanneer leefde de oudste persoon ter wereld?")
guess = input() #"TUSSEN GEBOORTE en dood" # input ()
guess_words = []
for g in guess.split():
guess_words.append(g.lower())
answer_words = ["tussen", "geboorte", "dood"]
incorrect = False
for word in answer_words:
if word not in ... | print('Raadsel 1:', '\n Wanneer leefde de oudste persoon ter wereld?')
guess = input()
guess_words = []
for g in guess.split():
guess_words.append(g.lower())
answer_words = ['tussen', 'geboorte', 'dood']
incorrect = False
for word in answer_words:
if word not in guess_words:
incorrect = True
if incorrec... |
# Problem code
def countAndSay(n):
if n == 1:
return "1"
current = "1"
for i in range(2, n + 1):
current = helper(current)
return current
def helper(current):
group_count = 1
group_member = current[0]
result = ""
for i in range(1, len(current)):
if current[i] =... | def count_and_say(n):
if n == 1:
return '1'
current = '1'
for i in range(2, n + 1):
current = helper(current)
return current
def helper(current):
group_count = 1
group_member = current[0]
result = ''
for i in range(1, len(current)):
if current[i] == group_member:... |
"""
This package contains serializers. Purpose of serializer class
is to convert hwt representations of designed architecture
to target language or form (VHDL/Verilog/SystemC...).
"""
| """
This package contains serializers. Purpose of serializer class
is to convert hwt representations of designed architecture
to target language or form (VHDL/Verilog/SystemC...).
""" |
# A classroom consists of N students, whose friendships can be represented in
# an adjacency list. For example, the following descibes a situation where 0
# is friends with 1 and 2, 3 is friends with 6, and so on.
# {0: [1, 2],
# 1: [0, 5],
# 2: [0],
# 3: [6],
# 4: [],
# 5: [1],
# 6: [3]}
# Each stu... | def friend_group(adjacency):
groups = []
mapping = {}
for i in adjacency:
if i in mapping:
continue
for adj in adjacency[i]:
if adj in mapping:
groups[mapping[adj]].add(i)
mapping[i] = mapping[adj]
if i not in mapping:
... |
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
if not text1 or not text2:
return 0
m = len(text1)
n = len(text2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if text1[i-1]... | class Solution(object):
def longest_common_subsequence(self, text1, text2):
if not text1 or not text2:
return 0
m = len(text1)
n = len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
... |
class Printer(object):
def __init__(self, sort_keys=None, order=None, header=None):
self.sort_keys = sort_keys
self.order = order
self.header = header
def print(self, d, format='table'):
print(self.value(d,format=format))
def value(self, d, format='table'):
return ... | class Printer(object):
def __init__(self, sort_keys=None, order=None, header=None):
self.sort_keys = sort_keys
self.order = order
self.header = header
def print(self, d, format='table'):
print(self.value(d, format=format))
def value(self, d, format='table'):
return... |
# Copyright 2020 BlueCat Networks. All rights reserved.
# -*- coding: utf-8 -*-
type = 'api'
sub_pages = [
{
'name' : 'user_inventory_page',
'title' : u'user_inventory',
'endpoint' : 'user_inventory/user_inventory_endpoint',
'description' : u'user_inventory'
},
]... | type = 'api'
sub_pages = [{'name': 'user_inventory_page', 'title': u'user_inventory', 'endpoint': 'user_inventory/user_inventory_endpoint', 'description': u'user_inventory'}] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.