content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Template:
def __init__(self, bot, channel):
self.bot = bot
self.channel = channel
channel.set_command("!command", self.on_command, "!command description")
def on_command(self, message):
pass
# runs when a personal message is received
# message is a dictionary con... | class Template:
def __init__(self, bot, channel):
self.bot = bot
self.channel = channel
channel.set_command('!command', self.on_command, '!command description')
def on_command(self, message):
pass
def on_personal_message(self, message):
pass
def on_message(sel... |
def setup(app):
"""Additions and customizations to Sphinx that are useful for documenting
the Salt project.
"""
app.add_crossref_type(directivename="conf_master", rolename="conf_master",
indextemplate="pair: %s; conf/master")
app.add_crossref_type(directivename="conf_minion", rolename="... | def setup(app):
"""Additions and customizations to Sphinx that are useful for documenting
the Salt project.
"""
app.add_crossref_type(directivename='conf_master', rolename='conf_master', indextemplate='pair: %s; conf/master')
app.add_crossref_type(directivename='conf_minion', rolename='conf_minion'... |
# -*- coding: utf-8 -*-
DEBUG = True
TESTING = True
SECRET_KEY = 'SECRET_KEY'
DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1/git_webhook'
CELERY_BROKER_URL = 'redis://:@127.0.0.1:6379/0'
CELERY_RESULT_BACKEND = 'redis://:@127.0.0.1:6379/0'
SOCKET_MESSAGE_QUEUE = 'redis://:@127.0.0.1:6379/0'
GITHUB_CLIENT_ID = '... | debug = True
testing = True
secret_key = 'SECRET_KEY'
database_uri = 'mysql+pymysql://root:root@127.0.0.1/git_webhook'
celery_broker_url = 'redis://:@127.0.0.1:6379/0'
celery_result_backend = 'redis://:@127.0.0.1:6379/0'
socket_message_queue = 'redis://:@127.0.0.1:6379/0'
github_client_id = '123'
github_client_secret =... |
__title__ = 'django-activeurl'
__package_name__ = 'django_activeurl'
__version__ = '0.1.12'
__description__ = 'Easy-to-use active URL highlighting for Django'
__email__ = 'hellysmile@gmail.com'
__author__ = 'hellysmile'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright (c) hellysmile@gmail.com'
| __title__ = 'django-activeurl'
__package_name__ = 'django_activeurl'
__version__ = '0.1.12'
__description__ = 'Easy-to-use active URL highlighting for Django'
__email__ = 'hellysmile@gmail.com'
__author__ = 'hellysmile'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright (c) hellysmile@gmail.com' |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """Implementation of compilation logic for Swift."""
load(':actions.bzl', 'run_toolchain_action')
load(':deps.bzl', 'collect_link_libraries')
load(':derived_files.bzl', 'derived_files')
load(':providers.bzl', 'SwiftClangModuleInfo', 'SwiftInfo', 'SwiftToolchainInfo')
load(':utils.bzl', 'collect_transitive')
load('@baze... |
"""Sample Configuration
The bot doesn't actually read sample-config.py; it reads config.py instead.
So you need to copy this file to config.py then make your local changes there.
(The reason for this extra step is to make it harder for me to accidentally
check in private information like server names or passwords.)
""... | """Sample Configuration
The bot doesn't actually read sample-config.py; it reads config.py instead.
So you need to copy this file to config.py then make your local changes there.
(The reason for this extra step is to make it harder for me to accidentally
check in private information like server names or passwords.)
""... |
#
# PySNMP MIB module AT-ISDN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-ISDN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:14: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, 0... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, constraints_intersection, value_size_constraint) ... |
# Compound Interest
P = float(input('Enter principal amount: $'))
r = float(input('Enter annual interest rate %'))
n = float(input('Enter number of times per year interest has compounded: '))
t = float(
input('Enter number of years account will be left to earn interest: '))
r /= 100 # 50% = .50
A = P * ((1 + (r ... | p = float(input('Enter principal amount: $'))
r = float(input('Enter annual interest rate %'))
n = float(input('Enter number of times per year interest has compounded: '))
t = float(input('Enter number of years account will be left to earn interest: '))
r /= 100
a = P * (1 + r / n) ** (n * t)
print('After ', t, ' years... |
#coding: utf-8
# Copyright 2005-2010 Wesabe, 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 by applicable law or a... | class Routingnumber:
def __init__(self, number):
self.number = number
try:
self.digits = [int(digit) for digit in str(self.number).strip()]
self.region_code = int(str(self.digits[0]) + str(self.digits[1]))
self.converted = True
except ValueError:
... |
def pytest_addoption(parser):
parser.addoption("--project", action="store", default='None')
def pytest_generate_tests(metafunc):
# This is called for every test. Only get/set command line arguments
# if the argument is specified in the list of test "fixturenames".
option_value = metafunc.config.option... | def pytest_addoption(parser):
parser.addoption('--project', action='store', default='None')
def pytest_generate_tests(metafunc):
option_value = metafunc.config.option.project
if 'project' in metafunc.fixturenames and option_value is not None:
metafunc.parametrize('project', [option_value]) |
def endswith(x, lst):
""" Select longest suffix that matches x from provided list(lst)
:param x: input string
:param lst: suffixes to compare with
:return: longest suffix that matches input string if available otherwise None
"""
longest_suffix = None
for suffix in lst:
if x.endswith... | def endswith(x, lst):
""" Select longest suffix that matches x from provided list(lst)
:param x: input string
:param lst: suffixes to compare with
:return: longest suffix that matches input string if available otherwise None
"""
longest_suffix = None
for suffix in lst:
if x.endswith... |
#!/usr/bin/env python3
class Solution:
def findCircleNum(self, M):
sz, num = len(M), 0
marked = [False] * sz
def dfs(p):
marked[p] = True
for q in range(sz):
if M[p][q] and (not marked[q]):
dfs(q)
for p in range(sz):
... | class Solution:
def find_circle_num(self, M):
(sz, num) = (len(M), 0)
marked = [False] * sz
def dfs(p):
marked[p] = True
for q in range(sz):
if M[p][q] and (not marked[q]):
dfs(q)
for p in range(sz):
if not mar... |
#prints all TRs in a table
table = soup.findAll('table')[3]
for row in table.findAll('tr'):
print(row)
#prints each TR and each child tag in TR
table = soup.findAll('table')[3]
for row in table.findAll('tr'):
for line in row.findAll():
print(line)
| table = soup.findAll('table')[3]
for row in table.findAll('tr'):
print(row)
table = soup.findAll('table')[3]
for row in table.findAll('tr'):
for line in row.findAll():
print(line) |
#1. Idea here is we want to return a list of strings which contains all of the root to leaf paths in the binary tree.
#2. So initialize a list (path_list) then we are going to make a recursive call function. In the function we will pass the root of the binary tree and a empty string which we will modify and add node v... | def binary_tree_paths(self, root):
path_list = []
def recurse(root, path):
if root:
path += str(root.val)
if not root.left and (not root.right):
path_list.append(path)
else:
recurse(root.left, path + '->')
recurse(root.... |
class NfDictionaryTryGetResults:
def __init__(
self):
self.__key_exists = \
False
self.__value = \
None
def __get_key_exists(
self) \
-> bool:
key_exists = \
self.__key_exists
return \
key_exis... | class Nfdictionarytrygetresults:
def __init__(self):
self.__key_exists = False
self.__value = None
def __get_key_exists(self) -> bool:
key_exists = self.__key_exists
return key_exists
def __set_key_exists(self, key_exists: bool):
self.__key_exists = key_exists
... |
class Solution:
"""
@param nums: An integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def findPosition(self, nums, target):
low = 0
high = len(nums) - 1
while low<=high :
mid = (low+high) >> 1
if nums[mid]>ta... | class Solution:
"""
@param nums: An integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def find_position(self, nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = low + high >> 1
if nums[mid]... |
# pylint: disable=missing-function-docstring, missing-module-docstring/
# coding: utf-8
x = 1
e1 = x + a
e3 = f(x) + 1
# TODO e4 not working yet. we must get 2 errors
#e4 = f(x,y) + 1
| x = 1
e1 = x + a
e3 = f(x) + 1 |
# -*- coding: utf-8 -*-
"""A Collection of Financial Calculators.
This script contains a variety of financial calculator functions needed to
determine loan qualifications.
"""
"""Credit Score Filter.
This script filters a bank list by the user's minimum credit score.
"""
def filter_credit_score(credit_score, ban... | """A Collection of Financial Calculators.
This script contains a variety of financial calculator functions needed to
determine loan qualifications.
"""
"Credit Score Filter.\n\nThis script filters a bank list by the user's minimum credit score.\n\n"
def filter_credit_score(credit_score, bank_list):
"""Filters th... |
# -*- coding: utf-8 -*-
def command():
return "edit-instance-vmware"
def init_argument(parser):
parser.add_argument("--instance-no", required=True)
parser.add_argument("--instance-type", required=True)
parser.add_argument("--key-name", required=True)
parser.add_argument("--compute-resource", requi... | def command():
return 'edit-instance-vmware'
def init_argument(parser):
parser.add_argument('--instance-no', required=True)
parser.add_argument('--instance-type', required=True)
parser.add_argument('--key-name', required=True)
parser.add_argument('--compute-resource', required=True)
parser.add_... |
##############################################################################
# Documentation/conf.py
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership. The... | project = 'NuttX'
copyright = '2020, The Apache Software Foundation'
author = 'NuttX community'
version = release = 'latest'
extensions = ['sphinx_rtd_theme', 'm2r2', 'sphinx.ext.autosectionlabel', 'sphinx.ext.todo', 'sphinx_tabs.tabs']
source_suffix = ['.rst', '.md']
todo_include_todos = True
autosectionlabel_prefix_d... |
config = {
'Department_level_configs': {
'Department_Name': 'Data Analisys Department',
'Department_Short_Name': 'DATA'
}
}
| config = {'Department_level_configs': {'Department_Name': 'Data Analisys Department', 'Department_Short_Name': 'DATA'}} |
"""
At a lemonade stand, each lemonade costs $5.
Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).
Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net tra... | """
At a lemonade stand, each lemonade costs $5.
Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).
Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net tra... |
# coding: utf-8
class UtgError(Exception):
MSG = None
def __init__(self, **kwargs):
super(UtgError, self).__init__(self.MSG % kwargs)
self.arguments = kwargs
class WordsError(UtgError):
pass
class WrongFormsNumberError(WordsError):
MSG = 'constuctor of word receive wrong number of... | class Utgerror(Exception):
msg = None
def __init__(self, **kwargs):
super(UtgError, self).__init__(self.MSG % kwargs)
self.arguments = kwargs
class Wordserror(UtgError):
pass
class Wrongformsnumbererror(WordsError):
msg = 'constuctor of word receive wrong number of forms (%(wrong_numb... |
''' Abstract class of healthcheck. There is only one method to implement,
that determines state of Vm or its underlying services.
Initialization - consider following config:
::
healthcheck:
driver: SomeHC
param1: AAAA
param2: BBBB
some_x: CCC
All params will be passed as config dict to the dr... | """ Abstract class of healthcheck. There is only one method to implement,
that determines state of Vm or its underlying services.
Initialization - consider following config:
::
healthcheck:
driver: SomeHC
param1: AAAA
param2: BBBB
some_x: CCC
All params will be passed as config dict to the dr... |
# Solution
#----------------------------------------------------#
def prepend(self, value):
""" Prepend a node to the beginning of the list """
if self.head is None:
self.head = Node(value)
return
new_head = Node(value)
new_head.next = self.head
self.head = new_head
#-------------... | def prepend(self, value):
""" Prepend a node to the beginning of the list """
if self.head is None:
self.head = node(value)
return
new_head = node(value)
new_head.next = self.head
self.head = new_head
def append(self, value):
""" Append a node to the end of the list """
if s... |
class State(object):
def __init__(self):
print("Processing current state: ", str(self))
def on_event(self, event):
"""
Handle events that are delegated to this State.
"""
pass
def __repr__(self):
"""
Leverages the __str__ method to describe the State.
"""
return self.__str__()
def __str__(self)... | class State(object):
def __init__(self):
print('Processing current state: ', str(self))
def on_event(self, event):
"""
Handle events that are delegated to this State.
"""
pass
def __repr__(self):
"""
Leverages the __str__ method to describe the State.
"""
r... |
lines = int(input("Please enter number of lines : \n"))
ln = 1
while ln <= lines:
col = 1
while col <= lines:
if ln == 1 or col == 1 or col == lines or ln == lines:
print('*', end='')
else:
print(' ', end = '')
col += 1
print()
ln += 1
| lines = int(input('Please enter number of lines : \n'))
ln = 1
while ln <= lines:
col = 1
while col <= lines:
if ln == 1 or col == 1 or col == lines or (ln == lines):
print('*', end='')
else:
print(' ', end='')
col += 1
print()
ln += 1 |
# Valid API version in URL path: YYYY-MM or unstable
VERSION_PATTERN = r"([0-9]{4}-[0-9]{2})|unstable"
# /oauth/authorize, /oauth/access_token do not require authentication
NOT_AUTHABLE_PATTERN = r"\/oauth\/(authorize|access_token)"
# /oauth/access_scopes does not require versioned API path
NOT_VERSIONABLE_PATTERN = r"... | version_pattern = '([0-9]{4}-[0-9]{2})|unstable'
not_authable_pattern = '\\/oauth\\/(authorize|access_token)'
not_versionable_pattern = '\\/(oauth\\/access_scopes)'
link_pattern = '<.*?page_info=([a-zA-Z0-9\\-_]+).*?>; rel=\\"(next|previous)\\"'
retry_header = 'retry-after'
link_header = 'link'
access_token_header = 'x... |
def iterate(pop):
p = pop.copy()
for i in range(8):
p[i] = pop[i + 1]
p[8] = pop[0]
p[6] += pop[0]
return p
pop = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}
population = [int(n) for n in open('input.txt', 'r').readline().split(',')]
for fish in population:
pop[fish] += 1
f... | def iterate(pop):
p = pop.copy()
for i in range(8):
p[i] = pop[i + 1]
p[8] = pop[0]
p[6] += pop[0]
return p
pop = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}
population = [int(n) for n in open('input.txt', 'r').readline().split(',')]
for fish in population:
pop[fish] += 1
for ... |
for c in range(6, 0,-1):
print(c)
n1 = int(input('Inicio: '))
n2 = int(input('Fim: '))
n3 = int(input('Passo: '))
for c in range(n1, n2 + 1, n3):
print(c) | for c in range(6, 0, -1):
print(c)
n1 = int(input('Inicio: '))
n2 = int(input('Fim: '))
n3 = int(input('Passo: '))
for c in range(n1, n2 + 1, n3):
print(c) |
#
# PySNMP MIB module SLAPM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SLAPM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:06:04 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, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
"""The CLI package."""
__all__ = [
"main", "bootstrap", "config", "log", "project", "experiment", "report",
"run", "slurm"
]
| """The CLI package."""
__all__ = ['main', 'bootstrap', 'config', 'log', 'project', 'experiment', 'report', 'run', 'slurm'] |
# To format the names in title case
input_first_name=input("Enter the first name: ")
input_last_name= input("Enter the last name: ")
def format_name(first_name,last_name):
first_name = first_name.title()
last_name = last_name.title()
full_name = first_name + " "+last_name
return full_name
name = forma... | input_first_name = input('Enter the first name: ')
input_last_name = input('Enter the last name: ')
def format_name(first_name, last_name):
first_name = first_name.title()
last_name = last_name.title()
full_name = first_name + ' ' + last_name
return full_name
name = format_name(input_first_name, input_... |
def determine_dim_size(dim_modalities, pick_modalities):
if len(pick_modalities) < len(dim_modalities):
dim_modalities = [dim_modalities[mod_idx] for mod_idx in pick_modalities]
return dim_modalities
def prepare_batch(multidimensional_ts, split_modalities, pick_modalities, dim_modalities):
if split... | def determine_dim_size(dim_modalities, pick_modalities):
if len(pick_modalities) < len(dim_modalities):
dim_modalities = [dim_modalities[mod_idx] for mod_idx in pick_modalities]
return dim_modalities
def prepare_batch(multidimensional_ts, split_modalities, pick_modalities, dim_modalities):
if split... |
#################################################################
# #
# Program Code for Spot Micro MRL #
# Of the Cyber_One YouTube Channel #
# https://www.youtube.com/cyber_one ... | runing_folder = 'Spot'
execfile(RuningFolder + '/1_Configuration/1_Sys_Config.py')
if RunWebGUI == True:
plan = runtime.load('webgui', 'WebGui')
config = plan.get('webgui')
config.autoStartBrowser = False
runtime.start('webgui', 'WebGui')
execfile(RuningFolder + '/Common_Variables.py')
execfile(RuningFo... |
#!/usr/bin/env python3
# Extra Line added
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 13:52:32 2018
@author: jaley
"""
class Dog(object):
# 2 Underscores
def __init__(self,breed):
self.breed = breed
sam = Dog(breed='Lab')
frank = Dog(breed='Huskie')
print (sam.breed)
class Animal(... | """
Created on Sun Sep 30 13:52:32 2018
@author: jaley
"""
class Dog(object):
def __init__(self, breed):
self.breed = breed
sam = dog(breed='Lab')
frank = dog(breed='Huskie')
print(sam.breed)
class Animal(object):
def __init__(self, name):
self.name = name
print(self.name + ' create... |
def printg(grid, name):
print( '%s: [' % name)
for row in grid:
print( row)
print( ']')
def dist(p, q):
dx = abs(p[0] - q[0])
dy = abs(p[1] - q[1])
return dx + dy;
def reconstruct_path(came_from, current):
total_path = [current]
while current in came_from.keys():
curren... | def printg(grid, name):
print('%s: [' % name)
for row in grid:
print(row)
print(']')
def dist(p, q):
dx = abs(p[0] - q[0])
dy = abs(p[1] - q[1])
return dx + dy
def reconstruct_path(came_from, current):
total_path = [current]
while current in came_from.keys():
current = ... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class ZtdDevice(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value ... | class Ztddevice(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {'serialNu... |
msg_soc='BA:?'
msg_p='P:?'
msg_ppvt='PV:?'
msg_conso='CON:?'
soc=101
try:
tree = etree.parse(configGet('tmpFileDataXml'))
for datas in tree.xpath("/devices/device/datas/data"):
if datas.get("id") in configGet('lcd','dataPrint'):
for data in datas.getchildren():
if data.tag =... | msg_soc = 'BA:?'
msg_p = 'P:?'
msg_ppvt = 'PV:?'
msg_conso = 'CON:?'
soc = 101
try:
tree = etree.parse(config_get('tmpFileDataXml'))
for datas in tree.xpath('/devices/device/datas/data'):
if datas.get('id') in config_get('lcd', 'dataPrint'):
for data in datas.getchildren():
i... |
HP_SERIAL_FORMAT_DEFAULT = "auto"
HP_SERIAL_FORMAT_CHOICES = ["auto", "yaml", "pickle"]
HP_ACTION_PREFIX_DEFAULT = "hp"
| hp_serial_format_default = 'auto'
hp_serial_format_choices = ['auto', 'yaml', 'pickle']
hp_action_prefix_default = 'hp' |
"""Implements the BiDi Rule.
(Source: RFC 5893, Section 2)
The following rule, consisting of six conditions, applies to labels
in Bidi domain names. The requirements that this rule satisfies are
described in Section 3. All of the conditions must be satisfied for
the rule to be satisfied.
1. The first character mus... | """Implements the BiDi Rule.
(Source: RFC 5893, Section 2)
The following rule, consisting of six conditions, applies to labels
in Bidi domain names. The requirements that this rule satisfies are
described in Section 3. All of the conditions must be satisfied for
the rule to be satisfied.
1. The first character mus... |
class TranslatorExceptions(Exception):
def __init__(self, message):
super().__init__()
self.message = message
class LangDoesNotExists(TranslatorExceptions):
def __init__(self):
super().__init__(
'Requested language does not exists\nTry to run \'lang\' command to be familiar... | class Translatorexceptions(Exception):
def __init__(self, message):
super().__init__()
self.message = message
class Langdoesnotexists(TranslatorExceptions):
def __init__(self):
super().__init__("Requested language does not exists\nTry to run 'lang' command to be familiar with supporte... |
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
# Runtime: 20 ms
# Memory: 13.7 MB
if needle in haystack:
return haystack.index(needle)
else:
return -... | class Solution(object):
def str_str(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle in haystack:
return haystack.index(needle)
else:
return -1 |
{
"targets": [
{
"target_name": "mtrace",
"sources": [ "mtrace.cc" ],
"include_dirs" : [
"<!(node -e \"require('nan')\")"
]
}
]
}
| {'targets': [{'target_name': 'mtrace', 'sources': ['mtrace.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]} |
class TCPServer(object):
def process_request(self, request, client_address):
self.do_work(request, client_address)
self.shutdown_request(request)
class ThreadingMixIn:
"""Mix-in class to handle each request in a new thread."""
def process_request(self, request, client_address):
... | class Tcpserver(object):
def process_request(self, request, client_address):
self.do_work(request, client_address)
self.shutdown_request(request)
class Threadingmixin:
"""Mix-in class to handle each request in a new thread."""
def process_request(self, request, client_address):
""... |
class Node:
def __init__(self, data, parent=None):
self.parent = parent
self.data = data
self.left = None
self.right = None
def leftChild(self, left):
self.left = Node(left, self)
def rightChild... | class Node:
def __init__(self, data, parent=None):
self.parent = parent
self.data = data
self.left = None
self.right = None
def left_child(self, left):
self.left = node(left, self)
def right_child(self, right):
self.right = node(right, self)
def __str_... |
class Solution:
def isPalindrome(self, s: str) -> bool:
formattedString = ''.join([c.lower() for c in s if c.isalnum()])
if formattedString == formattedString[::-1]:
return True
return False | class Solution:
def is_palindrome(self, s: str) -> bool:
formatted_string = ''.join([c.lower() for c in s if c.isalnum()])
if formattedString == formattedString[::-1]:
return True
return False |
VERSION = (0, 0, 2, 3)
__version__ = '.'.join(map(str, VERSION))
default_app_config = 'django.chatbot.apps.DjangoChatBotConfig'
| version = (0, 0, 2, 3)
__version__ = '.'.join(map(str, VERSION))
default_app_config = 'django.chatbot.apps.DjangoChatBotConfig' |
# Use right join to merge the movie_to_genres and pop_movies tables
genres_movies = movie_to_genres.merge(pop_movies, how='right',
left_on='movie_id',
right_on='id')
# Count the number of genres
genre_count = genres_movies.groupby('genre... | genres_movies = movie_to_genres.merge(pop_movies, how='right', left_on='movie_id', right_on='id')
genre_count = genres_movies.groupby('genre').agg({'id': 'count'})
genre_count.plot(kind='bar')
plt.show() |
counter = 10
sums = 1
k = 2
currLast = 1
while counter > 0:
k += 1
while sums < (k + 1) ** 2:
currLast += 1
sums += currLast
if sums == (k + 1) ** 2:
counter -= 1
print (k + 1), currLast
| counter = 10
sums = 1
k = 2
curr_last = 1
while counter > 0:
k += 1
while sums < (k + 1) ** 2:
curr_last += 1
sums += currLast
if sums == (k + 1) ** 2:
counter -= 1
(print(k + 1), currLast) |
# IMPORTS
# DATA
data = []
with open("Data - Day11.txt") as file:
for line in file:
for direction in line.strip().split(","):
data.append(direction)
# GOAL 1
"""
The hexagons ("hexes") in this grid are aligned such that adjacent hexes can be found to the north,
northeast, southeast, south, so... | data = []
with open('Data - Day11.txt') as file:
for line in file:
for direction in line.strip().split(','):
data.append(direction)
'\nThe hexagons ("hexes") in this grid are aligned such that adjacent hexes can be found to the north,\n northeast, southeast, south, southwest, and northwest:\n\nY... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
lo = 0
hi = len(nums) - 1
while (lo < hi):
if nums[lo] == 0:
lo += 1
... | class Solution(object):
def sort_colors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
lo = 0
hi = len(nums) - 1
while lo < hi:
if nums[lo] == 0:
lo += 1
el... |
CONVERT_JSON_TO_YAML = {
"type": "post",
"endpoint": "/convertJSONtoYAML",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoint} {response_code}"
}
CONVERT_RANGE_FROM_TO = {
"type": "get",
"endpoint": "/convertRangeFromTo",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoi... | convert_json_to_yaml = {'type': 'post', 'endpoint': '/convertJSONtoYAML', 'call_message': '{type} {endpoint}', 'error_message': '{type} {endpoint} {response_code}'}
convert_range_from_to = {'type': 'get', 'endpoint': '/convertRangeFromTo', 'call_message': '{type} {endpoint}', 'error_message': '{type} {endpoint} {respon... |
number = 0
total = 0
while number != -1:
total += number
number = float(input("Please enter a positive number (-1 to stop):"))
print(total)
| number = 0
total = 0
while number != -1:
total += number
number = float(input('Please enter a positive number (-1 to stop):'))
print(total) |
"""
This module contains several parsers. This includes utilities for reading and converting molecular
dynamics input files to instructions for the :obj:`schnetpack.md.simulator.Simulator`. In addition, there is
a full package for parsing ORCA output files.
"""
| """
This module contains several parsers. This includes utilities for reading and converting molecular
dynamics input files to instructions for the :obj:`schnetpack.md.simulator.Simulator`. In addition, there is
a full package for parsing ORCA output files.
""" |
# Define your handoff handlers here
# for more information, see:
# http://docs.tethysplatform.org/en/dev/tethys_sdk/handoff.html
def csv(request, csv_url):
"""
Test Handoff handler.
"""
return 'test_app:home'
| def csv(request, csv_url):
"""
Test Handoff handler.
"""
return 'test_app:home' |
#
# PySNMP MIB module ZHONE-CARD-DIAGNOSTICS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-CARD-DIAGNOSTICS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:46:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) ... |
line = input()
party = {}
unlikes = 0
while line != "Stop":
act, guest, meal = line.split("-")
if act == "Like":
if guest in party.keys():
if meal in party[guest]:
line = input()
continue
party[guest].append(meal)
line = input()
... | line = input()
party = {}
unlikes = 0
while line != 'Stop':
(act, guest, meal) = line.split('-')
if act == 'Like':
if guest in party.keys():
if meal in party[guest]:
line = input()
continue
party[guest].append(meal)
line = input()
... |
L=raw_input("Please Enter the length of the layer (in m): ")
A=raw_input("Please Enter the area of the wall (in m2): ")
material=raw_input("Please Enter the material of the layer: ")
if material=="glass":
type_glas=raw_input("which type of glass do you mean:window=1, wool insulation=2 ")
if int(type_glas)==1:
... | l = raw_input('Please Enter the length of the layer (in m): ')
a = raw_input('Please Enter the area of the wall (in m2): ')
material = raw_input('Please Enter the material of the layer: ')
if material == 'glass':
type_glas = raw_input('which type of glass do you mean:window=1, wool insulation=2 ')
if int(type_g... |
def test_user_create_public_group( # noqa
user, public_group,
):
accessible = public_group.is_accessible_by(user, mode="create")
assert accessible
def test_user_create_public_groupuser(
user, public_groupuser,
):
accessible = public_groupuser.is_accessible_by(user, mode="create")
assert not a... | def test_user_create_public_group(user, public_group):
accessible = public_group.is_accessible_by(user, mode='create')
assert accessible
def test_user_create_public_groupuser(user, public_groupuser):
accessible = public_groupuser.is_accessible_by(user, mode='create')
assert not accessible
def test_use... |
#define a value holder function
# => True
def switch(value):
switch.value=value
return True
#define matching case function
# => True or False
def case(*args):
return any((arg == switch.value for arg in args))
# Switch example:
print("Describe a number from range:")
for n in range(0,10):
print(n, end=" "... | def switch(value):
switch.value = value
return True
def case(*args):
return any((arg == switch.value for arg in args))
print('Describe a number from range:')
for n in range(0, 10):
print(n, end=' ', flush=True)
print()
x = input('n:')
n = int(x)
while switch(n):
if case(0):
print('n is zero... |
# Recursive solution (TLE)
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
def util(s, wordDict):
if s == "":
return True
for i in range(1, len(s)+1):
... | class Solution(object):
def word_break(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
def util(s, wordDict):
if s == '':
return True
for i in range(1, len(s) + 1):
if str(s[:i])... |
# Copyright 2019 AUI, Inc. Washington DC, USA
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | def uvmodelfit(xds, field=None, spw=None, timerange=None, uvrange=None, antenna=None, scan=None, niter=5, comptype='p', sourcepar=[1, 0, 0], varypar=[]):
"""
.. todo::
This function is not yet implemented
Fit simple analytic source component models directly to visibility data
Parameters
--... |
#!/usr/bin/python3
"""
This is a simple implementation of BST
binary search tree
"""
class Node(object):
def __init__(self, value=None, left=None, right=None, parent=None):
self.value = value
self.left = left
self.right = right
self.parent = parent
def __str__(self):
... | """
This is a simple implementation of BST
binary search tree
"""
class Node(object):
def __init__(self, value=None, left=None, right=None, parent=None):
self.value = value
self.left = left
self.right = right
self.parent = parent
def __str__(self):
"""
... |
#!/usr/bin/python3
# Guilhem Mizrahi 09/2019
def first():
var1=input("Enter the first number: ")
var2=input("Enter the second number: ")
print(var1/var2)
def second():
var1=int(input("Enter the first number: "))
var2=int(input("Enter the second number: "))
print(var1/var2)
def third():
... | def first():
var1 = input('Enter the first number: ')
var2 = input('Enter the second number: ')
print(var1 / var2)
def second():
var1 = int(input('Enter the first number: '))
var2 = int(input('Enter the second number: '))
print(var1 / var2)
def third():
retvalue1 = ''
while not retvalu... |
PROG = 'censor'
fin = open(PROG + '.in', 'r')
fout = open(PROG + '.out', 'w')
def main():
s = fin.readline()
s = s[:len(s) - 1]
t = fin.readline()
t = t[:len(t) - 1]
while True:
i = s.find(t)
if i == -1:
break
s = s[0:i] + s[i + len(t):]
fout.write(s + '\n')
main()
fin.close()
fout.close()
| prog = 'censor'
fin = open(PROG + '.in', 'r')
fout = open(PROG + '.out', 'w')
def main():
s = fin.readline()
s = s[:len(s) - 1]
t = fin.readline()
t = t[:len(t) - 1]
while True:
i = s.find(t)
if i == -1:
break
s = s[0:i] + s[i + len(t):]
fout.write(s + '\n')
... |
# tests.py
# Run `conda install pytest`
# Run `pytest test_main.py` from the speech2phone/ directory.
"""
To use pytest, the file must be named "test***.py". For example, `tests.py` or `test_pca.py`.
Test functions must be prefixed with `test_`. So `multiply()` is not a test function, but `test_numbers_3_4()` is.
We u... | """
To use pytest, the file must be named "test***.py". For example, `tests.py` or `test_pca.py`.
Test functions must be prefixed with `test_`. So `multiply()` is not a test function, but `test_numbers_3_4()` is.
We use simple assert statements for our testing. No assertThis() or assertThat().
https://docs.pytest.org/... |
class IncorrectInputVectorLength(Exception):
pass
class NetIsNotInitialized(Exception):
pass
class IncorrectFactorValue(Exception):
pass
class NetIsNotCalculated(Exception):
pass
class IncorrectExpectedOutputVectorLength(Exception):
pass
class NetConfigIndefined(Exception):
pass
clas... | class Incorrectinputvectorlength(Exception):
pass
class Netisnotinitialized(Exception):
pass
class Incorrectfactorvalue(Exception):
pass
class Netisnotcalculated(Exception):
pass
class Incorrectexpectedoutputvectorlength(Exception):
pass
class Netconfigindefined(Exception):
pass
class Netc... |
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
"""
:rtype: int
"""
v = (rand7()-1)*7 + rand7()-1
while v >= 40: v = (rand7()-1)*7 + rand7()-1
return v%10 + 1 | class Solution:
def rand10(self):
"""
:rtype: int
"""
v = (rand7() - 1) * 7 + rand7() - 1
while v >= 40:
v = (rand7() - 1) * 7 + rand7() - 1
return v % 10 + 1 |
class BingoBoard:
def __init__(self, numbers):
self.numbers = [int(n) for n in numbers.replace("\n", " ").split()]
self.marked = set()
def mark(self, n):
if n in self.numbers:
self.marked.add(n)
return self.check_win()
return False
def get_score(sel... | class Bingoboard:
def __init__(self, numbers):
self.numbers = [int(n) for n in numbers.replace('\n', ' ').split()]
self.marked = set()
def mark(self, n):
if n in self.numbers:
self.marked.add(n)
return self.check_win()
return False
def get_score(sel... |
#from http://rosettacode.org/wiki/Greatest_common_divisor#Python
#pythran export gcd_iter(int, int)
#pythran export gcd(int, int)
#pythran export gcd_bin(int, int)
#runas gcd_iter(40902, 24140)
#runas gcd(40902, 24140)
#runas gcd_bin(40902, 24140)
def gcd_iter(u, v):
while v:
u, v = v, u % v
return abs... | def gcd_iter(u, v):
while v:
(u, v) = (v, u % v)
return abs(u)
def gcd(u, v):
return gcd(v, u % v) if v else abs(u)
def gcd_bin(u, v):
(u, v) = (abs(u), abs(v))
if u < v:
(u, v) = (v, u)
if v == 0:
return u
k = 1
while u & 1 == 0 and v & 1 == 0:
u >>= 1
... |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | class Jobmode:
collective = 'collective'
ps = 'ps'
heter = 'heter'
class Job(object):
def __init__(self, jid='default', mode=JobMode.COLLECTIVE, nnodes='1'):
self._mode = mode
self._id = jid
self._replicas = 0
self._replicas_min = self._replicas
self._replicas_m... |
def Menunggu(n,des):
#basis
if n == 0:
return 0
#rekuren
print(des)
return Menunggu(n-1,des)
def MySum(n):
#basis
if n == 0:
return 0
#rekuren
return n+MySum(n-1)
def main():
# solusi iteratif/pengulangan dengan teknik for loop
#n = 10
#for i in range(n... | def menunggu(n, des):
if n == 0:
return 0
print(des)
return menunggu(n - 1, des)
def my_sum(n):
if n == 0:
return 0
return n + my_sum(n - 1)
def main():
menunggu(10, 'Menunggu si dia.')
print(my_sum(10))
if __name__ == '__main__':
main() |
i = input().split()
N,Q = int(i[0]),int(i[1])
AI = input().split()
ai = []
for n in AI:
ai.append(int(n))
QI = input().split()
qi = []
for n in QI:
qi.append(int(n))
for q in qi:
ai_aux = ai.copy()
count = 0
p = 0
while(p<len(ai_aux)-1):
if q in ai_aux:
... | i = input().split()
(n, q) = (int(i[0]), int(i[1]))
ai = input().split()
ai = []
for n in AI:
ai.append(int(n))
qi = input().split()
qi = []
for n in QI:
qi.append(int(n))
for q in qi:
ai_aux = ai.copy()
count = 0
p = 0
while p < len(ai_aux) - 1:
if q in ai_aux:
count += 1
... |
class hparams:
train_or_test = 'train'
output_dir = 'logs/your_program_name'
aug = False
latest_checkpoint_file = 'checkpoint_latest.pt'
total_epochs = 100
epochs_per_checkpoint = 10
batch_size = 2
ckpt = None
init_lr = 0.0002
scheduer_step_size = 20
scheduer_gamma = 0.8
... | class Hparams:
train_or_test = 'train'
output_dir = 'logs/your_program_name'
aug = False
latest_checkpoint_file = 'checkpoint_latest.pt'
total_epochs = 100
epochs_per_checkpoint = 10
batch_size = 2
ckpt = None
init_lr = 0.0002
scheduer_step_size = 20
scheduer_gamma = 0.8
... |
'''
--- Day 1: The Tyranny of the Rocket Equation ---
-- Part 1 --
The Elves quickly load you into a spacecraft and prepare to launch.
At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper.
They haven't determined the amount of fuel required yet.
Fuel required to launch a given module is based... | """
--- Day 1: The Tyranny of the Rocket Equation ---
-- Part 1 --
The Elves quickly load you into a spacecraft and prepare to launch.
At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper.
They haven't determined the amount of fuel required yet.
Fuel required to launch a given module is based... |
"""
exceptions/__init__.py
Comments:
Author: Dennis Whitney
Email: dennis@runasroot.com
Copyright (c) 2021, iRunAsRoot
"""
class ValueReadOnly(Exception):
pass
class ValueNotAllowed(Exception):
pass
class UnauthorizedAccess(Exception):
pass
class UnknownEndpoint(Exception):
pass
| """
exceptions/__init__.py
Comments:
Author: Dennis Whitney
Email: dennis@runasroot.com
Copyright (c) 2021, iRunAsRoot
"""
class Valuereadonly(Exception):
pass
class Valuenotallowed(Exception):
pass
class Unauthorizedaccess(Exception):
pass
class Unknownendpoint(Exception):
pass |
"""
map data could be a 2D grid with data for each cell as N, S, E, W. A special data
set would highlight "here" information, like if there's a pit, item, encounter or
teleportation.
w - wall
d - door
o - open
s - secret door (shows as 'w' on other side)
A box with a door leading east from the NE quadrant would look ... | """
map data could be a 2D grid with data for each cell as N, S, E, W. A special data
set would highlight "here" information, like if there's a pit, item, encounter or
teleportation.
w - wall
d - door
o - open
s - secret door (shows as 'w' on other side)
A box with a door leading east from the NE quadrant would look ... |
#This is a simple inventory program for a small car dealership.
print('Automotive Inventory')
class Automobile:
def __init__(self):
self._make = ''
self._model = ''
self._year = 0
self._color = ''
self._mileage = 0
def addVehicle(self):
try:
... | print('Automotive Inventory')
class Automobile:
def __init__(self):
self._make = ''
self._model = ''
self._year = 0
self._color = ''
self._mileage = 0
def add_vehicle(self):
try:
self._make = input('Enter vehicle make: ')
self._model = i... |
class Registry:
def __init__(self):
self.addr = ["134.209.83.144"]
self._config = None
self._executor = None
@property
def executor(self):
if not self._executor:
self._executor = ExecutorSSH(self.addr[0], 22)
return self._executor
@property
def m... | class Registry:
def __init__(self):
self.addr = ['134.209.83.144']
self._config = None
self._executor = None
@property
def executor(self):
if not self._executor:
self._executor = executor_ssh(self.addr[0], 22)
return self._executor
@property
def... |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
""" qisrc actcions """
| """ qisrc actcions """ |
__author__ = 'ian.collins'
currentcolor = True # true=day, false=night
lightthreshold = 50
lightchecktime = 10.0
gpsrefreshtime = 15.0
netrefreshtime = 30.0
crvincidentmain = None
# The actualt status bar
statusbar = None
# Where the statusbar fields are kept
statusbarbox = None
# An alternate statusbar ... | __author__ = 'ian.collins'
currentcolor = True
lightthreshold = 50
lightchecktime = 10.0
gpsrefreshtime = 15.0
netrefreshtime = 30.0
crvincidentmain = None
statusbar = None
statusbarbox = None
altstatusbarbox = None
alstatusbarclick = ''
alstatusbarparent = None
quickpopup = None
data = None
msgbox = None
mycurl = None... |
#########################################################################################################################################################################
# Author : Remi Monthiller, remi.monthiller@etu.enseeiht.fr
# Adapted from the code of Raphael Maurin, raphael.maurin@imft.fr
# 30/10/2018
#
# Inclin... | def length_vector3(vect):
return (vect[0] ** 2.0 + vect[1] ** 2.0 + vect[2] ** 2.0) ** (1.0 / 2.0) |
class Solution(object):
def wordsAbbreviation(self, dict):
"""
:type dict: List[str]
:rtype: List[str]
"""
res = []
countMap = {}
prefix = [1] * len(dict)
for word in dict:
abbr = self.abbreviateWord(word, 1)
res.append(abbr)
... | class Solution(object):
def words_abbreviation(self, dict):
"""
:type dict: List[str]
:rtype: List[str]
"""
res = []
count_map = {}
prefix = [1] * len(dict)
for word in dict:
abbr = self.abbreviateWord(word, 1)
res.append(abbr)... |
DRIVERS = {
"default": "cookie",
"cookie": {},
}
| drivers = {'default': 'cookie', 'cookie': {}} |
string = "resource"
if len(string) < 2:
print("--")
else:
print(string[0:2] + string[-2:])
| string = 'resource'
if len(string) < 2:
print('--')
else:
print(string[0:2] + string[-2:]) |
def increment_id(tag):
if tag == "error":
filename = "errorarena"
elif tag == "valid":
filename = "validarena"
elif tag == "gif":
filename = "gif"
file = open(f"./results/id/{filename}.txt","r")
id_line = file.readline()
file.close()
curr_id = int(id_line.strip())... | def increment_id(tag):
if tag == 'error':
filename = 'errorarena'
elif tag == 'valid':
filename = 'validarena'
elif tag == 'gif':
filename = 'gif'
file = open(f'./results/id/{filename}.txt', 'r')
id_line = file.readline()
file.close()
curr_id = int(id_line.strip())
... |
for char in 'One':
print (char)
'''
O
n
e
''' | for char in 'One':
print(char)
'\nO\nn \ne\n' |
# program to convert degrees f to degrees c
# need to use (degF - 32) * 5/9
user = input('Hello, what is your name? ')
print('Hello', user)
degF = int(input('Enter a temperature in degrees F: '))
degC = (degF -32) * 5/9
print('{} ,degrees F converts to , {} ,degrees C'.format(degF, (degC)))
| user = input('Hello, what is your name? ')
print('Hello', user)
deg_f = int(input('Enter a temperature in degrees F: '))
deg_c = (degF - 32) * 5 / 9
print('{} ,degrees F converts to , {} ,degrees C'.format(degF, degC)) |
num =10
num2= 20
num3=30
num4=40
| num = 10
num2 = 20
num3 = 30
num4 = 40 |
class A(object):
x:int = 1
class B(A):
def __init__(self: "B"):
pass
class C(B):
z:bool = True
a:A = None
b:B = None
c:C = None
a = A()
b = B()
c = C()
| class A(object):
x: int = 1
class B(A):
def __init__(self: 'B'):
pass
class C(B):
z: bool = True
a: A = None
b: B = None
c: C = None
a = a()
b = b()
c = c() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 20:55:21 2017
@author: Lama Hamadeh
"""
'''
Case Study about DNA translation
'''
'''
NCBI is the United States' main public repository of DNA and related information
We will download two files from NCBI: the first is a strand of DNA and the secon... | """
Created on Tue Feb 21 20:55:21 2017
@author: Lama Hamadeh
"""
'\nCase Study about DNA translation\n'
"\nNCBI is the United States' main public repository of DNA and related information\nWe will download two files from NCBI: the first is a strand of DNA and the second \nis the protein sequence of amino acids transla... |
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
'''
Number of missing element at index i =
= arr[0] - 1 + arr[idx] - arr[0] - idx =
= arr[idx] - idx - 1
For more description, see: 1060 Missing Element in Sorted Array
T: O(log n) a... | class Solution:
def find_kth_positive(self, arr: List[int], k: int) -> int:
"""
Number of missing element at index i =
= arr[0] - 1 + arr[idx] - arr[0] - idx =
= arr[idx] - idx - 1
For more description, see: 1060 Missing Element in Sorted Array
T: O(log n... |
z = "Tests were ran for service: matchService \n" \
"Passed: \n" \
"Failed: \n" \
"Error: \n" \
"Skipped: \n"
| z = 'Tests were ran for service: matchService \nPassed: \nFailed: \nError: \nSkipped: \n' |
ip_addr1="192.168.1.1"
ip_addr2="10.1.1.1"
ip_addr3="172.16.1.1"
print ("\n")
print ("-" * 80)
print ("{my_ip:^20}{ip:^20}{ip_alt:^20}".format(ip_alt=ip_addr1, ip=ip_addr2, my_ip=ip_addr3))
print ("-" * 80)
print ("\n")
octets = ip_addr1.split('.')
| ip_addr1 = '192.168.1.1'
ip_addr2 = '10.1.1.1'
ip_addr3 = '172.16.1.1'
print('\n')
print('-' * 80)
print('{my_ip:^20}{ip:^20}{ip_alt:^20}'.format(ip_alt=ip_addr1, ip=ip_addr2, my_ip=ip_addr3))
print('-' * 80)
print('\n')
octets = ip_addr1.split('.') |
"""
find the last item in a singly linked list
"""
#keep checking list until there is node has no next
def lastnode(linked_list, k):
if k <= 0:
return None
pointer2 = linkedlist.head
for i in range(k-1):
if pointer2.next != None:
pointer2 = pointer2.next
else:
... | """
find the last item in a singly linked list
"""
def lastnode(linked_list, k):
if k <= 0:
return None
pointer2 = linkedlist.head
for i in range(k - 1):
if pointer2.next != None:
pointer2 = pointer2.next
else:
return 'loop'
pointer1 = linkedlist.head
... |
"""Define module exceptions."""
class SeventeenTrackError(Exception):
"""Define a base error."""
pass
class InvalidTrackingNumberError(SeventeenTrackError):
"""Define an error for an invalid tracking number."""
pass
class RequestError(SeventeenTrackError):
"""Define an error for HTTP request... | """Define module exceptions."""
class Seventeentrackerror(Exception):
"""Define a base error."""
pass
class Invalidtrackingnumbererror(SeventeenTrackError):
"""Define an error for an invalid tracking number."""
pass
class Requesterror(SeventeenTrackError):
"""Define an error for HTTP request erro... |
class Registers(object):
def __eq__(self, other) :
return self.__dict__ == other.__dict__
def __init__(self):
self.accumulator = 0
self.x_index = 0
self.y_index = 0
self.sp = 0xFD
self.pc = 0
self.carry_flag = False
self.zero_flag = ... | class Registers(object):
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __init__(self):
self.accumulator = 0
self.x_index = 0
self.y_index = 0
self.sp = 253
self.pc = 0
self.carry_flag = False
self.zero_flag = False
s... |
def take_input():
"""Helper function to take input for a user"""
name_marks = input().split()
name = name_marks[0]
marks = [float(x) for x in name_marks[1:]]
return name, marks
def rank_user(users_name_list, users_score_lst):
"""Returns a dictionary. Key is user_name and values is rank"""
user_score ... | def take_input():
"""Helper function to take input for a user"""
name_marks = input().split()
name = name_marks[0]
marks = [float(x) for x in name_marks[1:]]
return (name, marks)
def rank_user(users_name_list, users_score_lst):
"""Returns a dictionary. Key is user_name and values is rank"""
... |
class Solution:
def anagrams(self, strs):
key = lambda s: ''.join(sorted(s))
strs = sorted(strs, key=key)
strs = itertools.groupby(strs, key=key)
result = []
for k, g in strs:
l = list(g)
if len(l) == 1:
continue
... | class Solution:
def anagrams(self, strs):
key = lambda s: ''.join(sorted(s))
strs = sorted(strs, key=key)
strs = itertools.groupby(strs, key=key)
result = []
for (k, g) in strs:
l = list(g)
if len(l) == 1:
continue
result.e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.