content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
# @return a string
def convertToTitle(self, n: int) -> str:
capitals = [chr(x) for x in range(ord('A'), ord('Z')+1)]
result = []
while n > 0:
result.insert(0, capitals[(n-1)%len(capitals)])
n = (n-1) % len(capitals)
# result.reverse()
... | class Solution:
def convert_to_title(self, n: int) -> str:
capitals = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
result = []
while n > 0:
result.insert(0, capitals[(n - 1) % len(capitals)])
n = (n - 1) % len(capitals)
return ''.join(result) |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
# Intermediate target grouping the android tools needed to run native
# unittests and instrumentation test apks.
{
'ta... | {'targets': [{'target_name': 'android_tools', 'type': 'none', 'dependencies': ['adb_reboot/adb_reboot.gyp:adb_reboot', 'forwarder2/forwarder.gyp:forwarder2', 'md5sum/md5sum.gyp:md5sum', 'purge_ashmem/purge_ashmem.gyp:purge_ashmem']}, {'target_name': 'memdump', 'type': 'none', 'dependencies': ['memdump/memdump.gyp:memdu... |
# Factory-like class for mortgage options
class MortgageOptions:
def __init__(self,kind,**inputOptions):
self.set_default_options()
self.set_kind_options(kind = kind)
self.set_input_options(**inputOptions)
def set_default_options(self):
self.optionList = dict()
self.optionList['commonDefaul... | class Mortgageoptions:
def __init__(self, kind, **inputOptions):
self.set_default_options()
self.set_kind_options(kind=kind)
self.set_input_options(**inputOptions)
def set_default_options(self):
self.optionList = dict()
self.optionList['commonDefaults'] = dict(name=None... |
# Copyright 2016 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 writing,... | """Defines external repositories needed by rules_webtesting."""
load('//web/internal:platform_http_file.bzl', 'platform_http_file')
load('@bazel_gazelle//:deps.bzl', 'go_repository')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:java.bzl', 'java_import_ex... |
# Copyright 2018 Google LLC
# Copyright 2018-present Open Networking Foundation
# SPDX-License-Identifier: Apache-2.0
"""A portable build system for Stratum P4 switch stack.
To use this, load() this file in a BUILD file, specifying the symbols needed.
The public symbols are the macros:
decorate(path)
sc_cc_lib ... | """A portable build system for Stratum P4 switch stack.
To use this, load() this file in a BUILD file, specifying the symbols needed.
The public symbols are the macros:
decorate(path)
sc_cc_lib Declare a portable Library.
sc_proto_lib Declare a portable .proto Library.
sc_cc_bin Declare a portable B... |
__all__ = (
"Role",
)
class Role:
def __init__(self, data):
self.data = data
self._update(data)
def _get_json(self):
return self.data
def __repr__(self):
return (
f"<Role id={self.id} name={self.name}>"
)
def __str__(self):
... | __all__ = ('Role',)
class Role:
def __init__(self, data):
self.data = data
self._update(data)
def _get_json(self):
return self.data
def __repr__(self):
return f'<Role id={self.id} name={self.name}>'
def __str__(self):
return f'{self.name}'
def _update(se... |
_Msun_kpc3_to_GeV_cm3_factor = 0.3/8.0e6
def Msun_kpc3_to_GeV_cm3(value):
return value*_Msun_kpc3_to_GeV_cm3_factor
| __msun_kpc3_to__ge_v_cm3_factor = 0.3 / 8000000.0
def msun_kpc3_to__ge_v_cm3(value):
return value * _Msun_kpc3_to_GeV_cm3_factor |
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums: return
n = len(nums)-1
while n > 0 and nums[n-1] >= nums[n]:
n -= 1
t = n... | class Solution(object):
def next_permutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return
n = len(nums) - 1
while n > 0 and nums[n - 1] >= nums[n]:
n ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""recumpiler
Recompile text to be semi-readable memey garbage.
"""
__version__ = (0, 0, 0)
| """recumpiler
Recompile text to be semi-readable memey garbage.
"""
__version__ = (0, 0, 0) |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
'linux_link_kerberos%': 0,
'conditions': [
['chromeos==1 or OS=="android" or OS=="ios"', {
... | {'variables': {'chromium_code': 1, 'linux_link_kerberos%': 0, 'conditions': [['chromeos==1 or OS=="android" or OS=="ios"', {'use_kerberos%': 0}, {'use_kerberos%': 1}], ['OS=="android" and target_arch != "ia32"', {'posix_avoid_mmap%': 1}, {'posix_avoid_mmap%': 0}], ['OS=="ios"', {'enable_websockets%': 0, 'use_v8_in_net%... |
#Author Theodosis Paidakis
print("Hello World")
hello_list = ["Hello World"]
print(hello_list[0])
for i in hello_list:
print(i) | print('Hello World')
hello_list = ['Hello World']
print(hello_list[0])
for i in hello_list:
print(i) |
print('Digite seu nome completo: ')
nome = input().strip().upper()
print('Seu nome tem "Silva"?')
print('SILVA' in nome)
| print('Digite seu nome completo: ')
nome = input().strip().upper()
print('Seu nome tem "Silva"?')
print('SILVA' in nome) |
dataset_type = 'STVQADATASET'
data_root = '/home/datasets/mix_data/iMIX/'
feature_path = 'data/datasets/stvqa/defaults/features/'
ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/'
annotation_path = 'data/datasets/stvqa/defaults/annotations/'
vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/'
trai... | dataset_type = 'STVQADATASET'
data_root = '/home/datasets/mix_data/iMIX/'
feature_path = 'data/datasets/stvqa/defaults/features/'
ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/'
annotation_path = 'data/datasets/stvqa/defaults/annotations/'
vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/'
train... |
""" Module docstring """
def _impl(_ctx):
""" Function docstring """
pass
some_rule = rule(
attrs = {
"attr1": attr.int(
default = 2,
mandatory = False,
),
"attr2": 5,
},
implementation = _impl,
)
| """ Module docstring """
def _impl(_ctx):
""" Function docstring """
pass
some_rule = rule(attrs={'attr1': attr.int(default=2, mandatory=False), 'attr2': 5}, implementation=_impl) |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: I am
#
# Created: 02/11/2017
# Copyright: (c) I am 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
... | def main():
pass
if __name__ == '__main__':
main() |
matrix = [list(map(int, input().split())) for _ in range(6)]
max_sum = None
for i in range(4):
for j in range(4):
s = sum(matrix[i][j:j+3]) + matrix[i+1][j+1] + sum(matrix[i+2][j:j+3])
if max_sum is None or s > max_sum:
max_sum = s
print(max_sum)
| matrix = [list(map(int, input().split())) for _ in range(6)]
max_sum = None
for i in range(4):
for j in range(4):
s = sum(matrix[i][j:j + 3]) + matrix[i + 1][j + 1] + sum(matrix[i + 2][j:j + 3])
if max_sum is None or s > max_sum:
max_sum = s
print(max_sum) |
class Bunch(dict):
"""Container object exposing keys as attributes.
Bunch objects are sometimes used as an output for functions and methods.
They extend dictionaries by enabling values to be accessed by key,
`bunch["value_key"]`, or by an attribute, `bunch.value_key`.
Examples
--------
>>>... | class Bunch(dict):
"""Container object exposing keys as attributes.
Bunch objects are sometimes used as an output for functions and methods.
They extend dictionaries by enabling values to be accessed by key,
`bunch["value_key"]`, or by an attribute, `bunch.value_key`.
Examples
--------
>>>... |
pessoas = {'nomes': "Rafael","sexo":"macho alfa","idade":19}
print(f"o {pessoas['nomes']} que se considera um {pessoas['sexo']} possui {pessoas['idade']}")
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
for c in pessoas.keys():
print(c)
for c in pessoas.values():
print(c)
for c, j in pe... | pessoas = {'nomes': 'Rafael', 'sexo': 'macho alfa', 'idade': 19}
print(f"o {pessoas['nomes']} que se considera um {pessoas['sexo']} possui {pessoas['idade']}")
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
for c in pessoas.keys():
print(c)
for c in pessoas.values():
print(c)
for (c, j) i... |
config = {
"Luminosity": 1000,
"InputDirectory": "results",
"Histograms" : {
"WtMass" : {},
"etmiss" : {},
"lep_n" : {},
"lep_pt" : {},
"lep_eta" : {},
"lep_E" : {},
"lep_phi" : {"y_margin" : 0.6},
"lep_... | config = {'Luminosity': 1000, 'InputDirectory': 'results', 'Histograms': {'WtMass': {}, 'etmiss': {}, 'lep_n': {}, 'lep_pt': {}, 'lep_eta': {}, 'lep_E': {}, 'lep_phi': {'y_margin': 0.6}, 'lep_charge': {'y_margin': 0.6}, 'lep_type': {'y_margin': 0.5}, 'lep_ptconerel30': {}, 'lep_etconerel20': {}, 'lep_d0': {}, 'lep_z0':... |
"""
Determine the number of bits required to convert integer A to integer B
Example
Given n = 31, m = 14,return 2
(31)10=(11111)2
(14)10=(01110)2
"""
__author__ = 'Danyang'
class Solution:
def bitSwapRequired(self, a, b):
"""
:param a:
:param b:
:return: int
"""
... | """
Determine the number of bits required to convert integer A to integer B
Example
Given n = 31, m = 14,return 2
(31)10=(11111)2
(14)10=(01110)2
"""
__author__ = 'Danyang'
class Solution:
def bit_swap_required(self, a, b):
"""
:param a:
:param b:
:return: int
"""
... |
# Desempacotamento de parametros em funcoes
# somando valores de uma tupla
def soma(*num):
soma = 0
print('Tupla: {}' .format(num))
for i in num:
soma += i
return soma
# Programa principal
print('Resultado: {}\n' .format(soma(1, 2)))
print('Resultado: {}\n' .format(soma(1, 2, 3, 4, 5, 6, 7, 8,... | def soma(*num):
soma = 0
print('Tupla: {}'.format(num))
for i in num:
soma += i
return soma
print('Resultado: {}\n'.format(soma(1, 2)))
print('Resultado: {}\n'.format(soma(1, 2, 3, 4, 5, 6, 7, 8, 9))) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
temp = head
array = []
while temp:
a... | class Solution:
def swap_nodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
temp = head
array = []
while temp:
array.append(temp.val)
temp = temp.next
(array[k - 1], array[len(array) - k]) = (array[len(array) - k], array[k - 1])
head... |
DATABASE_OPTIONS = {
'database': 'klazor',
'user': 'root',
'password': '',
'charset': 'utf8mb4',
}
HOSTS = ['127.0.0.1', '67.209.115.211']
| database_options = {'database': 'klazor', 'user': 'root', 'password': '', 'charset': 'utf8mb4'}
hosts = ['127.0.0.1', '67.209.115.211'] |
"""
Django settings.
Generated by 'django-admin startproject' using Django 2.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
#DEBUG = False
DEBUG = True
SERV... | """
Django settings.
Generated by 'django-admin startproject' using Django 2.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
debug = True
serve_static = DEBUG... |
def HAHA():
return 1,2,3
a = HAHA()
print(a)
print(a[0])
| def haha():
return (1, 2, 3)
a = haha()
print(a)
print(a[0]) |
ser = int(input())
mas = list(map(int, input().split()))
mas.sort()
print(*mas)
| ser = int(input())
mas = list(map(int, input().split()))
mas.sort()
print(*mas) |
backgroundurl = "https://storage.needpix.com/rsynced_images/colored-background.jpg" # <- Need to be a Image URL!!!
lang = "en" # <- language code
displayset = True # <- Display the Set of the Item
raritytext = True # <- Display the Rarity of the Item
typeconfig = {
"BannerToken": True,
"AthenaBackpack":... | backgroundurl = 'https://storage.needpix.com/rsynced_images/colored-background.jpg'
lang = 'en'
displayset = True
raritytext = True
typeconfig = {'BannerToken': True, 'AthenaBackpack': True, 'AthenaPetCarrier': True, 'AthenaPet': True, 'AthenaPickaxe': True, 'AthenaCharacter': True, 'AthenaSkyDiveContrail': True, 'Athe... |
def cube(number):
return number*number*number
digit = input(" the cube of which digit do you want >")
result = cube(int(digit))
print(result)
| def cube(number):
return number * number * number
digit = input(' the cube of which digit do you want >')
result = cube(int(digit))
print(result) |
def main(request, response):
headers = [("Content-type", "text/html;charset=shift-jis")]
# Shift-JIS bytes for katakana TE SU TO ('test')
content = chr(0x83) + chr(0x65) + chr(0x83) + chr(0x58) + chr(0x83) + chr(0x67);
return headers, content
| def main(request, response):
headers = [('Content-type', 'text/html;charset=shift-jis')]
content = chr(131) + chr(101) + chr(131) + chr(88) + chr(131) + chr(103)
return (headers, content) |
# Vicfred
# https://atcoder.jp/contests/abc132/tasks/abc132_a
# implementation
S = list(input())
if len(set(S)) == 2:
if S.count(S[0]) == 2:
print("Yes")
quit()
print("No")
| s = list(input())
if len(set(S)) == 2:
if S.count(S[0]) == 2:
print('Yes')
quit()
print('No') |
for _ in range(int(input())):
x, y = list(map(int, input().split()))
flag = 1
for i in range(x, y + 1):
n = i * i + i + 41
for j in range(2, n):
if j * j > n:
break
if n % j == 0:
flag = 0
break
if flag == 0:
break
if flag:
print("OK")
else:
print("Sorry") | for _ in range(int(input())):
(x, y) = list(map(int, input().split()))
flag = 1
for i in range(x, y + 1):
n = i * i + i + 41
for j in range(2, n):
if j * j > n:
break
if n % j == 0:
flag = 0
break
if flag == 0:
... |
{
'targets': [
{
'target_name': 'hiredis',
'sources': [
'src/hiredis.cc'
, 'src/reader.cc'
],
'include_dirs': ["<!(node -e \"require('nan')\")"],
'dependencies': [
'deps/hiredis.gyp:hiredis-c'
],
'defines': [
'_GNU_SOURCE'
],
... | {'targets': [{'target_name': 'hiredis', 'sources': ['src/hiredis.cc', 'src/reader.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'dependencies': ['deps/hiredis.gyp:hiredis-c'], 'defines': ['_GNU_SOURCE'], 'cflags': ['-Wall', '-O3']}]} |
#!/usr/bin/env python3
"""
Build a table of Python / Pydantic to JSON Schema mappings.
Done like this rather than as a raw rst table to make future edits easier.
Please edit this file directly not .tmp_schema_mappings.rst
"""
table = [
[
'bool',
'boolean',
'',
'JSON Schema Core',
... | """
Build a table of Python / Pydantic to JSON Schema mappings.
Done like this rather than as a raw rst table to make future edits easier.
Please edit this file directly not .tmp_schema_mappings.rst
"""
table = [['bool', 'boolean', '', 'JSON Schema Core', ''], ['str', 'string', '', 'JSON Schema Core', ''], ['float', ... |
# mako/__init__.py
# Copyright (C) 2006-2016 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
__version__ = '1.0.9'
| __version__ = '1.0.9' |
def pick_food(name):
if name == "chima":
return "chicken"
else:
return "dry food"
| def pick_food(name):
if name == 'chima':
return 'chicken'
else:
return 'dry food' |
# Creating a elif chain
alien_color = 'red'
if alien_color == 'green':
print('Congratulations! You won 5 points!')
elif alien_color == 'yellow':
print('Congratulations! You won 10 points!')
elif alien_color == 'red':
print('Congratulations! You won 15 points!')
| alien_color = 'red'
if alien_color == 'green':
print('Congratulations! You won 5 points!')
elif alien_color == 'yellow':
print('Congratulations! You won 10 points!')
elif alien_color == 'red':
print('Congratulations! You won 15 points!') |
# https://www.codechef.com/START8C/problems/PENALTY
for T in range(int(input())):
n=list(map(int,input().split()))
a=b=0
for i in range(len(n)):
if(n[i]==1):
if(i%2==0): a+=1
else: b+=1
if(a>b): print(1)
elif(b>a): print(2)
else: print(0) | for t in range(int(input())):
n = list(map(int, input().split()))
a = b = 0
for i in range(len(n)):
if n[i] == 1:
if i % 2 == 0:
a += 1
else:
b += 1
if a > b:
print(1)
elif b > a:
print(2)
else:
print(0) |
MATH_BYTECODE = (
"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000"
"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22"
"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780"
"63dcf537b11461014057610074565b... | math_bytecode = '606060405261022e806100126000396000f360606040523615610074576000357c01000000000000000000000000000000000000000000000000000000009004806316216f391461007657806361bc221a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d578063dcf537b11461014057610074565b005b610083600480505061016c565b604... |
def modify(y):
return y # returns same reference. No new object is created
x = [1, 2, 3]
y = modify(x)
print("x == y", x == y)
print("x == y", x is y) | def modify(y):
return y
x = [1, 2, 3]
y = modify(x)
print('x == y', x == y)
print('x == y', x is y) |
# 1. Create students score dictionary.
students_score = {}
# 2. Input student's name and check if input is correct. (Alphabet, period, and blank only.)
# 2.1 Creat a function that evaluate the validity of name.
def check_name(name):
# 2.1.1 Remove period and blank and check it if the name is comprised with on... | students_score = {}
def check_name(name):
list_of_spelling = list(name)
while '.' in list_of_spelling:
list_of_spelling.remove('.')
while ' ' in list_of_spelling:
list_of_spelling.remove(' ')
list_to_string = ''
list_to_string = list_to_string.join(list_of_spelling)
return list_... |
#$Id$
class Instrumentation:
"""This class is used tocreate object for instrumentation."""
def __init__(self):
"""Initialize parameters for Instrumentation object."""
self.query_execution_time = ''
self.request_handling_time = ''
self.response_write_time = ''
self.page_c... | class Instrumentation:
"""This class is used tocreate object for instrumentation."""
def __init__(self):
"""Initialize parameters for Instrumentation object."""
self.query_execution_time = ''
self.request_handling_time = ''
self.response_write_time = ''
self.page_context... |
load("@rules_jvm_external//:defs.bzl", "artifact")
# For more information see
# - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD
# - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5
# - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starte... | load('@rules_jvm_external//:defs.bzl', 'artifact')
def junit5_test(name, srcs, test_package, resources=[], deps=[], runtime_deps=[], **kwargs):
"""JUnit runner macro"""
filter_kwargs = ['main_class', 'use_testrunner', 'args']
for arg in FILTER_KWARGS:
if arg in kwargs.keys():
kwargs.pop... |
# This module provides mocked versions of classes and functions provided
# by Carla in our runtime environment.
class Location(object):
""" A mock class for carla.Location. """
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Rotation(object):
""" A mock class... | class Location(object):
""" A mock class for carla.Location. """
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Rotation(object):
""" A mock class for carla.Rotation. """
def __init__(self, pitch, yaw, roll):
self.pitch = pitch
self.yaw = y... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
ee = '\033[1m'
green = '\033[32m'
yellow = '\033[33m'
cyan = '\033[36m'
line = cyan+'-' * 0x2D
print(ee+line)
R,G,B = [float(X) / 0xFF for X in input(f'{yellow}RGB: {green}').split()]
K = 1-max(R,G,B)
C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]]
K = r... | ee = '\x1b[1m'
green = '\x1b[32m'
yellow = '\x1b[33m'
cyan = '\x1b[36m'
line = cyan + '-' * 45
print(ee + line)
(r, g, b) = [float(X) / 255 for x in input(f'{yellow}RGB: {green}').split()]
k = 1 - max(R, G, B)
(c, m, y) = [round(float((1 - X - K) / (1 - K) * 100), 1) for x in [R, G, B]]
k = round(K * 100, 1)
print(f'{y... |
def selection_sort(A): # O(n^2)
n = len(A)
for i in range(n-1): # percorre a lista
min = i
for j in range(i+1, n): # encontra o menor elemento da lista a partir de i + 1
if A[j] < A[min]:
min = j
A[i], A[min] = A[min], A[i] # insere o elemento na posicao corre... | def selection_sort(A):
n = len(A)
for i in range(n - 1):
min = i
for j in range(i + 1, n):
if A[j] < A[min]:
min = j
(A[i], A[min]) = (A[min], A[i])
return A |
tajniBroj = 51
broj = 2
while tajniBroj != broj:
broj = int(input("Pogodite tajni broj: "))
if tajniBroj == broj:
print("Pogodak!")
elif tajniBroj < broj:
print("Tajni broj je manji od tog broja.")
else:
print("Tajni broj je veci od tog broja.")
print("Kraj programa")
| tajni_broj = 51
broj = 2
while tajniBroj != broj:
broj = int(input('Pogodite tajni broj: '))
if tajniBroj == broj:
print('Pogodak!')
elif tajniBroj < broj:
print('Tajni broj je manji od tog broja.')
else:
print('Tajni broj je veci od tog broja.')
print('Kraj programa') |
class CoinbaseResponse:
bid = 0
ask = 0
product_id = None
def set_bid(self, bid):
self.bid = float(bid)
def get_bid(self):
return self.bid
def set_ask(self, ask):
self.ask = float(ask)
def get_ask(self):
return self.ask
def get_product_id(self):
... | class Coinbaseresponse:
bid = 0
ask = 0
product_id = None
def set_bid(self, bid):
self.bid = float(bid)
def get_bid(self):
return self.bid
def set_ask(self, ask):
self.ask = float(ask)
def get_ask(self):
return self.ask
def get_product_id(self):
... |
'''
Problem description:
Given a string, determine whether or not the parentheses are balanced
'''
def balanced_parens(str):
'''
runtime: O(n)
space : O(1)
'''
if str is None:
return True
open_count = 0
for char in str:
if char == '(':
open_count += 1
... | """
Problem description:
Given a string, determine whether or not the parentheses are balanced
"""
def balanced_parens(str):
"""
runtime: O(n)
space : O(1)
"""
if str is None:
return True
open_count = 0
for char in str:
if char == '(':
open_count += 1
el... |
#!/usr/bin/env python3
# Coded by Massimiliano Tomassoli, 2012.
#
# - Thanks to b49P23TIvg for suggesting that I should use a set operation
# instead of repeated membership tests.
# - Thanks to Ian Kelly for pointing out that
# - "minArgs = None" is better than "minArgs = -1",
# - "if args" is better than ... | def gen_cur(func, unique=True, minArgs=None):
""" Generates a 'curried' version of a function. """
def g(*myArgs, **myKwArgs):
def f(*args, **kwArgs):
if args or kwArgs:
new_args = myArgs + args
new_kw_args = dict.copy(myKwArgs)
if unique and... |
greeting = """
--------------- BEGIN SESSION ---------------
You have connected to a chat server. Welcome!
:: About
Chat is a small piece of server software
written by Evan Pratten to allow people to
talk to eachother from any computer as long
as it has an internet connection. (Even an
arduino!). Check out the proje... | greeting = "\n--------------- BEGIN SESSION ---------------\nYou have connected to a chat server. Welcome!\n\n:: About\nChat is a small piece of server software \nwritten by Evan Pratten to allow people to \ntalk to eachother from any computer as long\nas it has an internet connection. (Even an\narduino!). Check out th... |
# 13. Join
# it allows to print list a bit better
friends = ['Pythobit','boy','Pythoman']
print(f'My friends are {friends}.') # Output - My friends are ['Pythobit', 'boy', 'Pythoman'].
# So, the Output needs to be a bit clearer.
friends = ['Pythobit','boy','Pythoman']
friend = ', '.join(friends)
print(f'My friend... | friends = ['Pythobit', 'boy', 'Pythoman']
print(f'My friends are {friends}.')
friends = ['Pythobit', 'boy', 'Pythoman']
friend = ', '.join(friends)
print(f'My friends are {friend}') |
# settings file for builds.
# if you want to have custom builds, copy this file to "localbuildsettings.py" and make changes there.
# possible fields:
# resourceBaseUrl - optional - the URL base for external resources (all resources embedded in standard IITC)
# distUrlBase - optional - the base URL to use for update c... | build_settings = {'randomizax': {'resourceUrlBase': None, 'distUrlBase': 'https://randomizax.github.io/polygon-label'}, 'local8000': {'resourceUrlBase': 'http://0.0.0.0:8000/dist', 'distUrlBase': None}, 'mobile': {'resourceUrlBase': None, 'distUrlBase': None, 'buildMobile': 'debug'}} |
class Point3D:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
'''
Returns the distance between two 3D points
'''
def distance(self, value):
return abs(self.x - value.x) + abs(self.y - value.y) + abs(self.z - value.z)
def __eq__(self, value):
... | class Point3D:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
'\n Returns the distance between two 3D points\n '
def distance(self, value):
return abs(self.x - value.x) + abs(self.y - value.y) + abs(self.z - value.z)
def __eq__(self, value):
... |
# API keys
# YF_API_KEY = "YRVHVLiFAt3ANYZf00BXr2LHNfZcgKzdWVmsZ9Xi" # yahoo finance api key
TICKER = "TSLA"
INTERVAL = "1m"
PERIOD = "1d"
LOOK_BACK = 30 # hard limit to not reach rate limit of 100 per day | ticker = 'TSLA'
interval = '1m'
period = '1d'
look_back = 30 |
FILE = r'../src/etc-hosts.txt'
hostnames = []
try:
with open(FILE, encoding='utf-8') as file:
content = file.readlines()
except FileNotFoundError:
print('File does not exist')
except PermissionError:
print('Permission denied')
for line in content:
if line.startswith('#'):
continue
... | file = '../src/etc-hosts.txt'
hostnames = []
try:
with open(FILE, encoding='utf-8') as file:
content = file.readlines()
except FileNotFoundError:
print('File does not exist')
except PermissionError:
print('Permission denied')
for line in content:
if line.startswith('#'):
continue
if ... |
def n_subimissions_per_day( url, headers ):
"""Get the number of submissions we can make per day for the selected challenge.
Parameters
----------
url : {'prize', 'points', 'knowledge' , 'all'}, default='all'
The reward of the challenges for top challengers.
headers : dictionary ,
T... | def n_subimissions_per_day(url, headers):
"""Get the number of submissions we can make per day for the selected challenge.
Parameters
----------
url : {'prize', 'points', 'knowledge' , 'all'}, default='all'
The reward of the challenges for top challengers.
headers : dictionary ,
The... |
def getRoot(config):
if not config.parent:
return config
return getRoot(config.parent)
root = getRoot(config)
# We only run a small set of tests on Windows for now.
# Override the parent directory's "unsupported" decision until we can handle
# all of its tests.
if root.host_os in ['Windows']:
config.unsuppo... | def get_root(config):
if not config.parent:
return config
return get_root(config.parent)
root = get_root(config)
if root.host_os in ['Windows']:
config.unsupported = False
else:
config.unsupported = True |
"""Constant values."""
STATUS_SUCCESS = (0,)
STATUS_AUTH_FAILED = (100, 101, 102, 200, 401)
STATUS_INVALID_PARAMS = (
201,
202,
203,
204,
205,
206,
207,
208,
209,
210,
211,
212,
213,
216,
217,
218,
220,
221,
223,
225,
227,
228,
... | """Constant values."""
status_success = (0,)
status_auth_failed = (100, 101, 102, 200, 401)
status_invalid_params = (201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 216, 217, 218, 220, 221, 223, 225, 227, 228, 229, 230, 234, 235, 236, 238, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252... |
FACTS = ['espoem multiplied by zero still equals espoem.',
'There is no theory of evolution. Just a list of creatures espoem has allowed to live.',
'espoem does not sleep. He waits.',
'Alexander Graham Bell had three missed calls from espoem when he invented the telephone.',
'espoem ... | facts = ['espoem multiplied by zero still equals espoem.', 'There is no theory of evolution. Just a list of creatures espoem has allowed to live.', 'espoem does not sleep. He waits.', 'Alexander Graham Bell had three missed calls from espoem when he invented the telephone.', 'espoem is the reason why Waldo is hiding.',... |
#
# LeetCode
#
# Problem - 106
# URL - https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = ri... | class Solution:
def build_tree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not inorder:
return None
r = postorder.pop()
root = tree_node(r)
index = inorder.index(r)
root.right = self.buildTree(inorder[index + 1:], postorder)
root.left ... |
#
# PySNMP MIB module EXTREME-RTSTATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-BASE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:53:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, M... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
# https://www.acmicpc.net/problem/1260
n, m, v = map(int, input().split())
graph = [[0] * (n+1) for _ in range(n+1)]
visit = [False] * (n+1)
for _ in range(m):
R, C = map(int, input().split())
graph[R][C] = 1
graph[C][R] = 1
def dfs(v):
visit[v] = True
print(v, end=" ")
for i in range(1, n+... | (n, m, v) = map(int, input().split())
graph = [[0] * (n + 1) for _ in range(n + 1)]
visit = [False] * (n + 1)
for _ in range(m):
(r, c) = map(int, input().split())
graph[R][C] = 1
graph[C][R] = 1
def dfs(v):
visit[v] = True
print(v, end=' ')
for i in range(1, n + 1):
if not visit[i] and... |
class Solution:
def modifyString(self, s: str) -> str:
s = list(s)
for i in range(len(s)):
if s[i] == "?":
for c in "abc":
if (i == 0 or s[i-1] != c) and (i+1 == len(s) or s[i+1] != c):
s[i] = c
break ... | class Solution:
def modify_string(self, s: str) -> str:
s = list(s)
for i in range(len(s)):
if s[i] == '?':
for c in 'abc':
if (i == 0 or s[i - 1] != c) and (i + 1 == len(s) or s[i + 1] != c):
s[i] = c
b... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
An `image.layer` is a set of `feature` with some additional parameters. Its
purpose to materialize those `feature`s as a btrfs subvolume ... | """
An `image.layer` is a set of `feature` with some additional parameters. Its
purpose to materialize those `feature`s as a btrfs subvolume in the
per-repo `buck-image/out/volume/targets`.
We call the subvolume a "layer" because it can be built on top of a snapshot
of its `parent_layer`, and thus can be represented ... |
# ------------------------------
# 515. Find Largest Value in Each Tree Row
#
# Description:
# You need to find the largest value in each row of a binary tree.
# Example:
# Input:
# 1
# / \
# 3 2
# / \ \
# 5 3 9
# Output: [1, 3, 9]
#
# Version: 1.0
# 12/22/18 by Jia... | class Solution:
def largest_values(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
children = [root]
res = []
while children:
temp = []
largest = -sys.maxsize
for i in ... |
class DynamicObject(object):
def __init__(self, name, id_):
self.name = name
self.id = id_
| class Dynamicobject(object):
def __init__(self, name, id_):
self.name = name
self.id = id_ |
""" TextRNN model configuration """
class TextRNNConfig(object):
def __init__(
self,
vocab_size=30000,
pretrained_embedding=None,
embedding_matrix=None,
embedding_dim=300,
embedding_dropout=0.3,
lstm_hidden_size=128,
output_dim=1,
**kwargs
... | """ TextRNN model configuration """
class Textrnnconfig(object):
def __init__(self, vocab_size=30000, pretrained_embedding=None, embedding_matrix=None, embedding_dim=300, embedding_dropout=0.3, lstm_hidden_size=128, output_dim=1, **kwargs):
self.pretrained_embedding = pretrained_embedding
self.emb... |
"""Provides all the data related to the development."""
LICENSES = [
"Apache License, 2.0 (Apache-2.0)",
"The BSD 3-Clause License",
"The BSD 2-Clause License",
"GNU General Public License (GPL)",
"General Public License (LGPL)",
"MIT License (MIT)",
"Mozilla Public License 2.0 (MPL-2.0)",
... | """Provides all the data related to the development."""
licenses = ['Apache License, 2.0 (Apache-2.0)', 'The BSD 3-Clause License', 'The BSD 2-Clause License', 'GNU General Public License (GPL)', 'General Public License (LGPL)', 'MIT License (MIT)', 'Mozilla Public License 2.0 (MPL-2.0)', 'Common Development and Distri... |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: protocolo.py
#
# Tests: vistprotocol unit test
#
# Mark C. Miller, Tue Jan 11 10:19:23 PST 2011
# ----------------------------------------------------------------------------
tapp = visit_bin_path(... | tapp = visit_bin_path('visitprotocol')
res = sexe(tapp, ret_output=True)
if res['return_code'] == 0:
excode = 111
else:
excode = 113
exit(excode) |
""" Insertion Sort Algorithm:"""
"""Implementation"""
def insertion_sort(arr) -> list:
n = len(arr)
for i in range(1, n):
swap_index = i
for j in range(i-1, -1, -1):
if arr[swap_index] < arr[j]:
arr[swap_index], arr[j] = arr[j], arr[swap_index]
swa... | """ Insertion Sort Algorithm:"""
'Implementation'
def insertion_sort(arr) -> list:
n = len(arr)
for i in range(1, n):
swap_index = i
for j in range(i - 1, -1, -1):
if arr[swap_index] < arr[j]:
(arr[swap_index], arr[j]) = (arr[j], arr[swap_index])
swap... |
# store information about a pizza being ordered
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra vegan cheese']
}
# summarize the order
print("You ordered a " + pizza['crust'] + "-crust pizza" +
"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping) | pizza = {'crust': 'thick', 'toppings': ['mushrooms', 'extra vegan cheese']}
print('You ordered a ' + pizza['crust'] + '-crust pizza' + 'with the following toppings:')
for topping in pizza['toppings']:
print('\t' + topping) |
"""
Given 3 bottles of capacities 3, 5, and 9 liters,
count number of all possible solutions to get 7 liters
"""
current_path = [[0, 0, 0]]
CAPACITIES = (3, 5, 9)
solutions_count = 0
def move_to_new_state(current_state):
global solutions_count, current_path
if 7 in current_state:
solutions_co... | """
Given 3 bottles of capacities 3, 5, and 9 liters,
count number of all possible solutions to get 7 liters
"""
current_path = [[0, 0, 0]]
capacities = (3, 5, 9)
solutions_count = 0
def move_to_new_state(current_state):
global solutions_count, current_path
if 7 in current_state:
solutions_cou... |
# Tumblr Setup
# Replace the values with your information
# OAuth keys can be generated from https://api.tumblr.com/console/calls/user/info
consumer_key='ShbOqI5zErQXOL7Qnd5XduXpY9XQUlBgJDpCLeq1OYqnY2KzSt' #replace with your key
consumer_secret='ulZradkbJGksjpl2MMlshAfJgEW6TNeSdZucykqeTp8jvwgnhu' #replace with your sec... | consumer_key = 'ShbOqI5zErQXOL7Qnd5XduXpY9XQUlBgJDpCLeq1OYqnY2KzSt'
consumer_secret = 'ulZradkbJGksjpl2MMlshAfJgEW6TNeSdZucykqeTp8jvwgnhu'
oath_token = 'uUcBuvJx8yhk4HJIZ39sfcYo0W4VoqcvUetR2EwcI5Sn8SLgNt'
oath_secret = 'iNJlqQJI6dwhAGmdNbMtD9u7VazmX2Rk5uW0fuIozIEjk97lz4'
tumblr_blog = 'soniaetjeremie'
tags_for_tumblr =... |
class Solution:
"""
@param s: a string
@param t: a string
@return: true if they are both one edit distance apart or false
"""
def isOneEditDistance(self, s, t):
# write your code here
if s == t:
return False
if abs(len(s) - len(t)) > 1:
return Fal... | class Solution:
"""
@param s: a string
@param t: a string
@return: true if they are both one edit distance apart or false
"""
def is_one_edit_distance(self, s, t):
if s == t:
return False
if abs(len(s) - len(t)) > 1:
return False
(n, m) = (len(s),... |
df8.cbind(df9)
# A B C D A0 B0 C0 D0
# ----- ------ ------ ------ ------ ----- ----- -----
# -0.09 0.944 0.160 0.271 -0.351 1.66 -2.32 -0.86
# -0.95 0.669 0.664 1.535 -0.633 -1.78 0.32 1.27
# 0.17 0.657 0.970 -0.419 -1.413 -0.51 0.64 -1.25
# 0.58 -0.516 -1.598 -1.346 0.71... | df8.cbind(df9) |
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | """A rule for creating a Java container image.
The signature of java_image is compatible with java_binary.
The signature of war_image is compatible with java_library.
"""
load('//container:container.bzl', 'container_pull', _repositories='repositories')
load(':java.bzl', _JAVA_DIGESTS='DIGESTS')
load(':jetty.bzl', _JE... |
try:
# num = 10 / 0
number = int(input("Enter a number: "))
print(number)
# catch specific errors
except ZeroDivisionError as err:
print(err)
except ValueError:
print("Invalid input")
| try:
number = int(input('Enter a number: '))
print(number)
except ZeroDivisionError as err:
print(err)
except ValueError:
print('Invalid input') |
class Deque:
def add_first(self, value):
...
def add_last(self, value):
...
def delete_first(self):
...
def delete_last(self):
...
def first(self):
...
def last(self):
...
def is_empty(self):
...
def __len__(self):
..... | class Deque:
def add_first(self, value):
...
def add_last(self, value):
...
def delete_first(self):
...
def delete_last(self):
...
def first(self):
...
def last(self):
...
def is_empty(self):
...
def __len__(self):
.... |
# A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
# S is empty;
# S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; S has the form "VW" where V and W are properly nested strings.
# For example, the string "{[()()]}" is prope... | def solution(s):
sets = dict(zip('({[', ')}]'))
if not isinstance(s, str):
return 'Invalid input'
collector = []
for bracket in s:
if bracket in sets:
collector.append(sets[bracket])
elif bracket not in sets.values():
return 'Invalid input'
elif br... |
class RedisBackend(object):
def __init__(self, settings={}, *args, **kwargs):
self.settings = settings
@property
def connection(self):
# cached redis connection
if not hasattr(self, '_connection'):
self._connection = self.settings.get('redis.connector').get()
re... | class Redisbackend(object):
def __init__(self, settings={}, *args, **kwargs):
self.settings = settings
@property
def connection(self):
if not hasattr(self, '_connection'):
self._connection = self.settings.get('redis.connector').get()
return self._connection
@proper... |
"""
1. Write a Python program to reverse only the vowels of a given string.
Sample Output:
w3resuorce
Python
Perl
ASU
2. Write a Python program to check whether a given integer is a palindrome or not.
Note: An integer is a palindrome when it reads the same backward as forward. Negative numbers are not palindromic.
Sa... | """
1. Write a Python program to reverse only the vowels of a given string.
Sample Output:
w3resuorce
Python
Perl
ASU
2. Write a Python program to check whether a given integer is a palindrome or not.
Note: An integer is a palindrome when it reads the same backward as forward. Negative numbers are not palindromic.
Sa... |
# CHECK-TREE: { const <- \x -> \y -> x; y <- const #true #true; z <- const #false #false; #record { const: const, y : y, z: z, }}
const = lambda x, y: x
y = const(True, True)
z = const(False, False)
| const = lambda x, y: x
y = const(True, True)
z = const(False, False) |
_base_ = '../faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco.py'
model = dict(
backbone=dict(
num_stages=4,
#frozen_stages=4
),
roi_head=dict(
bbox_head=dict(
num_classes=3
)
)
)
dataset_type = 'COCODataset'
classes = ('luchs', 'rotfuchs', 'wolf')
data = dict... | _base_ = '../faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco.py'
model = dict(backbone=dict(num_stages=4), roi_head=dict(bbox_head=dict(num_classes=3)))
dataset_type = 'COCODataset'
classes = ('luchs', 'rotfuchs', 'wolf')
data = dict(train=dict(img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/trai... |
h = int(input())
i = 1
a = 1
b = 1
c = 1
while h >= a:
a = 2 ** i
i += 1
s = 0
t = True
for j in range(1, i-1):
c += 2 ** j
print(c)
| h = int(input())
i = 1
a = 1
b = 1
c = 1
while h >= a:
a = 2 ** i
i += 1
s = 0
t = True
for j in range(1, i - 1):
c += 2 ** j
print(c) |
class ArmorVisitor:
def __init__(self, num_pages, first_page_col_start, first_page_row_start,
last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3):
self.num_pages = num_pages
self.first_page_col_start = first_page_col_start
self.first_page_row_start = first_page_... | class Armorvisitor:
def __init__(self, num_pages, first_page_col_start, first_page_row_start, last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3):
self.num_pages = num_pages
self.first_page_col_start = first_page_col_start
self.first_page_row_start = f... |
#
# PySNMP MIB module InternetThruway-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/InternetThruway-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:58:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, constraints_intersection, single_value_constraint) ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 16:04:52 2020
@author: rjovelin
"""
| """
Created on Tue Oct 20 16:04:52 2020
@author: rjovelin
""" |
# 2. Repeat Strings
# Write a Program That Reads a list of strings. Each string is repeated N times, where N is the length of the string. Print the concatenated string.
strings = input().split()
output_string = ""
for string in strings:
N = len(string)
output_string += string * N
print(output_string)
| strings = input().split()
output_string = ''
for string in strings:
n = len(string)
output_string += string * N
print(output_string) |
def dfs(V):
print(V, end=' ')
visited[V] = True
for n in graph[V]:
if not visited[n]:
dfs(n)
def dfs_s(V):
stack = [V]
visited[V] = True
while stack:
now = stack.pop()
print(now, end=' ')
for n in graph[now]:
if not visited[n]:
... | def dfs(V):
print(V, end=' ')
visited[V] = True
for n in graph[V]:
if not visited[n]:
dfs(n)
def dfs_s(V):
stack = [V]
visited[V] = True
while stack:
now = stack.pop()
print(now, end=' ')
for n in graph[now]:
if not visited[n]:
... |
# Time Complexity - O(n) ; Space Complexity - O(n)
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
out = temp = ListNode()
while l1 is not None and l2 is not None:
tempsum = l1.val + l2.val
tempsum += carry
... | class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
out = temp = list_node()
while l1 is not None and l2 is not None:
tempsum = l1.val + l2.val
tempsum += carry
if tempsum > 9:
carry = tempsum // 10... |
_base_ = [
'../_base_/models/faster_rcnn_r50_fpn.py'
]
model = dict(
type='FasterRCNN',
# pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requir... | _base_ = ['../_base_/models/faster_rcnn_r50_fpn.py']
model = dict(type='FasterRCNN', backbone=dict(type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict(type='FPN', in_channels=[256, 512, 1024, 2048], o... |
# Binary Search Tree
# Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
#
# Example:
#
# Input:
#
# 1
# \
# 3
# /
# 2
#
# Output:
# 1
#
# Explanation:
# The minimum absolute difference is 1, which is the difference between 2 a... | class Solution:
def get_minimum_difference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.minDiff = []
def travel(node):
if not node:
return
self.minDiff.append(node.val)
l = travel(node.left)
... |
"""
``exposing``
"""
__version__ = '0.2.2'
| """
``exposing``
"""
__version__ = '0.2.2' |
# Message class Implementation
# @author: Gaurav Yeole <gauravyeole@gmail.com>
class Message:
class Request:
def __init__(self, action="", data=None):
self.action = action
self.data = data
class Rsponse:
def __init__(self):
self.status = False
se... | class Message:
class Request:
def __init__(self, action='', data=None):
self.action = action
self.data = data
class Rsponse:
def __init__(self):
self.status = False
self.data = None
def __init__(self):
pass
def set_request(sel... |
#
# PySNMP MIB module CISCO-VSI-CONTROLLER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VSI-CONTROLLER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:03:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, constraints_intersection, value_range_constraint, single_value_constraint) ... |
class SceneRelation:
def __init__(self):
self.on_ground = set()
self.on_block = {}
self.clear = set()
def print_relation(self):
print(self.on_ground)
print(self.on_block)
print(self.clear) | class Scenerelation:
def __init__(self):
self.on_ground = set()
self.on_block = {}
self.clear = set()
def print_relation(self):
print(self.on_ground)
print(self.on_block)
print(self.clear) |
def _jpeg_compression(im):
assert torch.is_tensor(im)
im = ToPILImage()(im)
savepath = BytesIO()
im.save(savepath, 'JPEG', quality=75)
im = Image.open(savepath)
im = ToTensor()(im)
return im | def _jpeg_compression(im):
assert torch.is_tensor(im)
im = to_pil_image()(im)
savepath = bytes_io()
im.save(savepath, 'JPEG', quality=75)
im = Image.open(savepath)
im = to_tensor()(im)
return im |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 15:58:44 2019
@author: babin
"""
posits_def = [251, 501, 751, 1001, 1251, 1501, 1751, 2001, 2251, 2501, 2751, 3001, 3215]
dist_whole_align_ref = {'AB048704.1_genotype_C_':
[0.88,
0.938,
0.914,
0.886,
0.89,
0.908,
0.938,
0.948,
0.948,
0.886,
0.8... | """
Created on Tue Oct 22 15:58:44 2019
@author: babin
"""
posits_def = [251, 501, 751, 1001, 1251, 1501, 1751, 2001, 2251, 2501, 2751, 3001, 3215]
dist_whole_align_ref = {'AB048704.1_genotype_C_': [0.88, 0.938, 0.914, 0.886, 0.89, 0.908, 0.938, 0.948, 0.948, 0.886, 0.852, 0.8580645161290322, 0.827906976744186], 'AB01... |
"""
This file contains meta information and default configurations of the project
"""
RSC_YEARS = [1660, 1670, 1680, 1690,
1700, 1710, 1720, 1730, 1740, 1750, 1760, 1770, 1780, 1790,
1800, 1810, 1820, 1830, 1840, 1850, 1860, 1870, 1880, 1890,
1900, 1910, 1920]
# cf. Chapter 4.... | """
This file contains meta information and default configurations of the project
"""
rsc_years = [1660, 1670, 1680, 1690, 1700, 1710, 1720, 1730, 1740, 1750, 1760, 1770, 1780, 1790, 1800, 1810, 1820, 1830, 1840, 1850, 1860, 1870, 1880, 1890, 1900, 1910, 1920]
space_pair_selection = [(1740, 1750), (1750, 1760), (1680, ... |
# ------------------------------
# 200. Number of Islands
#
# Description:
# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrou... | class Solution(object):
def num_islands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def sink(i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and (grid[i][j] == '1'):
grid[i][j] = '0'
map(sink, (i + 1, i - 1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.