content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""Basic function package for main model."""
__author__ = """Shiyue Nie"""
__email__ = 'snie@logitech.com'
__version__ = '0.1.0'
| """Basic function package for main model."""
__author__ = 'Shiyue Nie'
__email__ = 'snie@logitech.com'
__version__ = '0.1.0' |
def build_errors(resp: dict, errors: Exception) -> dict:
resp["statusCode"] = 500
resp["status"] = f"Internal Server Error: {errors}"
return resp
def build_data_dict(status: str, status_code: int, data: bool) -> dict:
data_dict = {
"statusCode": status_code,
"status": status,
} ... | def build_errors(resp: dict, errors: Exception) -> dict:
resp['statusCode'] = 500
resp['status'] = f'Internal Server Error: {errors}'
return resp
def build_data_dict(status: str, status_code: int, data: bool) -> dict:
data_dict = {'statusCode': status_code, 'status': status}
if data:
data_d... |
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
words = sentence.split()
for index, word in enumerate(words):
if word.startswith(searchWord):
return index + 1
return -1 | class Solution:
def is_prefix_of_word(self, sentence: str, searchWord: str) -> int:
words = sentence.split()
for (index, word) in enumerate(words):
if word.startswith(searchWord):
return index + 1
return -1 |
"""
Slice Resource Orchestrator
Manages the process of obtaining access information from Itinerant DC and replicating the container
"""
| """
Slice Resource Orchestrator
Manages the process of obtaining access information from Itinerant DC and replicating the container
""" |
x=[]
s=0
n=int(input("enter the number of elements"))
for y in range(n):
d=int(input("enter the elements"))
x.append(d)
c=0
for j in x:
c=0
for b in x:
if j==b:
c+=1
if c==1:
s=s+j
print("sum",s)
| x = []
s = 0
n = int(input('enter the number of elements'))
for y in range(n):
d = int(input('enter the elements'))
x.append(d)
c = 0
for j in x:
c = 0
for b in x:
if j == b:
c += 1
if c == 1:
s = s + j
print('sum', s) |
"""
Authors
-------
Dr. Randal J. Barnes
Department of Civil, Environmental, and Geo- Engineering
University of Minnesota
Richard Soule
Source Water Protection
Minnesota Department of Health
Version
-------
03 May 2020
"""
PROJECTNAME = 'Paynesville example'
TARGET = 0
NPATHS = 500
DUR... | """
Authors
-------
Dr. Randal J. Barnes
Department of Civil, Environmental, and Geo- Engineering
University of Minnesota
Richard Soule
Source Water Protection
Minnesota Department of Health
Version
-------
03 May 2020
"""
projectname = 'Paynesville example'
target = 0
npaths = 500
durat... |
#
# PySNMP MIB module CISCO-COPS-CLIENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COPS-CLIENT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, constraints_union, single_value_constraint, value_size_constraint) ... |
"""
Business layer. Classes from this package
define how logical operations should act
in certain domain.
Here you have to create multiple atomic
modules/classes, following SOLID principles.
These classes should be used by Service layer.
"""
| """
Business layer. Classes from this package
define how logical operations should act
in certain domain.
Here you have to create multiple atomic
modules/classes, following SOLID principles.
These classes should be used by Service layer.
""" |
"""
Some modularized command line application.
Some detailed description.
"""
| """
Some modularized command line application.
Some detailed description.
""" |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
pre = p = head
while(p and p.next):
np = p.next
... | class Solution:
def swap_pairs(self, head):
pre = p = head
while p and p.next:
np = p.next
p.next = np.next
np.next = p
if pre == head:
head = np
else:
pre.next = np
pre = p
p = p.nex... |
"""
Common errors for the S3 adapter.
"""
class EmptyFolderError(Exception):
pass
class InvalidFileFormatError(Exception):
pass
| """
Common errors for the S3 adapter.
"""
class Emptyfoldererror(Exception):
pass
class Invalidfileformaterror(Exception):
pass |
'''
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 wit... | """
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 wit... |
def inputFileIntro(numberOfPoints):
result = "-- Input geometry blade\n"
result += str(numberOfPoints)
result += " ! NSPANB\n"
result += " r chord twist xaer zaer\n"
return result
def writeInput(r,chord,twist):
f = open("geomb.inp","w")
f.write(inputFileIntro(len(r)))
... | def input_file_intro(numberOfPoints):
result = '-- Input geometry blade\n'
result += str(numberOfPoints)
result += ' ! NSPANB\n'
result += ' r chord twist xaer zaer\n'
return result
def write_input(r, chord, twist):
f = open('geomb.inp', 'w')
f.write(input_file_intro(len(r)... |
_base_ = [
'../_base_/models/hv_pointpillars_secfpn_kitti.py',
'../_base_/datasets/kitti-3d-3class.py',
'../_base_/schedules/cyclic_40e.py', '../_base_/default_runtime.py'
]
point_cloud_range = [-51.2, -51.2, -4, 51.2, 51.2, 1]
anchor_generator=dict(
type='Anchor3DRangeGenerator',
... | _base_ = ['../_base_/models/hv_pointpillars_secfpn_kitti.py', '../_base_/datasets/kitti-3d-3class.py', '../_base_/schedules/cyclic_40e.py', '../_base_/default_runtime.py']
point_cloud_range = [-51.2, -51.2, -4, 51.2, 51.2, 1]
anchor_generator = dict(type='Anchor3DRangeGenerator', ranges=[[-50, -50, -2.6, 50, 50, -2.6],... |
def perf_ans_calc(L1, L2, C1, C2, C_max):
vals = [0] * len(L1)
wts = [0] * len(L1)
W = C_max - sum(C1)
for jj, (l1, l2, c1, c2) in enumerate(zip(L1, L2, C1, C2)):
vals[jj] = l2 - l1
wts[jj] = c2 - c1
def dp(W, wt, val, n):
k = [[0 for x in range(W + 1)] for x in range(n + 1)... | def perf_ans_calc(L1, L2, C1, C2, C_max):
vals = [0] * len(L1)
wts = [0] * len(L1)
w = C_max - sum(C1)
for (jj, (l1, l2, c1, c2)) in enumerate(zip(L1, L2, C1, C2)):
vals[jj] = l2 - l1
wts[jj] = c2 - c1
def dp(W, wt, val, n):
k = [[0 for x in range(W + 1)] for x in range(n + ... |
class TablePrinter:
"""
Class for generating a table from a header and table body. Prints in
either regular ascii text or in latex format.
"""
def __init__(self, header, table):
"""
Initializer for TablePrinter. Sets up a NxM table.
Args:
header: list of N str ... | class Tableprinter:
"""
Class for generating a table from a header and table body. Prints in
either regular ascii text or in latex format.
"""
def __init__(self, header, table):
"""
Initializer for TablePrinter. Sets up a NxM table.
Args:
header: list of N str ... |
class Tree:
def __init__(self, key=None, children=None):
if children is None:
children = []
self.root = key
self.children = children
def get_root(self):
return self.root
def set_root(self, key):
self.root = key
def get_children(self):
return... | class Tree:
def __init__(self, key=None, children=None):
if children is None:
children = []
self.root = key
self.children = children
def get_root(self):
return self.root
def set_root(self, key):
self.root = key
def get_children(self):
retur... |
"""List of known API endpoints."""
API_PATH = {
"assets": "api/v2/assets",
"markets": "api/v1/markets",
"news": "api/v1/news",
"asset": "api/v1/assets/{asset}",
"asset_profile": "api/v2/assets/{... | """List of known API endpoints."""
api_path = {'assets': 'api/v2/assets', 'markets': 'api/v1/markets', 'news': 'api/v1/news', 'asset': 'api/v1/assets/{asset}', 'asset_profile': 'api/v2/assets/{asset}/profile', 'asset_metrics': 'api/v1/assets/{asset}/metrics', 'asset_market_data': 'api/v1/assets/{asset}/metrics/market-d... |
# START LAB EXERCISE 07
print('Lab Exercise 07 \n')
# SETUP
houseplants = [
{"Name": "Areca Palm", "Max height": "8 feet", "Water": "Low", "Sunlight": "Part shade"},
{"Name": "Parlor Palm", "Max height": "6 feet", "Water": "Medium" , "Sunlight": "Part shade"},
{"Name": "Aloe Vera", "Max height": "2 feet",... | print('Lab Exercise 07 \n')
houseplants = [{'Name': 'Areca Palm', 'Max height': '8 feet', 'Water': 'Low', 'Sunlight': 'Part shade'}, {'Name': 'Parlor Palm', 'Max height': '6 feet', 'Water': 'Medium', 'Sunlight': 'Part shade'}, {'Name': 'Aloe Vera', 'Max height': '2 feet', 'Water': 'Low', 'Light': 'Full sun'}, {'Name': ... |
"""English-language verb forms for all but the most simply conjugated verbs.
Not only irregular verbs (strictly speaking) but also any regular verbs that
are not correctly conjugated by the simple algorithm in the Realizer. The
Realizer does not do any consonant doubling, so verbs whose consontants are
doubled have to... | """English-language verb forms for all but the most simply conjugated verbs.
Not only irregular verbs (strictly speaking) but also any regular verbs that
are not correctly conjugated by the simple algorithm in the Realizer. The
Realizer does not do any consonant doubling, so verbs whose consontants are
doubled have to... |
def describe_list():
def describe_GET():
def it_returns_all_fonts(expect, client):
request, response = client.get("/fonts")
expect(len(response.json)) == 6
def describe_detail():
def describe_GET():
def it_includes_filename(expect, client):
request, response... | def describe_list():
def describe_get():
def it_returns_all_fonts(expect, client):
(request, response) = client.get('/fonts')
expect(len(response.json)) == 6
def describe_detail():
def describe_get():
def it_includes_filename(expect, client):
(request, re... |
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = "AIzaSyAB6p3VGqOsDBL_q-c4rNDRjTPMfMBPsDA"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = ... | developer_key = 'AIzaSyAB6p3VGqOsDBL_q-c4rNDRjTPMfMBPsDA'
youtube_api_service_name = 'youtube'
youtube_api_version = 'v3' |
#
# PySNMP MIB module ZHONE-GEN-INTERFACE-CONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-GEN-INTERFACE-CONFIG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:47:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... | (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) ... |
class Solution:
def traverse(self, prov: int, visited, isConnected: List[List[int]]):
visited[prov] = True
for i in range(0, len(isConnected)):
if isConnected[prov][i] and not visited[i]:
self.traverse(i, visited, isConnected)
def findCircleNum(self, isConnected: Lis... | class Solution:
def traverse(self, prov: int, visited, isConnected: List[List[int]]):
visited[prov] = True
for i in range(0, len(isConnected)):
if isConnected[prov][i] and (not visited[i]):
self.traverse(i, visited, isConnected)
def find_circle_num(self, isConnected... |
def readint(msg):
ok = False
value = 0
while True:
n1 = str(input(msg))
if n1.isdigit():
value = int(n1)
ok = True
else:
print('\033[0;31mError! Please enter a valid INTEGER number. \033[m')
if ok:
break
return value
def r... | def readint(msg):
ok = False
value = 0
while True:
n1 = str(input(msg))
if n1.isdigit():
value = int(n1)
ok = True
else:
print('\x1b[0;31mError! Please enter a valid INTEGER number. \x1b[m')
if ok:
break
return value
def re... |
#!/usr/bin/python3
def test_sequence():
assert 2 + 2 == 4
| def test_sequence():
assert 2 + 2 == 4 |
def check_while_exit_condition():
num1 = 1
while num1 <= 5:
# 1
# 2
# 3
# 4
# 5
print(num1)
num1 = num1 + 1
print("\n")
num2 = 10
while num2 <= 5:
print(num2)
num2 = num2 + 1
return
def let_user_choose_when_exit():
pr... | def check_while_exit_condition():
num1 = 1
while num1 <= 5:
print(num1)
num1 = num1 + 1
print('\n')
num2 = 10
while num2 <= 5:
print(num2)
num2 = num2 + 1
return
def let_user_choose_when_exit():
print("Welcome. \nEnter 'quit' to end the program.")
prompt ... |
author = "Palguno Wicaksono"
def antiTamper(author):
dataList = author.split(" ")
b = len(dataList[0])
c = len(dataList[1])
d = b**2 - 4*c
x = list(bin(d))
y = len(bin(d))
while True:
try:
try:
x = len("Palguno Wicaksono")/int(x[y-1])
... | author = 'Palguno Wicaksono'
def anti_tamper(author):
data_list = author.split(' ')
b = len(dataList[0])
c = len(dataList[1])
d = b ** 2 - 4 * c
x = list(bin(d))
y = len(bin(d))
while True:
try:
try:
x = len('Palguno Wicaksono') / int(x[y - 1])
... |
# -*- coding: utf-8 -*-
"""
766. Toeplitz Matrix
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Note:
matrix will be a 2D array of integers.
matrix will have a number of rows and columns in rang... | """
766. Toeplitz Matrix
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Note:
matrix will be a 2D array of integers.
matrix will have a number of rows and columns in range [1, 20].
matrix[i][j] ... |
n = int(input())
a = list(map(lambda x: int(x) % n, input().split()))
b = [ True for i in range(n) ]
flag = True
for x in a:
if b[x] == False:
flag = False
break
b[x] = False
print("YES" if flag else "NO") | n = int(input())
a = list(map(lambda x: int(x) % n, input().split()))
b = [True for i in range(n)]
flag = True
for x in a:
if b[x] == False:
flag = False
break
b[x] = False
print('YES' if flag else 'NO') |
__all__ = (
"CabbageException",
"Unexplained",
"HTTPException",
"NotModified",
"Unauthorized",
"HTTPUnexplained",
)
def flatten_error_dict(d, key=""):
items = []
for k, v in d.items():
new_key = key + "." + k if key else k
if isinstance(v, dict):
try:
... | __all__ = ('CabbageException', 'Unexplained', 'HTTPException', 'NotModified', 'Unauthorized', 'HTTPUnexplained')
def flatten_error_dict(d, key=''):
items = []
for (k, v) in d.items():
new_key = key + '.' + k if key else k
if isinstance(v, dict):
try:
_errors = v['_er... |
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
# Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
#
# The function twoSum should return indices of the two numbers such that they add up to the target, where index1... | class Solution(object):
def two_sum(self, numbers, target):
left = 0
right = len(numbers) - 1
while left < right:
sum = numbers[left] + numbers[right]
if sum < target:
left += 1
elif sum > target:
right -= 1
els... |
class Monitor:
name = 'Samsung'
matrix = 'VA'
res = 'WQHD'
freq = 60
class Headphones:
name = 'Sony'
sensitivity = 108
micro = True
mon1 = Monitor
mon1.freq = 75
mon2 = Monitor
mon2.freq = 144
mon3 = Monitor
mon3.freq = 280
mon4 = Monitor
mon4.freq = 360
hd1 = Headphones
hd2 = Headphone... | class Monitor:
name = 'Samsung'
matrix = 'VA'
res = 'WQHD'
freq = 60
class Headphones:
name = 'Sony'
sensitivity = 108
micro = True
mon1 = Monitor
mon1.freq = 75
mon2 = Monitor
mon2.freq = 144
mon3 = Monitor
mon3.freq = 280
mon4 = Monitor
mon4.freq = 360
hd1 = Headphones
hd2 = Headphones
hd... |
# Kandu! Entertainment est. 6/30/2018
# This is the story module for Mysteries of Galoo.
def welcome_to_galoo():
clear_buffer()
print("""
Welcome to Mysteries of Galoo!
_________________________________________________________________
Far away near the dark mountain of Soochun lives a dark energy... | def welcome_to_galoo():
clear_buffer()
print('\n\nWelcome to Mysteries of Galoo!\n_________________________________________________________________\n\nFar away near the dark mountain of Soochun lives a dark energy genie,\nKathun the Enforcer. Wise young traveler you are all we have hoped\nfor in these last few ... |
__all__ = [
'aiohttp_session',
'curio_asks_session',
'trio_asks_session',
'abc'
] | __all__ = ['aiohttp_session', 'curio_asks_session', 'trio_asks_session', 'abc'] |
def matching_random_motif(N, gc_content, seq):
GC_count=0
AT_count=0
for i in range(len(seq)):
if(seq[i]=='G' or seq[i]=='C'):
GC_count+=1
else:
AT_count+=1
prob_seq = (gc_content/2)**GC_count*((1-gc_content)/2)**AT_count
prob_not_motif = (1-... | def matching_random_motif(N, gc_content, seq):
gc_count = 0
at_count = 0
for i in range(len(seq)):
if seq[i] == 'G' or seq[i] == 'C':
gc_count += 1
else:
at_count += 1
prob_seq = (gc_content / 2) ** GC_count * ((1 - gc_content) / 2) ** AT_count
prob_not_motif ... |
class _MasterProblemBase:
"""Base class for the master problems.
Args:
G (DiGraph): Underlying network.
routes_with_node (dict): Keys : nodes ; Values : list of routes which contain the node
routes (list): Current routes/variables/columns.
drop_penalty (int, optional): Value of ... | class _Masterproblembase:
"""Base class for the master problems.
Args:
G (DiGraph): Underlying network.
routes_with_node (dict): Keys : nodes ; Values : list of routes which contain the node
routes (list): Current routes/variables/columns.
drop_penalty (int, optional): Value of ... |
#
# @lc app=leetcode id=154 lang=python3
#
# [154] Find Minimum in Rotated Sorted Array II
#
# @lc code=start
class Solution:
def findMin(self, nums):
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return nums[i + 1]
return nums[0]
# @lc code=end
| class Solution:
def find_min(self, nums):
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return nums[i + 1]
return nums[0] |
#
# PySNMP MIB module Juniper-Frame-Relay-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-Frame-Relay-CONF
# Produced by pysmi-0.3.4 at Wed May 1 14:02:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 11 19:19:54 2019
@author: NOTEBOOK
"""
def main():
show_interest(1000,10,0.01)
def show_interest(principal,period,rate):
interest = principal * period * rate
print('The interest will be $', format(interest,',.2f'), sep='')
main() | """
Created on Wed Dec 11 19:19:54 2019
@author: NOTEBOOK
"""
def main():
show_interest(1000, 10, 0.01)
def show_interest(principal, period, rate):
interest = principal * period * rate
print('The interest will be $', format(interest, ',.2f'), sep='')
main() |
"""
Problem Statement: Reduce a number to 1 by performing given operations
Given number in binary form, if its even -> you can divide it by 2; if its odd -> you can substract 1 from it.
You can repeat above steps as many times as you want to reach 0. How many steps it took to reach zero?
Language: Python
Written by:... | """
Problem Statement: Reduce a number to 1 by performing given operations
Given number in binary form, if its even -> you can divide it by 2; if its odd -> you can substract 1 from it.
You can repeat above steps as many times as you want to reach 0. How many steps it took to reach zero?
Language: Python
Written by:... |
def trajectory_importance_max_min(states_importance):
""" computes the importance of the trajectory, according to max-min approach: delta(max state, min state) """
max, min = float("-inf"), float("inf")
for i in range(len(states_importance)):
state_importance = states_importance[i]
if state_... | def trajectory_importance_max_min(states_importance):
""" computes the importance of the trajectory, according to max-min approach: delta(max state, min state) """
(max, min) = (float('-inf'), float('inf'))
for i in range(len(states_importance)):
state_importance = states_importance[i]
if st... |
#
# @lc app=leetcode id=260 lang=python3
#
# [260] Single Number III
#
# @lc code=start
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
digist = {}
for num in nums:
digist[num] = digist.get(num, 0) + 1
res = [num for num in digist.keys() if digist[num] =... | class Solution:
def single_number(self, nums: List[int]) -> List[int]:
digist = {}
for num in nums:
digist[num] = digist.get(num, 0) + 1
res = [num for num in digist.keys() if digist[num] == 1]
return res |
class Error(Exception):
"""Base exception."""
class StylespaceError(Error):
"""Represents a consistency error in Stylespaces."""
| class Error(Exception):
"""Base exception."""
class Stylespaceerror(Error):
"""Represents a consistency error in Stylespaces.""" |
comp1 = (1, 2, 3) < (1, 2, 4)
comp2 = [1, 2, 3] < [1, 2, 4]
comp3 = 'ABC' < 'C' < 'Pascal' < 'Python'
comp4 = (1, 2, 3, 4) < (1, 2, 4)
comp5 = (1, 2) < (1, 2, -1)
comp6 = (1, 2, 3) == (1.0, 2.0, 3.0)
comp7 = (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)... | comp1 = (1, 2, 3) < (1, 2, 4)
comp2 = [1, 2, 3] < [1, 2, 4]
comp3 = 'ABC' < 'C' < 'Pascal' < 'Python'
comp4 = (1, 2, 3, 4) < (1, 2, 4)
comp5 = (1, 2) < (1, 2, -1)
comp6 = (1, 2, 3) == (1.0, 2.0, 3.0)
comp7 = (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
print(comp1, comp2, comp3, comp4, comp5, comp6, comp7) |
CACHE = {}
@profile
def leonardo(number):
if number in (0, 1):
return 1
if number not in CACHE:
result = leonardo(number - 1) + leonardo(number - 2) + 1
CACHE[number] = result
return CACHE[number]
NUMBER = 35000
for i in range(NUMBER + 1):
print(f'leonardo[{i}] = {leonard... | cache = {}
@profile
def leonardo(number):
if number in (0, 1):
return 1
if number not in CACHE:
result = leonardo(number - 1) + leonardo(number - 2) + 1
CACHE[number] = result
return CACHE[number]
number = 35000
for i in range(NUMBER + 1):
print(f'leonardo[{i}] = {leonardo(i)}') |
'''
QUEUE IS A LINEAR DATASTRUCTURE , WHICH SIMULATES
REALWORLD QUEUE PROGRAMATICALLY , IT REPRESENTS
QUEUE OF ITEMS , WHERE NEW ITEMS CAN BE ENQUEUED AT REAR
POSITION , WHILE EXIST ITEMS CAN BE DEQUEUED FROM
FRONT POSITION
'''
class queue:
def __init__(self, lim=10):
self.size = lim
# alotting ... | """
QUEUE IS A LINEAR DATASTRUCTURE , WHICH SIMULATES
REALWORLD QUEUE PROGRAMATICALLY , IT REPRESENTS
QUEUE OF ITEMS , WHERE NEW ITEMS CAN BE ENQUEUED AT REAR
POSITION , WHILE EXIST ITEMS CAN BE DEQUEUED FROM
FRONT POSITION
"""
class Queue:
def __init__(self, lim=10):
self.size = lim
self.q = [... |
LANIA = 1032200
sm.lockInGameUI(True)
sm.curNodeEventEnd(True)
sm.forcedInput(4)
sm.showEffect("Effect/OnUserEff.img/guideEffect/evanTutorial/evanBalloon401", 0, 0, 20, -2, -2, False, 0)
sm.spawnNpc(LANIA, 800, -40)
sm.showNpcSpecialActionByTemplateId(LANIA, "summon", 0)
sm.reservedEffect("Effect/Direction8.img/lightn... | lania = 1032200
sm.lockInGameUI(True)
sm.curNodeEventEnd(True)
sm.forcedInput(4)
sm.showEffect('Effect/OnUserEff.img/guideEffect/evanTutorial/evanBalloon401', 0, 0, 20, -2, -2, False, 0)
sm.spawnNpc(LANIA, 800, -40)
sm.showNpcSpecialActionByTemplateId(LANIA, 'summon', 0)
sm.reservedEffect('Effect/Direction8.img/lightni... |
#Calling a method multiple times by using explicit calls when a base uses super()
class Vehicle(object):
def __del__(self):
recycle(self.base_parts)
super(Vehicle, self).__del__()
class Car(Vehicle):
def __del__(self):
recycle(self.car_parts)
super(Car, self)... | class Vehicle(object):
def __del__(self):
recycle(self.base_parts)
super(Vehicle, self).__del__()
class Car(Vehicle):
def __del__(self):
recycle(self.car_parts)
super(Car, self).__del__()
class Sportscar(Car, Vehicle):
def __del__(self):
recycle(self.sports_car_p... |
def get_athlete_from_id(athlete_id):
connection = sqlite3.connect(db_name)
cursor = connection.cursor()
results = cursor.execute("""SELECT name, dob FROM athletes WHERE id=?""",
(athlete_id,))
(name, dob) = results.fetchone()
results = cursor.execute("""SELECT va... | def get_athlete_from_id(athlete_id):
connection = sqlite3.connect(db_name)
cursor = connection.cursor()
results = cursor.execute('SELECT name, dob FROM athletes WHERE id=?', (athlete_id,))
(name, dob) = results.fetchone()
results = cursor.execute('SELECT value FROM timing_data WHERE athlete_id=?', (... |
class KiveAuthException(Exception):
pass
class KiveClientException(Exception):
pass
class KiveServerException(Exception):
pass
class KiveMalformedDataException(Exception):
pass
class KiveRunFailedException(Exception):
pass
def is_client_error(code):
return 400 <= code <= 499
def is_s... | class Kiveauthexception(Exception):
pass
class Kiveclientexception(Exception):
pass
class Kiveserverexception(Exception):
pass
class Kivemalformeddataexception(Exception):
pass
class Kiverunfailedexception(Exception):
pass
def is_client_error(code):
return 400 <= code <= 499
def is_server_... |
"""
This module concerns converting strokes to gcode.
"""
def write_gcode(
writer,
strokes,
offset,
z_hop=2,
feedrate_draw=1800,
feedrate_travel=3600,
feedrate_z_hop=300,
start_gcode='G28\nG21\n',
end_gcode='G28 X0 Y0\n',
):
"""
Converts strokes to gcode.
... | """
This module concerns converting strokes to gcode.
"""
def write_gcode(writer, strokes, offset, z_hop=2, feedrate_draw=1800, feedrate_travel=3600, feedrate_z_hop=300, start_gcode='G28\nG21\n', end_gcode='G28 X0 Y0\n'):
"""
Converts strokes to gcode.
Parameters
----------
writer : writable
... |
src =Split('''
''')
component =aos_component('lib_mico_ble_firmware', src)
BT_CHIP = aos_global_config.get('BT_CHIP')
BT_CHIP_REVISION = aos_global_config.get('BT_CHIP_REVISION')
BT_CHIP_XTAL_FREQUENCY = aos_global_config.get('BT_CHIP_XTAL_FREQUENCY')
if BT_CHIP_XTAL_FREQUENCY == None:
src.add_sources( BT... | src = split(' \n')
component = aos_component('lib_mico_ble_firmware', src)
bt_chip = aos_global_config.get('BT_CHIP')
bt_chip_revision = aos_global_config.get('BT_CHIP_REVISION')
bt_chip_xtal_frequency = aos_global_config.get('BT_CHIP_XTAL_FREQUENCY')
if BT_CHIP_XTAL_FREQUENCY == None:
src.add_sources(BT_CHIP + BT_... |
"""mandelbrot pure python"""
def pprint(arr, w):
x = []
for a in arr:
x.append(a)
if len(x) >= w:
print( [ round(y,2) for y in x] )
x = []
def main():
@returns( array=[64,64] )
@typedef( x=float, y=float, tempX=float, i=int, runaway=int, c=vec2)
@gpu.main
def gpufunc():
c = get_global_id()
x = 0.... | """mandelbrot pure python"""
def pprint(arr, w):
x = []
for a in arr:
x.append(a)
if len(x) >= w:
print([round(y, 2) for y in x])
x = []
def main():
@returns(array=[64, 64])
@typedef(x=float, y=float, tempX=float, i=int, runaway=int, c=vec2)
@gpu.main
d... |
#!/usr/bin/env python3
"""Advent of Code 2021 Day 20 - Trench Map"""
def enhance_image(image_coords, steps):
explored = set()
for step in range(steps):
x_values = sorted([coords[0] for coords in image_coords])
y_values = sorted([coords[1] for coords in image_coords])
min_x, max_x = x_... | """Advent of Code 2021 Day 20 - Trench Map"""
def enhance_image(image_coords, steps):
explored = set()
for step in range(steps):
x_values = sorted([coords[0] for coords in image_coords])
y_values = sorted([coords[1] for coords in image_coords])
(min_x, max_x) = (x_values[0] - 1, x_value... |
# San Francisco International
# https://www.openstreetmap.org/way/23718192
assert_has_feature(
13, 1311, 3170, 'pois',
{ 'kind': 'aerodrome',
'iata': 'SFO' })
# Oakland airport
# https://www.openstreetmap.org/way/54363486
assert_has_feature(
13, 1314, 3167, 'pois',
{ 'kind': 'aerodrome',
'i... | assert_has_feature(13, 1311, 3170, 'pois', {'kind': 'aerodrome', 'iata': 'SFO'})
assert_has_feature(13, 1314, 3167, 'pois', {'kind': 'aerodrome', 'iata': 'OAK'}) |
class AST(object):
pass
class String(AST):
def __init__(self, value: str):
self.value = value
class Load(AST):
def __init__(self, child: String):
self.child = child
class Create(AST):
def __init__(self, child: String):
self.child = child
class Append(AST):
def __init_... | class Ast(object):
pass
class String(AST):
def __init__(self, value: str):
self.value = value
class Load(AST):
def __init__(self, child: String):
self.child = child
class Create(AST):
def __init__(self, child: String):
self.child = child
class Append(AST):
def __init_... |
# -*- coding: utf-8 -*-
"""Testing package for the ROSCO controller."""
__author__ = """Dan Zalkind and Nikhar J. Abbas"""
__email__ = 'daniel.zalkind@nrel.gov'
| """Testing package for the ROSCO controller."""
__author__ = 'Dan Zalkind and Nikhar J. Abbas'
__email__ = 'daniel.zalkind@nrel.gov' |
# This file is part of P4wnP1.
#
# Copyright (c) 2017, Marcus Mengs.
#
# P4wnP1 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... | class Config:
def __init__(self, configfile):
self.conf = Config.conf_to_dict(configfile)
@staticmethod
def conf_to_dict(filename):
result_dict = {}
lines = []
with open(filename, 'r') as f:
lines = f.readlines()
for l in lines:
l = l.split('... |
class CameraHandler:
def __init__(self, resolution, zoom=1.0, camera_pos=(0, 0)):
self.resolution = resolution
self.zoom = zoom
self.camera_pos = camera_pos
def home(self):
self.camera_pos = (0, 0)
self.zoom = 1.0
def move_camera(self, x, y):
self.camera_pos... | class Camerahandler:
def __init__(self, resolution, zoom=1.0, camera_pos=(0, 0)):
self.resolution = resolution
self.zoom = zoom
self.camera_pos = camera_pos
def home(self):
self.camera_pos = (0, 0)
self.zoom = 1.0
def move_camera(self, x, y):
self.camera_po... |
class PermError(Exception):
pass
class ObjectNotPersisted(PermError):
pass
class IncorrectObject(PermError):
pass
class IncorrectContentType(PermError):
pass
class ImproperlyConfigured(PermError):
pass
| class Permerror(Exception):
pass
class Objectnotpersisted(PermError):
pass
class Incorrectobject(PermError):
pass
class Incorrectcontenttype(PermError):
pass
class Improperlyconfigured(PermError):
pass |
HOUR = range(24) # 0->23
DOW = range(1,8) # 1-6
SLOT = (0,12,13,24,25,30,36,37,48,49)
SPOT_TYPE = [
"Live Read Promo",
"Recorded Promo",
"Live Read PSA",
"Recorded PSA",
"Underwriting Spot",
"Pledge Liner",
"Station ID",
"Other"
]
DAY = (
'Monday',
'Tuesday',
'Wednes... | hour = range(24)
dow = range(1, 8)
slot = (0, 12, 13, 24, 25, 30, 36, 37, 48, 49)
spot_type = ['Live Read Promo', 'Recorded Promo', 'Live Read PSA', 'Recorded PSA', 'Underwriting Spot', 'Pledge Liner', 'Station ID', 'Other']
day = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
dow_choice... |
class LastWord:
def lengthOfLastWord(self, s: str) -> int:
last=s.split()
if len(last)==0:
return 0
while s:
last_word=last[-1]
x=len(last_word)
if x==0:
return 0
else:
return x
break
... | class Lastword:
def length_of_last_word(self, s: str) -> int:
last = s.split()
if len(last) == 0:
return 0
while s:
last_word = last[-1]
x = len(last_word)
if x == 0:
return 0
else:
return x
... |
"""Package version and other metadata"""
__author__ = 'ThreatConnect (support@threatconnect.com)'
__author_email__ = 'support@threatconnect.com'
__description__ = 'A pre-commit hook to check the README.md file of an App.'
__license__ = 'Apache License, Version 2'
__package_name__ = 'check_app_readme'
__url__ = 'https:/... | """Package version and other metadata"""
__author__ = 'ThreatConnect (support@threatconnect.com)'
__author_email__ = 'support@threatconnect.com'
__description__ = 'A pre-commit hook to check the README.md file of an App.'
__license__ = 'Apache License, Version 2'
__package_name__ = 'check_app_readme'
__url__ = 'https:/... |
print(
'-----------------------------------------\n'\
'Practical python education || Exercise-19:\n'\
'-----------------------------------------\n'
)
print(
'Task:\n'\
'-----------------------------------------\n'\
'Write a Python program to get a new string from a given string where "Is" has been added ... | print('-----------------------------------------\nPractical python education || Exercise-19:\n-----------------------------------------\n')
print('Task:\n-----------------------------------------\nWrite a Python program to get a new string from a given string where "Is" has been added to the front. If the given string ... |
"""
You can check this by going back the interactive demo 2.1 and set the
weight to w<0. You will notice that the system has only one fixed point and that
is at zero value. For this particular dynamics, the system will eventually converge
to zero. But try it out!
"""; | """
You can check this by going back the interactive demo 2.1 and set the
weight to w<0. You will notice that the system has only one fixed point and that
is at zero value. For this particular dynamics, the system will eventually converge
to zero. But try it out!
""" |
with open('myfile.csv') as fh:
line = fh.readline()
value = line.split('\t')[0]
with open('other.txt',"w") as fw:
fw.write(str(int(value)*.2))
| with open('myfile.csv') as fh:
line = fh.readline()
value = line.split('\t')[0]
with open('other.txt', 'w') as fw:
fw.write(str(int(value) * 0.2)) |
"""
Codemonk link: https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/big-p-and-punishment-5/
Big P has become a Physical Education teacher at Hack International School. Today, the students of class XII have been
very undisciplined and he decides to punish them all. H... | """
Codemonk link: https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/big-p-and-punishment-5/
Big P has become a Physical Education teacher at Hack International School. Today, the students of class XII have been
very undisciplined and he decides to punish them all. H... |
text = "X-DSPAM-Confidence: 0.8475";
numbers = text.find(' ')
decibel = text.find('5', numbers)
floater = text[numbers + 1 : decibel + 1]
floating = floater.strip()
print(floating)
| text = 'X-DSPAM-Confidence: 0.8475'
numbers = text.find(' ')
decibel = text.find('5', numbers)
floater = text[numbers + 1:decibel + 1]
floating = floater.strip()
print(floating) |
#
# PySNMP MIB module HM2-USERMGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-USERMGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:32:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ... |
class RelPos(object):
def __init__(self,row,col):
assert(isinstance(row,int))
assert(isinstance(col,int))
self.__row = row
self.__col = col
def __str__(self):
return str(self.__row) + 'x' + \
str(self.__col)
def __repr__(self):
return 'Stream... | class Relpos(object):
def __init__(self, row, col):
assert isinstance(row, int)
assert isinstance(col, int)
self.__row = row
self.__col = col
def __str__(self):
return str(self.__row) + 'x' + str(self.__col)
def __repr__(self):
return 'Stream.RelPos(' + rep... |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, "download.php","yonyouup")
| def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, 'download.php', 'yonyouup') |
## first thing to do is to access the file
## r = read
## w = write
## a = append
## r++ = read and write
##open(" name of file + extension", "r" | "w" | "a", "r+")
## writing and appending to files
## writing new file and appending to existing
##employee_file = open("employees.txt", "a" )
#check if file is ... | employee_file = open('emploees1.txt', 'w')
employee_file.write('\nJohn - Assistant Manager')
employee_file.close() |
'''
Time : O(n)
Space : O(n)
'''
class Solution(object):
def twoSum(self, nums, target):
map = {}
for i in range(0,len(nums)):
goal = target - nums[i]
if goal in map:
return [map[goal], i]
map[nums[i]] = i
if __name__ == "__main__":
... | """
Time : O(n)
Space : O(n)
"""
class Solution(object):
def two_sum(self, nums, target):
map = {}
for i in range(0, len(nums)):
goal = target - nums[i]
if goal in map:
return [map[goal], i]
map[nums[i]] = i
if __name__ == '__main__':
sl = so... |
a = ["1", 1, "1", 2]
# ex-14: Remove duplicates from list a
a = list(set(a))
print(a)
# ex-15: Create a dictionary that contains the keys a and b and their respec
# tive values 1 and 2 .
my_dict = {"a":1, "b":2}
print(my_dict)
print(type(my_dict))
# Add "c":3 to dictionary
my_dict["c"] = 3
print(my_dict)
my_dict2... | a = ['1', 1, '1', 2]
a = list(set(a))
print(a)
my_dict = {'a': 1, 'b': 2}
print(my_dict)
print(type(my_dict))
my_dict['c'] = 3
print(my_dict)
my_dict2 = dict([('a', 1), ('b', 2)])
print(my_dict2)
d = {'a': 1, 'b': 2}
print(d['b'])
d = {'a': 1, 'b': 2, 'c': 3}
sum = d['a'] + d['b']
print(sum)
d = {'a': 1, 'b': 2}
d['c']... |
def main():
print("Hello GitHub!")
print("Another Try")
print("new branch")
main()
| def main():
print('Hello GitHub!')
print('Another Try')
print('new branch')
main() |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'chromeos_tools.gypi'
],
'targets': [
{
'target_name': 'chromeos',
... | {'variables': {'chromium_code': 1}, 'includes': ['chromeos_tools.gypi'], 'targets': [{'target_name': 'chromeos', 'type': '<(component)', 'dependencies': ['../base/base.gyp:base', '../base/base.gyp:base_prefs', '../build/linux/system.gyp:dbus', '../build/linux/system.gyp:ssl', '../dbus/dbus.gyp:dbus', '../net/net.gyp:ne... |
#!/usr/bin/python3
print('Content-Type: text/html; charset=UTF-8\n\n')
my_var = 'Python'
print('<h1>Hello World From ' + my_var + '</h1>')
| print('Content-Type: text/html; charset=UTF-8\n\n')
my_var = 'Python'
print('<h1>Hello World From ' + my_var + '</h1>') |
# The current volume of a water reservoir (in cubic metres)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic metres)
rainfall = 5e6
# decrease the rainfall variable by 10% to account for runoff
rainfall *= ( 1 - 0.1 )
# add the rainfall variable to the reservoir_volume variable
reservoir_vol... | reservoir_volume = 444500000.0
rainfall = 5000000.0
rainfall *= 1 - 0.1
reservoir_volume += rainfall
reservoir_volume *= 1.05
reservoir_volume *= 0.95
reservoir_volume -= 250000.0
print(reservoir_volume) |
# Define a list
# Can add and remove elements
l = ["Bob" , "Rolf", "Anne"]
# Define a tuple
# Can NOT add and remove elements
# Cannot be modified after created
t = ("Bob" , "Rolf", "Anne")
# Define a Set
# Cannot have duplicate values
# Does not always keep the order
s = {"Bob" , "Rolf", "Anne"}
print( l[0] )
# p... | l = ['Bob', 'Rolf', 'Anne']
t = ('Bob', 'Rolf', 'Anne')
s = {'Bob', 'Rolf', 'Anne'}
print(l[0])
l.append('Smith')
print(l)
l.remove('Bob')
print(l)
s.add('Smith')
print(s)
s.add('Smith')
print(s) |
'''
Description:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ ... | """
Description:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ 4 8
/ / 11 13 4
/ \\ ... |
"""
Entradas
Temperatura-->float-->T
Salidas
Deporte-->float-->D
"""
#entrada
T=float(input("Ingrese la temperatura: "))
D=""#str
#caja negra
if(T>85):
D="Natacion"
elif(T>70 and T<=85):
D="Tenis"
elif(T>32 and T<=70):
D="Golf"
elif(T>10 and T<=32):
D="Esqui"
elif(T<=10):
D="Marcha"
#salida
print("El deporte... | """
Entradas
Temperatura-->float-->T
Salidas
Deporte-->float-->D
"""
t = float(input('Ingrese la temperatura: '))
d = ''
if T > 85:
d = 'Natacion'
elif T > 70 and T <= 85:
d = 'Tenis'
elif T > 32 and T <= 70:
d = 'Golf'
elif T > 10 and T <= 32:
d = 'Esqui'
elif T <= 10:
d = 'Marcha'
print('El depor... |
a = set()
print (type(a))
# adding values to an empty set
a.add(4)
a.add(5)
# a.add([4, 5, 6]) You can not add list in a set
a.add((1, 2, 3)) # but you can add tuple in a set
# a.add({'amresh':'You are a hero'}) # dictionary can not be inserted in a set
print (a)
# Length of the set
print (len(a))# show t... | a = set()
print(type(a))
a.add(4)
a.add(5)
a.add((1, 2, 3))
print(a)
print(len(a))
a.remove(5)
print(a)
print(a.pop())
print(a.clear()) |
t=int(input())
while(t):
t=t-1
n,k=input().split()
n,k=int(n),int(k)
d=set()
st=0
i=0
while(i<n):
i=i+1
c=set(map(int,input().split()[1:]))
d|=c
f=len(d)
if(f==k and i!=n):
st=1
break
while(i<n):
i=i+1
c=inpu... | t = int(input())
while t:
t = t - 1
(n, k) = input().split()
(n, k) = (int(n), int(k))
d = set()
st = 0
i = 0
while i < n:
i = i + 1
c = set(map(int, input().split()[1:]))
d |= c
f = len(d)
if f == k and i != n:
st = 1
break
... |
"""Sentiment labels for providing a text description of sentiment scores"""
CLEAN = "Clean"
QUESTIONABLE = "Questionable"
PROFANE = "Profane"
| """Sentiment labels for providing a text description of sentiment scores"""
clean = 'Clean'
questionable = 'Questionable'
profane = 'Profane' |
def fibonacci():
current = 0
previous = 1
while True:
temp = current
current = current + previous
previous = temp
yield current
def main():
for index, element in enumerate(fibonacci()):
if len(str(element)) >= 1000:
answer = index + 1 #starts from 0
br... | def fibonacci():
current = 0
previous = 1
while True:
temp = current
current = current + previous
previous = temp
yield current
def main():
for (index, element) in enumerate(fibonacci()):
if len(str(element)) >= 1000:
answer = index + 1
br... |
'''
See details at https://realpython.com/linked-lists-python/
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:... | """
See details at https://realpython.com/linked-lists-python/
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class Linkedlist:
def __init__(self, nodes=None):
self.head = None
if nodes is not None... |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 19:26
__version__ = '2.1.0-beta.15'
"""HanLP version"""
class NotCompatible(Exception):
pass
| __version__ = '2.1.0-beta.15'
'HanLP version'
class Notcompatible(Exception):
pass |
# link: https://leetcode.com/problems/design-hashmap/
class ListNode(object):
def __init__(self, key, val):
self.value = (key, val)
self.next = None
class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.... | class Listnode(object):
def __init__(self, key, val):
self.value = (key, val)
self.next = None
class Myhashmap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.bucket_size = 1000
self.bucket = [None] * self.bucket_size
... |
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
lastOne = -1
for i, num in enumerate(nums):
if num == 1:
if lastOne != -1 and i - lastOne - 1 < k:
return False
lastOne = i
return True
| class Solution:
def k_length_apart(self, nums: List[int], k: int) -> bool:
last_one = -1
for (i, num) in enumerate(nums):
if num == 1:
if lastOne != -1 and i - lastOne - 1 < k:
return False
last_one = i
return True |
__all__ = ["SerializationError", "DeserializationError"]
class SerializationError(TypeError):
pass
class DeserializationError(TypeError):
pass
| __all__ = ['SerializationError', 'DeserializationError']
class Serializationerror(TypeError):
pass
class Deserializationerror(TypeError):
pass |
"""
Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def find_sum_of_multiples(n):
multiples = [num for num in range(n) if num % 3 == 0 or num ... | """
Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def find_sum_of_multiples(n):
multiples = [num for num in range(n) if num % 3 == 0 or num... |
class Metric:
def __init__(self):
self.name = 'Name not implemented' ## This should be replaced in implemented metrics.
self.iter_counter = 0
def __iter__(self):
self.iter_counter = 0
return self
def __next__(self):
self.iter_counter += 1
if self.iter_count... | class Metric:
def __init__(self):
self.name = 'Name not implemented'
self.iter_counter = 0
def __iter__(self):
self.iter_counter = 0
return self
def __next__(self):
self.iter_counter += 1
if self.iter_counter > 1:
raise StopIteration
ret... |
#
# PySNMP MIB module NBFLT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBFLT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:07:15 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:23... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
print(fruits[2]) #accessing list index
print(change.index(2))
for number in count:
print("Count:", number)
for fruit in fruits:
print("Fruit of type:", fruit)
for i in change:
... | count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
print(fruits[2])
print(change.index(2))
for number in count:
print('Count:', number)
for fruit in fruits:
print('Fruit of type:', fruit)
for i in change:
print('I got:', i)
elements... |
class MockRobot:
def __init__(self):
self._axis = [
Axis(),
Axis(),
Axis(),
Axis(),
Axis(),
Axis()
]
self._target = list(map(lambda a: a.getPosition(), self._axis))
self._target.append(0) # Mock gripper
def ... | class Mockrobot:
def __init__(self):
self._axis = [axis(), axis(), axis(), axis(), axis(), axis()]
self._target = list(map(lambda a: a.getPosition(), self._axis))
self._target.append(0)
def is_busy(self):
return False
def set_goal_target(self, points):
self._target... |
"""
print_prime_factors function print all the prime factors of a number. A prime factor is a number that is prime and divides another without a remainder.
"""
def print_prime_factors(number):
# Start with two, which is the first prime
factor = 2
# Keep going until the factor is larger than the number
... | """
print_prime_factors function print all the prime factors of a number. A prime factor is a number that is prime and divides another without a remainder.
"""
def print_prime_factors(number):
factor = 2
while factor <= number:
if number % factor == 0:
print(factor)
number = num... |
# Show the odd number in a given sequence
odd = [x for x in input().split(',') if int(x) % 2 != 0]
print(','.join(odd)) | odd = [x for x in input().split(',') if int(x) % 2 != 0]
print(','.join(odd)) |
class UDPPacket(object):
def __init__(self, time, size, id, src, dst = None):
self.time = time
self.size = size
self.id = id
self.src = src
self.dst = dst
def __repr__(self):
return "id: {}, src: {}, time: {}, size: {}".format(self.id, self.src, self.time, self.s... | class Udppacket(object):
def __init__(self, time, size, id, src, dst=None):
self.time = time
self.size = size
self.id = id
self.src = src
self.dst = dst
def __repr__(self):
return 'id: {}, src: {}, time: {}, size: {}'.format(self.id, self.src, self.time, self.si... |
# My Initial solution. Got TLE offcourse
class Solution(object):
def bulbSwitch(self, n):
"""
:type n: int
:rtype: int
"""
bulbs = [False] * n
for i in range(1, n + 1):
currentBuldIdx = 0
while currentBuldIdx < n:
currentBuldIdx... | class Solution(object):
def bulb_switch(self, n):
"""
:type n: int
:rtype: int
"""
bulbs = [False] * n
for i in range(1, n + 1):
current_buld_idx = 0
while currentBuldIdx < n:
current_buld_idx += i
if currentBul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.