content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
The `~certbot_dns_google.dns_google` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the Google Cloud DNS API.
Named Arguments
---------------
======================================== =========================... | """
The `~certbot_dns_google.dns_google` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the Google Cloud DNS API.
Named Arguments
---------------
======================================== =========================... |
"""Constants for the Subaru integration."""
DOMAIN = "subaru"
FETCH_INTERVAL = 300
UPDATE_INTERVAL = 7200
CONF_UPDATE_ENABLED = "update_enabled"
CONF_COUNTRY = "country"
# entry fields
ENTRY_CONTROLLER = "controller"
ENTRY_COORDINATOR = "coordinator"
ENTRY_VEHICLES = "vehicles"
# update coordinator name
COORDINATOR_... | """Constants for the Subaru integration."""
domain = 'subaru'
fetch_interval = 300
update_interval = 7200
conf_update_enabled = 'update_enabled'
conf_country = 'country'
entry_controller = 'controller'
entry_coordinator = 'coordinator'
entry_vehicles = 'vehicles'
coordinator_name = 'subaru_data'
vehicle_vin = 'vin'
veh... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
class TwoStackQueue:
def __init__(self):
self.forward_stack = []
self.reverse_stack = []
def dequeue(self):
if not self.reverse_stack:
while self.forward_stack:
self.reverse_stac... | class Twostackqueue:
def __init__(self):
self.forward_stack = []
self.reverse_stack = []
def dequeue(self):
if not self.reverse_stack:
while self.forward_stack:
self.reverse_stack.append(self.forward_stack.pop())
return self.reverse_stack.pop()
... |
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... | """ZODB connection registry
"""
class Connectionregistry:
"""ZODB connection registry
This registry can hold either ZODB.Connection objects or OFS.Application
objects. In the latter case, a close operation will close the REQUEST as
well as the Connection referenced by the Application's _p_jar attribut... |
N, K = map(int, input().split())
result = 0
while N != 0:
result += 1
N //= K
print(result)
| (n, k) = map(int, input().split())
result = 0
while N != 0:
result += 1
n //= K
print(result) |
EXPECTED_SECRETS = [
"EQ_SERVER_SIDE_STORAGE_USER_ID_SALT",
"EQ_SERVER_SIDE_STORAGE_USER_IK_SALT",
"EQ_SERVER_SIDE_STORAGE_ENCRYPTION_USER_PEPPER",
"EQ_SECRET_KEY",
"EQ_RABBITMQ_USERNAME",
"EQ_RABBITMQ_PASSWORD",
]
def validate_required_secrets(secrets):
for required_secret in EXPECTED_SEC... | expected_secrets = ['EQ_SERVER_SIDE_STORAGE_USER_ID_SALT', 'EQ_SERVER_SIDE_STORAGE_USER_IK_SALT', 'EQ_SERVER_SIDE_STORAGE_ENCRYPTION_USER_PEPPER', 'EQ_SECRET_KEY', 'EQ_RABBITMQ_USERNAME', 'EQ_RABBITMQ_PASSWORD']
def validate_required_secrets(secrets):
for required_secret in EXPECTED_SECRETS:
if required_se... |
"""Top-level package for NEMO CF."""
__author__ = """Willi Rath"""
__email__ = 'wrath@geomar.de'
__version__ = '0.1.0'
| """Top-level package for NEMO CF."""
__author__ = 'Willi Rath'
__email__ = 'wrath@geomar.de'
__version__ = '0.1.0' |
{
"targets": [{
"target_name": "fuse",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")",
"<!(node -e \"require('fuse-shared-library/include')\")",
],
"libraries": [
"<!(node -e \"require('fuse-shared-library/lib')\")",
],
"sources": [
"fuse-native.c"
],
... | {'targets': [{'target_name': 'fuse', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")', '<!(node -e "require(\'fuse-shared-library/include\')")'], 'libraries': ['<!(node -e "require(\'fuse-shared-library/lib\')")'], 'sources': ['fuse-native.c'], 'xcode_settings': {'OTHER_CFLAGS': ['-g', '-O3', '-Wall']}, 'cflag... |
def split_list(list, n):
target_list = []
cut = int(len(list) / n)
if cut == 0:
list = [[x] for x in list]
none_array = [[] for i in range(0, n - len(list))]
return list + none_array
for i in range(0, n - 1):
target_list.append(list[cut * i:cut * (1 + i)])
target_list... | def split_list(list, n):
target_list = []
cut = int(len(list) / n)
if cut == 0:
list = [[x] for x in list]
none_array = [[] for i in range(0, n - len(list))]
return list + none_array
for i in range(0, n - 1):
target_list.append(list[cut * i:cut * (1 + i)])
target_list... |
#
# This file contains the Python code from Program 15.18 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm15_18.txt
#
class RadixSorter... | class Radixsorter(Sorter):
r = 8
r = 1 << r
p = (32 + r - 1) / r
def __init__(self):
self._count = array(self.R)
self._tempArray = None |
extensions = dict(
required_params=[], # empty to override defaults in gen_defaults
validate_required_params="""
# Required args: either model_key or path
if (is.null(model_key) && is.null(path)) stop("argument 'model_key' or 'path' must be provided")
""",
set_required_params="",
)
doc = dict(
preamb... | extensions = dict(required_params=[], validate_required_params='\n# Required args: either model_key or path\nif (is.null(model_key) && is.null(path)) stop("argument \'model_key\' or \'path\' must be provided")\n', set_required_params='')
doc = dict(preamble='\nImports a generic model into H2O. Such model can be used th... |
somthing = 'F5fjDxitafeZwPdwsmBL-Q'
key_api = 'MiT75-jn5D_6MENzkehT5EReeVdYhp_86hQKYQp-3o10wIVXAbOakIT6khg8Y-_PBiy2fKPuAQFp9x7W80Ubn3xdiS8eCfy-nc7qtLNvs6oyAzdU2CsCRHEniyJUYHYx' | somthing = 'F5fjDxitafeZwPdwsmBL-Q'
key_api = 'MiT75-jn5D_6MENzkehT5EReeVdYhp_86hQKYQp-3o10wIVXAbOakIT6khg8Y-_PBiy2fKPuAQFp9x7W80Ubn3xdiS8eCfy-nc7qtLNvs6oyAzdU2CsCRHEniyJUYHYx' |
class ListView(Control,IComponent,IDisposable,IOleControl,IOleObject,IOleInPlaceObject,IOleInPlaceActiveObject,IOleWindow,IViewObject,IViewObject2,IPersist,IPersistStreamInit,IPersistPropertyBag,IPersistStorage,IQuickActivate,ISupportOleDropSource,IDropTarget,ISynchronizeInvoke,IWin32Window,IArrangedElement,IBindableCo... | class Listview(Control, IComponent, IDisposable, IOleControl, IOleObject, IOleInPlaceObject, IOleInPlaceActiveObject, IOleWindow, IViewObject, IViewObject2, IPersist, IPersistStreamInit, IPersistPropertyBag, IPersistStorage, IQuickActivate, ISupportOleDropSource, IDropTarget, ISynchronizeInvoke, IWin32Window, IArranged... |
# -*- coding: utf-8 -*-
## courses table
Course = db.define_table("courses",
Field("title", label=T('Title')),
Field("short_description", "text", label=T('Short Description')),
Field("description", "text", widget=ckeditor.widget, label=T('Description')),
Fiel... | course = db.define_table('courses', field('title', label=t('Title')), field('short_description', 'text', label=t('Short Description')), field('description', 'text', widget=ckeditor.widget, label=t('Description')), field('price', 'float', default=0, label=t('Price')), field('discount', 'float', default=0, label=t('Disco... |
def get_encoder_decoder_hp(model='gin', decoder=None):
if model == 'gin':
model_hp = {
"num_layers": 5,
"hidden": [64,64,64,64],
"dropout": 0.5,
"act": "relu",
"eps": "False",
"mlp_layers": 2,
"neighbor_pooling_type": "sum"... | def get_encoder_decoder_hp(model='gin', decoder=None):
if model == 'gin':
model_hp = {'num_layers': 5, 'hidden': [64, 64, 64, 64], 'dropout': 0.5, 'act': 'relu', 'eps': 'False', 'mlp_layers': 2, 'neighbor_pooling_type': 'sum'}
elif model == 'gat':
model_hp = {'num_layers': 2, 'hidden': [8], 'hea... |
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
count_r={}
for c in ransomNote:
if c not in count_r:
count_r[c]=1
else:
count_r[c]+=1
print(count_r)
for cr in magazine:
if cr n... | class Solution:
def can_construct(self, ransomNote: str, magazine: str) -> bool:
count_r = {}
for c in ransomNote:
if c not in count_r:
count_r[c] = 1
else:
count_r[c] += 1
print(count_r)
for cr in magazine:
if cr n... |
BOTTLE_CONTENT_MANAGER_API_PORT = 8081
BOTTLE_DEORATOR_PORTFOLIOS_API_PORT = 8082
BOTTLE_DEORATOR_TAGS_API_PORT = 8083
BOTTLE_DEORATOR_VOTES_API_PORT = 8084
USE_SOLR_AS_PERSISTENCE = True
SOLR_URL = 'http://localhost:8983/solr'
DECORATION_SOLR_FIELD_0 = 'portfolios'
DECORATION_SOLR_FIELD_1 = 'tags'
| bottle_content_manager_api_port = 8081
bottle_deorator_portfolios_api_port = 8082
bottle_deorator_tags_api_port = 8083
bottle_deorator_votes_api_port = 8084
use_solr_as_persistence = True
solr_url = 'http://localhost:8983/solr'
decoration_solr_field_0 = 'portfolios'
decoration_solr_field_1 = 'tags' |
# keep a list of the N best things we have seen, discard anything else
class nbest(object):
def __init__(self,N=1000):
self.store = []
self.N = N
def add(self,item):
self.store.append(item)
self.store.sort(reverse=True)
self.store = self.store[:self.N]
d... | class Nbest(object):
def __init__(self, N=1000):
self.store = []
self.N = N
def add(self, item):
self.store.append(item)
self.store.sort(reverse=True)
self.store = self.store[:self.N]
def __getitem__(self, k):
return self.store[k]
def __len__(self):
... |
#f = open("datum/iris.csv")
#print (f.read())
#f.close()
#closing file is good practice
#Using ff code will make closing file unnecessary
with open("datum/iris.csv") as f:
contents = (f.read())
print(contents) | with open('datum/iris.csv') as f:
contents = f.read()
print(contents) |
def main(j, args, params, tags, tasklet):
page = args.page
logpath = args.requestContext.params.get('logpath')
templatepath = args.requestContext.params.get('templatepath')
installedpath = args.requestContext.params.get('installedpath')
metapath = args.requestContext.params.get('metapath')
dom... | def main(j, args, params, tags, tasklet):
page = args.page
logpath = args.requestContext.params.get('logpath')
templatepath = args.requestContext.params.get('templatepath')
installedpath = args.requestContext.params.get('installedpath')
metapath = args.requestContext.params.get('metapath')
domai... |
# ==================================================================================== #
# base_response.py - This file is part of the YFrake package. #
# ------------------------------------------------------------------------------------ #
# ... | class Baseresponse:
"""
Base class of the ClientResponse.
"""
_err_msg = 'Operation not available on response object attributes! (YFrake)'
def __init__(self):
self._endpoint: str | None = None
self._error: dict | None = None
self._data: dict | None = None
@classmethod
... |
def cargarListas(nombrearchivo,lista):
try:
archivo = open(nombrearchivo, "rt")
while True:
linea = archivo.readline()
if not linea:
break
linea = linea[:-1]
listaNombre, Articulos = linea.split("=")
if Articulos.stri... | def cargar_listas(nombrearchivo, lista):
try:
archivo = open(nombrearchivo, 'rt')
while True:
linea = archivo.readline()
if not linea:
break
linea = linea[:-1]
(lista_nombre, articulos) = linea.split('=')
if Articulos.strip(... |
# Time: O(n^2 * k)
# Space: O(k)
class Solution(object):
def maxVacationDays(self, flights, days):
"""
:type flights: List[List[int]]
:type days: List[List[int]]
:rtype: int
"""
if not days or not flights:
return 0
dp = [[0] * len(days) for _ in ... | class Solution(object):
def max_vacation_days(self, flights, days):
"""
:type flights: List[List[int]]
:type days: List[List[int]]
:rtype: int
"""
if not days or not flights:
return 0
dp = [[0] * len(days) for _ in xrange(2)]
for week in r... |
first_number = int(input())
prime_count = 0
while True:
if 1>= first_number:
break
running_number = first_number
divider = first_number // 2 if ( 0 == first_number % 2 ) else ( first_number // 2 ) + 1;
count = 0
while divider != 1:
if 0 == running_number % divider:
c... | first_number = int(input())
prime_count = 0
while True:
if 1 >= first_number:
break
running_number = first_number
divider = first_number // 2 if 0 == first_number % 2 else first_number // 2 + 1
count = 0
while divider != 1:
if 0 == running_number % divider:
count += 1
... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | allowed_param_merge_strategies = (overwrite, merge, deep_merge) = ('overwrite', 'merge', 'deep_merge')
def get_param_merge_strategy(merge_strategies, param_key):
if merge_strategies is None:
return OVERWRITE
env_default = merge_strategies.get('default', OVERWRITE)
merge_strategy = merge_strategies.... |
# for item in ["mash","john","sera"]:
# print(item)
# for item in range(5,10,2):
# print(item)
# for x in range(4):
# for y in range(3):
# print(f"({x}, {y})")
numbers = [5, 2 , 5 ,2 ,2]
for item in numbers:
output = ""
for count in range(item):
output += "X"
print(output) | numbers = [5, 2, 5, 2, 2]
for item in numbers:
output = ''
for count in range(item):
output += 'X'
print(output) |
# Problem: https://www.hackerrank.com/challenges/30-data-types/problem
# Score: 30.0
i = 4
d = 4.0
s = 'HackerRank '
x = int(input())
y = float(input())
z = input()
print(i+x, d+y, s+z, sep='\n')
| i = 4
d = 4.0
s = 'HackerRank '
x = int(input())
y = float(input())
z = input()
print(i + x, d + y, s + z, sep='\n') |
class ConsumerRegister:
all_consumers = {}
def __init__(self, name):
self.name = name
self.consumer_class = None
def consumer(self):
def decorator(plugin_cls):
self.consumer_class = plugin_cls
self.all_consumers[self.name] = {
'consumer_cls':... | class Consumerregister:
all_consumers = {}
def __init__(self, name):
self.name = name
self.consumer_class = None
def consumer(self):
def decorator(plugin_cls):
self.consumer_class = plugin_cls
self.all_consumers[self.name] = {'consumer_cls': self.consumer_c... |
class ConfigBase:
def __init__(self,**kwargs):
for k,v in kwargs.items():
setattr(self,k,v)
@classmethod
def get_class_config_info_dict(cls):
if issubclass(cls.__base__, ConfigBase):
dic=cls.__base__.get_class_config_info_dict()
else:
dic = {}
... | class Configbase:
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
@classmethod
def get_class_config_info_dict(cls):
if issubclass(cls.__base__, ConfigBase):
dic = cls.__base__.get_class_config_info_dict()
else:
dic... |
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+= 1
els... | def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
l = arr[:mid]
r = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
... |
"""
Concrete data service.
This Django app manages API endpoints related to managing "concrete data", or
data that serves as the foundational sources of truth for users. This is opposed
to "derived data", which is data computed via mathematical, logical /
relational, or other types of transformations. For example, a m... | """
Concrete data service.
This Django app manages API endpoints related to managing "concrete data", or
data that serves as the foundational sources of truth for users. This is opposed
to "derived data", which is data computed via mathematical, logical /
relational, or other types of transformations. For example, a m... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 11 10:18:56 2020
@author: Ashish
"""
def add_num(num1, num2):
print("In module A")
return num1+num2 | """
Created on Sun Oct 11 10:18:56 2020
@author: Ashish
"""
def add_num(num1, num2):
print('In module A')
return num1 + num2 |
#python 3.5.2
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[l... | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
... |
class TextManipulation:
def formatText(text):
newText = text.replace("&", "\n")
return newText | class Textmanipulation:
def format_text(text):
new_text = text.replace('&', '\n')
return newText |
def define_orthonormal_basis(u):
"""
Calculates an orthonormal basis given an arbitrary vector u.
Args:
u (numpy array of floats) : arbitrary 2-dimensional vector used for new
basis
Returns:
(numpy array of floats) : new orthonormal basis
... | def define_orthonormal_basis(u):
"""
Calculates an orthonormal basis given an arbitrary vector u.
Args:
u (numpy array of floats) : arbitrary 2-dimensional vector used for new
basis
Returns:
(numpy array of floats) : new orthonormal basis
... |
# Map query config
QUERY_RADIUS = 3000 # mts. Radius to use on OSM data queries.
MIN_DISTANCE_FOR_NEW_QUERY = 1000 # mts. Minimum distance to query area edge before issuing a new query.
FULL_STOP_MAX_SPEED = 1.39 # m/s Max speed for considering car is stopped.
| query_radius = 3000
min_distance_for_new_query = 1000
full_stop_max_speed = 1.39 |
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module containing base test results classes."""
# The test passed.
PASS = 'SUCCESS'
# The test was intentionally skipped.
SKIP = 'SKIPPED'
# The test fa... | """Module containing base test results classes."""
pass = 'SUCCESS'
skip = 'SKIPPED'
fail = 'FAILURE'
crash = 'CRASH'
timeout = 'TIMEOUT'
unknown = 'UNKNOWN'
notrun = 'NOTRUN' |
# THIS FILE IS GENERATED FROM PYWAVELETS SETUP.PY
short_version = '0.3.0'
version = '0.3.0'
full_version = '0.3.0.dev-7ea3e91'
git_revision = '7ea3e919b1d7bbf4d7685c47d3d10c16c599cd06'
release = False
if not release:
version = full_version
| short_version = '0.3.0'
version = '0.3.0'
full_version = '0.3.0.dev-7ea3e91'
git_revision = '7ea3e919b1d7bbf4d7685c47d3d10c16c599cd06'
release = False
if not release:
version = full_version |
#/usr/bin/env python3
"""
Solution to problem: https://practice.geeksforgeeks.org/problems/adding-ones/0
We reduced the runtime of algorithm from O(nm) to O(n+m) resulting in
half the time running
"""
def get_array(array, n):
"""
gets the array
Gets input and returns final computed value
Parameters:... | """
Solution to problem: https://practice.geeksforgeeks.org/problems/adding-ones/0
We reduced the runtime of algorithm from O(nm) to O(n+m) resulting in
half the time running
"""
def get_array(array, n):
"""
gets the array
Gets input and returns final computed value
Parameters:
array: list
... |
'''
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.
For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.
Calling this returned function with a single argument will the... | """
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.
For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.
Calling this returned function with a single argument will then ... |
class ConfigHandlerException(Exception):
"""Main Config Handler Exception class"""
class ConfigHandlerFileReadException(ConfigHandlerException):
"""Config Handler ConfigFile Read Exception class"""
class ConfigHandlerNamingException(ConfigHandlerException):
"""Config Handler Naming Exception class"""
| class Confighandlerexception(Exception):
"""Main Config Handler Exception class"""
class Confighandlerfilereadexception(ConfigHandlerException):
"""Config Handler ConfigFile Read Exception class"""
class Confighandlernamingexception(ConfigHandlerException):
"""Config Handler Naming Exception class""" |
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(reduce(lambda a, b: a ^ ord(b), s + t, 0)) | class Solution(object):
def find_the_difference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(reduce(lambda a, b: a ^ ord(b), s + t, 0)) |
exp_name = 'prenet_c32s6d5_lstm'
work_dir = f'./work_dirs/{exp_name}'
# model settings
model = dict(
type='MultiStageRestorer',
generator=dict(
type='PReNet',
in_channels=3,
out_channels=3,
mid_channels=32,
recurrent_unit='LSTM',
num_stages=6,
num_resbloc... | exp_name = 'prenet_c32s6d5_lstm'
work_dir = f'./work_dirs/{exp_name}'
model = dict(type='MultiStageRestorer', generator=dict(type='PReNet', in_channels=3, out_channels=3, mid_channels=32, recurrent_unit='LSTM', num_stages=6, num_resblocks=5, recursive_resblock=False), losses=[dict(type='SSIMLoss', loss_weight=1.0, redu... |
class SchedulableField(object, IDisposable):
"""
A non-calculated field eligible to be included in a schedule.
SchedulableField(fieldType: ScheduleFieldType,parameterId: ElementId)
SchedulableField(fieldType: ScheduleFieldType)
SchedulableField()
"""
def Dispose(self):
""" Disp... | class Schedulablefield(object, IDisposable):
"""
A non-calculated field eligible to be included in a schedule.
SchedulableField(fieldType: ScheduleFieldType,parameterId: ElementId)
SchedulableField(fieldType: ScheduleFieldType)
SchedulableField()
"""
def dispose(self):
""" Dispose(self: Sche... |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Restaurant20to50, obj[4]: Distance
# {"feature": "Coupon", "instances": 127, "metric_value": 0.9671, "depth": 1}
if obj[0]>0:
# {"feature": "Occupation", "instances": 111, "metric_value": 0.9353, "depth": 2}
if obj[2]<=7.990990... | def find_decision(obj):
if obj[0] > 0:
if obj[2] <= 7.990990990990991:
if obj[3] <= 2.0:
if obj[4] > 1:
if obj[1] <= 2:
return 'True'
elif obj[1] > 2:
return 'True'
else:
... |
class AgentException(Exception):
""" Base exception"""
description = 'Unknown error'
statuscode = 5
def __str__(self):
return '{0}: {1}'.format(self.description, ' '.join(self.args))
class InactiveAgent(AgentException):
description = "Agent is not activated"
| class Agentexception(Exception):
""" Base exception"""
description = 'Unknown error'
statuscode = 5
def __str__(self):
return '{0}: {1}'.format(self.description, ' '.join(self.args))
class Inactiveagent(AgentException):
description = 'Agent is not activated' |
a = 1
a = a + 2
print(a)
a += 2
print(a)
word = "race"
word += " car"
print(word)
| a = 1
a = a + 2
print(a)
a += 2
print(a)
word = 'race'
word += ' car'
print(word) |
# compare_versions.py
# software library for question B
def compare_versions(string1, string2):
seperator = "."
# first load the strings and then seperate the individual numbers into a list by
# using the split function
string1 = string1.split(seperator)
string2 = string2.split(seperator)
# l... | def compare_versions(string1, string2):
seperator = '.'
string1 = string1.split(seperator)
string2 = string2.split(seperator)
for level in range(0, len(string1)):
if string1[level] == string2[level]:
continue
return print('Version %s is equal to version %s. ' % (seperator... |
-8
# ----------------------------------------------------------------------------
# <copyright company="Aspose" file="HttpRequest.py">
# Copyright (c) 2018-2019 Aspose Pty Ltd. All rights reserved.
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a
# copy o... | -8
class Httprequest(object):
def __init__(self, resource_path, path_params, query_params, header_params, form_params, body_params, files, collection_formats, auth_settings, return_http_data_only=None, preload_content=None, request_timeout=None):
"""Makes the HTTP request (synchronous) and returns deseria... |
class BaseSubmission:
def __init__(self, team_name, player_names):
self.team_name = team_name
self.player_names = player_names
def get_actions(self, obs):
'''
Overview:
You must implement this function.
'''
raise NotImplementedError
| class Basesubmission:
def __init__(self, team_name, player_names):
self.team_name = team_name
self.player_names = player_names
def get_actions(self, obs):
"""
Overview:
You must implement this function.
"""
raise NotImplementedError |
class R1DataCheckSpecificDto:
def __init__(self, id_r1_data_check_specific=None, init_event=None, end_event=None, init_pixel=None, end_pixel=None,
init_sample=None, end_sample=None,
init_subrun=None, end_subrun=None, type_of_gap_calc=None, list_of_module_in_detail=None):
s... | class R1Datacheckspecificdto:
def __init__(self, id_r1_data_check_specific=None, init_event=None, end_event=None, init_pixel=None, end_pixel=None, init_sample=None, end_sample=None, init_subrun=None, end_subrun=None, type_of_gap_calc=None, list_of_module_in_detail=None):
self.__id_r1_data_check_specific = ... |
def takethis():
fullspeed()
i01.moveHead(14,90)
i01.moveArm("left",13,45,95,10)
i01.moveArm("right",5,90,30,10)
i01.moveHand("left",2,2,2,2,2,60)
i01.moveHand("right",81,66,82,60,105,113)
i01.moveTorso(85,76,90)
sleep(3)
closelefthand()
i01.moveTorso(110,90,90)
sleep(2)
isitaball()
i01.mouth.s... | def takethis():
fullspeed()
i01.moveHead(14, 90)
i01.moveArm('left', 13, 45, 95, 10)
i01.moveArm('right', 5, 90, 30, 10)
i01.moveHand('left', 2, 2, 2, 2, 2, 60)
i01.moveHand('right', 81, 66, 82, 60, 105, 113)
i01.moveTorso(85, 76, 90)
sleep(3)
closelefthand()
i01.moveTorso(110, 9... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-05-18 23:29:05
# @Author : Ivy Mong (davy0328meng@gmail.com)
arr1 = [1, 3, 4, 6, 10]
arr2 = [2, 5, 8, 11]
ind = 0
ans = arr1.copy()
for i in range(len(arr2)):
while ind < len(arr1):
if arr2[i] <= arr1[ind]:
ans.insert(ind+i, ar... | arr1 = [1, 3, 4, 6, 10]
arr2 = [2, 5, 8, 11]
ind = 0
ans = arr1.copy()
for i in range(len(arr2)):
while ind < len(arr1):
if arr2[i] <= arr1[ind]:
ans.insert(ind + i, arr2[i])
break
else:
ind += 1
else:
ans = ans + arr2[i:]
print(ans) |
print('Dratuti!')
print('Hello!')
print('Hello, Georgios!')
print('Hello, Pupa!')
| print('Dratuti!')
print('Hello!')
print('Hello, Georgios!')
print('Hello, Pupa!') |
# Copyright (C) 2018 Google 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 agreed to in writ... | _base = 'https://chromium.googlesource.com/breakpad/breakpad'
def _breakpad_impl(repository_ctx):
repository_ctx.download_and_extract(url=_BASE + '/+archive/' + repository_ctx.attr.commit + '.tar.gz', output='.')
repository_ctx.symlink(label('@gapid//tools/build/third_party/breakpad:breakpad.BUILD'), 'BUILD')
... |
DEBUG = True
SECRET_KEY = "iECgbYWReMNxkRprrzMo5KAQYnb2UeZ3bwvReTSt+VSESW0OB8zbglT+6rEcDW9X"
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:999999@127.0.0.1:3306/fisher"
| debug = True
secret_key = 'iECgbYWReMNxkRprrzMo5KAQYnb2UeZ3bwvReTSt+VSESW0OB8zbglT+6rEcDW9X'
sqlalchemy_database_uri = 'mysql+pymysql://root:999999@127.0.0.1:3306/fisher' |
class RebarContainerItem(object,IDisposable):
""" Provides implementation for Rebar stored in RebarContainer. """
def CanApplyPresentationMode(self,dBView):
"""
CanApplyPresentationMode(self: RebarContainerItem,dBView: View) -> bool
Checks if a presentation mode can be applied for this rebar in the ... | class Rebarcontaineritem(object, IDisposable):
""" Provides implementation for Rebar stored in RebarContainer. """
def can_apply_presentation_mode(self, dBView):
"""
CanApplyPresentationMode(self: RebarContainerItem,dBView: View) -> bool
Checks if a presentation mode can be applied for this r... |
def test_shib_redirect(client, app):
r = client.get("/login/shib")
assert r.status_code == 302
def test_shib_login(app, client):
r = client.get(
"/login/shib/login", headers={app.config["SHIBBOLETH_HEADER"]: "test"}
)
assert r.status_code == 200
def test_shib_login_redirect(app, client):... | def test_shib_redirect(client, app):
r = client.get('/login/shib')
assert r.status_code == 302
def test_shib_login(app, client):
r = client.get('/login/shib/login', headers={app.config['SHIBBOLETH_HEADER']: 'test'})
assert r.status_code == 200
def test_shib_login_redirect(app, client):
r = client.... |
siblings = int(input())
popsicles = int(input())
#your code goes here
if((popsicles % siblings)==0):
print("give away")
else:
print("eat them yourself")
| siblings = int(input())
popsicles = int(input())
if popsicles % siblings == 0:
print('give away')
else:
print('eat them yourself') |
# encoding: utf-8
# module System.Text calls itself Text
# from mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class Encoding(object,ICloneable... | class Encoding(object, ICloneable):
""" Represents a character encoding. """
def clone(self):
"""
Clone(self: Encoding) -> object
When overridden in a derived class,creates a shallow copy of the current
System.Text.Encoding object.
Returns: A copy of the current System.Text.Enco... |
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
minHeap = [] # store end times of each room
for start, end in sorted(intervals):
if minHeap and start >= minHeap[0]:
heapq.heappop(minHeap)
heapq.heappush(minHeap, end)
return len(minHeap)
| class Solution:
def min_meeting_rooms(self, intervals: List[List[int]]) -> int:
min_heap = []
for (start, end) in sorted(intervals):
if minHeap and start >= minHeap[0]:
heapq.heappop(minHeap)
heapq.heappush(minHeap, end)
return len(minHeap) |
class custom_range:
def __init__(self, start, end, step=1):
self.start = start
self.end = end
self.step = step
self.increment = 1
if self.step < 0:
self.start, self.end = self.end, self.start
self.increment = -1
def __iter__(self):
return... | class Custom_Range:
def __init__(self, start, end, step=1):
self.start = start
self.end = end
self.step = step
self.increment = 1
if self.step < 0:
(self.start, self.end) = (self.end, self.start)
self.increment = -1
def __iter__(self):
re... |
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
return (((num == 0) and "0" )
or ( baseN(num // b, b).lstrip("0")
+ digits[num % b]))
# alternatively:
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += d... | digits = '0123456789abcdefghijklmnopqrstuvwxyz'
def base_n(num, b):
return num == 0 and '0' or base_n(num // b, b).lstrip('0') + digits[num % b]
def base_n(num, b):
if num == 0:
return '0'
result = ''
while num != 0:
(num, d) = divmod(num, b)
result += digits[d]
return resu... |
class Event:
""" The base for all Lavalink events. """
pass
class QueueEndEvent(Event):
""" This event is dispatched when there are no more songs in the queue. """
def __init__(self, player):
self.player = player
class TrackStuckEvent(Event):
""" This event is dispatched when the current... | class Event:
""" The base for all Lavalink events. """
pass
class Queueendevent(Event):
""" This event is dispatched when there are no more songs in the queue. """
def __init__(self, player):
self.player = player
class Trackstuckevent(Event):
""" This event is dispatched when the currentl... |
class Counter:
"This is a counter class"
def __init__(self):
self.value = 0
def increment(self):
"Increments the counter"
self.value = self.value + 1
def decrement(self):
"Decrements the counter"
self.value = self.value - 1 | class Counter:
"""This is a counter class"""
def __init__(self):
self.value = 0
def increment(self):
"""Increments the counter"""
self.value = self.value + 1
def decrement(self):
"""Decrements the counter"""
self.value = self.value - 1 |
# Find Fractional Number
# https://www.acmicpc.net/problem/1193
n = int(input())
i = 1
while True:
sums = int((1 + i) * i * 0.5)
if sums >= n:
if (i%2) == 0:
x = i - (sums - n)
y = (sums - n) + 1
else:
x = (sums - n) + 1
y = i - (sums - n)
... | n = int(input())
i = 1
while True:
sums = int((1 + i) * i * 0.5)
if sums >= n:
if i % 2 == 0:
x = i - (sums - n)
y = sums - n + 1
else:
x = sums - n + 1
y = i - (sums - n)
print(str(x) + '/' + str(y))
break
i = i + 1 |
def for_l():
for row in range(6):
for col in range(4):
if col==1 and row<5or (row==5 and (col==0 or col==2 or col==3)) :
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_l():
row=0
while row<6:
col=0
... | def for_l():
for row in range(6):
for col in range(4):
if col == 1 and row < 5 or (row == 5 and (col == 0 or col == 2 or col == 3)):
print('*', end=' ')
else:
print(' ', end=' ')
print()
def while_l():
row = 0
while row < 6:
co... |
#
# 120. Triangle
#
# Q: https://leetcode.com/problems/triangle/
# A: https://leetcode.com/problems/triangle/discuss/38726/Kt-Js-Py3-Cpp-The-ART-of-Dynamic-Programming
#
# TopDown
class Solution:
def minimumTotal(self, A: List[List[int]]) -> int:
N = len(A)
def go(i = 0, j = 0):
if i ==... | class Solution:
def minimum_total(self, A: List[List[int]]) -> int:
n = len(A)
def go(i=0, j=0):
if i == N:
return 0
return A[i][j] + min(go(i + 1, j), go(i + 1, j + 1))
return go()
class Solution:
def minimum_total(self, A: List[List[int]]) ->... |
def remove_duplicates_v2(arr):
dedupe_arr = []
for i in arr:
if i not in dedupe_arr:
dedupe_arr.append(i)
return dedupe_arr
result = remove_duplicates([0,0,0,1,1,2,2,3,4,5])
print(result)
| def remove_duplicates_v2(arr):
dedupe_arr = []
for i in arr:
if i not in dedupe_arr:
dedupe_arr.append(i)
return dedupe_arr
result = remove_duplicates([0, 0, 0, 1, 1, 2, 2, 3, 4, 5])
print(result) |
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions:
print(dimension)
| dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions:
print(dimension) |
class Config():
def __init__(self):
pass
def to_dict(self):
res_dict = dict()
for key, value in self.__dict__.items():
if isinstance(value, Config):
res_dict.update(value.to_dict())
else:
res_dict[key] = value
return res_di... | class Config:
def __init__(self):
pass
def to_dict(self):
res_dict = dict()
for (key, value) in self.__dict__.items():
if isinstance(value, Config):
res_dict.update(value.to_dict())
else:
res_dict[key] = value
return res_d... |
def lazy(func):
fnattr = "__lazy_" + func.__name__
@property
def wrapper(*args, **kwargs):
if not hasattr(func, fnattr):
setattr(func, fnattr, func(*args, **kwargs))
return getattr(func, fnattr)
return wrapper
| def lazy(func):
fnattr = '__lazy_' + func.__name__
@property
def wrapper(*args, **kwargs):
if not hasattr(func, fnattr):
setattr(func, fnattr, func(*args, **kwargs))
return getattr(func, fnattr)
return wrapper |
#def recursion():
#return recursion()
#def factorial(n):
# rslt = n
# for i in range(1, n):
# rslt *= i
# return rslt
"""
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(3))"""
"""
def pow(x, n):
rslt = 1
for i in range(n):
rslt *= x
return rslt
print(pow(3, 2))"""
... | """
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(3))"""
'\ndef pow(x, n):\n\trslt = 1\n\tfor i in range(n):\n\t\trslt *= x\n\treturn rslt\nprint(pow(3, 2))'
def pow(x, n):
if n == 0:
return 1
else:
return x * pow(x, n - 1)
print(pow(20, 9))
'num = ... |
class Profiles(object):
"""
A class to manage V2 API's for AirWatch Profiles Management
"""
def __init__(self, client):
self.client = client
def search(self, **kwargs):
"""
Returns the Profile information matching the search parameters.
/api/mdm/profiles/search?{pa... | class Profiles(object):
"""
A class to manage V2 API's for AirWatch Profiles Management
"""
def __init__(self, client):
self.client = client
def search(self, **kwargs):
"""
Returns the Profile information matching the search parameters.
/api/mdm/profiles/search?{pa... |
"""
Given an integer number n, define a function named printDict() which can print a dictionary where the keys are numbers between 1 and n (both included) and the values are square of keys.
The function printDict() doesn't take any argument.
Input Format:
The first line contains the number n.
Output Format:
Print t... | """
Given an integer number n, define a function named printDict() which can print a dictionary where the keys are numbers between 1 and n (both included) and the values are square of keys.
The function printDict() doesn't take any argument.
Input Format:
The first line contains the number n.
Output Format:
Print t... |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
xor = 0
for num in nums:
xor ^= num
xor = xor & -xor
a, b = 0, 0
for num in nums:
if num & xor:
... | class Solution(object):
def single_number(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
xor = 0
for num in nums:
xor ^= num
xor = xor & -xor
(a, b) = (0, 0)
for num in nums:
if num & xor:
... |
#
# PySNMP MIB module CXFrameRelay-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXFrameRelay-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:17:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, constraints_union, single_value_constraint) ... |
# Note that this file is multi-lingual and can be used in both Python
# and POSIX shell.
# This file should define a variable VERSION which we use as the
# debugger version number.
VERSION = '2.9.0'
| version = '2.9.0' |
"""
This module calculate Jaccard's distance score
parameters:
x : (numpy array) first string sequence
y : (numpy array) second string sequence
return:
(float) : Jaccard's distance socre (1 - Jaccard's similarlity)
"""
def jaccard_seq(x, y):
len_x = len(x)
len_y = len(y)
fst, snd = (x, y) if len_x < len_... | """
This module calculate Jaccard's distance score
parameters:
x : (numpy array) first string sequence
y : (numpy array) second string sequence
return:
(float) : Jaccard's distance socre (1 - Jaccard's similarlity)
"""
def jaccard_seq(x, y):
len_x = len(x)
len_y = len(y)
(fst, snd) = (x, y) if len_x < le... |
def reverse(input):
#reverse as string
return input[::-1]
#An alternative approach I wass using - string to list
'''myinput = input
mylist = list(myinput)
#print (mylist)
mylist.reverse()
return (mylist)'''
'''while True:
if input == None:
print (None)
... | def reverse(input):
return input[::-1]
'myinput = input\n mylist = list(myinput)\n #print (mylist)\n mylist.reverse()\n return (mylist)'
"while True:\n if input == None:\n print (None)\n break\n else:\n #find length of list\n l=len(mylist)-1\n #while ... |
# Similar to longest substring with k different characters, with k = 2
class Solution:
def totalFruit(self, tree: List[int]) -> int:
if not tree or len(tree) == 0:
return 0
left = 0
ans = 0
baskets = {}
# Use the dictionary to store the last index all fruits/lette... | class Solution:
def total_fruit(self, tree: List[int]) -> int:
if not tree or len(tree) == 0:
return 0
left = 0
ans = 0
baskets = {}
for (t, fruit) in enumerate(tree):
baskets[fruit] = t
if len(baskets) > 2:
left = min(bask... |
'''
Return Permutations of a String
Given a string, find and return all the possible permutations of the input string.
Note : The order of permutations are not important.
Sample Input :
abc
Sample Output :
abc
acb
bac
bca
cab
cba
'''
def permutations(string):
#Implement Your Code Here
if len(string) == 1:
... | """
Return Permutations of a String
Given a string, find and return all the possible permutations of the input string.
Note : The order of permutations are not important.
Sample Input :
abc
Sample Output :
abc
acb
bac
bca
cab
cba
"""
def permutations(string):
if len(string) == 1:
return [string]
te... |
def get_hours_since_midnight(seconds):
'''
Type the code to calculate total hours given n(number) of seconds
For example, given 3800 seconds the total hours is 1
'''
return (seconds//3600)
'''
IF YOU ARE OK WITH A GRADE OF 70 FOR THIS ASSIGNMENT STOP HERE.
'''
def get_minutes(seconds):
'''
... | def get_hours_since_midnight(seconds):
"""
Type the code to calculate total hours given n(number) of seconds
For example, given 3800 seconds the total hours is 1
"""
return seconds // 3600
'\nIF YOU ARE OK WITH A GRADE OF 70 FOR THIS ASSIGNMENT STOP HERE.\n'
def get_minutes(seconds):
"""
Ty... |
class BingoBoard:
def __init__(self) -> None:
self.board = []
self.markedNums = 0
def __repr__(self) -> str:
ret = ''
for line in self.board:
for num in line:
ret += num + ' '
ret += '\n'
return ret
def check_value(self, val:... | class Bingoboard:
def __init__(self) -> None:
self.board = []
self.markedNums = 0
def __repr__(self) -> str:
ret = ''
for line in self.board:
for num in line:
ret += num + ' '
ret += '\n'
return ret
def check_value(self, val:... |
#! /usr/bin/env python3
# coding: utf-8
def main():
with open('sample1.txt','r') as f:
content = f.read()
content = content.upper()
with open('sample2.txt','w') as f:
f.write(content)
if __name__ =='__main__':
main()
| def main():
with open('sample1.txt', 'r') as f:
content = f.read()
content = content.upper()
with open('sample2.txt', 'w') as f:
f.write(content)
if __name__ == '__main__':
main() |
f_chr6 = open("/hwfssz1/ST_BIOCHEM/P18Z10200N0032/liyiyan/SV_Caller/HG002/chr6_reads.fastq")
liness = f_chr6.readlines()
reads_list = []
for i in range(1,len(liness),4):
reads_list.append(liness[i])
res = min(reads_list, key=len,default='')
print(len(res)-1)
| f_chr6 = open('/hwfssz1/ST_BIOCHEM/P18Z10200N0032/liyiyan/SV_Caller/HG002/chr6_reads.fastq')
liness = f_chr6.readlines()
reads_list = []
for i in range(1, len(liness), 4):
reads_list.append(liness[i])
res = min(reads_list, key=len, default='')
print(len(res) - 1) |
qtd = 0
soma = 0
for i in range(1, 101, 1):
if i % 2 == 0:
qtd += 1
soma += i
media = soma / qtd
print('A media dos pares de 1 ate 100 e de {} '.format(media))
| qtd = 0
soma = 0
for i in range(1, 101, 1):
if i % 2 == 0:
qtd += 1
soma += i
media = soma / qtd
print('A media dos pares de 1 ate 100 e de {} '.format(media)) |
names = ["Adam", "Alex", "Mariah", "Martine", "Columbus"]
for word in names:
print(word)
| names = ['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
for word in names:
print(word) |
#
# PySNMP MIB module HPNSAECC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPNSAECC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:42:09 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,... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_size_constraint, value_range_constraint) ... |
"""
return the taker/maker commission rate
"""
class CommissionRate:
def __init__(self):
self.symbol = ""
self.makerCommissionRate = 0.0
self.takerCommissionRate = 0.0
@staticmethod
def json_parse(json_data):
result = CommissionRate()
result.symbol = json_data.get_s... | """
return the taker/maker commission rate
"""
class Commissionrate:
def __init__(self):
self.symbol = ''
self.makerCommissionRate = 0.0
self.takerCommissionRate = 0.0
@staticmethod
def json_parse(json_data):
result = commission_rate()
result.symbol = json_data.get... |
# status: testado com exemplos da prova
if __name__ == '__main__':
n = int(input())
cubes = [int(x) for x in input().split()]
ways = 0
for x in range(0, n):
x_sum = cubes[x]
for y in range(x, n):
if x == y:
if cubes[y] % 8 == 0:
ways += ... | if __name__ == '__main__':
n = int(input())
cubes = [int(x) for x in input().split()]
ways = 0
for x in range(0, n):
x_sum = cubes[x]
for y in range(x, n):
if x == y:
if cubes[y] % 8 == 0:
ways += 1
else:
x_sum +... |
""" Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted in ascending from left to right. Integers in
each column are sorted in ascending from top to bottom.
"""
class Solution240:
pass
| """ Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted in ascending from left to right. Integers in
each column are sorted in ascending from top to bottom.
"""
class Solution240:
pass |
def albumFromID(id:int):
return f'https://www.jiosaavn.com/api.php?__call=content.getAlbumDetails&_format=json&cc=in&_marker=0%3F_marker=0&albumid={id}'
def albumsearchFromSTRING(query:str):
return f'https://www.jiosaavn.com/api.php?__call=autocomplete.get&_format=json&_marker=0&cc=in&includeMetaTags=1&query... | def album_from_id(id: int):
return f'https://www.jiosaavn.com/api.php?__call=content.getAlbumDetails&_format=json&cc=in&_marker=0%3F_marker=0&albumid={id}'
def albumsearch_from_string(query: str):
return f"https://www.jiosaavn.com/api.php?__call=autocomplete.get&_format=json&_marker=0&cc=in&includeMetaTags=1&q... |
def normalize_inputs(data):
"""
Normalizes the inputs to [-1, 1]
:param data: input data array
:return: normalized data to [-1, 1]
"""
data = (data - 127.5) / 127.5
return data
| def normalize_inputs(data):
"""
Normalizes the inputs to [-1, 1]
:param data: input data array
:return: normalized data to [-1, 1]
"""
data = (data - 127.5) / 127.5
return data |
def samesign(a, b):
return a * b > 0
def bisect(func, low, high):
'Find root of continuous function where f(low) and f(high) have opposite signs'
assert not samesign(func(low), func(high))
for i in range(54):
midpoint = (low + high) / 2.0
if samesign(func(low), func(midpoint... | def samesign(a, b):
return a * b > 0
def bisect(func, low, high):
"""Find root of continuous function where f(low) and f(high) have opposite signs"""
assert not samesign(func(low), func(high))
for i in range(54):
midpoint = (low + high) / 2.0
if samesign(func(low), func(midpoint)):
... |
i = 1
while i <= 9:
j = 1
while j <= i:
print("{}x{}={}\t".format(j, i, i * j), end='')
j += 1
print()
i += 1 | i = 1
while i <= 9:
j = 1
while j <= i:
print('{}x{}={}\t'.format(j, i, i * j), end='')
j += 1
print()
i += 1 |
'''
Default quantization scheme
The options are:
iteration: Specify numbers of images for quantization
use_avg: Whether to use AVG method to calculate scale
data_scale: Specify data_scale to scale Min and Max
mean: When firstconv need mean preprocess input
std: When fistconv need std preprocess inpu... | """
Default quantization scheme
The options are:
iteration: Specify numbers of images for quantization
use_avg: Whether to use AVG method to calculate scale
data_scale: Specify data_scale to scale Min and Max
mean: When firstconv need mean preprocess input
std: When fistconv need std preprocess inpu... |
class StateMachine(object):
"""
Abstract character-driven finite state machine implementation, used to
chop down and transform strings.
Useful for implementig simple transpilators, compressors and so on.
Important: when implementing this class, you must set the :attr:`current`
attribute to a k... | class Statemachine(object):
"""
Abstract character-driven finite state machine implementation, used to
chop down and transform strings.
Useful for implementig simple transpilators, compressors and so on.
Important: when implementing this class, you must set the :attr:`current`
attribute to a k... |
"""
Utility functions for i3 blocks formatting
"""
################################################################################
def _to_sRGB(component):
"""
Convert linear Color to sRGB
"""
component = 12.92 * component if component <= 0.0031308 else (1.055 * (component**(1/2.4))) - 0.055
... | """
Utility functions for i3 blocks formatting
"""
def _to_s_rgb(component):
"""
Convert linear Color to sRGB
"""
component = 12.92 * component if component <= 0.0031308 else 1.055 * component ** (1 / 2.4) - 0.055
return int(255.9999 * component)
def _from_s_rgb(component):
"""
Lineari... |
def test_preamble(l: list) -> bool:
t = l.pop()
for i in range(len(l) - 1):
if t - l[i] in l[i + 1:]:
return True
return False
def find_preamble(s: str, p: int) -> int:
l = [int(l) for l in s.splitlines()]
for i in range(len(l) - p):
if not test_preamble(l[i:i + p + 1])... | def test_preamble(l: list) -> bool:
t = l.pop()
for i in range(len(l) - 1):
if t - l[i] in l[i + 1:]:
return True
return False
def find_preamble(s: str, p: int) -> int:
l = [int(l) for l in s.splitlines()]
for i in range(len(l) - p):
if not test_preamble(l[i:i + p + 1]):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.