content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class AbstractRanker:
def __init__(self, num_features):
self.num_features = num_features
def update(self, gradient):
raise NotImplementedError("Derived class needs to implement "
"update.")
def assign_weights(self, weights):
raise NotImplementedErr... | class Abstractranker:
def __init__(self, num_features):
self.num_features = num_features
def update(self, gradient):
raise not_implemented_error('Derived class needs to implement update.')
def assign_weights(self, weights):
raise not_implemented_error('Derived class needs to imple... |
'''
06 - Run_n_times()
In the video exercise, I showed you an example of a decorator that takes
an argument: run_n_times(). The code for that decorator is repeated below
to remind you how it works. Practice different ways of applying the decorator
to the function print_sum(). Then I'll show you a funny prank... | """
06 - Run_n_times()
In the video exercise, I showed you an example of a decorator that takes
an argument: run_n_times(). The code for that decorator is repeated below
to remind you how it works. Practice different ways of applying the decorator
to the function print_sum(). Then I'll show you a funny prank... |
#for basic
a = 10
for i in range(a):
print("perulangan ke - "+str(i))
print('')
#for dengan data variable
print('#for dengan data')
barang = ['wireless', 'access point', 'wajan bolic']
for i in barang:
print(i)
| a = 10
for i in range(a):
print('perulangan ke - ' + str(i))
print('')
print('#for dengan data')
barang = ['wireless', 'access point', 'wajan bolic']
for i in barang:
print(i) |
'''
Created on Mar 14, 2018
@author: abelit
'''
class Animal:
def __init__(self, action):
self.action = action
def run(self):
print('I can go!')
class Cat(Animal):
def __init__(self,name):
self.name = name
self.action = ''
def cat_print(self):
... | """
Created on Mar 14, 2018
@author: abelit
"""
class Animal:
def __init__(self, action):
self.action = action
def run(self):
print('I can go!')
class Cat(Animal):
def __init__(self, name):
self.name = name
self.action = ''
def cat_print(self):
self.run()
... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 24 13:47:35 2017
@author: Javier
"""
molecular_weight = 58.44 # expressed in g/mol
molarity = 0.6
final_volume = 1000 # expressed in ml
conversion_factor = final_volume / 1000 # expressed in ml
needed_moles = molarity * conversion_factor
amount_needed = mol... | """
Created on Wed May 24 13:47:35 2017
@author: Javier
"""
molecular_weight = 58.44
molarity = 0.6
final_volume = 1000
conversion_factor = final_volume / 1000
needed_moles = molarity * conversion_factor
amount_needed = molecular_weight * needed_moles
print('Weigh', amount_needed, 'grams.') |
q2 = dict()
count = 0
def checkQueen(x):
global count, q2, num
if (x == num):
count += 1
return
for i in range(num):
flag = True
for j in range(x):
if (i == q2[j] or abs(j - x) == abs(i - q2[j])):
flag = False
break
if (... | q2 = dict()
count = 0
def check_queen(x):
global count, q2, num
if x == num:
count += 1
return
for i in range(num):
flag = True
for j in range(x):
if i == q2[j] or abs(j - x) == abs(i - q2[j]):
flag = False
break
if flag:
... |
# Dependency Injection
class DI(object):
def __init__(self):
self.container = {}
def get(self, dependency):
return self.container.get(dependency)
def set(self, dependency, value):
self.container[dependency] = value
def containers(self):
return self.container.keys()
| class Di(object):
def __init__(self):
self.container = {}
def get(self, dependency):
return self.container.get(dependency)
def set(self, dependency, value):
self.container[dependency] = value
def containers(self):
return self.container.keys() |
class FileParser(object):
def __init__(self, file):
self.file = file
self.line = self.read_file()
def read_file(self):
with open(self.file) as file:
line = file.readlines()
return line
m = self.get_value(line[4])
print(m)
@staticmethod
def s... | class Fileparser(object):
def __init__(self, file):
self.file = file
self.line = self.read_file()
def read_file(self):
with open(self.file) as file:
line = file.readlines()
return line
m = self.get_value(line[4])
print(m)
@staticmethod
def s... |
# RUN: test-output.sh %s
x = 1
print("Test Case 1")
if x == 1:
print("A")
print("D")
# OUTPUT-LABEL: Test Case 1
# OUTPUT-NEXT: A
# OUTPUT-NEXT: D
print("Test Case 2")
if x != 1:
print("A")
print("D")
# OUTPUT-LABEL: Test Case 2
# OUTPUT-NEXT: D
print("Test Case 3")
if x == 1:
print("A")
else:
... | x = 1
print('Test Case 1')
if x == 1:
print('A')
print('D')
print('Test Case 2')
if x != 1:
print('A')
print('D')
print('Test Case 3')
if x == 1:
print('A')
else:
print('B')
print('D')
print('Test Case 4')
if x > 1:
print('A')
else:
print('B')
print('D')
print('Test Case 5')
if x == 1:
print... |
"""http and socket response messages in one place for re usability"""
auth_messages = {
"token_required": {
"status": "error",
"error": "token_not_found",
"message": "Ensure request headers contain a token",
},
"expired_token": {
'status': 'error',
'error': 'token_exp... | """http and socket response messages in one place for re usability"""
auth_messages = {'token_required': {'status': 'error', 'error': 'token_not_found', 'message': 'Ensure request headers contain a token'}, 'expired_token': {'status': 'error', 'error': 'token_expired', 'message': 'Get a new token'}, 'invalid_token': {'... |
def fun_decorator(some_funct):
def wrapper():
print("Here is the decorator, doing its thing")
for i in range(10):
print(i)
print("The decorator is done, returning to the originally scheduled function")
print(some_funct())
return wrapper
@fun_decorator
def a_funct():
... | def fun_decorator(some_funct):
def wrapper():
print('Here is the decorator, doing its thing')
for i in range(10):
print(i)
print('The decorator is done, returning to the originally scheduled function')
print(some_funct())
return wrapper
@fun_decorator
def a_funct():... |
#This code is best for future use of this program
for i in range(1, 101):
fizz = 3
buzz = 5
fizzbuzz = fizz * buzz
if i % fizzbuzz == 0:
print("FizzBuzz")
continue
elif i % fizz == 0:
print("Fizz")
continue
elif i % buzz == 0:
print("Buzz")
co... | for i in range(1, 101):
fizz = 3
buzz = 5
fizzbuzz = fizz * buzz
if i % fizzbuzz == 0:
print('FizzBuzz')
continue
elif i % fizz == 0:
print('Fizz')
continue
elif i % buzz == 0:
print('Buzz')
continue
else:
print(i) |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa
model = dict(
bac... | _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth'
model = dict(backbone=dict(_delete_=True, t... |
def formatset(rs,fs):
for key,value in rs.items():
if value:
fs=fs.replace('%'+key+'%',value)
else:
fs=fs.replace('%'+key+'%','')
return fs
def myfilter(lines,args):
for line in lines:
line=line.decode('utf8')
match=args['regex'].match(line)
... | def formatset(rs, fs):
for (key, value) in rs.items():
if value:
fs = fs.replace('%' + key + '%', value)
else:
fs = fs.replace('%' + key + '%', '')
return fs
def myfilter(lines, args):
for line in lines:
line = line.decode('utf8')
match = args['regex'... |
#!/usr/bin/python
""" Functions for calculating distributions (pT, eta)"""
def ptdistr(particles, ptypelist, ptpoints, deltapt,
ypoint, deltay, dndptsums, pseudorap=False):
""" Calculate identified particle pT distribution.
Input:
particles -- List of ParticleData objects
ptypelist ... | """ Functions for calculating distributions (pT, eta)"""
def ptdistr(particles, ptypelist, ptpoints, deltapt, ypoint, deltay, dndptsums, pseudorap=False):
""" Calculate identified particle pT distribution.
Input:
particles -- List of ParticleData objects
ptypelist -- List of particle typ... |
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
if nums == []:
return 0
res = 0
for i in range(1, len(nums)):
if nums[i] != nums[res]:
res += 1
nums[res] = nums[i]
return res + 1 | class Solution:
def remove_duplicates(self, nums: list[int]) -> int:
if nums == []:
return 0
res = 0
for i in range(1, len(nums)):
if nums[i] != nums[res]:
res += 1
nums[res] = nums[i]
return res + 1 |
_base_ = [
'../_base_/models/mocov3_vit-small-p16.py',
'../_base_/datasets/imagenet_mocov3.py',
'../_base_/schedules/adamw_coslr-300e_in1k.py',
'../_base_/default_runtime.py',
]
# dataset settings
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# the difference between ResNet... | _base_ = ['../_base_/models/mocov3_vit-small-p16.py', '../_base_/datasets/imagenet_mocov3.py', '../_base_/schedules/adamw_coslr-300e_in1k.py', '../_base_/default_runtime.py']
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_pipeline1 = [dict(type='RandomResizedCrop', size=224, scale=(0.0... |
reverse_num= 0
for i in range(10,1000):
for j in range(10,1000):
number= i*j
original_num= number
reverse_num= 0
while(number!=0):
r= number % 10
reverse_num = reverse_num *10 + r
number= number//10
if(original_num==reverse_num):
... | reverse_num = 0
for i in range(10, 1000):
for j in range(10, 1000):
number = i * j
original_num = number
reverse_num = 0
while number != 0:
r = number % 10
reverse_num = reverse_num * 10 + r
number = number // 10
if original_num == reverse_... |
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
... | menu = {'espresso': {'ingredients': {'water': 50, 'coffee': 18}, 'cost': 1.5}, 'latte': {'ingredients': {'water': 200, 'milk': 150, 'coffee': 24}, 'cost': 2.5}, 'cappuccino': {'ingredients': {'water': 250, 'milk': 100, 'coffee': 24}, 'cost': 3.0}}
resources = {'water': 300, 'milk': 200, 'coffee': 100, 'money': 2.5}
de... |
# Christian Webber
# August 30th, 2013
# Assignment 1
# Intended for Windows
debugging = False # Turn on or off test-specific pass/fail output
subDebugging = False # Turn on or off sub-function output
# Debugging output printer
# Input:
# - s: the string to be outputted
# Returns:
# - N/A
def debug(*s):
if d... | debugging = False
sub_debugging = False
def debug(*s):
if debugging == True:
print(*s)
def subdebug(*s):
if subDebugging == True:
print(*s)
def makettable(s1, s2):
output = {}
i = 0
for c in s1:
output[c] = s2[i]
i += 1
subdebug(output)
return output
def t... |
# Ex. 1
def partition(input_list, start, end, pivot_position):
pivot = input_list[pivot_position]
indexes = list(range(start, end + 1))
indexes.remove(pivot_position)
i = indexes[0]
for index in indexes:
if input_list[index] < pivot:
swap(input_list, index, i)
i = n... | def partition(input_list, start, end, pivot_position):
pivot = input_list[pivot_position]
indexes = list(range(start, end + 1))
indexes.remove(pivot_position)
i = indexes[0]
for index in indexes:
if input_list[index] < pivot:
swap(input_list, index, i)
i = next_positi... |
def sqrt(number: int) -> int:
if number in {0, 1}:
return number
low = 0
high = number // 2 + 1
_result = None
while high >= low:
mid = (low + high) // 2
sq = mid * mid
if sq == number:
return mid
elif sq < number:
low = mid + 1
... | def sqrt(number: int) -> int:
if number in {0, 1}:
return number
low = 0
high = number // 2 + 1
_result = None
while high >= low:
mid = (low + high) // 2
sq = mid * mid
if sq == number:
return mid
elif sq < number:
low = mid + 1
... |
# Standard Class definition
class BrazilianNumber:
countryCode = 55
def __init__(self, area_code, number):
self.area_code = area_code
self.number = number
def __str__(self):
return f'+ {BrazilianNumber.countryCode} ({self.area_code}) {self.number}'
# Defining a Class with th... | class Braziliannumber:
country_code = 55
def __init__(self, area_code, number):
self.area_code = area_code
self.number = number
def __str__(self):
return f'+ {BrazilianNumber.countryCode} ({self.area_code}) {self.number}'
def my_init(self, area_code, number):
self.area_code = ... |
"""Things that deal with UDF results that do not depend on the rest of DAGs.
Clients should almost never have to deal with anything in this module or its
submodules.
"""
| """Things that deal with UDF results that do not depend on the rest of DAGs.
Clients should almost never have to deal with anything in this module or its
submodules.
""" |
"""
This module contains stuff related to bandwidth scanners.
.. toctree::
:maxdepth: 2
bandwidth/file.rst
"""
# TODO: Write a better docstring
| """
This module contains stuff related to bandwidth scanners.
.. toctree::
:maxdepth: 2
bandwidth/file.rst
""" |
# This file is part of Moksha.
# Copyright (C) 2008-2010 Red Hat, Inc.
#
# 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 ... | """The application's Globals object"""
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via... |
numbers = frozenset({0 , 1, 2, 3, 4, 5, 6, 7, 8, 9})
# numbers.add(20) AttributeError
print(numbers)
users = {1, 2, 3, 4, 5}
users.add(2)
users.add(6)
print(len(users))
| numbers = frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
print(numbers)
users = {1, 2, 3, 4, 5}
users.add(2)
users.add(6)
print(len(users)) |
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
if not s:
return []
# dp[i] means first i letters can be formed by words in the dictionary
dp = [False] * (len(s)+1)
... | class Solution(object):
def word_break(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
if not s:
return []
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(len(s) + 1):
if dp[i... |
#!/usr/bin/env python3
# "+", "-", "*", "/".
# Must contain at least 2 lower case and 2 upper case characters, 2 digits, and 2 special chars.
__author__ = "Mert Erol"
pwd = "aA00++"
def is_valid():
special = ["+", "-", "*", "/"]
upper = 0
lower = 0
digit = 0
spam = 0
specialdigit = 0
# You... | __author__ = 'Mert Erol'
pwd = 'aA00++'
def is_valid():
special = ['+', '-', '*', '/']
upper = 0
lower = 0
digit = 0
spam = 0
specialdigit = 0
validity = True
validity1 = True
validity2 = False
if not any((char.isdigit() for char in pwd)):
validity1 = False
if not an... |
class CameraPoolManager:
"""Pool class for containing all camera instances."""
def __init__(self):
self._instances = {}
def __repr__(self):
return '<{0} id={1}>: {2}'.format(self.__class__.__name__, id(self),
repr(self._instances))
def __str__... | class Camerapoolmanager:
"""Pool class for containing all camera instances."""
def __init__(self):
self._instances = {}
def __repr__(self):
return '<{0} id={1}>: {2}'.format(self.__class__.__name__, id(self), repr(self._instances))
def __str__(self):
return str(self._instances... |
"""
Date Created: 2018-02-27
Date Modified: 2018-02-27
Version: 1
Contract Hash: 0a8b34b4097f0a472d5a31726d70ff807d37490d
Available on NEO TestNet: False
Available on CoZ TestNet: False
Available on MainNet: False
Example:
Test Invoke: ... | """
Date Created: 2018-02-27
Date Modified: 2018-02-27
Version: 1
Contract Hash: 0a8b34b4097f0a472d5a31726d70ff807d37490d
Available on NEO TestNet: False
Available on CoZ TestNet: False
Available on MainNet: False
Example:
Test Invoke: ... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class DatabaseStateEnum(object):
"""Implementation of the 'DatabaseState' enum.
Specifies the state of the Exchange database copy.
Specifies the state of Exchange Database Copy.
'kUnknown' indicates the status is not known.
'kMounted' indic... | class Databasestateenum(object):
"""Implementation of the 'DatabaseState' enum.
Specifies the state of the Exchange database copy.
Specifies the state of Exchange Database Copy.
'kUnknown' indicates the status is not known.
'kMounted' indicates the exchange database copy is mounted and healthy.
... |
def gkstn(N):
count = 0
for i in range(1,N+1):
arr = list(map(int,str(i)))
if i < 100:
count += 1
elif arr[0]-arr[1] == arr[1]-arr[2]:
count += 1
return count
N = int(input())
print(gkstn(N))
| def gkstn(N):
count = 0
for i in range(1, N + 1):
arr = list(map(int, str(i)))
if i < 100:
count += 1
elif arr[0] - arr[1] == arr[1] - arr[2]:
count += 1
return count
n = int(input())
print(gkstn(N)) |
class Season():
def __init__(self):
print("FUCK YOU!")
| class Season:
def __init__(self):
print('FUCK YOU!') |
# Assign foobar which gives the output shown in the last example.
# Hint: Use the triple quote as the outermost quote
foobar = '''"No, thanks, Mom," I said, "I don't know how long it will take."'''
print(foobar)
| foobar = '"No, thanks, Mom," I said, "I don\'t know how long it will take."'
print(foobar) |
'''
--- Day 1: No Time for a Taxicab ---
--- Part Two ---
Then, you notice the instructions continue on the back of the Recruiting Document. Easter Bunny HQ is actually at the first location you visit twice.
For example, if your instructions are R8, R4, R4, R8, the first location you visit twice is 4 blocks away, due... | """
--- Day 1: No Time for a Taxicab ---
--- Part Two ---
Then, you notice the instructions continue on the back of the Recruiting Document. Easter Bunny HQ is actually at the first location you visit twice.
For example, if your instructions are R8, R4, R4, R8, the first location you visit twice is 4 blocks away, due... |
class Event(object) :
"""
Events sent from NodeJS parent process websocket.
Handled in the Strategy base class.
"""
FIND_SIGNAL = 'FIND_SIGNAL'
BUILD_ORDER = 'BUILD_ORDER'
EXECUTE_ORDER = 'EXECUTE_ORDER'
AUDIT_STRATEGY = 'AUDIT_STRATEGY'
STORE_FILL = 'STORE_FILL'
FINISHED_TRADIN... | class Event(object):
"""
Events sent from NodeJS parent process websocket.
Handled in the Strategy base class.
"""
find_signal = 'FIND_SIGNAL'
build_order = 'BUILD_ORDER'
execute_order = 'EXECUTE_ORDER'
audit_strategy = 'AUDIT_STRATEGY'
store_fill = 'STORE_FILL'
finished_trading ... |
dataset_type = 'RCTW17Dataset'
data_root = 'data/rctw_17/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadOBBAnnotations', with_bbox=True,
with_label=True, with_poly_as_mask=True),
... | dataset_type = 'RCTW17Dataset'
data_root = 'data/rctw_17/'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadOBBAnnotations', with_bbox=True, with_label=True, with_poly_as_mask=True), dict(type='Resize', img_sca... |
ANTLR_JAR_PATH = 'antlr-3.5.2-complete-no-st3.jar'
def onrun_antlr(unit, *args):
unit.onpeerdir(['build/external_resources/antlr3'])
unit.on_run_java(['-jar', '$ANTLR3_RESOURCE_GLOBAL/' + ANTLR_JAR_PATH] + list(args))
| antlr_jar_path = 'antlr-3.5.2-complete-no-st3.jar'
def onrun_antlr(unit, *args):
unit.onpeerdir(['build/external_resources/antlr3'])
unit.on_run_java(['-jar', '$ANTLR3_RESOURCE_GLOBAL/' + ANTLR_JAR_PATH] + list(args)) |
''' auxiliar_functions
Series of tools for using in project development.
Created on 05/05/2019
@author: Carlos Cesar Brochine Junior
'''
def funcao_test(teste):
return teste
if __name__ == '__main__':
a = funcao_test('Hello World')
print(a) | """ auxiliar_functions
Series of tools for using in project development.
Created on 05/05/2019
@author: Carlos Cesar Brochine Junior
"""
def funcao_test(teste):
return teste
if __name__ == '__main__':
a = funcao_test('Hello World')
print(a) |
#!/usr/bin/python3
def explore(nodes, visited, path_list, node):
if node == 'start':
return path_list
if node != 'end' and node.islower() and node in visited:
return path_list
visits = visited + [node]
if node == 'end':
path_list.append(visits)
return path_list
next... | def explore(nodes, visited, path_list, node):
if node == 'start':
return path_list
if node != 'end' and node.islower() and (node in visited):
return path_list
visits = visited + [node]
if node == 'end':
path_list.append(visits)
return path_list
next_nodes = [n for n i... |
def query_custom_answers(question, answers, default=None):
"""Ask a question via raw_input() and return the chosen answer.
@param question {str} Printed on stdout before querying the user.
@param answers {list} A list of acceptable string answers. Particular
answers can include '&' before one o... | def query_custom_answers(question, answers, default=None):
"""Ask a question via raw_input() and return the chosen answer.
@param question {str} Printed on stdout before querying the user.
@param answers {list} A list of acceptable string answers. Particular
answers can include '&' before one o... |
if __name__ == '__main__':
a,b = int(input()),int(input())
div = divmod(a,b)
print(div[0])
print(div[1])
print(div) | if __name__ == '__main__':
(a, b) = (int(input()), int(input()))
div = divmod(a, b)
print(div[0])
print(div[1])
print(div) |
MORZE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",
".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
return len(set([''.join... | morze = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..']
class Solution:
def unique_morse_representations(self, words: List[str]) -> int:
return len(set([''.join((MORZE... |
def fetch_audio_features(sp, username, songs_collection, audio_features_collection):
# Audio features fetching
cursor = songs_collection.find({'user_id': username})
for doc in cursor:
artist = doc['song_artist']
name = doc['song_name']
id = doc['spotify_id']
print("=> Checkin... | def fetch_audio_features(sp, username, songs_collection, audio_features_collection):
cursor = songs_collection.find({'user_id': username})
for doc in cursor:
artist = doc['song_artist']
name = doc['song_name']
id = doc['spotify_id']
print('=> Checking audio features of: %s - %s' ... |
"""https://open.kattis.com/problems/freefood"""
N = int(input())
days = []
for _ in range(N):
s, t = map(int, input().split())
for each in range(s, t+1):
if each not in days:
days.append(each)
print(len(days))
| """https://open.kattis.com/problems/freefood"""
n = int(input())
days = []
for _ in range(N):
(s, t) = map(int, input().split())
for each in range(s, t + 1):
if each not in days:
days.append(each)
print(len(days)) |
# Extract class or function along with its docstring
# Docstring will be captured in group 1 and group 0 contains the whole class or function along with its docstring.
DEF_WITH_DOCS_REGEX = r'((def|class).*((\s*->\s*.*)|):\n\s*"""(\n\s*.*?)*""")'
# Given a docstring, identity each part, i.e, parameters and return valu... | def_with_docs_regex = '((def|class).*((\\s*->\\s*.*)|):\\n\\s*"""(\\n\\s*.*?)*""")'
identify_each_part_regex = '"""\\n\\s*(.*\\s*)*?(Parameters\\s*-*\\s*((.*\\s*)*?))?(Returns\\s*-*\\s*(.*\\s*)*?)?"""'
extract_camel = '(^(?!\\s*print.*).*)((\\b[a-z]+)(([A-Z]+[a-z]+)+?)\\b)'
split_readme_by_api = '^(?<![.\\n])(.*\\s*)*?... |
#!/usr/bin/python
"""
runs on the server, prints HTML to create a new page;
url=http://localhost/cgi-bin/tutor0.py
"""
print('Content-type: text/html\n')
print('<TITLE>CGI 101</TITLE>')
print('<H1>A First CGI Script</H1>')
print('<P>Hello, CGI World!</P>')
| """
runs on the server, prints HTML to create a new page;
url=http://localhost/cgi-bin/tutor0.py
"""
print('Content-type: text/html\n')
print('<TITLE>CGI 101</TITLE>')
print('<H1>A First CGI Script</H1>')
print('<P>Hello, CGI World!</P>') |
s=input();sl=len(s);l=0;r=0
for i in range(sl):
if s[i]==')':
if r==0:
l+=1
else:
r-=1
else:
r+=1
print(l+r)
| s = input()
sl = len(s)
l = 0
r = 0
for i in range(sl):
if s[i] == ')':
if r == 0:
l += 1
else:
r -= 1
else:
r += 1
print(l + r) |
class Caesar():
#CS50X Caesar task in python
def caesar_main(self):
key = int(input("Key (number) : ")) # get key number
caesar = input("Text : ") # get string
new_caesar = "" #converted string
for i in caesar: #loop in given string
if i.isalpha(): # if i is alpha (a-z)... | class Caesar:
def caesar_main(self):
key = int(input('Key (number) : '))
caesar = input('Text : ')
new_caesar = ''
for i in caesar:
if i.isalpha():
ascii_offset = 65 if i.isupper() else 97
ascii_number = ord(i) - ascii_offset
... |
"""
The Black shade analyser and comparison tool.
"""
__author__ = "Richard Si, et al."
__license__ = "MIT"
__version__ = "22.5.dev1"
| """
The Black shade analyser and comparison tool.
"""
__author__ = 'Richard Si, et al.'
__license__ = 'MIT'
__version__ = '22.5.dev1' |
def bubbleSort(arr):
# This is the bubble sort algorithm implementation.
ind = 0
while ind < len(arr):
x = 0
while x < len(arr):
if arr[x] > arr[ind]:
temp = arr[ind]
arr[ind] = arr[x]
arr[x] = temp
x+=1
ind+=1
... | def bubble_sort(arr):
ind = 0
while ind < len(arr):
x = 0
while x < len(arr):
if arr[x] > arr[ind]:
temp = arr[ind]
arr[ind] = arr[x]
arr[x] = temp
x += 1
ind += 1
return arr
print(bubble_sort([54, 26, 93, 17, 77... |
vet = list(map(int, input().split()))
a = vet[0]
ultimo_valor = len(vet) - 1
n = vet[ultimo_valor]
soma = 0
for i in range(0, n):
soma += a + i
print(soma)
| vet = list(map(int, input().split()))
a = vet[0]
ultimo_valor = len(vet) - 1
n = vet[ultimo_valor]
soma = 0
for i in range(0, n):
soma += a + i
print(soma) |
def sieve_of_eratosthenes(num):
prime = [True] * (num + 1)
p = 2
while (p * p <= num):
# If prime[p] is not changed, then it is a prime
if (prime[p] is True):
# Update all multiples of p
for i in range(p * 2, num + 1, p):
prime[i] = False
... | def sieve_of_eratosthenes(num):
prime = [True] * (num + 1)
p = 2
while p * p <= num:
if prime[p] is True:
for i in range(p * 2, num + 1, p):
prime[i] = False
p += 1
for p in range(2, num):
if prime[p]:
print(p)
def main():
num = 30
... |
#Written by Kenneth Nero <https://github.com/KennethNero>
# Simple function to create an array of mathcing elements
# between two lists.
def intersection(ls1, ls2):
result = [v for v in ls1 if v in ls2]
return result
# Main function that operates on the command line to take
# in and send output.
def main():
... | def intersection(ls1, ls2):
result = [v for v in ls1 if v in ls2]
return result
def main():
ls = []
inp = input('Please enter your first comma seperated list of integers: ')
inp2 = input('Please enter your second comma seperated list of integers: ')
result = intersection(inp.replace(' ', '').sp... |
# -*- coding: utf-8 -*-
openings = [
{"name": "Alekhine Defense", "eco": "B02", "fen": "rnbqkb1r/pppppppp/5n2/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq", "moves": "1. e4 Nf6", "position": "rnbqkb1r/pppppppp/5n2/8/4P3/8/PPPP1PPP/RNBQKBNR"},
{"name": "Alekhine Defense, 2. e5 Nd5 3. d4", "eco": "B03", "fen": "rnbqkb1r/pppppppp/... | openings = [{'name': 'Alekhine Defense', 'eco': 'B02', 'fen': 'rnbqkb1r/pppppppp/5n2/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq', 'moves': '1. e4 Nf6', 'position': 'rnbqkb1r/pppppppp/5n2/8/4P3/8/PPPP1PPP/RNBQKBNR'}, {'name': 'Alekhine Defense, 2. e5 Nd5 3. d4', 'eco': 'B03', 'fen': 'rnbqkb1r/pppppppp/8/3nP3/3P4/8/PPP2PPP/RNBQKBN... |
def kaziZdravo():
print("Pozdrav svima!") #blok koji pripada funkciji
#kraj funkcije
kaziZdravo() #poziv funkcije
kaziZdravo() #opet poziv funkcije
| def kazi_zdravo():
print('Pozdrav svima!')
kazi_zdravo()
kazi_zdravo() |
"""
2) :
Crie um programa que leia 6 valores inteiros e, em seguida, mostre na tela os valores lidos :
"""
n = []
for v in range(0, 6):
v = int(input("Digite valor: "))
n.append(v)
'\n'
for v in n:
print(v)
| """
2) :
Crie um programa que leia 6 valores inteiros e, em seguida, mostre na tela os valores lidos :
"""
n = []
for v in range(0, 6):
v = int(input('Digite valor: '))
n.append(v)
'\n'
for v in n:
print(v) |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if s == "": return ""
if s == None: return None
maxFound = s[0]
maxLen = 1
s_len = len(s)
#odd length palindromes
for i i... | class Solution(object):
def longest_palindrome(self, s):
"""
:type s: str
:rtype: str
"""
if s == '':
return ''
if s == None:
return None
max_found = s[0]
max_len = 1
s_len = len(s)
for i in range(len(s)):
... |
class GreyForecast:
tag = ""
k = 0
original_value = 0.0
forecast_value = 0.0
error_rate = 0.0
average_error_rate = 0.0
| class Greyforecast:
tag = ''
k = 0
original_value = 0.0
forecast_value = 0.0
error_rate = 0.0
average_error_rate = 0.0 |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ") # allow user to type the file name
try:
fh = open(fname)
except:
print("File does not exist")
quit() #when the file does not exist, then stop the programme
count = 0
total = 0
for line in fh:
if not line.startswith("X... | fname = input('Enter file name: ')
try:
fh = open(fname)
except:
print('File does not exist')
quit()
count = 0
total = 0
for line in fh:
if not line.startswith('X-DSPAM-Confidence:'):
continue
num_start = line.find(' ')
num_strip = line[num_start + 1:].strip()
num_float = float(num_s... |
def get_instance_name(x):
"""Gets the name of the instance"""
return x.__class__.__name__.lower()
def is_unique(xs):
"""Tests if all x in xs belong to the same instance"""
fn = get_instance_name
xs_set = {x for x in map(fn, xs)}
if len(xs_set) == 1:
return list(xs_set)[0]
return Fal... | def get_instance_name(x):
"""Gets the name of the instance"""
return x.__class__.__name__.lower()
def is_unique(xs):
"""Tests if all x in xs belong to the same instance"""
fn = get_instance_name
xs_set = {x for x in map(fn, xs)}
if len(xs_set) == 1:
return list(xs_set)[0]
return Fal... |
# create a bezier path
path = BezierPath()
# move to a point
path.moveTo((100, 100))
# line to a point
path.lineTo((100, 200))
path.lineTo((200, 200))
# close the path
path.closePath()
# loop over a range of 10
for i in range(10):
# set a random color with alpha value of .3
fill(random(), random(), random(), ... | path = bezier_path()
path.moveTo((100, 100))
path.lineTo((100, 200))
path.lineTo((200, 200))
path.closePath()
for i in range(10):
fill(random(), random(), random(), 0.3)
draw_path(path)
translate(5, 5) |
'''
Linear regression on appropriate Anscombe data
For practice, perform a linear regression on the data set from Anscombe's quartet that is most reasonably
interpreted with linear regression.
INSTRUCTIONS
100XP
-Compute the parameters for the slope and intercept using np.polyfit(). The Anscombe data are stored
in ... | """
Linear regression on appropriate Anscombe data
For practice, perform a linear regression on the data set from Anscombe's quartet that is most reasonably
interpreted with linear regression.
INSTRUCTIONS
100XP
-Compute the parameters for the slope and intercept using np.polyfit(). The Anscombe data are stored
in ... |
# pylint: disable=invalid-name, missing-class-docstring, too-few-public-methods
# flake8: noqa
""" Sample Submissions for test cases. """
class SampleSubmissions:
""" Static submissions for test cases - BASE and DATAPATH (which references BASE) """
class UNIT_TESTS:
STORAGE_VALID = "storage_connection... | """ Sample Submissions for test cases. """
class Samplesubmissions:
""" Static submissions for test cases - BASE and DATAPATH (which references BASE) """
class Unit_Tests:
storage_valid = "storage_connection_type: 'AWS_BLOB'"
storage_invalid = "storage_connection_type: 'xxxx'"
uuid_val... |
"""
"""
CARDINALITY_SLOP = 1
def is_discrete(num_records: int, cardinality: int, p=0.15):
"""
Estimate whether a feature is discrete given the number of records
observed and the cardinality (number of unique values)
The default assumption is that features are not discrete.
Parameters
-------... | """
"""
cardinality_slop = 1
def is_discrete(num_records: int, cardinality: int, p=0.15):
"""
Estimate whether a feature is discrete given the number of records
observed and the cardinality (number of unique values)
The default assumption is that features are not discrete.
Parameters
--------... |
{
"targets": [
{
"includes": [
"auto.gypi"
],
"sources": [
"../src/index.cc"
],
"cflags": [
"-Wall",
"-Wno-deprecated",
"-Wno-deprecated-declarations",
"-Wno-cast-function-type",
"-Wno-class-memaccess",
"-O2",
"-Ofast",
"-pthread"
]
}
],
"includes": [
... | {'targets': [{'includes': ['auto.gypi'], 'sources': ['../src/index.cc'], 'cflags': ['-Wall', '-Wno-deprecated', '-Wno-deprecated-declarations', '-Wno-cast-function-type', '-Wno-class-memaccess', '-O2', '-Ofast', '-pthread']}], 'includes': ['auto-top.gypi']} |
#!/usr/bin/env python
Pdir = "/root/ansible"
LOG_FILENAME = Pdir+'/ConfigGen.log'
LOGGER_NAME = 'ConfigGen'
CONFIG_DATA_FILE = '/root/input.json'
VAR_CONF_FILE = Pdir+'/vars/gen.yml'
PAYLOAD_LOC = Pdir+'/payload'
GEN_LOC = Pdir+'/payload'
| pdir = '/root/ansible'
log_filename = Pdir + '/ConfigGen.log'
logger_name = 'ConfigGen'
config_data_file = '/root/input.json'
var_conf_file = Pdir + '/vars/gen.yml'
payload_loc = Pdir + '/payload'
gen_loc = Pdir + '/payload' |
# ARRAYS-DS HACKERRANK SOLUTION:
# creating a function to reverse the given array.
def reverseArray(arr):
# code to reverse the given array.
reversed_array = arr[::-1]
# returning the reversed array.
return reversed_array
# receiving input.
arr_count = int(input().strip())
arr = list(ma... | def reverse_array(arr):
reversed_array = arr[::-1]
return reversed_array
arr_count = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = reverse_array(arr)
print(result) |
class BaseResponse(object):
_allowedResponses = []
_http_responses = {}
def __init__(self, allowedResponses=None):
self.__allowedResponses = allowedResponses
for code in allowedResponses:
status_code = str(code)
self._http_responses[status_code] = self._def... | class Baseresponse(object):
_allowed_responses = []
_http_responses = {}
def __init__(self, allowedResponses=None):
self.__allowedResponses = allowedResponses
for code in allowedResponses:
status_code = str(code)
self._http_responses[status_code] = self._default_resp... |
with open("map.txt", 'r') as fd:
contents = fd.readlines()
mapping = {}
for line in contents:
row, col, name = line.strip().split("\t")
pos = (int(row), int(col))
if pos in mapping:
print("Collision!", pos)
mapping[pos] = name | with open('map.txt', 'r') as fd:
contents = fd.readlines()
mapping = {}
for line in contents:
(row, col, name) = line.strip().split('\t')
pos = (int(row), int(col))
if pos in mapping:
print('Collision!', pos)
mapping[pos] = name |
'''Crie um programa que mostre na tela todos os numeros pares que estao no intervalo de 1 a 50.'''
for c in range(1,50 +1,):
if c % 2 == 0:
print(c) | """Crie um programa que mostre na tela todos os numeros pares que estao no intervalo de 1 a 50."""
for c in range(1, 50 + 1):
if c % 2 == 0:
print(c) |
# day one, advent 2020
def day_one():
# read input for day one, calculate and print answer
with open('advent/20201201.txt', 'r') as f:
data = f.read()
data = [int(i) for i in data.split()]
for i in data:
for j in data:
if i + j == 2020:
print(f"Day 1.1: i:... | def day_one():
with open('advent/20201201.txt', 'r') as f:
data = f.read()
data = [int(i) for i in data.split()]
for i in data:
for j in data:
if i + j == 2020:
print(f'Day 1.1: i: {i}, j: {j}, answer: {i * j}')
break
else:
cont... |
__author__ = 'petar@google.com (Petar Petrov)'
class GeneratedServiceType(type):
_DESCRIPTOR_KEY = 'DESCRIPTOR'
def __init__(cls, name, bases, dictionary):
if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:
return
descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY... | __author__ = 'petar@google.com (Petar Petrov)'
class Generatedservicetype(type):
_descriptor_key = 'DESCRIPTOR'
def __init__(cls, name, bases, dictionary):
if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:
return
descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY... |
def to_rna(dna):
rna = ''
dna_rna = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
for char in dna:
try:
rna = rna + dna_rna[char]
except:
return ""
return rna
| def to_rna(dna):
rna = ''
dna_rna = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'}
for char in dna:
try:
rna = rna + dna_rna[char]
except:
return ''
return rna |
POSITION = "position"
FORCE = "force"
TOTAL_ENERGY = "total_energy"
PER_ATOM_ENERGY = "per_atom_energy"
CELL = "cell"
NATOMS = "natoms"
PER_FRAME_ATTRS = "per_frame_attrs"
METADATA_ATTRS = "metadata_attrs"
FIXED_ATTRS = "fixed_attrs"
DIM = "dimension"
SPECIES = "species"
STRESS = "stress"
VELOCITY = "velocity"
| position = 'position'
force = 'force'
total_energy = 'total_energy'
per_atom_energy = 'per_atom_energy'
cell = 'cell'
natoms = 'natoms'
per_frame_attrs = 'per_frame_attrs'
metadata_attrs = 'metadata_attrs'
fixed_attrs = 'fixed_attrs'
dim = 'dimension'
species = 'species'
stress = 'stress'
velocity = 'velocity' |
# the following line reads the list from the input; do not modify it, please
numbers = [int(num) for num in input().split()]
print(numbers[16:3:-1]) # the line with an error
| numbers = [int(num) for num in input().split()]
print(numbers[16:3:-1]) |
# Copyright 2013 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Configures includes (appstats and components.auth).
https://developers.google.com/appengine/docs/python/tools/appengineconfig
"""
appstats_CALC_RPC_... | """Configures includes (appstats and components.auth).
https://developers.google.com/appengine/docs/python/tools/appengineconfig
"""
appstats_calc_rpc_costs = False
components_auth_ui_app_name = 'Swarming' |
userReply = input("Do you need to ship a package? (Enter yes or no) ")
if userReply == "yes":
print("We can help you ship that package!")
else:
print("Please come back when you need to ship a package. Thank you.")
userReply = input("Would you like to buy stamps, buy an envelope, or make a copy? (Enter... | user_reply = input('Do you need to ship a package? (Enter yes or no) ')
if userReply == 'yes':
print('We can help you ship that package!')
else:
print('Please come back when you need to ship a package. Thank you.')
user_reply = input('Would you like to buy stamps, buy an envelope, or make a copy? (Enter sta... |
"""
'||
|| ... ... ... .. .. ..
||' || || || || || ||
|| | || || || || ||
'|...' '|..'|. .|| || ||.
Created by Dylan Araps
"""
__version__ = "0.1.3"
| """
'||
|| ... ... ... .. .. ..
||' || || || || || ||
|| | || || || || ||
'|...' '|..'|. .|| || ||.
Created by Dylan Araps
"""
__version__ = '0.1.3' |
"""Default input parameters used in command line inface."""
mode = 'normal'
size = 1
fps = 20
cmap = 'hot'
output = ''
pixel_num = -1 | """Default input parameters used in command line inface."""
mode = 'normal'
size = 1
fps = 20
cmap = 'hot'
output = ''
pixel_num = -1 |
a = 'Tell mme somehting , I will give you feed back'
a += '\n(Enter quit to leave)'
message = ''
while message !='quit':
message = input(a)
if message == 'quit':
break
else:
print(message) | a = 'Tell mme somehting , I will give you feed back'
a += '\n(Enter quit to leave)'
message = ''
while message != 'quit':
message = input(a)
if message == 'quit':
break
else:
print(message) |
class InvalidEventType(Exception):
def __init__(self, event_type_passed):
self._event_type_value = type(event_type_passed)
def __str__(self):
return f"An invalid event type: {self._event_type_value} was passed. An event type must be a string!"
| class Invalideventtype(Exception):
def __init__(self, event_type_passed):
self._event_type_value = type(event_type_passed)
def __str__(self):
return f'An invalid event type: {self._event_type_value} was passed. An event type must be a string!' |
"""
ind the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.
"""
__author__ = 'Daniel'
class Solution:
def ... | """
ind the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.
"""
__author__ = 'Daniel'
class Solution:
def ... |
class PdbNotFoundError(LookupError):
"""PDB query returned a 404 Not Found"""
def __init__(self, tag, pk):
msg = f"pdb missing {tag}/{pk}"
super().__init__(msg)
| class Pdbnotfounderror(LookupError):
"""PDB query returned a 404 Not Found"""
def __init__(self, tag, pk):
msg = f'pdb missing {tag}/{pk}'
super().__init__(msg) |
def subset(A, B):
return A.issubset(B)
if __name__ == '__main__':
no_T = int(input()) # no. of test cases
for i in range(no_T):
no_A = int(input()) # no. of elements in A
A = set(map(int, input().split())) # elements of A
no_B = int(input()) # no. of elements in B
B = se... | def subset(A, B):
return A.issubset(B)
if __name__ == '__main__':
no_t = int(input())
for i in range(no_T):
no_a = int(input())
a = set(map(int, input().split()))
no_b = int(input())
b = set(map(int, input().split()))
print(subset(A, B)) |
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
class Solution(object):
# @param head, a ListNode
# @return nothi... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return '{} -> {}'.format(self.val, repr(self.next))
class Solution(object):
def reorder_list(self, head):
if head == None or head.next == None:
... |
# PIGEONHOLE SORT
# This is a non-comparison based sorting algorithm that works for
# arrays where number of elements and the range of possible key values are approximately the
# same. To perform this sort, we need to make some holes. The number of holes needed is decided
# by the range of numbers. In each hole, items... | def pigeonhole_sort(arr):
pig_size = max(arr) - min(arr) + 1
hole = [0] * pig_size
for i in range(len(arr)):
hole[arr[i] - min(arr)] += 1
i = 0
for j in range(pig_size):
while hole[j]:
hole[j] -= 1
arr[i] = j + min(arr)
i += 1
arr = [8, 3, 2, 7, 4,... |
#!/usr/bin/env python
"""
CREATED AT: 2021/7/24
Des:
https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences
https://leetcode.com/contest/biweekly-contest-57/problems/check-if-all-characters-have-equal-number-of-occurrences/
GITHUB: https://github.com/Jiezhi/myleetcode
"""
class Solutio... | """
CREATED AT: 2021/7/24
Des:
https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences
https://leetcode.com/contest/biweekly-contest-57/problems/check-if-all-characters-have-equal-number-of-occurrences/
GITHUB: https://github.com/Jiezhi/myleetcode
"""
class Solution:
def are_occurre... |
#!/usr/bin/env python3
if __name__ == "__main__":
with open("./seedpool.txt", "r") as inf, open("./seedpool.h", "w") as ouf:
ouf.write("#ifndef SEED_POOL_H_\n#define SEED_POOL_H_\n\n"
"#include <vector>\n\nnamespace pbsutil {\n")
ouf.write("std::vector<uint> loadSeedPool() {\n"
... | if __name__ == '__main__':
with open('./seedpool.txt', 'r') as inf, open('./seedpool.h', 'w') as ouf:
ouf.write('#ifndef SEED_POOL_H_\n#define SEED_POOL_H_\n\n#include <vector>\n\nnamespace pbsutil {\n')
ouf.write('std::vector<uint> loadSeedPool() {\n\treturn {')
seeds = [line.strip() for li... |
with open('./PrimeraMuestraSceneFrame.map') as f:
content = f.readlines()
with open('./PrimeraMuestraSceneFrame2.map', 'w') as f2:
first = True;
for line in content:
l = line.split(' ');
f2.write(str(int(l[0])+450)+" "+l[1]+"\n");
| with open('./PrimeraMuestraSceneFrame.map') as f:
content = f.readlines()
with open('./PrimeraMuestraSceneFrame2.map', 'w') as f2:
first = True
for line in content:
l = line.split(' ')
f2.write(str(int(l[0]) + 450) + ' ' + l[1] + '\n') |
class UnionFind:
"""An implementation of union find data structure.
It uses union by rank with path compression.
"""
def __init__(self, count):
self._elements = list(range(count))
self._count = count
self._rank = [0] * count
def __len__(self):
return self._count
... | class Unionfind:
"""An implementation of union find data structure.
It uses union by rank with path compression.
"""
def __init__(self, count):
self._elements = list(range(count))
self._count = count
self._rank = [0] * count
def __len__(self):
return self._count
... |
#!/usr/bin/env python
# Software License Agreement (MIT License)
#
# Copyright (c) 2020, tri_star
# All rights reserved.
#
# 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... | reset = '\x1b[0m'
black = '0'
red = '1'
green = '2'
yellow = '3'
blue = '4'
magenta = '5'
cyan = '6'
light_gray = '7'
foreground_regular = '3'
foreground_light = '9'
background_regular = '4'
background_light = '10'
bold = '1'
dim = '2'
italic = '3'
underline = '4'
blink = '5'
reverse = '7'
hidden = '8'
strikethrough = ... |
class TestMySQLCLi:
def test_create_mysql_client_command(self, return_bck_obj):
result = '/usr/bin/mysql --defaults-file= -uroot --password=12345 --socket=/var/run/mysqld/mysqld.sock -e "select 1"'
sql = "select 1"
assert return_bck_obj.mysql_cli.create_mysql_client_command(sql) == result
... | class Testmysqlcli:
def test_create_mysql_client_command(self, return_bck_obj):
result = '/usr/bin/mysql --defaults-file= -uroot --password=12345 --socket=/var/run/mysqld/mysqld.sock -e "select 1"'
sql = 'select 1'
assert return_bck_obj.mysql_cli.create_mysql_client_command(sql) == result
... |
# API contants
FAN_MODE_AWAY = 'away'
FAN_MODE_LOW = 'low'
FAN_MODE_MEDIUM = 'medium'
FAN_MODE_HIGH = 'high'
# Commands
CMD_FAN_MODE_AWAY = b'\x84\x15\x01\x01\x00\x00\x00\x00\x01\x00\x00\x00\x00'
CMD_FAN_MODE_LOW = b'\x84\x15\x01\x01\x00\x00\x00\x00\x01\x00\x00\x00\x01'
CMD_FAN_MO... | fan_mode_away = 'away'
fan_mode_low = 'low'
fan_mode_medium = 'medium'
fan_mode_high = 'high'
cmd_fan_mode_away = b'\x84\x15\x01\x01\x00\x00\x00\x00\x01\x00\x00\x00\x00'
cmd_fan_mode_low = b'\x84\x15\x01\x01\x00\x00\x00\x00\x01\x00\x00\x00\x01'
cmd_fan_mode_medium = b'\x84\x15\x01\x01\x00\x00\x00\x00\x01\x00\x00\x00\x0... |
# OpenWeatherMap API Key
api_key = "KEY HERE PLEASE"
# Google API Key
g_key = "KEY HERE PLEASE"
| api_key = 'KEY HERE PLEASE'
g_key = 'KEY HERE PLEASE' |
"""
Function Basics I - No Input
"""
# Write a and call a function called "rand_list" that generates a list of 5 random numbers between 1 and 500. Print out that list.
| """
Function Basics I - No Input
""" |
#
# PySNMP MIB module DGS-6600-ID-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DGS-6600-ID-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:30:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint) ... |
"""LevelNet configuration information.
"""
#: String with host which is serving FIB-B data
NETWORK_HOST = '192.168.15.39'
#: Integer with port number on NETWORK_HOST serving FIS-B data
NETWORK_PORT = 3333
#: If ``True``, print errors to sys.stderr. Otherwise errors are silent.
PRINT_ERRORS = False
| """LevelNet configuration information.
"""
network_host = '192.168.15.39'
network_port = 3333
print_errors = False |
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
# A..Z 1..26
mod = 10 ** 9 + 7
e0, e1, e2 = 1, 0, 0
for c in s:
if c == '*':
f0 = 9 * e0 + 9 * e1 + 6 * e2
f1 = f2 = e0
... | class Solution(object):
def num_decodings(self, s):
"""
:type s: str
:rtype: int
"""
mod = 10 ** 9 + 7
(e0, e1, e2) = (1, 0, 0)
for c in s:
if c == '*':
f0 = 9 * e0 + 9 * e1 + 6 * e2
f1 = f2 = e0
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.