content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Const:
GITHUB = "https://github.com/ayvytr/PythonBox"
ISSUE = "https://github.com/Ayvytr/PythonBox/issues"
MAIL = "mailto:ayvytr@163.com?subject=Bug-Report&body={}"
| class Const:
github = 'https://github.com/ayvytr/PythonBox'
issue = 'https://github.com/Ayvytr/PythonBox/issues'
mail = 'mailto:ayvytr@163.com?subject=Bug-Report&body={}' |
def prediction(image_path):
img = tf.keras.utils.load_img(
image_path, target_size=(img_height, img_width))
img = tf.keras.utils.img_to_array(img)
plt.title('Image')
plt.axis('off')
plt.imshow((img/255.0).squeeze())
predict = model.predict(img[np.newaxis , ... | def prediction(image_path):
img = tf.keras.utils.load_img(image_path, target_size=(img_height, img_width))
img = tf.keras.utils.img_to_array(img)
plt.title('Image')
plt.axis('off')
plt.imshow((img / 255.0).squeeze())
predict = model.predict(img[np.newaxis, ...])
predicted_class = labels[np.a... |
target_str = "hello python world"
# reverse encrypt
print(target_str[-1::-1])
| target_str = 'hello python world'
print(target_str[-1::-1]) |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) The Lab of Professor Weiwei Lin (linww@scut.edu.cn),
# School of Computer Science and Engineering, South China University of Technology.
# A-Tune is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan ... | x1 = 3
x2 = 1
x3 = 5
x4 = 3
x5 = 3
x6 = 3
x7 = 3
x8 = 3
x9 = 3
x10 = 2
x11 = 2
x12 = 4
x13 = 4
x14 = 2
x15 = 2
x16 = 1
x17 = 2
x18 = 5
x19 = 1
x20 = 1
x21 = 1
x22 = 1
x23 = 1
x24 = 2
x25 = 4
x26 = 2
x27 = 3
x28 = 1
x29 = 2
x30 = 4
x31 = 4
x32 = 1
x33 = 4
x34 = 1
x35 = 2
x36 = 1
x37 = 3
x38 = 2
x39 = 1
x40 = 2
x41 = 3
x... |
def solve():
n=int(input())
row,col=(n,n)
res=""
for i in range(row):
for j in range(col):
if i==j:
res+='1 '
elif i==j-1:
res+='1 '
elif i==j+1:
res+='1 '
else:
res+='0 '
if i... | def solve():
n = int(input())
(row, col) = (n, n)
res = ''
for i in range(row):
for j in range(col):
if i == j:
res += '1 '
elif i == j - 1:
res += '1 '
elif i == j + 1:
res += '1 '
else:
... |
tuple_a = 1, 2
tuple_b = (1, 2)
print(tuple_a == tuple_b)
print(tuple_a[1])
AngkorWat = (13.4125, 103.866667)
print(type(AngkorWat))
# <class 'tuple'="">
print("AngkorWat is at latitude: {}".format(AngkorWat[0]))
# AngkorWat is at latitude: 13.4125
print("AngkorWat is at longitude: {}".format(AngkorWat[1])... | tuple_a = (1, 2)
tuple_b = (1, 2)
print(tuple_a == tuple_b)
print(tuple_a[1])
angkor_wat = (13.4125, 103.866667)
print(type(AngkorWat))
print('AngkorWat is at latitude: {}'.format(AngkorWat[0]))
print('AngkorWat is at longitude: {}'.format(AngkorWat[1])) |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
''' Battery runner classes and Report classes '''
class BatteryRunner(object):
def __init__(self, checks):
self._checks = checks
def check_only(self, obj):
reports = []
fo... | """ Battery runner classes and Report classes """
class Batteryrunner(object):
def __init__(self, checks):
self._checks = checks
def check_only(self, obj):
reports = []
for check in self._checks:
reports.append(check(obj, False))
return reports
def check_fix(s... |
class Solution:
def spiralOrder(self, matrix) -> list:
result = []
m = len(matrix)
n = len(matrix[0])
flag = [[False] * n for _ in range(m)]
i = 0
j = 0
orient = (0, 1) # (0, 1)=left, (1, 0)=down, (0, -1)=right, (-1, 0)=up
while len(result) < m * n:
... | class Solution:
def spiral_order(self, matrix) -> list:
result = []
m = len(matrix)
n = len(matrix[0])
flag = [[False] * n for _ in range(m)]
i = 0
j = 0
orient = (0, 1)
while len(result) < m * n:
result.append(matrix[i][j])
fl... |
class RequireTwoFactorException(Exception):
pass
class LoginFailedException(Exception):
pass
| class Requiretwofactorexception(Exception):
pass
class Loginfailedexception(Exception):
pass |
"""
python-social-auth application, allows OpenId or OAuth user
registration/authentication just adding a few configurations.
"""
version = (0, 1, 16)
extra = ''
__version__ = '.'.join(map(str, version)) + extra
| """
python-social-auth application, allows OpenId or OAuth user
registration/authentication just adding a few configurations.
"""
version = (0, 1, 16)
extra = ''
__version__ = '.'.join(map(str, version)) + extra |
### Default Pins M5Stack bzw. Mapping auf IoTKitV3.1 small
DEFAULT_IOTKIT_LED1 = 27 # ohne Funktion - internes Neopixel verwenden
DEFAULT_IOTKIT_BUZZER = 27 # ohne Funktion - internen Vibrationsmotor verwenden
DEFAULT_IOTKIT_BUTTON1 = 39 # Pushbotton A unter Touchscreen M5Stack
# Port A
DE... | default_iotkit_led1 = 27
default_iotkit_buzzer = 27
default_iotkit_button1 = 39
default_iotkit_i2_c_sda = 32
default_iotkit_i2_c_scl = 33
default_iotkit_port_b_dac = 26
default_iotkit_port_b_adc = 27
default_iotkit_port_c_tx = 14
default_iotkit_port_c_rx = 13
default_iotkit_port_c_tx = 1
default_iotkit_port_c_rx = 3
de... |
categories = [
(82, False, "player", "defense_ast", "Assist to a tackle."),
(91, False, "player", "defense_ffum", "Defensive player forced a fumble."),
(88, False, "player", "defense_fgblk", "Defensive player blocked a field goal."),
(60, False, "player", "defense_frec", "Defensive player recovered a fu... | categories = [(82, False, 'player', 'defense_ast', 'Assist to a tackle.'), (91, False, 'player', 'defense_ffum', 'Defensive player forced a fumble.'), (88, False, 'player', 'defense_fgblk', 'Defensive player blocked a field goal.'), (60, False, 'player', 'defense_frec', 'Defensive player recovered a fumble by the oppos... |
"""
https://leetcode.com/problems/container-with-most-water/
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such... | """
https://leetcode.com/problems/container-with-most-water/
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such... |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
"""
Stubs for testing cloudformation.py
"""
describe_stack = {
'Stacks': [{
'Outputs': [{
'OutputKey': "DeploymentFrameworkRegionalKMSKey",
'OutputValue': "some_key_arn"
... | """
Stubs for testing cloudformation.py
"""
describe_stack = {'Stacks': [{'Outputs': [{'OutputKey': 'DeploymentFrameworkRegionalKMSKey', 'OutputValue': 'some_key_arn'}, {'OutputKey': 'DeploymentFrameworkRegionalS3Bucket', 'OutputValue': 'some_bucket_name'}], 'StackStatus': 'CREATE_IN_PROGRESS'}]} |
JAVA_EXEC_LABEL="//third_party/openjdk:java"
PHASICJ_AGENT_LABEL="//phasicj/agent:libpjagent"
RENAISSANCE_JAR_LABEL="//third_party/renaissance:jar"
RENAISSANCE_MAIN_CLASS="org.renaissance.core.Launcher"
PHASICJ_EXEC="//phasicj/cli"
EXTRA_PHASICJ_AGENT_OPTIONS="verbose"
def smoke_test_benchmark(name):
native.sh_tes... | java_exec_label = '//third_party/openjdk:java'
phasicj_agent_label = '//phasicj/agent:libpjagent'
renaissance_jar_label = '//third_party/renaissance:jar'
renaissance_main_class = 'org.renaissance.core.Launcher'
phasicj_exec = '//phasicj/cli'
extra_phasicj_agent_options = 'verbose'
def smoke_test_benchmark(name):
n... |
__author__ = """Christopher Bevan Barnett"""
__email__ = 'chrisbarnettster@gmail.com'
__version__ = '0.3.7'
| __author__ = 'Christopher Bevan Barnett'
__email__ = 'chrisbarnettster@gmail.com'
__version__ = '0.3.7' |
def trace(func):
def wrapper():
func_name = func.__name__
print(f'Entering "{func_name}" function')
func()
print(f'Exiting from "{func_name}" function')
return wrapper
def say_hello():
print('Hello!')
say_hello = trace(say_hello)
say_hello()
| def trace(func):
def wrapper():
func_name = func.__name__
print(f'Entering "{func_name}" function')
func()
print(f'Exiting from "{func_name}" function')
return wrapper
def say_hello():
print('Hello!')
say_hello = trace(say_hello)
say_hello() |
# Copyright 2019 Erik Maciejewski
#
# 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 writi... | """system file creation rules"""
nobody = 65534
nonroot = 65532
def _pad(max_len, text, extra=' '):
pad_spcs = max_len - len(text)
if pad_spcs <= 0:
return extra
return ''.join([' ' for i in range(0, pad_spcs)]) + extra
def _nsswitch_conf_file_impl(ctx):
doc = '# /etc/nsswitch.conf\n#\n# ge... |
bitcoin = int(input())
yuans = float(input())
commission = float(input()) / 100
bitcoin_lv = bitcoin * 1168
yuans_dollars = yuans * (0.15 * 1.76)
sum_lv = bitcoin_lv + yuans_dollars
sum_eur = sum_lv / 1.95
sum_eur = round(sum_eur - (commission * sum_eur), 2)
print(sum_eur)
| bitcoin = int(input())
yuans = float(input())
commission = float(input()) / 100
bitcoin_lv = bitcoin * 1168
yuans_dollars = yuans * (0.15 * 1.76)
sum_lv = bitcoin_lv + yuans_dollars
sum_eur = sum_lv / 1.95
sum_eur = round(sum_eur - commission * sum_eur, 2)
print(sum_eur) |
"""The simplest data reader."""
for line in open('ice-cream.csv'):
row = line.split(',')
print(row)
| """The simplest data reader."""
for line in open('ice-cream.csv'):
row = line.split(',')
print(row) |
description = 'Neutron Grating Interferometer'
group = 'optional'
tango_base = 'tango://antareshw.antares.frm2.tum.de:10000/antares/'
devices = dict(
G0rz = device('nicos.devices.entangle.Motor',
speed = 1,
unit = 'deg',
description = 'Rotation of G0 grating around beam direction',
... | description = 'Neutron Grating Interferometer'
group = 'optional'
tango_base = 'tango://antareshw.antares.frm2.tum.de:10000/antares/'
devices = dict(G0rz=device('nicos.devices.entangle.Motor', speed=1, unit='deg', description='Rotation of G0 grating around beam direction', tangodevice=tango_base + 'fzjs7/G0rz', abslimi... |
# -*- coding: utf-8 -*-
# coding: utf8
@auth.requires_membership('admin')
def index():
return locals()
@auth.requires_membership('admin')
def products():
products_grid = SQLFORM.grid(db.product, csv=False)
return locals()
@auth.requires_membership('admin')
def product_categories():
categories_grid... | @auth.requires_membership('admin')
def index():
return locals()
@auth.requires_membership('admin')
def products():
products_grid = SQLFORM.grid(db.product, csv=False)
return locals()
@auth.requires_membership('admin')
def product_categories():
categories_grid = SQLFORM.grid(db.category, csv=False)
... |
num = int(input("Insert some numbers: "))
even = 0
odd = 0
while num > 0:
if num%2 == 0:
even += 1
else:
odd += 1
num = num//10
print("Even numbers = %d, Odd numbers = %d" % (even,odd))
| num = int(input('Insert some numbers: '))
even = 0
odd = 0
while num > 0:
if num % 2 == 0:
even += 1
else:
odd += 1
num = num // 10
print('Even numbers = %d, Odd numbers = %d' % (even, odd)) |
"""A board is a list of list of str. For example, the board
ANTT
XSOB
is represented as the list
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
A word list is a list of str. For example, the list of words
ANT
BOX
SOB
TO
is represented as the list
['ANT', 'BOX', 'SOB', 'TO']
"""
def is_v... | """A board is a list of list of str. For example, the board
ANTT
XSOB
is represented as the list
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
A word list is a list of str. For example, the list of words
ANT
BOX
SOB
TO
is represented as the list
['ANT', 'BOX', 'SOB', 'TO']
"""
def is_va... |
def foo(x = []):
return x.append("x")
def bar(x = []):
return len(x)
foo()
bar()
class Owner(object):
@classmethod
def cm(cls, arg):
return cls
@classmethod
def cm2(cls, arg):
return arg
#Normal method
def m(self):
a = self.cm(0)
return a.cm2(1)
| def foo(x=[]):
return x.append('x')
def bar(x=[]):
return len(x)
foo()
bar()
class Owner(object):
@classmethod
def cm(cls, arg):
return cls
@classmethod
def cm2(cls, arg):
return arg
def m(self):
a = self.cm(0)
return a.cm2(1) |
#sequence cleaner removes sequences that are ambiguous (6-mer appending the poly sequence is indefinite ("N") and shifts all "N" characters
#in poly sequence right so that they can be combined
def sequenceCleaner(string):
if len(string) < 13:
return "", 0
if string[5] == "*":
return "", 0
if string[len(string)-... | def sequence_cleaner(string):
if len(string) < 13:
return ('', 0)
if string[5] == '*':
return ('', 0)
if string[len(string) - 6] == '*':
return ('', 0)
if not '*' in string[6:len(string) - 6]:
return (string[6:len(string) - 6], len(string) - 12)
else:
return r... |
# Copyright 2015 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law ... | load('@io_bazel_rules_scala//scala:scala_maven_import_external.bzl', _scala_maven_import_external='scala_maven_import_external')
'Helper functions for Scala cross-version support. Encapsulates the logic\nof abstracting over Scala major version (2.11, 2.12, etc) for dependency\nresolution.'
def default_scala_version():... |
def fibonaci(n):
if n <= 1:
return n
else:
return fibonaci(n-1)+fibonaci(n-2)
fibonaci(0) | def fibonaci(n):
if n <= 1:
return n
else:
return fibonaci(n - 1) + fibonaci(n - 2)
fibonaci(0) |
class Position:
def __init__(self, idx, ln, col, fn, ftxt) -> None:
self.idx = idx
self.ln = ln
self.col = col
self.fn = fn
self.ftxt = ftxt
def advance(self, current_char=None):
self.idx += 1
self.col += 1
if current_char == "\n":
se... | class Position:
def __init__(self, idx, ln, col, fn, ftxt) -> None:
self.idx = idx
self.ln = ln
self.col = col
self.fn = fn
self.ftxt = ftxt
def advance(self, current_char=None):
self.idx += 1
self.col += 1
if current_char == '\n':
se... |
def on_config():
# Here you can do all you want.
print("Called.")
def on_config_with_config(config):
print("Called with config.")
print(config["docs_dir"])
# You can change config, for example:
# config['docs_dir'] = 'other_directory'
# Optionally, you can return altered config to custom... | def on_config():
print('Called.')
def on_config_with_config(config):
print('Called with config.')
print(config['docs_dir'])
def on_config_with_mkapi(config, mkapi):
print('Called with config and mkapi.')
print(config['docs_dir'])
print(mkapi) |
##########################################################################
# Copyright (c) 2018-2019 NVIDIA Corporation. 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
#... | cuda_acceptable_src_extensions = ['.cu', '.c', '.cc', '.cxx', '.cpp']
cuda_acceptable_hdr_extensions = ['.h', '.cuh', '.hpp', '.inl']
cuda_acceptable_bin_extensions = ['.ptx', '.cubin', '.fatbin', '.o', '.obj', '.a', '.lib', '.res', '.so']
cuda_acceptable_extensions = CUDA_ACCEPTABLE_SRC_EXTENSIONS + CUDA_ACCEPTABLE_BI... |
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
my_car = Car("Chevv", "GOLDEN", 1933)
print(my_car.model)
print(my_car.color)
print(my_car.mpg)
| class Car(object):
condition = 'new'
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
my_car = car('Chevv', 'GOLDEN', 1933)
print(my_car.model)
print(my_car.color)
print(my_car.mpg) |
def validate(name, bracket, bracket_side, bfr):
"""
Check if bracket is lowercase
"""
return bfr[bracket.begin:bracket.end].islower()
| def validate(name, bracket, bracket_side, bfr):
"""
Check if bracket is lowercase
"""
return bfr[bracket.begin:bracket.end].islower() |
def add(a, b) :
s = a + b
return s
#main app begins here
x = 2
y = 3
z = add(x, y)
print('Sum : ', z) | def add(a, b):
s = a + b
return s
x = 2
y = 3
z = add(x, y)
print('Sum : ', z) |
#service.process.factory.proc_provider_factories
class ProcProviderFactories(object):
def __init__(self, log):
self._log = log
self._factory = None
def get_factory(self, process):
#should instantiate the teradata factory
if self._factory is None:
tmp = __import__('s... | class Procproviderfactories(object):
def __init__(self, log):
self._log = log
self._factory = None
def get_factory(self, process):
if self._factory is None:
tmp = __import__('service.process.factory.' + process.name.lower(), fromlist=[process.name + 'Factory'])
... |
# Time: ls: O(l + klogk), l is the path length, k is the number of entries in the last level directory
# mkdir: O(l)
# addContentToFile: O(l + c), c is the content size
# readContentFromFile: O(l + c)
# Space: O(n + s), n is the number of dir/file nodes, s is the total content size.
# Design an i... | class Trienode(object):
def __init__(self):
self.is_file = False
self.children = {}
self.content = ''
class Filesystem(object):
def __init__(self):
self.__root = trie_node()
def ls(self, path):
"""
:type path: str
:rtype: List[str]
"""
... |
def get_input():
file = open('inputs/bubble_sort.txt')
input = file.read()
file.close()
return input
def bubble_sort(a, n):
swap_count = 0
is_sorted = False
while not is_sorted:
is_sorted = True
for i in range(n-1):
if a[i] > a[i + 1]:
temp = a[i... | def get_input():
file = open('inputs/bubble_sort.txt')
input = file.read()
file.close()
return input
def bubble_sort(a, n):
swap_count = 0
is_sorted = False
while not is_sorted:
is_sorted = True
for i in range(n - 1):
if a[i] > a[i + 1]:
temp = a[... |
PROJECT_ID_LIST_URL = "https://cloudresourcemanager.googleapis.com/v1/projects"
HTTP_GET_METHOD = "GET"
class UtilBase(object):
def __init__(self, config):
self.config = config
self.__projectList = None
def getProjectList(self):
if self.__projectList != None:
return self._... | project_id_list_url = 'https://cloudresourcemanager.googleapis.com/v1/projects'
http_get_method = 'GET'
class Utilbase(object):
def __init__(self, config):
self.config = config
self.__projectList = None
def get_project_list(self):
if self.__projectList != None:
return self... |
NAME='logzmq'
CFLAGS = []
LDFLAGS = []
LIBS = ['-lzmq']
GCC_LIST = ['plugin']
| name = 'logzmq'
cflags = []
ldflags = []
libs = ['-lzmq']
gcc_list = ['plugin'] |
test = {
'name': 'Problem EC',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> # Testing status parameters
>>> slow = SlowThrower()
>>> scary = ScaryThrower()
>>> SlowThrower.food_cost
4
>>> ScaryThrower.food_cost
... | test = {'name': 'Problem EC', 'points': 2, 'suites': [{'cases': [{'code': '\n >>> # Testing status parameters\n >>> slow = SlowThrower()\n >>> scary = ScaryThrower()\n >>> SlowThrower.food_cost\n 4\n >>> ScaryThrower.food_cost\n 6\n >>> slow.armor\... |
# Copyright 2017 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.
DEPS = [
'chromium',
'chromium_android',
'depot_tools/bot_update',
'depot_tools/gclient',
]
def RunSteps(api):
api.gclient.set_config('chromium')... | deps = ['chromium', 'chromium_android', 'depot_tools/bot_update', 'depot_tools/gclient']
def run_steps(api):
api.gclient.set_config('chromium')
api.chromium.set_config('chromium')
update_step = api.bot_update.ensure_checkout()
api.chromium_android.upload_apks_for_bisect(update_properties=update_step.js... |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
if root:
root.left, root.right = self.solve(root.right), self.solve(root.left)
return root
| class Solution:
def solve(self, root):
if root:
(root.left, root.right) = (self.solve(root.right), self.solve(root.left))
return root |
products = ['bread','meat','egg','cheese']
file1 = open('products.txt','w')
for product in products:
file1.write(product+'\n')
file1.close()
file2= open('products.txt')
var = file2.readlines()
print(var)
| products = ['bread', 'meat', 'egg', 'cheese']
file1 = open('products.txt', 'w')
for product in products:
file1.write(product + '\n')
file1.close()
file2 = open('products.txt')
var = file2.readlines()
print(var) |
class Layer(object):
def __init__(self):
self.prevlayer = None
self.nextlayer = None
def forepropagation(self):
pass
def backpropagation(self):
pass
def initialization(self):
pass
| class Layer(object):
def __init__(self):
self.prevlayer = None
self.nextlayer = None
def forepropagation(self):
pass
def backpropagation(self):
pass
def initialization(self):
pass |
def collapse_sequences(message, collapse_char, collapsing = False):
if message == '':
return ''
# Approach 1:
prepend = message[0]
if prepend == collapse_char:
if collapsing:
prepend = ''
collapsing = True
else:
collapsing = False
return prepend ... | def collapse_sequences(message, collapse_char, collapsing=False):
if message == '':
return ''
prepend = message[0]
if prepend == collapse_char:
if collapsing:
prepend = ''
collapsing = True
else:
collapsing = False
return prepend + collapse_sequences(messa... |
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
minval=100000
nums.sort()
for i in range(len(nums)):
#if i>0 and num[i]==num[i-1]:
# continue
le... | class Solution:
def three_sum_closest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
minval = 100000
nums.sort()
for i in range(len(nums)):
left = i + 1
right = len(nums) - 1
while ... |
# Zombie Damage Skin
success = sm.addDamageSkin(2434661)
if success:
sm.chat("The Zombie Damage Skin has been added to your account's damage skin collection.")
| success = sm.addDamageSkin(2434661)
if success:
sm.chat("The Zombie Damage Skin has been added to your account's damage skin collection.") |
#
# Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... | {'includes': ['../build/features.gypi', '../build/scripts/scripts.gypi', '../build/win/precompile.gypi', 'blink_platform.gypi', 'heap/blink_heap.gypi'], 'targets': [{'target_name': 'blink_common', 'type': '<(component)', 'variables': {'enable_wexit_time_destructors': 1}, 'dependencies': ['../config.gyp:config', '../wtf... |
def poscode2word(pos):
tag_des = {
'CC': 'Coordinating conjunction',
'CD': 'Cardinal number',
'DT': 'Determiner',
'EX': 'Existential',
'FW': 'Foreign word',
'IN': 'Preposition',
'JJ': 'Adjective',
'JJR': 'Adjective, comparative',
'JJS': 'Adject... | def poscode2word(pos):
tag_des = {'CC': 'Coordinating conjunction', 'CD': 'Cardinal number', 'DT': 'Determiner', 'EX': 'Existential', 'FW': 'Foreign word', 'IN': 'Preposition', 'JJ': 'Adjective', 'JJR': 'Adjective, comparative', 'JJS': 'Adjective, superlative', 'LS': 'List item maker', 'MD': 'Modal', 'NN': 'Noun, s... |
"""
Faster R-CNN with DIOU Assigner
Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.054
Average Precision (AP) @[ IoU=0.25 | area= all | maxDets=1500 ] = -1.000
Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.113
Average Precision (AP) @[ IoU=0.75 |... | """
Faster R-CNN with DIOU Assigner
Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.054
Average Precision (AP) @[ IoU=0.25 | area= all | maxDets=1500 ] = -1.000
Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.113
Average Precision (AP) @[ IoU=0.75 |... |
def part1(arr):
s = 0
for v in arr:
s += v // 3 - 2
return s
def part2(arr):
s = 0
for v in arr:
fuel = v // 3 - 2
s += fuel
while fuel > 0:
fuel = fuel // 3 - 2
if fuel > 0:
s += fuel
return s
def day1():
arr = [
... | def part1(arr):
s = 0
for v in arr:
s += v // 3 - 2
return s
def part2(arr):
s = 0
for v in arr:
fuel = v // 3 - 2
s += fuel
while fuel > 0:
fuel = fuel // 3 - 2
if fuel > 0:
s += fuel
return s
def day1():
arr = [80891... |
BASE_JSON_PATH = '/home/mdd36/tools350/tools350/assembler/base_jsn'
BASE_JSON_LOCAL = '/Users/matthew/Documents/SchoolWork/TA/ECE350/2019s/350_tools_mk2/tools350/assembler/base_jsn'
class InstructionType:
def __init__(self, types: dict):
self._instruction_types: dict = types
def get_by_type(self, ty... | base_json_path = '/home/mdd36/tools350/tools350/assembler/base_jsn'
base_json_local = '/Users/matthew/Documents/SchoolWork/TA/ECE350/2019s/350_tools_mk2/tools350/assembler/base_jsn'
class Instructiontype:
def __init__(self, types: dict):
self._instruction_types: dict = types
def get_by_type(self, typ... |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def inorder(root):
if root is None:
return ""
res = ""
res += inorder(root.left)
res += "{} ".format(root.data)
res += inorder(root.right)
return res
def all_subtree... | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def inorder(root):
if root is None:
return ''
res = ''
res += inorder(root.left)
res += '{} '.format(root.data)
res += inorder(root.right)
return res
def all_subtree(r... |
test = {
'name': 'Problem 6',
'points': 1,
'suites': [
{
'cases': [
{
'answer': 'fd4dd892ccea3adcf9446dc4a9738d47',
'choices': [
r"""
Pair('quote', Pair(A, nil)), where:
A is the quoted expression
""",
r"""
... | test = {'name': 'Problem 6', 'points': 1, 'suites': [{'cases': [{'answer': 'fd4dd892ccea3adcf9446dc4a9738d47', 'choices': ["\n Pair('quote', Pair(A, nil)), where:\n A is the quoted expression\n ", '\n [A], where:\n A is the quoted expression\n ',... |
for i in range(int(input())):
sum = 0
y, x = map(int, input().split())
n = max(x,y)
sum += (n-1) * (n-1)
if n%2!=0:
sum += x + (n-y)
else:
sum += y + (n-x)
print(sum)
| for i in range(int(input())):
sum = 0
(y, x) = map(int, input().split())
n = max(x, y)
sum += (n - 1) * (n - 1)
if n % 2 != 0:
sum += x + (n - y)
else:
sum += y + (n - x)
print(sum) |
entries = [1, 2, 3, 4, 5]
print("all: {}".format(all(entries)))
print("any: {}".format(any(entries)))
print("Iterable with a 'False' value")
entries_with_zero = [1, 2, 0, 4, 5]
print("all: {}".format(all(entries_with_zero)))
print("any: {}".format(any(entries_with_zero)))
print()
print("Values interpreted as False i... | entries = [1, 2, 3, 4, 5]
print('all: {}'.format(all(entries)))
print('any: {}'.format(any(entries)))
print("Iterable with a 'False' value")
entries_with_zero = [1, 2, 0, 4, 5]
print('all: {}'.format(all(entries_with_zero)))
print('any: {}'.format(any(entries_with_zero)))
print()
print('Values interpreted as False in P... |
# -*- coding: utf-8 -*-
#
# PySceneDetect: Python-Based Video Scene Detector
# ---------------------------------------------------------------
# [ Site: http://www.bcastell.com/projects/PySceneDetect/ ]
# [ Github: https://github.com/Breakthrough/PySceneDetect/ ]
# [ Documentation: http://py... | """ Module: ``scenedetect.thirdparty``
This module includes all third-party libraries/dependencies that are distributed
with PySceneDetect. The source directory also includes the license files for all
packages that PySceneDetect depends on, to simplify distribution of binary builds.
""" |
class Solution(object):
def buddyStrings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A) != len(B):
return False
a, b, sa = [], [], set()
for i in range(0, len(A)):
if A[i] != B[i]:
a.append... | class Solution(object):
def buddy_strings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A) != len(B):
return False
(a, b, sa) = ([], [], set())
for i in range(0, len(A)):
if A[i] != B[i]:
a.... |
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
if len(J)==0 or len(S)==0:
return 0
answer=0
J_set = set(J)
for char in S:
if char in J_set:
answer... | class Solution(object):
def num_jewels_in_stones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
if len(J) == 0 or len(S) == 0:
return 0
answer = 0
j_set = set(J)
for char in S:
if char in J_set:
... |
class GetCashgramStatus:
end_point = "/payout/v1/getCashgramStatus"
req_type = "GET"
def __init__(self, *args, **kwargs):
self.cashgramId = kwargs["cashgramId"] | class Getcashgramstatus:
end_point = '/payout/v1/getCashgramStatus'
req_type = 'GET'
def __init__(self, *args, **kwargs):
self.cashgramId = kwargs['cashgramId'] |
# ------------------------------
# 25. Reverse Nodes in k-Group
#
# Description:
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
# k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then l... | class Solution(object):
def reverse_k_group(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
pointer = {}
if not head:
return None
else:
i = 0
temp = head
while temp and i < k:
... |
description = 'Small Beam Limiter in Experimental Chamber 1'
group = 'optional'
devices = dict(
nbl_l = device('nicos.devices.generic.VirtualReferenceMotor',
description = 'Beam Limiter Left Blade',
lowlevel = True,
abslimits = (-250, 260),
unit = 'mm',
speed = 10,
... | description = 'Small Beam Limiter in Experimental Chamber 1'
group = 'optional'
devices = dict(nbl_l=device('nicos.devices.generic.VirtualReferenceMotor', description='Beam Limiter Left Blade', lowlevel=True, abslimits=(-250, 260), unit='mm', speed=10, refswitch='high'), nbl_r=device('nicos.devices.generic.VirtualRefer... |
async def test_admin_auth(client, admin, user):
res = await client.get('/admin', follow_redirect=False)
assert res.status_code == 307
# Login as an simple user
res = await client.post('/login', data={'email': user.email, 'password': 'pass'})
assert res.status_code == 200
res = await client.get... | async def test_admin_auth(client, admin, user):
res = await client.get('/admin', follow_redirect=False)
assert res.status_code == 307
res = await client.post('/login', data={'email': user.email, 'password': 'pass'})
assert res.status_code == 200
res = await client.get('/admin', follow_redirect=False... |
# https://edabit.com/challenge/Yj2Rew5XQYpu7Nosq
# Create a function that returns the number of frames shown in a given number of minutes for a certain FPS.
def frames(minutes: int, fps: int) -> int:
try:
total_frames = (minutes * 60) * fps
return total_frames
except TypeError as err:
... | def frames(minutes: int, fps: int) -> int:
try:
total_frames = minutes * 60 * fps
return total_frames
except TypeError as err:
print(f'Error: {err}')
print(frames(1, 1))
print(frames(10, 1))
print(frames(10, 25))
print(frames('a', 'b')) |
"""
HTTP/1.0 301 Moved Permanently
Location: http://www.google.ca/
Content-Type: text/html; charset=UTF-8
Date: Wed, 03 Oct 2018 19:51:01 GMT
Expires: Fri, 02 Nov 2018 19:51:01 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 218
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
<HTML><... | """
HTTP/1.0 301 Moved Permanently
Location: http://www.google.ca/
Content-Type: text/html; charset=UTF-8
Date: Wed, 03 Oct 2018 19:51:01 GMT
Expires: Fri, 02 Nov 2018 19:51:01 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 218
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
<HTML><... |
class Node():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def __str__(self):
current = self.head
output = ''
while current:
output += f"{ {str(current.value)} } ->"
... | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def __str__(self):
current = self.head
output = ''
while current:
output += f'{ {str(current.value)}} ->'
... |
list_one = [1, 2, 3]
list_two = [4, 5, 6,7]
lst = [0, *list_one, *list_two]
print(lst)
country_lst_one = ['Finland', 'Sweden', 'Norway']
country_lst_two = ['Denmark', 'Iceland']
nordic_countries = [*country_lst_one, *country_lst_two]
print(nordic_countries)
| list_one = [1, 2, 3]
list_two = [4, 5, 6, 7]
lst = [0, *list_one, *list_two]
print(lst)
country_lst_one = ['Finland', 'Sweden', 'Norway']
country_lst_two = ['Denmark', 'Iceland']
nordic_countries = [*country_lst_one, *country_lst_two]
print(nordic_countries) |
input = """
a(1) | a(3).
a(2).
c(1,1).
c(1,3).
d(1,5).
b(X) :- a(X), c(Y,X).
ok :- #max{V :b(V)} < X, d(Y,X).
"""
output = """
a(1) | a(3).
a(2).
c(1,1).
c(1,3).
d(1,5).
b(X) :- a(X), c(Y,X).
ok :- #max{V :b(V)} < X, d(Y,X).
"""
| input = '\na(1) | a(3).\na(2).\nc(1,1).\nc(1,3).\nd(1,5).\n\nb(X) :- a(X), c(Y,X).\n\nok :- #max{V :b(V)} < X, d(Y,X).\n'
output = '\na(1) | a(3).\na(2).\nc(1,1).\nc(1,3).\nd(1,5).\n\nb(X) :- a(X), c(Y,X).\n\nok :- #max{V :b(V)} < X, d(Y,X).\n' |
offices=[]
expected_offices = ("Federal", "Legislative", "State", "Local Government")
class PoliticalOffice():
@staticmethod
def exists(name):
"""
Checks if an office with the same name exists
Returns a boolean
"""
for office in offices:
if office["name"] ==... | offices = []
expected_offices = ('Federal', 'Legislative', 'State', 'Local Government')
class Politicaloffice:
@staticmethod
def exists(name):
"""
Checks if an office with the same name exists
Returns a boolean
"""
for office in offices:
if office['name'] ==... |
"""
Queue.py
Description: This file contains the implementation of the queue data structure
"""
# The queue class is used to implement functionality of a queue using a list
class Queue:
# Default constructor
def __init__(self):
self.items = []
# Function used to tell us if the queue i... | """
Queue.py
Description: This file contains the implementation of the queue data structure
"""
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return ... |
# https://www.codechef.com/problems/DEVARRAY
n,Q=map(int,input().split())
max1,min1,a=-99999999999,99999999999,list(map(int,input().split()))
for z in range(n): min1,max1 = min(min1,a[z]),max(max1,a[z])
for z in range(Q): print("Yes") if(int(input()) in range(min1,max1+1)) else print("No") | (n, q) = map(int, input().split())
(max1, min1, a) = (-99999999999, 99999999999, list(map(int, input().split())))
for z in range(n):
(min1, max1) = (min(min1, a[z]), max(max1, a[z]))
for z in range(Q):
print('Yes') if int(input()) in range(min1, max1 + 1) else print('No') |
"""Task:"""
# Imports --------------------------------------------------------------
# Classes --------------------------------------------------------------
# Functions ------------------------------------------------------------
# Methods --------------------------------------------------------------
# Defin... | """Task:""" |
# Hash Table
# A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.co... | class Solution:
def subdomain_visits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
pair = collections.defaultdict(int)
for item in cpdomains:
(link_value, link) = item.split()
link_value = int(linkValue)
pa... |
class Solution(object):
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
st = 0
ed = len(nums) - 1
if nums[st] != nums[st + 1]:
return nums[st]
if nums[ed] !... | class Solution(object):
def single_non_duplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
st = 0
ed = len(nums) - 1
if nums[st] != nums[st + 1]:
return nums[st]
if nums[ed... |
_base_ = [
'../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py'
]
# model settings
model = dict(
type='CenterNet',
pretrained='torchvision://resnet18',
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages... | _base_ = ['../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py']
model = dict(type='CenterNet', pretrained='torchvision://resnet18', backbone=dict(type='ResNet', depth=18, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, zero_init_... |
class CTX:
"""
Global Class holding the configuration of the backward pass
"""
active_exts = tuple()
debug = False
@staticmethod
def set_active_exts(active_exts):
CTX.active_exts = tuple()
for act_ext in active_exts:
CTX.active_exts += (act_ext,)
@staticmet... | class Ctx:
"""
Global Class holding the configuration of the backward pass
"""
active_exts = tuple()
debug = False
@staticmethod
def set_active_exts(active_exts):
CTX.active_exts = tuple()
for act_ext in active_exts:
CTX.active_exts += (act_ext,)
@staticmeth... |
# Copyright (c) 2012 OpenStack, LLC.
#
# 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 wr... | extended_attributes_2_0 = {'networks': {'v2attrs:something': {'allow_post': False, 'allow_put': False, 'is_visible': True}, 'v2attrs:something_else': {'allow_post': True, 'allow_put': False, 'is_visible': False}}}
class V2Attributes(object):
def get_name(self):
return 'V2 Extended Attributes Example'
... |
class HostVisual(ContainerVisual,IResource):
"""
Represents a System.Windows.Media.Visual object that can be connected anywhere to a parent visual tree.
HostVisual()
"""
def AddVisualChild(self,*args):
"""
AddVisualChild(self: Visual,child: Visual)
Defines the parent-child relationship between... | class Hostvisual(ContainerVisual, IResource):
"""
Represents a System.Windows.Media.Visual object that can be connected anywhere to a parent visual tree.
HostVisual()
"""
def add_visual_child(self, *args):
"""
AddVisualChild(self: Visual,child: Visual)
Defines the parent-child relationship... |
# Python Program to subtract two numbers
# Store input numbers
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
# Sub two numbers
sub = float(num1) - float(num2)
# Display the sub
print("The sub of {0} and {1} is {2}".format(num1, num2, sub))
| num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
sub = float(num1) - float(num2)
print('The sub of {0} and {1} is {2}'.format(num1, num2, sub)) |
BACKTEST_FLOW_OK = {
"nodeList": {
"1": {
"blockType": "DATA_BLOCK",
"blockId": 1,
"equity_name": {"options": ["AAPL"], "value": ""},
"data_type": {"options": ["intraday", "daily_adjusted"], "value": ""},
"interval": {"options": ["1min"], "value": ... | backtest_flow_ok = {'nodeList': {'1': {'blockType': 'DATA_BLOCK', 'blockId': 1, 'equity_name': {'options': ['AAPL'], 'value': ''}, 'data_type': {'options': ['intraday', 'daily_adjusted'], 'value': ''}, 'interval': {'options': ['1min'], 'value': ''}, 'outputsize': {'options': ['compact', 'full'], 'value': ''}, 'start_da... |
numbers = [14, 2,3,4,5,6,7,6,5,7,8,8,9,10,11,12,13,14,14]
numbers2 =[]
for number in numbers:
if number not in numbers2:
numbers2.append(number)
print(numbers2) | numbers = [14, 2, 3, 4, 5, 6, 7, 6, 5, 7, 8, 8, 9, 10, 11, 12, 13, 14, 14]
numbers2 = []
for number in numbers:
if number not in numbers2:
numbers2.append(number)
print(numbers2) |
def solution(n: int) -> int:
b = to_bin(n)
if len(b) < 3:
return 0
gaps = []
gap_count = 0
for i in range(len(b)):
if b[i] == "1":
# gap stop. save gap and start counting again
gaps.append(gap_count)
# reset gap count
gap_count = 0
... | def solution(n: int) -> int:
b = to_bin(n)
if len(b) < 3:
return 0
gaps = []
gap_count = 0
for i in range(len(b)):
if b[i] == '1':
gaps.append(gap_count)
gap_count = 0
else:
gap_count += 1
print(gaps)
return max(gaps)
def solution2... |
class MyClass:
print('MyClass created')
# instansiate a class
my_var = MyClass()
print(type(my_var))
print(dir(my_var)) | class Myclass:
print('MyClass created')
my_var = my_class()
print(type(my_var))
print(dir(my_var)) |
"""Provides a redirection point for platform specific implementations of starlark utilities."""
load(
"//tensorflow/core/platform:default/build_config.bzl",
_pyx_library = "pyx_library",
_tf_additional_all_protos = "tf_additional_all_protos",
_tf_additional_binary_deps = "tf_additional_binary_deps",
... | """Provides a redirection point for platform specific implementations of starlark utilities."""
load('//tensorflow/core/platform:default/build_config.bzl', _pyx_library='pyx_library', _tf_additional_all_protos='tf_additional_all_protos', _tf_additional_binary_deps='tf_additional_binary_deps', _tf_additional_core_deps='... |
"""Should raise SyntaxError: name 'cc' is assigned to prior to global declaration
"""
aa, bb, cc, dd = 1, 2, 3, 4
def fn():
cc = 1
global aa, bb, cc, dd
| """Should raise SyntaxError: name 'cc' is assigned to prior to global declaration
"""
(aa, bb, cc, dd) = (1, 2, 3, 4)
def fn():
cc = 1
global aa, bb, cc, dd |
class BTNode:
__slots__ = "value", "left", "right"
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def test_BTNode():
parent = BTNode(10)
left = BTNode(20)
right = BTNode(30)
parent.left = left
parent.right =... | class Btnode:
__slots__ = ('value', 'left', 'right')
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def test_bt_node():
parent = bt_node(10)
left = bt_node(20)
right = bt_node(30)
parent.left = left
parent.ri... |
"""
Convenience classes for returning multiple values from functions
Examples:
Success w/ data: return ok_resp(some_obj)
Success w/ data and a message: return ok_resp(some_obj, 'It worked')
Error w/ message: return err_resp('some error message')
Error w/ message and data: return err_resp('some error m... | """
Convenience classes for returning multiple values from functions
Examples:
Success w/ data: return ok_resp(some_obj)
Success w/ data and a message: return ok_resp(some_obj, 'It worked')
Error w/ message: return err_resp('some error message')
Error w/ message and data: return err_resp('some error m... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
DEBUG = True
USE_TZ = True
SECRET_KEY = "KEY"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
ROOT_URLCONF = "tests.urls"
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.messages",
"d... | debug = True
use_tz = True
secret_key = 'KEY'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
root_urlconf = 'tests.urls'
installed_apps = ['django.contrib.admin', 'django.contrib.messages', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.co... |
#!/home/rob/.pyenv/shims/python3
def example(param):
"""param must be greater than 0"""
assert param > 0
#if __debug__:
# if not param > 0:
# raise AssertionError
# do stuff here...
if __name__ == '__main__':
example(0) | def example(param):
"""param must be greater than 0"""
assert param > 0
if __name__ == '__main__':
example(0) |
"""
VIS_DATA
"""
#def get_img_figure(n_subplots=1):
def plot_img(ax, img, **kwargs):
title = kwargs.pop('title', 'Image')
ax.imshow(img)
ax.set_title(title)
| """
VIS_DATA
"""
def plot_img(ax, img, **kwargs):
title = kwargs.pop('title', 'Image')
ax.imshow(img)
ax.set_title(title) |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Configuration file
The PlanHeat tool was implemented as part of the PLANHEAT project.
This file contains several global variables used inside the different sub-modules.
-------------... | """
/***************************************************************************
Configuration file
The PlanHeat tool was implemented as part of the PLANHEAT project.
This file contains several global variables used inside the different sub-modules.
-------------------
begin ... |
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
n = len(prices)
if n < 2:
return 0
min_price = prices[0]
res = 0
for i in xrange(1, n):
res = max(res, prices[i]-min_price)
min_pr... | class Solution:
def max_profit(self, prices):
n = len(prices)
if n < 2:
return 0
min_price = prices[0]
res = 0
for i in xrange(1, n):
res = max(res, prices[i] - min_price)
min_price = min(min_price, prices[i])
return res |
# Python 3: Simple output (with Unicode)
print("Hello, I'm Python!")
# Input, assignment
name = input('What is your name?\n')
print('Hi, %s.' % name)
| print("Hello, I'm Python!")
name = input('What is your name?\n')
print('Hi, %s.' % name) |
# Time complexity: O(n) where n is number of nodes in Tree
# Approach: Checking binary search tree conditions on each node recursively.
# 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... | class Solution:
def is_valid_bst(self, root: Optional[TreeNode], l=-2 ** 31 - 1, r=2 ** 31) -> bool:
if not root:
return True
elif l < root.val and root.val < r:
return self.isValidBST(root.left, l, root.val) and self.isValidBST(root.right, root.val, r)
return False |
"""
1. Clarification
2. Possible solutions
- simulation
- math
3. Coding
4. Tests
"""
# T=O(n), S=O(n)
class Solution:
def totalMoney(self, n: int) -> int:
return sum(i%7 + 1 + i//7 for i in range(n))
# # T=O(1), S=O(1)
# class Solution:
# def totalMoney(self, n: int) -> int:
# extra, weeks ... | """
1. Clarification
2. Possible solutions
- simulation
- math
3. Coding
4. Tests
"""
class Solution:
def total_money(self, n: int) -> int:
return sum((i % 7 + 1 + i // 7 for i in range(n))) |
class Node():
def __init__(self):
self.children = {}
self.endofword = False
self.string = ""
class Trie():
def __init__(self):
self.root = Node()
def insert(self, word):
pointer = self.root
for char in word:
if char not in pointer.children:
... | class Node:
def __init__(self):
self.children = {}
self.endofword = False
self.string = ''
class Trie:
def __init__(self):
self.root = node()
def insert(self, word):
pointer = self.root
for char in word:
if char not in pointer.children:
... |
#-----------------------------------------------------------------------
# helper modules for argparse:
# - check if values are in a certain range, are positive, etc.
# - https://github.com/Sorbus/artichoke
#-----------------------------------------------------------------------
def check_range(value):
ivalue = in... | def check_range(value):
ivalue = int(value)
if ivalue < 1 or ivalue > 3200:
raise argparse.ArgumentTypeError('%s is not a valid positive int value' % value)
return ivalue
def check_positive(value):
ivalue = int(value)
if ivalue < 0:
raise argparse.ArgumentTypeError('%s is not a vali... |
#logaritmica
#No. de digitos de un numero
def digitos(i):
cont=0
if i == 0:
return '0'
while i > 0:
cont=cont+1
i = i//10
return cont
numeros=list(range(1,1000))
print(numeros)
ite=[]
for a in numeros:
ite.append(digitos(a))
print(digitos(a))
| def digitos(i):
cont = 0
if i == 0:
return '0'
while i > 0:
cont = cont + 1
i = i // 10
return cont
numeros = list(range(1, 1000))
print(numeros)
ite = []
for a in numeros:
ite.append(digitos(a))
print(digitos(a)) |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 00:23:43 2019
@author: yanxi
"""
def addDummyNP(fname):
res=[]
with open(fname) as f:
for line in f:
l = line.split(',')
l.insert(2,'0')
res.append(','.join(l))
if len(res) != 0:
with open(fname, 'w') as ... | """
Created on Mon Oct 21 00:23:43 2019
@author: yanxi
"""
def add_dummy_np(fname):
res = []
with open(fname) as f:
for line in f:
l = line.split(',')
l.insert(2, '0')
res.append(','.join(l))
if len(res) != 0:
with open(fname, 'w') as f:
for ... |
# Guess Number Higher or Lower II
class Solution(object):
def getMoneyAmount(self, n):
"""
the strategy is to choose the option that if the worst consequence of that option occurs,
it's the least worst case among all options
specifically, if picking any number in a range, find the h... | class Solution(object):
def get_money_amount(self, n):
"""
the strategy is to choose the option that if the worst consequence of that option occurs,
it's the least worst case among all options
specifically, if picking any number in a range, find the highest amount of money to pay,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.