content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | """AppEngine Datastore/GQL related Utilities module.
This common util provides helper functionality to extend/support
various GQL related queries.
"""
def fetch_entities(query_obj, limit):
"""Fetches number of Entities up to limit using query object.
Args:
query_obj: AppEngine Datastore Query Object.
l... |
'''
QUESTION:
344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable a... | """
QUESTION:
344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable a... |
{
"targets":[
{
"target_name":"stp",
"sources":["calc_grid.cc"]
}
]
} | {'targets': [{'target_name': 'stp', 'sources': ['calc_grid.cc']}]} |
s = input()
hachi = set()
if len(s) < 3:
if int(s) % 8 == 0 or int(s[::-1]) % 8 == 0:
print("Yes")
else:
print("No")
exit()
t = 104
while t < 1000:
hachi.add(str(t))
t += 8
counter = [0 for _ in range(10)]
for i in s:
counter[int(i)] += 1
for h in hachi:
count = [0 for _ in r... | s = input()
hachi = set()
if len(s) < 3:
if int(s) % 8 == 0 or int(s[::-1]) % 8 == 0:
print('Yes')
else:
print('No')
exit()
t = 104
while t < 1000:
hachi.add(str(t))
t += 8
counter = [0 for _ in range(10)]
for i in s:
counter[int(i)] += 1
for h in hachi:
count = [0 for _ in r... |
#
# PySNMP MIB module DLINK-3100-BRIDGEMIBOBJECTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-BRIDGEMIBOBJECTS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:33:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ... |
def has_doi(bib_info):
return "doi" in bib_info
def get_doi(bib_info):
return bib_info["doi"]
def has_title(bib_info):
return "title" in bib_info
def get_title(bib_info):
return bib_info["title"]
def has_url(bib_info):
return "url" in bib_info
def get_url(bib_info):
if "url" in bib_inf... | def has_doi(bib_info):
return 'doi' in bib_info
def get_doi(bib_info):
return bib_info['doi']
def has_title(bib_info):
return 'title' in bib_info
def get_title(bib_info):
return bib_info['title']
def has_url(bib_info):
return 'url' in bib_info
def get_url(bib_info):
if 'url' in bib_info:
... |
payload_mass=5
payload_fairing_height=1
stage1_height=7.5
stage1_burnTime=74
stage1_propellant_mass=15000
stage1_engine_mass=1779
stage1_thrust=469054
stage1_isp=235.88175331294596
stage1_coastTime=51
stage2_height=3.35
stage2_burnTime=64
stage2_propellant_mass=5080
stage2_engine_mass=527
stag... | payload_mass = 5
payload_fairing_height = 1
stage1_height = 7.5
stage1_burn_time = 74
stage1_propellant_mass = 15000
stage1_engine_mass = 1779
stage1_thrust = 469054
stage1_isp = 235.88175331294596
stage1_coast_time = 51
stage2_height = 3.35
stage2_burn_time = 64
stage2_propellant_mass = 5080
stage2_engine_mass = 527
s... |
digit1 = 999
digit2 = 999
largestpal = 0 #always save the largest palindrome
#nested loop for 3digit product
while digit1 >= 1:
while digit2 >= 1:
#get string from int
p1 = str(digit1 * digit2)
#check string for palindrome by comparing first-last, etc.
for i in range(0, (len(p1) - 1)):
#no pal?... | digit1 = 999
digit2 = 999
largestpal = 0
while digit1 >= 1:
while digit2 >= 1:
p1 = str(digit1 * digit2)
for i in range(0, len(p1) - 1):
if p1[i] != p1[len(p1) - i - 1]:
break
elif i >= (len(p1) - 1) / 2:
if largestpal < int(p1):
... |
class InvalidMoveException(Exception):
pass
class InvalidPlayerException(Exception):
pass
class InvalidGivenBallsException(Exception):
pass
class GameIsOverException(Exception):
pass
| class Invalidmoveexception(Exception):
pass
class Invalidplayerexception(Exception):
pass
class Invalidgivenballsexception(Exception):
pass
class Gameisoverexception(Exception):
pass |
while True:
try:
dinheiro = []
nota = input()
cent = input()
if(len(cent) < 2):
cent += '0'
cent = cent[::-1]
dinheiro += '.' + cent
print(dinheiro)
except EOFError:
break | while True:
try:
dinheiro = []
nota = input()
cent = input()
if len(cent) < 2:
cent += '0'
cent = cent[::-1]
dinheiro += '.' + cent
print(dinheiro)
except EOFError:
break |
# import sys
# from io import StringIO
#
# input_1 = """3, 6
# 7, 1, 3, 3, 2, 1
# 1, 3, 9, 8, 5, 6
# 4, 6, 7, 9, 1, 0
# """
#
# sys.stdin = StringIO(input_1)
rows, columns = [int(x) for x in input().split(", ")]
matrix = []
sum_matrix = 0
for _ in range(rows):
row = [int(x) for x in input().split(", ")]
matri... | (rows, columns) = [int(x) for x in input().split(', ')]
matrix = []
sum_matrix = 0
for _ in range(rows):
row = [int(x) for x in input().split(', ')]
matrix.append(row)
sum_matrix += sum(row)
print(sum_matrix)
print(matrix) |
'''
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a value in the HashSet. If the value doe... | """
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a value in the HashSet. If the value does not e... |
# -*- coding: UTF-8 -*-
class MyClass(object):
def __init__(self):
pass
def __eq__(self, other):
return type(self) == type(other)
if __name__ == '__main__':
print (MyClass())
print (MyClass())
print (MyClass() == MyClass())
print (MyClass() == 42)
| class Myclass(object):
def __init__(self):
pass
def __eq__(self, other):
return type(self) == type(other)
if __name__ == '__main__':
print(my_class())
print(my_class())
print(my_class() == my_class())
print(my_class() == 42) |
"""pandas-data-dictionary - Pandas extension adding data dictionary accessor for describing and validating data."""
__version__ = '0.1.0'
__author__ = 'Tom Couch <t.couch@ucl.ac.uk>'
__all__ = []
| """pandas-data-dictionary - Pandas extension adding data dictionary accessor for describing and validating data."""
__version__ = '0.1.0'
__author__ = 'Tom Couch <t.couch@ucl.ac.uk>'
__all__ = [] |
# 2020.08.02
# Problem Statement:
# https://leetcode.com/problems/substring-with-concatenation-of-all-words/
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
# check if s is empty or words is empty
if len(s) * len(words) == 0: return []
# length is th... | class Solution:
def find_substring(self, s: str, words: List[str]) -> List[int]:
if len(s) * len(words) == 0:
return []
length = len(words) * len(words[0])
word_length = len(words[0])
word_dict = {}
for word in words:
word_dict[word] = 0
for w... |
print("hello")
print("hello")
print("hello")
print("hello")
print("It's me")
print("I'm here")
| print('hello')
print('hello')
print('hello')
print('hello')
print("It's me")
print("I'm here") |
class CourseType():
__doc__ = "Type of degree, e.g. BA, BEng, BSc"
possibleCourseTypes = ["BA", "BSc"] #TODO extend to values from http://typesofdegrees.org/
def __init__(self, name, accepts, singleHons = 0, jointHons = 0):
if self.checkName(name):
self._name = name
self.accepts = accepts
self.singleHons ... | class Coursetype:
__doc__ = 'Type of degree, e.g. BA, BEng, BSc'
possible_course_types = ['BA', 'BSc']
def __init__(self, name, accepts, singleHons=0, jointHons=0):
if self.checkName(name):
self._name = name
self.accepts = accepts
self.singleHons = singleHons
sel... |
#Given an array of integers, return the 3rd Maximum Number in this array, if it doesn't exist, return the Maximum Number. The time complexity must be O(n) or less.
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a=b=c=-pow(10, 18)
nums=set(nums)
for i in nums:... | class Solution(object):
def third_max(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = b = c = -pow(10, 18)
nums = set(nums)
for i in nums:
if i >= a:
(c, b, a) = (b, a, i)
elif i >= b:
(c, b) = (b, i)
... |
def collatz_len(n):
ct = 1
while n != 1:
if n % 2 == 0:
n = n/2
else:
n = 3*n+1
ct += 1
return ct
len_max = i_max = 0
for i in range(1, 1000001):
current_len = collatz_len(i)
if current_len > len_max:
len_max = current_len
i_max = i
... | def collatz_len(n):
ct = 1
while n != 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
ct += 1
return ct
len_max = i_max = 0
for i in range(1, 1000001):
current_len = collatz_len(i)
if current_len > len_max:
len_max = current_len
i_max =... |
# Sorts a Python list in ascending order using the quick sort
# algorithm
def quickSort(theList):
n = len(theList)
recQuickSort(theList, 0, n-1)
# The recursive "in-place" implementation
def recQuickSort(theList, first, last):
# Check the base case (range is trivially sorted)
if first >= last:
... | def quick_sort(theList):
n = len(theList)
rec_quick_sort(theList, 0, n - 1)
def rec_quick_sort(theList, first, last):
if first >= last:
return
else:
pos = partition_seq(theList, first, last)
rec_quick_sort(theList, first, pos - 1)
rec_quick_sort(theList, pos + 1, last)
... |
class Commitment(object):
"""
Abstraction from the messages.Commitment
Purpose: don't mix messaging logic with internal logic
Expect that the `protocol.send()` takes an instance of Commitment and constructs the message by itself.
On incoming messages, the protocol will use the `Commitment.from_mess... | class Commitment(object):
"""
Abstraction from the messages.Commitment
Purpose: don't mix messaging logic with internal logic
Expect that the `protocol.send()` takes an instance of Commitment and constructs the message by itself.
On incoming messages, the protocol will use the `Commitment.from_mess... |
class Time:
max_hours = 23
max_minutes = 59
max_seconds = 59
def __init__(self, hours: int, minutes: int, seconds: int):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def set_time(self, hours, minutes, seconds):
self.hours = hours
... | class Time:
max_hours = 23
max_minutes = 59
max_seconds = 59
def __init__(self, hours: int, minutes: int, seconds: int):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def set_time(self, hours, minutes, seconds):
self.hours = hours
self.min... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def subfun(root, minimal, maximal):
... | class Solution:
def is_valid_bst(self, root: Optional[TreeNode]) -> bool:
def subfun(root, minimal, maximal):
if not root:
return
if root.val >= maximal or root.val <= minimal:
self.out = False
else:
subfun(root.left, mini... |
# Lambda funkcie
#
# Tato sekcia sluzi na precvicenie si lambda vyrazov
#
# Uloha 1:
def make_square():
return(lambda x: x*x)
# Uloha 2:
def make_upper():
return(lambda x: x.upper())
# Uloha 3:
def make_power():
return(lambda x, N: x ** N)
# Uloha 4:
def make_power2(N):
return(lambda x: x ** N)
... | def make_square():
return lambda x: x * x
def make_upper():
return lambda x: x.upper()
def make_power():
return lambda x, N: x ** N
def make_power2(N):
return lambda x: x ** N
def call_name():
return lambda x, name: getattr(x, name)() |
def forever2():
pass
forever(forever2) | def forever2():
pass
forever(forever2) |
IMU_BUS = 2
# MPU9250 Default I2C slave address
MPU_DEFAULT_I2C_ADDR = 0x68
"""
register offsets
"""
SMPLRT_DIV = 0x19
CONFIG = 0x1A
GYRO_CONFIG = 0x1B
ACCEL_CONFIG = 0x1C
ACCEL_CONFIG_2 = 0x1D
INT_PIN_CFG = 0x37
ACCEL_XOUT_H = 0x3B
ACCEL_XOUT_L = 0x3C
ACCEL_YOUT_H = 0x3D
ACCEL_YOUT_L = 0x3E
ACCEL_ZOUT_H = 0x3F
ACCEL... | imu_bus = 2
mpu_default_i2_c_addr = 104
'\nregister offsets\n'
smplrt_div = 25
config = 26
gyro_config = 27
accel_config = 28
accel_config_2 = 29
int_pin_cfg = 55
accel_xout_h = 59
accel_xout_l = 60
accel_yout_h = 61
accel_yout_l = 62
accel_zout_h = 63
accel_zout_l = 64
temp_out_h = 65
temp_out_l = 66
gyro_xout_h = 67
... |
def retrieve_page(page):
if page > 3:
return {"next_page": None, "items": []}
return {"next_page": page + 1, "items": ["A", "B", "C"]}
items = []
page = 1
while page is not None:
page_result = retrieve_page(page)
items += page_result["items"]
page = page_result["next_page"]
print(items) ... | def retrieve_page(page):
if page > 3:
return {'next_page': None, 'items': []}
return {'next_page': page + 1, 'items': ['A', 'B', 'C']}
items = []
page = 1
while page is not None:
page_result = retrieve_page(page)
items += page_result['items']
page = page_result['next_page']
print(items) |
# SIEL type compliance cases require a specific control code prefixes. currently: (0 to 9)D, (0 to 9)E, ML21, ML22.
COMPLIANCE_CASE_ACCEPTABLE_GOOD_CONTROL_CODES = "(^[0-9][DE].*$)|(^ML21.*$)|(^ML22.*$)"
class ComplianceVisitTypes:
FIRST_CONTACT = "first_contact"
FIRST_VISIT = "first_visit"
ROUTINE_VISIT ... | compliance_case_acceptable_good_control_codes = '(^[0-9][DE].*$)|(^ML21.*$)|(^ML22.*$)'
class Compliancevisittypes:
first_contact = 'first_contact'
first_visit = 'first_visit'
routine_visit = 'routine_visit'
revisit = 'revisit'
choices = [(FIRST_CONTACT, 'First contact'), (FIRST_VISIT, 'First visit... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
k=-1
pre=ListNode(-1000,list1)
x=List... | class Solution:
def merge_in_between(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
k = -1
pre = list_node(-1000, list1)
x = list_node()
y = list_node()
while pre:
if pre.next and k == a - 1:
x = pre
while k !... |
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
def get_max(self):
return ma... | class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
def get_max(self):
return max(s... |
def palindrome(word, index):
left = index
right = len(word) - 1 - index
if left >= right:
return f"{word} is a palindrome"
right_letter = word[len(word)-1-index]
left_letter = word[index]
if left_letter != right_letter:
return f"{word} is not a palindrome"
return palindrome... | def palindrome(word, index):
left = index
right = len(word) - 1 - index
if left >= right:
return f'{word} is a palindrome'
right_letter = word[len(word) - 1 - index]
left_letter = word[index]
if left_letter != right_letter:
return f'{word} is not a palindrome'
return palindro... |
#
# PySNMP MIB module CISCO-HEALTH-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HEALTH-MONITOR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:59:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
class ListNode:
def __init__(self, key=None, value=None, next_node=None):
self.key = key
self.val = value
self.next = next_node
class MyHashMap:
def __init__(self):
self.size = 8
self.used = 0
self.threshold = 0.618
self.buckets = [None] * self.size
... | class Listnode:
def __init__(self, key=None, value=None, next_node=None):
self.key = key
self.val = value
self.next = next_node
class Myhashmap:
def __init__(self):
self.size = 8
self.used = 0
self.threshold = 0.618
self.buckets = [None] * self.size
... |
DOC_CHAPTER(
header = 'If statements',
topic = 'Reference',
text = """
There are two main forms of if-statements.
1. Regular if-then with optional else-clause
$DOC_LIST_UNORDERED(
$DOC_WORD( if ) $DOC_QUOTE( [ condition ] ),
$DOC_WORD( if ) $DOC_QUOTE( [ condition ] ) $DOC_WORD( then ) $DOC_QUOTE( [ valu... | doc_chapter(header='If statements', topic='Reference', text='\n\nThere are two main forms of if-statements.\n\n1. Regular if-then with optional else-clause\n\n$DOC_LIST_UNORDERED(\n $DOC_WORD( if ) $DOC_QUOTE( [ condition ] ),\n $DOC_WORD( if ) $DOC_QUOTE( [ condition ] ) $DOC_WORD( then ) $DOC_QUOTE( [ value ] ),\n ... |
n=int(input());ans=0
def s(x,h):
global ans
for i in range(3):
if i==0 and x==0: continue
if x==n:
if h%3==0: ans+=1;return
else:
s(x+1,h+i)
s(0,0)
print(ans)
| n = int(input())
ans = 0
def s(x, h):
global ans
for i in range(3):
if i == 0 and x == 0:
continue
if x == n:
if h % 3 == 0:
ans += 1
return
else:
s(x + 1, h + i)
s(0, 0)
print(ans) |
def slack_escape(text: str) -> str:
"""
Escape special control characters in text formatted for Slack's markup.
This applies escaping rules as documented on
https://api.slack.com/reference/surfaces/formatting#escaping
"""
return text.replace("&", "&").replace("<", "<").replace(">", ">... | def slack_escape(text: str) -> str:
"""
Escape special control characters in text formatted for Slack's markup.
This applies escaping rules as documented on
https://api.slack.com/reference/surfaces/formatting#escaping
"""
return text.replace('&', '&').replace('<', '<').replace('>', '>... |
class NoChoice(Exception):
def __init__(self):
super().__init__("Took too long.")
class PaginationError(Exception):
pass
class CannotEmbedLinks(PaginationError):
def __init__(self):
super().__init__("Bot cannot embed links in this channel.")
| class Nochoice(Exception):
def __init__(self):
super().__init__('Took too long.')
class Paginationerror(Exception):
pass
class Cannotembedlinks(PaginationError):
def __init__(self):
super().__init__('Bot cannot embed links in this channel.') |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
def isStringHTML(s):
if not isinstance(s, str):
return False
s = s.lower()
return any(... | def is_string_html(s):
if not isinstance(s, str):
return False
s = s.lower()
return any((tag in s for tag in ('<p>', '<p ', '<br', '<li>'))) |
def assert_dict_equal(expected, actual):
message = []
equal = True
for k, v in expected.items():
if actual[k] != v:
message.append(f"For key {k} want {v}, got {actual[k]}")
equal = False
for k, v in actual.items():
if not k in expected:
message.append(f"Got extra key {k} with value {v... | def assert_dict_equal(expected, actual):
message = []
equal = True
for (k, v) in expected.items():
if actual[k] != v:
message.append(f'For key {k} want {v}, got {actual[k]}')
equal = False
for (k, v) in actual.items():
if not k in expected:
message.app... |
"""
:copyright: (c) 2020 Yotam Rechnitz
:license: MIT, see LICENSE for more details
"""
class Assists:
def __init__(self, js: dict):
self._defensive_assists = js["defensiveAssists"] if "defensiveAssists" in js else 0
self._healing_done = js["healing_done"] if "healing_done" in js else 0
se... | """
:copyright: (c) 2020 Yotam Rechnitz
:license: MIT, see LICENSE for more details
"""
class Assists:
def __init__(self, js: dict):
self._defensive_assists = js['defensiveAssists'] if 'defensiveAssists' in js else 0
self._healing_done = js['healing_done'] if 'healing_done' in js else 0
se... |
x = int(input())
for j in range(x):
q = int(input())
print("Case", j + 1, end=": ")
for t in range(1, int(q / 2 + 1)):
if q % t == 0:
print(t, end=" ")
print(q)
| x = int(input())
for j in range(x):
q = int(input())
print('Case', j + 1, end=': ')
for t in range(1, int(q / 2 + 1)):
if q % t == 0:
print(t, end=' ')
print(q) |
"""
Write a Python program to replace last element in a list with another list.
"""
num1 = [1, 3, 5, 7, 9]
num2 = [2, 4, 6, 8, 0]
num1[-1:] = num2
print(num1) | """
Write a Python program to replace last element in a list with another list.
"""
num1 = [1, 3, 5, 7, 9]
num2 = [2, 4, 6, 8, 0]
num1[-1:] = num2
print(num1) |
class RobotStatus:
def __init__(self):
self.status = 'init'
self.position = ''
def isAvailable(self):
if self.status == 'available':
return True
else:
return False
def isWaitEV(self):
if self.status == 'waitEV':
return True
... | class Robotstatus:
def __init__(self):
self.status = 'init'
self.position = ''
def is_available(self):
if self.status == 'available':
return True
else:
return False
def is_wait_ev(self):
if self.status == 'waitEV':
return True
... |
# The language mapping for 2 and 3 character language code.
language_dict = {
"kn": "kannada",
"kan": "kannada",
"hi": "hindi",
"hin": "hindi",
}
| language_dict = {'kn': 'kannada', 'kan': 'kannada', 'hi': 'hindi', 'hin': 'hindi'} |
# Recursive Functions
def iterTest(low, high):
while low <= high:
print(low)
low=low+1
def recurTest(low,high):
if low <= high:
print(low)
recurTest(low+1, high)
| def iter_test(low, high):
while low <= high:
print(low)
low = low + 1
def recur_test(low, high):
if low <= high:
print(low)
recur_test(low + 1, high) |
#!/usr/bin/env python3
"""
Bradley N. Miller, David L. Ranum
Problem Solving with Algorithms and Data Structures using Python
Copyright 2005
Updated by Roman Yasinovskyy, 2017
"""
class BinaryHeap:
"""Minimal Binary Heap"""
def __init__(self):
"""Create a heap"""
self._heap = []
def _per... | """
Bradley N. Miller, David L. Ranum
Problem Solving with Algorithms and Data Structures using Python
Copyright 2005
Updated by Roman Yasinovskyy, 2017
"""
class Binaryheap:
"""Minimal Binary Heap"""
def __init__(self):
"""Create a heap"""
self._heap = []
def _perc_up(self, cur_idx):
... |
# find min. no. of sets an array (awards) can be divided into such that couple-wise difference of each element is at most k
# ex: awards=[1,5,4,6,8,9,2], k=3, o/p=3
# [1,2][4,5,6][8,9] with max diff 1,2,1 respectively
# int minimumGroups(int awards[n],int k) => o/p
def max_diff(arr):
return max(arr) - min(arr)... | def max_diff(arr):
return max(arr) - min(arr)
def minimum_groups(awards, k):
awards.sort()
count = 1
n = len(awards)
(i, j) = (0, 1)
while j != n:
if max_diff(awards[i:j + 1]) >= k:
count += 1
i = j
j = i + 1
j = j + 1
return count
def ma... |
class Solution:
def countBits(self, n: int) -> List[int]:
arr = []
for i in range(n+1):
i_b = int(bin(i)[2:])
arr.append(self.calculate1(i_b))
return arr
def calculate1(self, i):
count = 0
while i >= 1:
re... | class Solution:
def count_bits(self, n: int) -> List[int]:
arr = []
for i in range(n + 1):
i_b = int(bin(i)[2:])
arr.append(self.calculate1(i_b))
return arr
def calculate1(self, i):
count = 0
while i >= 1:
res = i % 10
if ... |
class Heap:
def __init__(self, arr):
self.arr = arr
self.size = len(self.arr)
def max_heapify(self, current_index):
if not self.is_leaf(current_index):
left_child = (2 * current_index) + 1
right_child = (2 * current_index) + 2
if right_child < self.... | class Heap:
def __init__(self, arr):
self.arr = arr
self.size = len(self.arr)
def max_heapify(self, current_index):
if not self.is_leaf(current_index):
left_child = 2 * current_index + 1
right_child = 2 * current_index + 2
if right_child < self.size:... |
# -*- coding: utf-8 -*-
# @Author: Wenwen Yu
# @Created Time: 7/8/2020 9:34 PM
Entities_list = [
"date_echeance",
"date_facture",
"methode_payement",
"numero_facture",
"rib",
"adresse",
"contact",
"nom_fournisseur",
"matricule_fiscale",
"total_ht",
"total_ttc"
]
# Entities_... | entities_list = ['date_echeance', 'date_facture', 'methode_payement', 'numero_facture', 'rib', 'adresse', 'contact', 'nom_fournisseur', 'matricule_fiscale', 'total_ht', 'total_ttc'] |
""" Script to specify the config
@author: AbinayaM02
"""
# Gunicorn config
bind = '0.0.0.0:5069'
workers = 1
timeout = 0
max_requests = 1
| """ Script to specify the config
@author: AbinayaM02
"""
bind = '0.0.0.0:5069'
workers = 1
timeout = 0
max_requests = 1 |
data = (
'Guo ', # 0x00
'Yin ', # 0x01
'Hun ', # 0x02
'Pu ', # 0x03
'Yu ', # 0x04
'Han ', # 0x05
'Yuan ', # 0x06
'Lun ', # 0x07
'Quan ', # 0x08
'Yu ', # 0x09
'Qing ', # 0x0a
'Guo ', # 0x0b
'Chuan ', # 0x0c
'Wei ', # 0x0d
'Yuan ', # 0x0e
'Quan ', # 0x0f
'K... | data = ('Guo ', 'Yin ', 'Hun ', 'Pu ', 'Yu ', 'Han ', 'Yuan ', 'Lun ', 'Quan ', 'Yu ', 'Qing ', 'Guo ', 'Chuan ', 'Wei ', 'Yuan ', 'Quan ', 'Ku ', 'Fu ', 'Yuan ', 'Yuan ', 'E ', 'Tu ', 'Tu ', 'Tu ', 'Tuan ', 'Lue ', 'Hui ', 'Yi ', 'Yuan ', 'Luan ', 'Luan ', 'Tu ', 'Ya ', 'Tu ', 'Ting ', 'Sheng ', 'Pu ', 'Lu ', 'Iri ', ... |
FEATURES = {"DEBUG_MODE": False}
def feature(feature_id: str) -> bool:
if feature_id not in FEATURES:
raise ValueError("Key not a valid feature")
return FEATURES[feature_id]
| features = {'DEBUG_MODE': False}
def feature(feature_id: str) -> bool:
if feature_id not in FEATURES:
raise value_error('Key not a valid feature')
return FEATURES[feature_id] |
team_names = ['LA Chargers', 'LA Rams', 'NE Patriots', 'NY Giants',
'Chicago Bears']
locations = ['LA', 'NY', 'SF', 'CH', 'NE']
weeks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] | team_names = ['LA Chargers', 'LA Rams', 'NE Patriots', 'NY Giants', 'Chicago Bears']
locations = ['LA', 'NY', 'SF', 'CH', 'NE']
weeks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] |
def any_lowercase(s):
""" incorrect - only checks whether first letter is lower case"""
for c in s:
if c.islower():
return True
else:
return False
def any_lowercase_fixed(s):
for c in s:
if c.islower():
return True
return Fa... | def any_lowercase(s):
""" incorrect - only checks whether first letter is lower case"""
for c in s:
if c.islower():
return True
else:
return False
def any_lowercase_fixed(s):
for c in s:
if c.islower():
return True
return False
def any_lowerc... |
"""
53. Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Examples
--------
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1... | """
53. Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Examples
--------
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1... |
x = int(input(""))
y = int(input(""))
div = int(x/y)
print(div)
mod = int(x % y)
print(mod)
z = divmod(x, y)
print(z) | x = int(input(''))
y = int(input(''))
div = int(x / y)
print(div)
mod = int(x % y)
print(mod)
z = divmod(x, y)
print(z) |
red = 'Red'
blue = 'Blue'
green = 'Green'
spring_green = 'SpringGreen'
hot_pink = 'HotPink'
blue_violet = 'BlueViolet'
cadet_blue = 'CadetBlue'
chocolate = 'Chocolate'
coral = 'Coral'
dodger_blue = 'DodgerBlue'
firebrick = 'Firebrick'
golden_rod = 'GoldenRod'
orange_red = 'OrangeRed'
yellow_green = 'YellowGreen'
sea_gr... | red = 'Red'
blue = 'Blue'
green = 'Green'
spring_green = 'SpringGreen'
hot_pink = 'HotPink'
blue_violet = 'BlueViolet'
cadet_blue = 'CadetBlue'
chocolate = 'Chocolate'
coral = 'Coral'
dodger_blue = 'DodgerBlue'
firebrick = 'Firebrick'
golden_rod = 'GoldenRod'
orange_red = 'OrangeRed'
yellow_green = 'YellowGreen'
sea_gr... |
class Solution:
def numSub(self, s: str) -> int:
l = [int(i) for i in s]
res = 0
i = 0
while i < len(l):
if l[i] != 1:
i += 1
continue
count = 0
curr = 0
while i < len(l) and l[i] == 1:
i ... | class Solution:
def num_sub(self, s: str) -> int:
l = [int(i) for i in s]
res = 0
i = 0
while i < len(l):
if l[i] != 1:
i += 1
continue
count = 0
curr = 0
while i < len(l) and l[i] == 1:
... |
class conta_corrente:
def __Init__(self, nome):
self.nome = nome
self.email = None
self.telefone = None
self._saldo = 0
def _checar_saldo(self, valor):
return self._saldo >= valor
def depositar(self, valor):
self._saldo += valor
def sacar(self, valor):
... | class Conta_Corrente:
def ___init__(self, nome):
self.nome = nome
self.email = None
self.telefone = None
self._saldo = 0
def _checar_saldo(self, valor):
return self._saldo >= valor
def depositar(self, valor):
self._saldo += valor
def sacar(self, valor)... |
chromedriver_path='***'
from_station='***'
to_station='***'
email='***'
phone_num='***'
full_name='***'
card_num='***'
exp='***'
cvv='***' | chromedriver_path = '***'
from_station = '***'
to_station = '***'
email = '***'
phone_num = '***'
full_name = '***'
card_num = '***'
exp = '***'
cvv = '***' |
# terrascript/data/camptocamp/jwt.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:19:50 UTC)
__all__ = []
| __all__ = [] |
mon_fichier = open("mdp.txt" , "r")
crypt = mon_fichier.read()
mon_fichier.close()
mon_fichier = open("encrypt.txt" , "r")
decrypt1 = mon_fichier.read()
mon_fichier.close()
def encrypt(crypt):
number=input("donner une cle de cryptage (numero)")
b=list(crypt)
str(b)
c=[ord(x)for x in(b)]
... | mon_fichier = open('mdp.txt', 'r')
crypt = mon_fichier.read()
mon_fichier.close()
mon_fichier = open('encrypt.txt', 'r')
decrypt1 = mon_fichier.read()
mon_fichier.close()
def encrypt(crypt):
number = input('donner une cle de cryptage (numero)')
b = list(crypt)
str(b)
c = [ord(x) for x in b]
d = []
... |
'''dom.py contains all referenced dom elements. Gathering all fragile dom elements in one config file makes it easier to maintain the code'''
def dom():
dom = {
'loginButton': 'html/body/div[3]/header/div/div/div/div[2]/button/span',
'einverstandenButton': 'div.c-button--bold... | """dom.py contains all referenced dom elements. Gathering all fragile dom elements in one config file makes it easier to maintain the code"""
def dom():
dom = {'loginButton': 'html/body/div[3]/header/div/div/div/div[2]/button/span', 'einverstandenButton': 'div.c-button--bold', 'usernameInput': 'Username'}
retu... |
def template_expand(tool, template, output, subs, executable = False, execution_requirements = None):
"""Powerful template expansion rule.
template_expand uses the powerful golang text/template engine to expand an input template
into an output file. The subs dict provide keys and values, where the values c... | def template_expand(tool, template, output, subs, executable=False, execution_requirements=None):
"""Powerful template expansion rule.
template_expand uses the powerful golang text/template engine to expand an input template
into an output file. The subs dict provide keys and values, where the values can e... |
'''
2. Write a Python Program to read the contents of a file and find how many upper case letters,
lower case letters and digits existed in the file.
'''
file = open('SampleCount.txt','r')
data = file.read()
print('Contents of a file is')
print(data)
digit = upper = lower = special = 0
for ch in data:
if ch.islo... | """
2. Write a Python Program to read the contents of a file and find how many upper case letters,
lower case letters and digits existed in the file.
"""
file = open('SampleCount.txt', 'r')
data = file.read()
print('Contents of a file is')
print(data)
digit = upper = lower = special = 0
for ch in data:
if ch.isl... |
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 5 Module Part 2 Exercise 02
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Want to see this in action?
# In this code, there's a Person class that has an attribute name, which gets set when constructing... | class Person:
def __init__(self, name):
self.name = name
def greeting(self):
return 'hi, my name is {}'.format(self.name)
some_person = person('Nobody')
print(some_person.greeting()) |
def solve(data):
result = 0
# Declares an unordered collection of unique elements
unique_frequencies = set()
while True:
for number in data:
result += number
# Checks if current sum(result) already exists in the collection
if result in unique_frequencies:
... | def solve(data):
result = 0
unique_frequencies = set()
while True:
for number in data:
result += number
if result in unique_frequencies:
return result
unique_frequencies.add(result) |
class InMemoryStorage:
__instance = None
def __init__(self):
self.room_data = dict()
self.user_data = dict()
@classmethod
def __getInstance(cls):
return cls.__instance
@classmethod
def instance(cls, *args, **kargs):
cls.__instance = cls(*args, **kargs)
... | class Inmemorystorage:
__instance = None
def __init__(self):
self.room_data = dict()
self.user_data = dict()
@classmethod
def __get_instance(cls):
return cls.__instance
@classmethod
def instance(cls, *args, **kargs):
cls.__instance = cls(*args, **kargs)
... |
def next_13_numbers_product(num, start):
if start + 13 > len(num):
return 0
x = 1
for index in range(start, start + 13):
x *= int(num[index])
return x
number = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
858615607891129494... | def next_13_numbers_product(num, start):
if start + 13 > len(num):
return 0
x = 1
for index in range(start, start + 13):
x *= int(num[index])
return x
number = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017... |
class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
ans = []
i = 0
j = 0
while i < len(A) and j < len(B):
if A[i][0] <= B[j][0] and A[i][1] >= B[j][1]:
C = []
C.append(B[j][0])... | class Solution:
def interval_intersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
ans = []
i = 0
j = 0
while i < len(A) and j < len(B):
if A[i][0] <= B[j][0] and A[i][1] >= B[j][1]:
c = []
C.append(B[j][0])
... |
def fibonacci():
a = 0
b = 1
while True: # keep going...
yield a # report value, a, during this pass
future = a + b
a = b # this will be next value reported
b = future # and subsequently this
| def fibonacci():
a = 0
b = 1
while True:
yield a
future = a + b
a = b
b = future |
X = int(input())
Y = int(input())
print(int(input())*60 + int(input()))
a = int(input())
print(a//60)
print(a%60)
x=int(input())
h=int(input())
m=int(input())
print(h+(x+m)//60)
print((x+m)%60) | x = int(input())
y = int(input())
print(int(input()) * 60 + int(input()))
a = int(input())
print(a // 60)
print(a % 60)
x = int(input())
h = int(input())
m = int(input())
print(h + (x + m) // 60)
print((x + m) % 60) |
def confusion_matrix(yreal, ypred):
n_classes = len(set(yreal))
new_matrix = []
print("len yreal: ", len(yreal))
print("len ypred: ", len(ypred))
print("n classes: ", n_classes)
for i_class in range(n_classes):
new_matrix.append([])
for _ in range(n_classes): #i_ypred
... | def confusion_matrix(yreal, ypred):
n_classes = len(set(yreal))
new_matrix = []
print('len yreal: ', len(yreal))
print('len ypred: ', len(ypred))
print('n classes: ', n_classes)
for i_class in range(n_classes):
new_matrix.append([])
for _ in range(n_classes):
new_matr... |
def quicksort(array):
if len(array) < 2:
return array
print(quicksort([ ])) | def quicksort(array):
if len(array) < 2:
return array
print(quicksort([])) |
"""Generate a file.
In this example, the content is passed via an attribute. If you generate
large files with a lot of static content, consider using
`ctx.actions.expand_template` instead.
"""
def file(**kwargs):
_file(out = "{name}.txt".format(**kwargs), **kwargs)
def _impl(ctx):
output = ctx.outputs.out
... | """Generate a file.
In this example, the content is passed via an attribute. If you generate
large files with a lot of static content, consider using
`ctx.actions.expand_template` instead.
"""
def file(**kwargs):
_file(out='{name}.txt'.format(**kwargs), **kwargs)
def _impl(ctx):
output = ctx.outputs.out
... |
# Assign String to a Variable
a = 'Hello'
print (a,'\n')
# Multiline Strings
# using three double quotes:
b = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt."""
print(b,'\n')
# using three single quotes:
b = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed... | a = 'Hello'
print(a, '\n')
b = 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt.'
print(b, '\n')
b = 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.'
print(b, '\n')
a = 'I Love Bangladesh'
print(a... |
#
# PySNMP MIB module Unisphere-Data-SONET-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-SONET-CONF
# Produced by pysmi-0.3.4 at Wed May 1 15:32:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_range_constraint, constraints_intersection, value_size_constraint) ... |
name1=["ales","Mark","Deny","Hendry"]
name2=name1
name3=name1[:]
name1=["Anand"]
name3=["Murugan"]
sum=0
for ls in (name1,name2,name3):
if ls[0]=="Anand":
sum+=1
pass
if ls[1]=="Murugan":
sum+=5
print(sum)
pass | name1 = ['ales', 'Mark', 'Deny', 'Hendry']
name2 = name1
name3 = name1[:]
name1 = ['Anand']
name3 = ['Murugan']
sum = 0
for ls in (name1, name2, name3):
if ls[0] == 'Anand':
sum += 1
pass
if ls[1] == 'Murugan':
sum += 5
print(sum)
pass |
def solution():
def integers():
x = 1
while True:
yield x
x += 1
def halves():
for x in integers():
yield x / 2
def take(n, seq):
result = []
for i in range(n):
result.append(next(seq))
return result
retu... | def solution():
def integers():
x = 1
while True:
yield x
x += 1
def halves():
for x in integers():
yield (x / 2)
def take(n, seq):
result = []
for i in range(n):
result.append(next(seq))
return result
ret... |
"""Classes for stateful data stream sampling
"""
def create_sampler(mode, **kwargs):
"""Creates a specified sampler instance
"""
if mode == 'uniform':
return UniformSampler(**kwargs)
elif mode == 'contiguous':
return ContiguousSampler(**kwargs)
else:
raise ValueError('Unkno... | """Classes for stateful data stream sampling
"""
def create_sampler(mode, **kwargs):
"""Creates a specified sampler instance
"""
if mode == 'uniform':
return uniform_sampler(**kwargs)
elif mode == 'contiguous':
return contiguous_sampler(**kwargs)
else:
raise value_error('Unk... |
# Copyright (c) 2017 Pieter Wuille
# Copyright (c) 2018 Oskar Hladky
# Copyright (c) 2018 Pavol Rusnak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without... | charset = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
address_type_p2_kh = 0
address_type_p2_sh = 8
def cashaddr_polymod(values):
generator = [656907472481, 522768456162, 1044723512260, 748107326120, 130178868336]
chk = 1
for value in values:
top = chk >> 35
chk = (chk & 34359738367) << 5 ^ value
... |
class Iec6205621Exception(Exception):
"""General IEC62056-21 Exception"""
class Iec6205621ClientError(Iec6205621Exception):
"""Client error"""
class Iec6205621ParseError(Iec6205621Exception):
"""Error in parsing IEC62056-21 data"""
class ValidationError(Iec6205621Exception):
"""Not valid data erro... | class Iec6205621Exception(Exception):
"""General IEC62056-21 Exception"""
class Iec6205621Clienterror(Iec6205621Exception):
"""Client error"""
class Iec6205621Parseerror(Iec6205621Exception):
"""Error in parsing IEC62056-21 data"""
class Validationerror(Iec6205621Exception):
"""Not valid data error""... |
lines = open('input','r').readlines()
size_linea = 12
unos = [0,0,0,0,0,0,0,0,0,0,0,0]
for line in lines:
for i in range(size_linea):
if (line[i] == '1'):
unos[i] += 1
media = len(lines)/2
gamma = 0
epsilon = 0
for i in range(size_linea):
if (unos[i] > media):
gamma += 2**(size_... | lines = open('input', 'r').readlines()
size_linea = 12
unos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for line in lines:
for i in range(size_linea):
if line[i] == '1':
unos[i] += 1
media = len(lines) / 2
gamma = 0
epsilon = 0
for i in range(size_linea):
if unos[i] > media:
gamma += 2 **... |
# Using flag
prompt = "\nTell me your name, and I will reprint your name: "
prompt += "\nEnter 'quit' to end the program."
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message) | prompt = '\nTell me your name, and I will reprint your name: '
prompt += "\nEnter 'quit' to end the program."
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message) |
print('Numeros pares!!!')
print('=-=' * 15)
for c in range(2, 52, 2):
print(c)
print('=-=' * 15)
print('ACABOU.')
| print('Numeros pares!!!')
print('=-=' * 15)
for c in range(2, 52, 2):
print(c)
print('=-=' * 15)
print('ACABOU.') |
class medicamento:
def __init__(self, id, nombre, precio, descripcion, cantidad, rol):
self.id = id
self.nombre = nombre
self.precio = precio
self.descripcion = descripcion
self.cantidad = cantidad
self.rol = rol
def actualizar_datos(self, id, nombre, preci... | class Medicamento:
def __init__(self, id, nombre, precio, descripcion, cantidad, rol):
self.id = id
self.nombre = nombre
self.precio = precio
self.descripcion = descripcion
self.cantidad = cantidad
self.rol = rol
def actualizar_datos(self, id, nombre, precio, de... |
def test_it(binbb, groups_cfg):
for account, accgrp_cfg in groups_cfg.items():
bbcmd = ["groups", "--account", account]
res = binbb.sysexec(*bbcmd)
# very simple test of group names and member names being seen in output
for group_name, members in accgrp_cfg.items():
asser... | def test_it(binbb, groups_cfg):
for (account, accgrp_cfg) in groups_cfg.items():
bbcmd = ['groups', '--account', account]
res = binbb.sysexec(*bbcmd)
for (group_name, members) in accgrp_cfg.items():
assert group_name in res
for member_name in members:
... |
def pattern_eighten(steps):
''' Pattern eighteen
9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2
9 8 7 6 5 4 3
9 8 7 6 5 4
9 8 7 6 5
9 8 7 6
9 8 7
9 8
9
'''
get_range = [str(i) for i in range(1, steps + 1)][::-1]
for i in range... | def pattern_eighten(steps):
""" Pattern eighteen
9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2
9 8 7 6 5 4 3
9 8 7 6 5 4
9 8 7 6 5
9 8 7 6
9 8 7
9 8
9
"""
get_range = [str(i) for i in range(1, steps + 1)][::-1]
for i in range(len(get_range), 0... |
#!/usr/bin/env python3
class Album:
""" Class representing an album """
def __init__(self, title):
self.title = str(title)
self.tracks = []
self.coverFile = None
def add(self, track):
self.tracks.append(track)
| class Album:
""" Class representing an album """
def __init__(self, title):
self.title = str(title)
self.tracks = []
self.coverFile = None
def add(self, track):
self.tracks.append(track) |
# -*- coding: utf-8 -*-
"""
abide.registry
~~~~~~~~~~~~~~
"""
class PropertyDoesNotExist(AttributeError):
pass
class AbidePropertyRegistry():
"""
Contains the properties that have been registered for persistence.
When a Class is created, the
"""
def __init__(self, *args, **kwargs):... | """
abide.registry
~~~~~~~~~~~~~~
"""
class Propertydoesnotexist(AttributeError):
pass
class Abidepropertyregistry:
"""
Contains the properties that have been registered for persistence.
When a Class is created, the
"""
def __init__(self, *args, **kwargs):
self._property_referen... |
# puck_properties_consts.py
#
# ~~~~~~~~~~~~
#
# pyHand Constants File
#
# ~~~~~~~~~~~~
#
# ------------------------------------------------------------------
# Authors : Chloe Eghtebas,
# Brendan Ritter,
# Pravina Samaratunga,
# Jason Schwartz
#
# Last change: 08.08.2013
#
#... | finger1 = 11
finger2 = 12
finger3 = 13
spread = 14
all_fingers = (FINGER1, FINGER2, FINGER3, SPREAD)
grasp = (FINGER1, FINGER2, FINGER3)
accel = 82
addr = 6
ana0 = 18
ana1 = 19
baud = 12
cmd = 29
cmd_load = 0
cmd_save = 1
cmd_reset = 2
cmd_def = 3
cmd_get = 4
cmd_find = 5
cmd_set = 6
cmd_home = 7
cmd_keep = 8
cmd_loop ... |
#
# @lc app=leetcode id=680 lang=python3
#
# [680] Valid Palindrome II
#
# https://leetcode.com/problems/valid-palindrome-ii/description/
#
# algorithms
# Easy (37.22%)
# Total Accepted: 275.1K
# Total Submissions: 737.9K
# Testcase Example: '"aba"'
#
# Given a string s, return true if the s can be palindrome after... | class Solution:
def valid_palindrome(self, s: str) -> bool:
head = 0
tail = len(s) - 1
while head < tail:
if s[head] == s[tail]:
head += 1
tail -= 1
else:
return self.isPalindrome(s[head + 1:tail + 1]) or self.isPalindr... |
'''
Module contains basic functions
'''
def number_to_power(number, power):
'''
:param number: number to be taken
:param power:
:return: number to power
>>> number_to_power(3, 2)
9
>>> number_to_power(2, 3)
8
'''
return number**power
def number_addition(... | """
Module contains basic functions
"""
def number_to_power(number, power):
"""
:param number: number to be taken
:param power:
:return: number to power
>>> number_to_power(3, 2)
9
>>> number_to_power(2, 3)
8
"""
return number ** power
def number_addition(number1, number... |
def mask_out(sentence, banned, substitutes):
# write your answer between #start and #end
#start
return ''
#end
print('Test 1')
print('Expected:abcd#')
print('Actual :' + mask_out('abcde', 'e', '#'))
print()
print('Test 2')
print('Expected:#$solute')
print('Actual :' + mask_out('absolute', 'ab', '#$... | def mask_out(sentence, banned, substitutes):
return ''
print('Test 1')
print('Expected:abcd#')
print('Actual :' + mask_out('abcde', 'e', '#'))
print()
print('Test 2')
print('Expected:#$solute')
print('Actual :' + mask_out('absolute', 'ab', '#$'))
print()
print('Test 3')
print('Expected:121hon')
print('Actual :' ... |
def linear_search_recursive(arr, value, start, end):
if start >= end: return -1
if arr[start] == value:
return start
if arr[end] == value: return end
else:
return linear_search_recursive(arr, value, start+1, end-1)
test_list = [1,3,9,11,15,19,29]
print(linear_search_recursive(tes... | def linear_search_recursive(arr, value, start, end):
if start >= end:
return -1
if arr[start] == value:
return start
if arr[end] == value:
return end
else:
return linear_search_recursive(arr, value, start + 1, end - 1)
test_list = [1, 3, 9, 11, 15, 19, 29]
print(linear_se... |
'''
Joe Walter
difficulty: 5%
run time: 0:20
answer: 40730
***
034 Digit Factorials
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
***
O... | """
Joe Walter
difficulty: 5%
run time: 0:20
answer: 40730
***
034 Digit Factorials
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
***
O... |
class Config:
"""
:ivar endpoint: url path for docs
:ivar filename: openapi spec file name
:ivar openapi_version: openapi spec version
:ivar title: document title
:ivar version: service version
:ivar ui: ui theme, choose 'redoc' or 'swagger'
:ivar mode: mode for route. **normal** include... | class Config:
"""
:ivar endpoint: url path for docs
:ivar filename: openapi spec file name
:ivar openapi_version: openapi spec version
:ivar title: document title
:ivar version: service version
:ivar ui: ui theme, choose 'redoc' or 'swagger'
:ivar mode: mode for route. **normal** include... |
config = {
"bootstrap_servers": 'localhost:9092',
"async_produce": False,
"models": [
{
"module_name": "image_classification.predict",
"class_name": "ModelPredictor",
}
]
} | config = {'bootstrap_servers': 'localhost:9092', 'async_produce': False, 'models': [{'module_name': 'image_classification.predict', 'class_name': 'ModelPredictor'}]} |
# -*- coding: utf-8 -*-
"""As the name suggests, this file contains (almost?) all the constants we need:
- The tablenames and their web urls
- The county sets
- Column names for all the tables
"""
url_prefix = 'http://www.cdss.ca.gov/inforesources/'
table_url_map = {
'tbl_cf296': url_prefix + 'Resear... | """As the name suggests, this file contains (almost?) all the constants we need:
- The tablenames and their web urls
- The county sets
- Column names for all the tables
"""
url_prefix = 'http://www.cdss.ca.gov/inforesources/'
table_url_map = {'tbl_cf296': url_prefix + 'Research-and-Data/CalFresh-Data-Table... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.