content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# settings.py
# sdNum = subdomain number
# p1 = spatial bandwidth
# p2 = temporal bandwidth
# p3 = spatial resolution
# p4 = temporal resolution
# p5 = number of points threshold (T1)
# p6 = buffer ratio threshold (T2)
# dir1 = point files (resulting from decomposition)
# dir2 = time files (resulting from de... | def init():
global sdNum, p1, p2, p3, p4, p5, p6, dir1, dir2, pList, cList
(sd_num, p1, p2, p3, p4, p5, p6, dir1, dir2, p_list, c_list) = (0, 0, 0, 0, 0, 0, 0, 0, 0, [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]) |
# -*- coding: utf-8 -*-
"""
pip_services_runtime.State
~~~~~~~~~~~~~~~~~~~~~~~~~~
Component state enumeration
:copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
class State(object):
"""
State in lifec... | """
pip_services_runtime.State
~~~~~~~~~~~~~~~~~~~~~~~~~~
Component state enumeration
:copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
class State(object):
"""
State in lifecycle of components or th... |
class AutoTrackConfig:
hog_cell_size=4
hog_n_dim=31
gray_cell_size=4
cn_use_for_gray=False
cn_cell_size=4
cn_n_dim=10
search_area_shape = 'square' # the shape of the samples
search_area_scale = 5.0 # the scaling of the target size to get the search area
... | class Autotrackconfig:
hog_cell_size = 4
hog_n_dim = 31
gray_cell_size = 4
cn_use_for_gray = False
cn_cell_size = 4
cn_n_dim = 10
search_area_shape = 'square'
search_area_scale = 5.0
min_image_sample_size = 150 ** 2
max_image_sample_size = 200 ** 2
feature_downsample_ratio = ... |
#
# PySNMP MIB module TPLINK-DHCPSERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-DHCPSERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:17:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
print('first')
print('second')
if True:
x = 1
y = 2
print('hi')
| print('first')
print('second')
if True:
x = 1
y = 2
print('hi') |
'''
sekarang kita menghitung bunganya! ooh ya,
apakah anda tahu bahwa kita bisa merantai perhitungan
seperti ini
jawaban = 2000 * /100
kita buat hal serupa di sini
'''
'''
ciptakan variabel suku_bunga dan berikan nilai
antara 5 hingga 30
-ciptakan juga varibel jumlah_bunga yang merupakan
hasil perkalian sisa_cicilan d... | """
sekarang kita menghitung bunganya! ooh ya,
apakah anda tahu bahwa kita bisa merantai perhitungan
seperti ini
jawaban = 2000 * /100
kita buat hal serupa di sini
"""
'\nciptakan variabel suku_bunga dan berikan nilai\nantara 5 hingga 30\n-ciptakan juga varibel jumlah_bunga yang merupakan\nhasil perkalian sisa_cicilan... |
# Title : Insert new element before each element
# Author : Kiran raj R.
# Date : 23:10:2020
def insert_b4(list_in, str_elem):
out = [elem for list_elem in list_in for elem in (str_elem, list_elem)]
print(f"After inserting element: {out}")
def insert_after(list_in, str_elem):
out = [elem for list_el... | def insert_b4(list_in, str_elem):
out = [elem for list_elem in list_in for elem in (str_elem, list_elem)]
print(f'After inserting element: {out}')
def insert_after(list_in, str_elem):
out = [elem for list_elem in list_in for elem in (list_elem, str_elem)]
print(f'After inserting element: {out}')
insert... |
NOP = 0
RD = 1
WR = 2
class mmiodev(object):
def __init__(self):
self.regmap = {}
self.regidx = {}
def addReg(self, name, addr, length, readonly=0, default=0):
# make sure it doesn't overlap with anything.
for (a0,a1) in self.regmap:
assert addr < a0 or addr >= a... | nop = 0
rd = 1
wr = 2
class Mmiodev(object):
def __init__(self):
self.regmap = {}
self.regidx = {}
def add_reg(self, name, addr, length, readonly=0, default=0):
for (a0, a1) in self.regmap:
assert addr < a0 or addr >= a1
assert name not in self.regidx
self.... |
def of(n, acc1=0, acc2=1):
if n < 0:
raise ValueError
if n == 0:
return 0
elif n <= 1:
return acc2
else:
return of(n - 1, acc2, acc1 + acc2)
| def of(n, acc1=0, acc2=1):
if n < 0:
raise ValueError
if n == 0:
return 0
elif n <= 1:
return acc2
else:
return of(n - 1, acc2, acc1 + acc2) |
#!/usr/bin/python3
# Create a file and call it lyrics.txt (it does not need to have any content)
# Create a new file and call it songs.docx and in this file write 3 lines
# of text to it.
# Open and read the content and write it to your terminal
# window. * you should use the read(), readline(), and readlines()
# ... | songs_dox = '../files/songs.docx'
def separator(text):
print(f'\n#----- Reading from songs.docx with {text} -----#\n')
lyrics_file = open('../files/lyrics.txt', 'w+')
print('lyrics.txt has been created in folder files,', 'any previous data has been deleted')
lyricsFile.close()
songs_file = open(songs_dox, 'w+')
so... |
class Star:
def __init__(self):
self.x = random(-width/2, width/2)
self.y = random(-height/2, height/2)
self.z = random(width/2)
self.pz = self.z
def update(self, speed):
self.z = self.z - speed
if self.z < 1:
self.z = width/2
... | class Star:
def __init__(self):
self.x = random(-width / 2, width / 2)
self.y = random(-height / 2, height / 2)
self.z = random(width / 2)
self.pz = self.z
def update(self, speed):
self.z = self.z - speed
if self.z < 1:
self.z = width / 2
... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ValueTypeEnum(object):
"""Implementation of the 'ValueType' enum.
Specifies the type of the value contained here. All values are returned
as
pointers to strings, but they can be casted to the type indicated here.
'kInt64' indicates that... | class Valuetypeenum(object):
"""Implementation of the 'ValueType' enum.
Specifies the type of the value contained here. All values are returned
as
pointers to strings, but they can be casted to the type indicated here.
'kInt64' indicates that the value stored in the Task Attribute is
a 64-bit i... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@file : hooks.py
@Time : 2021/3/31 15:32
@Author: Tao.Xu
@Email : tao.xu2008@outlook.com
"""
def pytest_smtp_report_title(report):
""" Called before adding the title to the report """
def pytest_smtp_results_summary(prefix, summary, postfix):
""" Called before... | """
@file : hooks.py
@Time : 2021/3/31 15:32
@Author: Tao.Xu
@Email : tao.xu2008@outlook.com
"""
def pytest_smtp_report_title(report):
""" Called before adding the title to the report """
def pytest_smtp_results_summary(prefix, summary, postfix):
""" Called before adding the summary section to the report ""... |
DATABASE_AUTO_CREATE_INDEX = True
DATABASES = {
'default': {
'db': 'billing',
'host': 'localhost',
'port': 27017,
'username': '',
'password': ''
}
}
CACHES = {
'default': {},
'local': {
'backend': 'spaceone.core.cache.local_cache.LocalCache',
'max... | database_auto_create_index = True
databases = {'default': {'db': 'billing', 'host': 'localhost', 'port': 27017, 'username': '', 'password': ''}}
caches = {'default': {}, 'local': {'backend': 'spaceone.core.cache.local_cache.LocalCache', 'max_size': 128, 'ttl': 300}}
handlers = {}
connectors = {'BillingPluginConnector':... |
# We're trying to find the sum of the even fibonacci numbers
# from 1 to `max_num`
class Solution:
# We're going to do fibonacci iteratively
def solution(self, max_num: int) -> int:
# `minus1` and `minus2` keep track of the last two values
# starting with 0 and 1, `num` keeps track of the curren... | class Solution:
def solution(self, max_num: int) -> int:
(minus1, minus2) = (1, 0)
num = 0
sum = 0
while num < max_num:
num = minus1 + minus2
minus2 = minus1
minus1 = num
if num % 2 == 0:
sum += num
return sum |
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
position=sorted(position)
dis=position[-1]-position[0]
if m==2:
return position[-1]-position[0]
low=1
high=dis
def validInterval(interval):
n=m-1
... | class Solution:
def max_distance(self, position: List[int], m: int) -> int:
position = sorted(position)
dis = position[-1] - position[0]
if m == 2:
return position[-1] - position[0]
low = 1
high = dis
def valid_interval(interval):
n = m - 1
... |
project = 'django-sms'
copyright = '2021, Roald Nefs'
author = 'Roald Nefs'
release = '0.4.0'
extensions = ['m2r2']
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
source_suffix = ['.rst', '.md']
html_theme = 'alabaster'
html_theme_options = {
"description": "A Django app f... | project = 'django-sms'
copyright = '2021, Roald Nefs'
author = 'Roald Nefs'
release = '0.4.0'
extensions = ['m2r2']
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
source_suffix = ['.rst', '.md']
html_theme = 'alabaster'
html_theme_options = {'description': 'A Django app for send... |
def main():
f = [int(i) for i in [line.rstrip("\n") for line in open("Data.txt")][0].split(",")]
f[1] = 12
f[2] = 2
i = 0
while True:
if f[i] == 99:
break
elif f[i] == 1:
f[f[i + 3]] = f[f[i + 1]] + f[f[i + 2]]
elif f[i] == 2:
f[f[i + 3]] =... | def main():
f = [int(i) for i in [line.rstrip('\n') for line in open('Data.txt')][0].split(',')]
f[1] = 12
f[2] = 2
i = 0
while True:
if f[i] == 99:
break
elif f[i] == 1:
f[f[i + 3]] = f[f[i + 1]] + f[f[i + 2]]
elif f[i] == 2:
f[f[i + 3]] =... |
def register(mf):
mf.register_event("main", lambda: print("tests"), unique=False)
register_parents = False
| def register(mf):
mf.register_event('main', lambda : print('tests'), unique=False)
register_parents = False |
# 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 = right
class Solution:
def buildTree(se... | class Solution:
def build_tree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
map_inorder = {}
for (i, val) in enumerate(inorder):
map_inorder[val] = i
def recur(low, high):
if low > high:
return None
x = tree_node(postorder... |
DATABASE = {
'host': None,
'port': None,
'username': None, # 'data'
'password': None, # 'cafl-2021'
'db': None,
'uri': None,
}
BROWSER = {
# broswer settings
'options': [
"--no-sandbox",
"--dns-prefetch-disable",
"--disable-browser-side-navigation",
"--... | database = {'host': None, 'port': None, 'username': None, 'password': None, 'db': None, 'uri': None}
browser = {'options': ['--no-sandbox', '--dns-prefetch-disable', '--disable-browser-side-navigation', '--disable-dev-shm-usage', '--disable-infobars', 'enable-automation'], 'delay': 0, 'waitInterval': 10, 'elementTimeou... |
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """Implementation for macOS universal binary rule."""
load(':apple_support.bzl', 'apple_support')
load(':lipo.bzl', 'lipo')
load(':transitions.bzl', 'macos_universal_transition')
load('@bazel_skylib//lib:dicts.bzl', 'dicts')
def _universal_binary_impl(ctx):
inputs = [binary.files.to_list()[0] for binary in ctx.spl... |
# compose tree to describe object dictionary
# assume all instrument readings are four-byte floats
theTree = {
0x1000: {
0x00: {0x40: 0, 'size': 4}
},
0x6001: {
0x00: {0x40: 5},
0x01: {0x40: 'INST:SEL CH1;:SOUR:VOLT?', 0x23: 'INST:SEL CH1;:SOUR:VOLT'},
0x02: {0x40: 'INST:SEL CH1;:SOUR:CURR?', 0x23: 'INST:SEL... | the_tree = {4096: {0: {64: 0, 'size': 4}}, 24577: {0: {64: 5}, 1: {64: 'INST:SEL CH1;:SOUR:VOLT?', 35: 'INST:SEL CH1;:SOUR:VOLT'}, 2: {64: 'INST:SEL CH1;:SOUR:CURR?', 35: 'INST:SEL CH1;:SOUR:CURR'}, 3: {64: 'FETCH:VOLT? CH1'}, 4: {64: 'FETCH:CURR? CH1'}, 5: {64: 'FETCH:POW? CH1'}}, 24578: {0: {64: 5}, 1: {64: 'INST:SEL... |
api_key = ""
api_secret = ""
access_token_key = ""
access_token_secret = ""
| api_key = ''
api_secret = ''
access_token_key = ''
access_token_secret = '' |
USERS = {}
def update_user(user):
if user not in USERS:
USERS[user] = 0
USERS[user] += 1
return {'name': user, 'access': USERS[user]}
| users = {}
def update_user(user):
if user not in USERS:
USERS[user] = 0
USERS[user] += 1
return {'name': user, 'access': USERS[user]} |
N, A, B = map(int, input().split())
if B >= A*N:
print(A*N)
else:
print(B) | (n, a, b) = map(int, input().split())
if B >= A * N:
print(A * N)
else:
print(B) |
class Network:
def __init__(self):
self.layer_list = []
self.num_layer = 0
def add(self, layer):
self.num_layer = self.num_layer + 1
self.layer_list.append(layer)
def forward(self, x):
for i in range(self.num_layer):
x = self.layer_list[i].forward(x)
... | class Network:
def __init__(self):
self.layer_list = []
self.num_layer = 0
def add(self, layer):
self.num_layer = self.num_layer + 1
self.layer_list.append(layer)
def forward(self, x):
for i in range(self.num_layer):
x = self.layer_list[i].forward(x)
... |
"""
define in here e.g. the number of class, box scale, ...
meaning constants class
date: 9/30
author: arabian9ts
"""
# the number of classified class
classes = 21
# the number of boxes per feature map
boxes = [4, 6, 6, 6, 6, 6,]
# default box ratios
# each length should be matches boxes[index]
box_ratios = [
[... | """
define in here e.g. the number of class, box scale, ...
meaning constants class
date: 9/30
author: arabian9ts
"""
classes = 21
boxes = [4, 6, 6, 6, 6, 6]
box_ratios = [[1.0, 1.0, 2.0, 1.0 / 2.0], [1.0, 1.0, 2.0, 1.0 / 2.0, 3.0, 1.0 / 3.0], [1.0, 1.0, 2.0, 1.0 / 2.0, 3.0, 1.0 / 3.0], [1.0, 1.0, 2.0, 1.0 / 2.0, 3.0,... |
_base_ = [
'../../_base_/models/detr.py',
'../../_base_/datasets/mot15.py',
'../../_base_/default_runtime.py'
#'../../_base_/datasets/mot_challenge.py',
]
custom_imports = dict(imports=['mmtrack.models.mot.kf'], allow_failed_imports=False)
link = 'https://download.openmmlab.com/mmdetection/v2.0/detr... | _base_ = ['../../_base_/models/detr.py', '../../_base_/datasets/mot15.py', '../../_base_/default_runtime.py']
custom_imports = dict(imports=['mmtrack.models.mot.kf'], allow_failed_imports=False)
link = 'https://download.openmmlab.com/mmdetection/v2.0/detr/detr_r50_8x2_150e_coco/detr_r50_8x2_150e_coco_20201130_194835-2c... |
_base_ = [
'../_base_/default_runtime.py'
]
model = dict(
type='opera.InsPose',
backbone=dict(
type='mmdet.ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_eval=False,
style='pytorch',
init_cfg=dict(type='Pretrai... | _base_ = ['../_base_/default_runtime.py']
model = dict(type='opera.InsPose', backbone=dict(type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_eval=False, style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), neck=dict(type='mmdet.FPN', in_chan... |
# -*- coding: utf-8 -*-
"""
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class ObjectTypeEnum(object):
"""Implementation of the 'objectType' enum.
TODO: type enum description here.
Attributes:
PERSON: TODO: type de... | """
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Objecttypeenum(object):
"""Implementation of the 'objectType' enum.
TODO: type enum description here.
Attributes:
PERSON: TODO: type description here.
VEHICLE: TODO: ty... |
""" Define multi-algoritmic simulation errors.
:Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu>
:Date: 2016-12-12
:Copyright: 2016-2018, Karr Lab
:License: MIT
"""
class Error(Exception):
""" Base class for exceptions involving multi-algoritmic simulation
Attributes:
message (:obj:`str`): the exc... | """ Define multi-algoritmic simulation errors.
:Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu>
:Date: 2016-12-12
:Copyright: 2016-2018, Karr Lab
:License: MIT
"""
class Error(Exception):
""" Base class for exceptions involving multi-algoritmic simulation
Attributes:
message (:obj:`str`): the exce... |
class Employee():
def __init__(self, first_name, last_name, money):
self.first_name = first_name
self.last_name = last_name
self.money = money
def give_raise(self, add_money=5000):
self.money += add_money
return self.money
| class Employee:
def __init__(self, first_name, last_name, money):
self.first_name = first_name
self.last_name = last_name
self.money = money
def give_raise(self, add_money=5000):
self.money += add_money
return self.money |
#Shape of capital B:
def for_B():
"""printing capital 'B' using for loop"""
for row in range(7):
for col in range(5):
if col==0 or row==0 and col!=4 or row==3 and col!=4 or row==6 and col!=4 or col==4 and row%3!=0:
print("*",end=" ")
else:
... | def for_b():
"""printing capital 'B' using for loop"""
for row in range(7):
for col in range(5):
if col == 0 or (row == 0 and col != 4) or (row == 3 and col != 4) or (row == 6 and col != 4) or (col == 4 and row % 3 != 0):
print('*', end=' ')
else:
... |
def add(x,y):
return x + y
def multiply(x,y):
return x * y
def subtract(x,y):
return x - y
def divide(x,y):
return y/x
def power(x,y):
return x**y | def add(x, y):
return x + y
def multiply(x, y):
return x * y
def subtract(x, y):
return x - y
def divide(x, y):
return y / x
def power(x, y):
return x ** y |
"""
https://leetcode.com/problems/longest-increasing-subsequence/
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more... | """
https://leetcode.com/problems/longest-increasing-subsequence/
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more... |
'''
Created on 1.12.2016
@author: Darren
''''''
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
The above elevation map is ... | """
Created on 1.12.2016
@author: Darren
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
The above elevation map is represented by array [... |
## -*- coding: utf-8 -*- ##
## Sage Doctest File ##
#**************************************#
#* Generated from PreTeXt source *#
#* on 2017-08-24T11:43:34-07:00 *#
#* *#
#* http://mathbook.pugetsound.edu *#
#* ... | """
Please contact Rob Beezer (beezer@ups.edu) with
any test failures here that need to be changed
as a result of changes accepted into Sage. You
may edit/change this file in any sensible way, so
that development work may procede. Your changes
may later be replaced by the authors of "Abstract
Algebra: Theory and Appl... |
# EclipseCon Europe Che Challenge
#
# This program prints the numbers from 1 to 100, with every multiple of 3
# replaced by "Fizz", and every multiple of 5 replaced by "Buzz". Numbers
# divisible by both are replaced by "FizzBuzz". Otherwise, the program
# prints the number.
#
# Your mission, if you choose to accept it... | for i in range(1, 101):
num = '%s' % i
if i % 3 == 0:
num = 'Fizz'
if i % 5 == 0:
num = 'Buzz'
print(f'{num}') |
class DataPacker:
#list data type will only write out the values without the key
@staticmethod
def dataTypeList():
return "list"
@staticmethod
def dataTypeObject():
return "object"
def __init__(self, type):
self.type = type
self.data = []
def add_pair(... | class Datapacker:
@staticmethod
def data_type_list():
return 'list'
@staticmethod
def data_type_object():
return 'object'
def __init__(self, type):
self.type = type
self.data = []
def add_pair(self, key, value):
self.data.append([key, value])
def ... |
#! /usr/bin/python
# Filename: object_init
# Description: the constructor in python
class Persion:
def __init__(self, name):
self.name = name
def sayHi(self):
print(self.name)
test = Persion("Hello,world")
test.sayHi()
| class Persion:
def __init__(self, name):
self.name = name
def say_hi(self):
print(self.name)
test = persion('Hello,world')
test.sayHi() |
arr = [-3, 4, 8, -2, -1, 5, 4, 8]
for i in range(0, len(arr)-1):
if(arr[i] > 0):
#num is positive
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
print(arr)
| arr = [-3, 4, 8, -2, -1, 5, 4, 8]
for i in range(0, len(arr) - 1):
if arr[i] > 0:
temp = arr[i]
arr[i] = arr[i + 1]
arr[i + 1] = temp
print(arr) |
class Rememberer:
def __init__(self):
self.funcs = []
def register(self, fn):
self.funcs.append(fn)
fn.__conform__ = lambda new: self.recode(fn, new)
return self
def recode(self, fn, new):
if new is None:
self.funcs.remove(fn)
else:
... | class Rememberer:
def __init__(self):
self.funcs = []
def register(self, fn):
self.funcs.append(fn)
fn.__conform__ = lambda new: self.recode(fn, new)
return self
def recode(self, fn, new):
if new is None:
self.funcs.remove(fn)
else:
... |
"""
categories: Core,Functions
description: Assign instance variable to function
cause: Unknown
workaround: Unknown
"""
def f():
pass
f.x = 0
print(f.x)
| """
categories: Core,Functions
description: Assign instance variable to function
cause: Unknown
workaround: Unknown
"""
def f():
pass
f.x = 0
print(f.x) |
# Create a program that reads an integer and shows on the screen whether it is even or odd
n = int(input('Type a integer: '))
if n % 2 == 0:
print('The number {} is {} EVEN {}'.format(n, '\033[1;31;40m', '\033[m'))
else:
print('The number {} is {} ODD {}'.format(n, '\033[7;30m', '\033[m'))
| n = int(input('Type a integer: '))
if n % 2 == 0:
print('The number {} is {} EVEN {}'.format(n, '\x1b[1;31;40m', '\x1b[m'))
else:
print('The number {} is {} ODD {}'.format(n, '\x1b[7;30m', '\x1b[m')) |
# @Time : 2019/4/24 23:22
# @Author : shakespere
# @FileName: 3Sum.py
'''
15. 3Sum
Medium
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate tr... | """
15. 3Sum
Medium
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
... |
# Handshake
# Count the number of Handshakes in a board meeting.
#
# https://www.hackerrank.com/challenges/handshake/problem
#
T = int(input())
for a0 in range(T):
N = int(input())
print(N * (N - 1) // 2)
| t = int(input())
for a0 in range(T):
n = int(input())
print(N * (N - 1) // 2) |
inicial = int(input('Qual o numero inicial?'))
final = int(input('Qual o numero final?'))
x = inicial
while( x <= final):
if(x % 2 == 0):
print(x)
x = x + 1 | inicial = int(input('Qual o numero inicial?'))
final = int(input('Qual o numero final?'))
x = inicial
while x <= final:
if x % 2 == 0:
print(x)
x = x + 1 |
#!/usr/bin/env python3
# Everything in Python are objects.
# This means that everything that's created is an
# instance on a pre-defined class, or a self-defined class.
# These instances are in memory (hence named objects), and
# has access to the functions defined in the original classes
# and is called methods.
# 1... | name = 'Rob'
print(type(name))
print(dir(name))
class Animal:
"""Animal Class"""
def __init__(self):
"""Constructor for Animal Class"""
pass
def print_name(self, name):
print('{} is an Animal'.format(name))
my_animal = animal()
my_animal.print_name('Deer')
class Vehicle:
"""V... |
def main_screen(calendar):
while True:
print("What would you like to do? ")
print("\ta) Add event")
print("\tb) Delete event")
print("\tc) Print events")
print("\td) Exit")
answer = input(" $ ")
if "a" in answer:
add_event(calendar)
elif "... | def main_screen(calendar):
while True:
print('What would you like to do? ')
print('\ta) Add event')
print('\tb) Delete event')
print('\tc) Print events')
print('\td) Exit')
answer = input(' $ ')
if 'a' in answer:
add_event(calendar)
elif 'b... |
def levenshtein_Distance(word1,word2):
word1="#"+word1
wordTmp="#"+word2
letters1 = list(word1)
letters2 = list(wordTmp)
# Initializing table
table = [ [0 for i in range(len(word1))] for j in range(len(wordTmp))]
for i in range (len(word1)):
table[0][i] = i
fo... | def levenshtein__distance(word1, word2):
word1 = '#' + word1
word_tmp = '#' + word2
letters1 = list(word1)
letters2 = list(wordTmp)
table = [[0 for i in range(len(word1))] for j in range(len(wordTmp))]
for i in range(len(word1)):
table[0][i] = i
for j in range(len(wordTmp)):
... |
#
# PySNMP MIB module ACMEPACKET-PRODUCTS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ACMEPACKET-PRODUCTS
# Produced by pysmi-0.3.4 at Mon Apr 29 16:57:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (acmepacket,) = mibBuilder.importSymbols('ACMEPACKET-SMI', 'acmepacket')
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, s... |
# Feature flag to raise an exception in case of a non existing device feature.
# The flag should be fully removed in a later release.
# It allows dependend libraries to gracefully migrate to the new behaviour
raise_exception_on_not_supported_device_feature = True
# Feature flag to raise exception if rate limit of the ... | raise_exception_on_not_supported_device_feature = True
raise_exception_on_rate_limit = True
raise_exception_on_command_failure = True |
class Solution:
def countOdds(self, low: int, high: int) -> int:
c = high - low + 1
if c % 2 == 1 and low % 2 == 1:
r = 1
else:
r = 0
return r + c // 2
| class Solution:
def count_odds(self, low: int, high: int) -> int:
c = high - low + 1
if c % 2 == 1 and low % 2 == 1:
r = 1
else:
r = 0
return r + c // 2 |
class Solution:
def reverseWords(self, s: str) -> str:
res, blank = '', False
for _ in s[::-1]:
res += _
return ' '.join(res.split()[::-1])
| class Solution:
def reverse_words(self, s: str) -> str:
(res, blank) = ('', False)
for _ in s[::-1]:
res += _
return ' '.join(res.split()[::-1]) |
# -----------------------------------------------------------------------------
# Copyright * 2014, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache
#... | modis_classifiers = dict()
radar_classifiers = dict()
modis_classifiers['default'] = [(u'dartmouth', 0.30887438055782945, 1.4558371112080295), (u'b2', 2020.1975382568198, 0.9880130793929531), (u'MNDWI', 0.3677501330908955, 0.5140443440746121), (u'b2', 1430.1463073852296, 0.15367606716883875), (u'b1', 1108.5241042345276... |
def N():
for row in range(7):
for col in range(7):
if (col==0 or col==6) or row-col==0:
print("*",end=" ")
else:
print(end=" ")
print()
| def n():
for row in range(7):
for col in range(7):
if (col == 0 or col == 6) or row - col == 0:
print('*', end=' ')
else:
print(end=' ')
print() |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type ... | class Solution(object):
def add_one_row(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode
"""
dummy = tree_node(-1)
dummy.left = root
stack = [(1, dummy, 0)]
while stack:
(p, node, h) = ... |
a=list(map(int,input().split(',')))[:4]
x,y,p,q=a[0],a[1],a[2],a[3]
b1,b2,b3=1,1,1
print(b1,'C',x,b2,'H',y,',',b3,',C',p,'H',q)
print((b1*x+b2*y),(b3*(p*q)))
while (b1*x+b2*y)!=(b3*(p*q)):
while b1*x!=b3*p:
print('l1')
if b1*x!=p:
b1+=1
elif x!=b3*p:
b3+=1
... | a = list(map(int, input().split(',')))[:4]
(x, y, p, q) = (a[0], a[1], a[2], a[3])
(b1, b2, b3) = (1, 1, 1)
print(b1, 'C', x, b2, 'H', y, ',', b3, ',C', p, 'H', q)
print(b1 * x + b2 * y, b3 * (p * q))
while b1 * x + b2 * y != b3 * (p * q):
while b1 * x != b3 * p:
print('l1')
if b1 * x != p:
... |
league_schema_name = None
def tn(tablename: str) -> str:
if league_schema_name is not None:
return '`{0}`.`{1}`'.format(league_schema_name, tablename)
else:
return '`{0}`'.format(tablename)
| league_schema_name = None
def tn(tablename: str) -> str:
if league_schema_name is not None:
return '`{0}`.`{1}`'.format(league_schema_name, tablename)
else:
return '`{0}`'.format(tablename) |
A = [1, 2, 3]
for i, x in enumerate(A):
A[i] += x
B = A[0]
C = A[0]
D: int = 3
while C < A[2]:
C += 1
if C == A[2]:
print('True')
def main():
print("Main started")
print(A)
print(B)
print(C)
print(D)
if __name__ == '__main__':
main()
| a = [1, 2, 3]
for (i, x) in enumerate(A):
A[i] += x
b = A[0]
c = A[0]
d: int = 3
while C < A[2]:
c += 1
if C == A[2]:
print('True')
def main():
print('Main started')
print(A)
print(B)
print(C)
print(D)
if __name__ == '__main__':
main() |
# Folders
FOLDER_SCHEMA = "graphql"
# Packages
PACKAGE_RESOLVERS = "resolvers"
# Modules
MODULE_MODELS = "models"
MODULE_DIRECTIVES = "directives"
MODULE_SETTINGS = "settings"
MODULE_PYDANTIC = "pyd_models"
| folder_schema = 'graphql'
package_resolvers = 'resolvers'
module_models = 'models'
module_directives = 'directives'
module_settings = 'settings'
module_pydantic = 'pyd_models' |
"""
The ``covertutils`` module provides ready plug-n-play tools for `Remote Code Execution Agent` programming.
Features like `chunking`, `encryption`, `data identification` are all handled transparently by its classes.
The :class:`SimpleOrchestrator` handles all data manipulation, and the :class:`Handlers.BaseHandler` ... | """
The ``covertutils`` module provides ready plug-n-play tools for `Remote Code Execution Agent` programming.
Features like `chunking`, `encryption`, `data identification` are all handled transparently by its classes.
The :class:`SimpleOrchestrator` handles all data manipulation, and the :class:`Handlers.BaseHandler` ... |
# 2. Matching Parentheses
# You are given an algebraic expression with parentheses. Scan through the string and extract each set of parentheses.
# Print the result back on the console.
string = list(input())
stack_index = []
for index in range(len(string)):
if string[index] == "(":
stack_index.append(in... | string = list(input())
stack_index = []
for index in range(len(string)):
if string[index] == '(':
stack_index.append(index)
elif string[index] == ')':
start_index = stack_index.pop()
end_index = index
parentheses_set = string[start_index:end_index + 1]
print(''.join(paren... |
#
# PySNMP MIB module JUNIPER-FABRIC-CHASSIS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-FABRIC-CHASSIS
# Produced by pysmi-0.3.4 at Wed May 1 13:59:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) ... |
"""Rules for simple testing without dependencies by parsing output logs."""
def tflite_micro_cc_test(
name,
expected_in_logs = "~~~ALL TESTS PASSED~~~",
srcs = [],
includes = [],
defines = [],
copts = [],
nocopts = "",
linkopts = [],
deps = [],
... | """Rules for simple testing without dependencies by parsing output logs."""
def tflite_micro_cc_test(name, expected_in_logs='~~~ALL TESTS PASSED~~~', srcs=[], includes=[], defines=[], copts=[], nocopts='', linkopts=[], deps=[], tags=[], visibility=None):
"""Tests a C/C++ binary without testing framework dependenc... |
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
rows=len(grid)
columns=len(grid[0])
for i in range(1,columns):
grid[0][i]+=grid[0][i-1]
for j in range(1,rows):
grid[j][0]+=grid[j-1][0]
for k in range(1,rows):
for l in ra... | class Solution:
def min_path_sum(self, grid: List[List[int]]) -> int:
rows = len(grid)
columns = len(grid[0])
for i in range(1, columns):
grid[0][i] += grid[0][i - 1]
for j in range(1, rows):
grid[j][0] += grid[j - 1][0]
for k in range(1, rows):
... |
'''
Take two sorted linked lists L, R and return the merge of L and R
Notes:
* when declaring a python class, inherit from object if not otherwise specified
* in the python class __init__ function, self is a required first argument
* next is a reserved name (iterator method) in python. use the variable name next_node ... | """
Take two sorted linked lists L, R and return the merge of L and R
Notes:
* when declaring a python class, inherit from object if not otherwise specified
* in the python class __init__ function, self is a required first argument
* next is a reserved name (iterator method) in python. use the variable name next_node ... |
# -*- coding: utf-8 -*-
"""Top-level package for mvstats."""
__author__ = """Hrishikesh A. Chandanpurkar"""
__email__ = 'hrishikeshac@gmail.com'
__version__ = '0.1.0'
| """Top-level package for mvstats."""
__author__ = 'Hrishikesh A. Chandanpurkar'
__email__ = 'hrishikeshac@gmail.com'
__version__ = '0.1.0' |
global_transform = 0
# TODO: add types / proper data structures to variables
def find_attitude_data(timestamp):
"""
Find corresponding attitude data by time stamp.
:param timestamp: The timestamp.
:return: ?
"""
pass
def find_displacement_data(timestamp):
"""
Find corresponding d... | global_transform = 0
def find_attitude_data(timestamp):
"""
Find corresponding attitude data by time stamp.
:param timestamp: The timestamp.
:return: ?
"""
pass
def find_displacement_data(timestamp):
"""
Find corresponding displacement data by time stamp.
:param timestamp: The ti... |
PRED_TYPE = 'Basic'
TTA_PRED_TYPE = 'TTA'
ENS_TYPE = 'Ens'
MEGA_ENS_TYPE = 'MegaEns'
| pred_type = 'Basic'
tta_pred_type = 'TTA'
ens_type = 'Ens'
mega_ens_type = 'MegaEns' |
# Copyright (c) 2017 Dustin Doloff
# Licensed under Apache License v2.0
load(
":internal.bzl",
"assert_files_equal_rule",
"assert_label_struct_rule",
)
def assert_equal(v1, v2):
"""
Asserts that two values are equal. If not, fails the build
"""
if v1 != v2:
fail("Values were not eq... | load(':internal.bzl', 'assert_files_equal_rule', 'assert_label_struct_rule')
def assert_equal(v1, v2):
"""
Asserts that two values are equal. If not, fails the build
"""
if v1 != v2:
fail('Values were not equal (' + str(v1) + ') (' + str(v2) + ')')
def assert_str_equal(v1, v2):
"""
Ass... |
class Application:
def __init__(self, owner, raw):
self.id = raw['app_id']
self.owner_id = raw['owner_id']
self._update(owner, raw)
def _update(self, owner, raw):
self._raw = raw
self.owner = owner
self.name = raw['name']
self.type = raw['type']
... | class Application:
def __init__(self, owner, raw):
self.id = raw['app_id']
self.owner_id = raw['owner_id']
self._update(owner, raw)
def _update(self, owner, raw):
self._raw = raw
self.owner = owner
self.name = raw['name']
self.type = raw['type']
... |
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... | """THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['a']
# Cell
def a(b):
"qgerhwtejyrkafher arerhtrw"
return 10 | __all__ = ['a']
def a(b):
"""qgerhwtejyrkafher arerhtrw"""
return 10 |
print ("Hello there welcome to Medieval Village.")
print ("You have a village that you need to take care of. Choose one of the options to keep the village in good shape 1) Plant and harvest the crops 2) Use resources from the forest near the village 3) Get your defenses up")
user_choice = input()
user_choice = int(user... | print('Hello there welcome to Medieval Village.')
print('You have a village that you need to take care of. Choose one of the options to keep the village in good shape 1) Plant and harvest the crops 2) Use resources from the forest near the village 3) Get your defenses up')
user_choice = input()
user_choice = int(user_c... |
def solution(board, moves):
# At first, make stack of each columns
boardStack = [[] for _ in range(len(board[0]))]
for row in board[::-1]:
# Watch out, column index is subtracted by -1
for column, element in enumerate(row):
if element != 0:
boardStack[column].appe... | def solution(board, moves):
board_stack = [[] for _ in range(len(board[0]))]
for row in board[::-1]:
for (column, element) in enumerate(row):
if element != 0:
boardStack[column].append(element)
bucket_stack = []
exploded = 0
for move in moves:
if boardStac... |
repeat = int(input())
for x in range(repeat):
inlist = list(map( int, input().split()))
inlen = inlist.pop(0)
avg = sum(inlist)//inlen
inlist.sort()
for i in range(inlen):
if inlist[i] > avg:
result = (inlen-i)/inlen *100
break
result = 0
print("%.3f"%resu... | repeat = int(input())
for x in range(repeat):
inlist = list(map(int, input().split()))
inlen = inlist.pop(0)
avg = sum(inlist) // inlen
inlist.sort()
for i in range(inlen):
if inlist[i] > avg:
result = (inlen - i) / inlen * 100
break
result = 0
print('%.3f... |
"""
CCC Problem J2
Randy Zhu
"""
infection_limit = int(input())
patient_zeroes = int(input())
infection_rate = int(input())
infected = 0
# newly_infected = 0
# infected = 0
currently_infected = patient_zeroes
# infected = 0
days = 0
while infected < infection_limit:
infected += (currently_infected... | """
CCC Problem J2
Randy Zhu
"""
infection_limit = int(input())
patient_zeroes = int(input())
infection_rate = int(input())
infected = 0
currently_infected = patient_zeroes
days = 0
while infected < infection_limit:
infected += currently_infected * infection_rate * infection_rate + patient_zeroes
currently_infe... |
#!/usr/bin/env python
#
# Copyright 2009-2020 NTESS. Under the terms
# of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
#
# Copyright (c) 2009-2020, NTESS
# All rights reserved.
#
# Portions are copyright of other developers:
# See the file CONTRIBUTORS.TXT in the top ... | clock = '100MHz'
memory_clock = '100MHz'
coherence_protocol = 'MSI'
memory_backend = 'timing'
memory_controllers_per_group = 1
groups = 8
memory_capacity = 16384 * 4
cpu_params = {'verbose': 0, 'printStats': 1}
l1cache_params = {'clock': clock, 'coherence_protocol': coherence_protocol, 'cache_frequency': clock, 'replac... |
"""
Given the capacity of the knapsack and items specified by weights and values,
return the maximum summarized value of the items that can be fit in the
knapsack.
Example:
capacity = 5, items(value, weight) = [(60, 5), (50, 3), (70, 4), (30, 2)]
result = 80 (items valued 50 and 30 can both be fit in the knapsack)
Th... | """
Given the capacity of the knapsack and items specified by weights and values,
return the maximum summarized value of the items that can be fit in the
knapsack.
Example:
capacity = 5, items(value, weight) = [(60, 5), (50, 3), (70, 4), (30, 2)]
result = 80 (items valued 50 and 30 can both be fit in the knapsack)
Th... |
class TBikeTruck:
def __init__(self, id, capacity, init_location):
self.id = id
self.capacity = capacity
self.location = init_location
self.bikes_count = 0
self.distance = 0
def to_json(self):
return {
'id': self.id,
'location_id': self.lo... | class Tbiketruck:
def __init__(self, id, capacity, init_location):
self.id = id
self.capacity = capacity
self.location = init_location
self.bikes_count = 0
self.distance = 0
def to_json(self):
return {'id': self.id, 'location_id': self.location.id, 'loaded_bikes... |
class Stack:
topIndex = 0
items = [None] * 64
def push(self, item):
self.topIndex += 1
self.items[self.topIndex] = item
def pop(self):
if self.topIndex == 0:
return None
else:
itemToReturn = self.items[self.topIndex]
self.topIndex -= 1
... | class Stack:
top_index = 0
items = [None] * 64
def push(self, item):
self.topIndex += 1
self.items[self.topIndex] = item
def pop(self):
if self.topIndex == 0:
return None
else:
item_to_return = self.items[self.topIndex]
self.topIndex ... |
# Cheering Expression (6510)
rinz = 2012007
scissorhands = 1162003
sweetness = 5160021
sm.setSpeakerID(rinz)
sm.sendNext("Welcome! What can I do for you today? ...A gift? For me? "
"Wow, a customer's never given me a gift before!")
sm.giveItem(sweetness)
sm.completeQuest(parentID)
sm.consumeItem(scissorhands)
sm.s... | rinz = 2012007
scissorhands = 1162003
sweetness = 5160021
sm.setSpeakerID(rinz)
sm.sendNext("Welcome! What can I do for you today? ...A gift? For me? Wow, a customer's never given me a gift before!")
sm.giveItem(sweetness)
sm.completeQuest(parentID)
sm.consumeItem(scissorhands)
sm.sendNext(''.join(['WOW! #t', repr(scis... |
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='sweetberry'
inas = [
('sweetberry', '0x40:3', 'pp1050_a', 1.05, 0.010, 'j2', True), # R462, SOC
('sweetberry', '0x40:1', '... | config_type = 'sweetberry'
inas = [('sweetberry', '0x40:3', 'pp1050_a', 1.05, 0.01, 'j2', True), ('sweetberry', '0x40:1', 'pp1050_st', 1.05, 0.01, 'j2', True), ('sweetberry', '0x40:2', 'pp1050_stg', 1.05, 0.01, 'j2', True), ('sweetberry', '0x40:0', 'pp1200_dram_u', 1.2, 0.01, 'j2', True), ('sweetberry', '0x41:3', 'pp18... |
def selectionSort(A):
for i in range(len(A) - 1):
index_min = i
value_min = A[i]
for j in range(i + 1, len(A)):
if A[j] < value_min:
index_min = j
value_min = A[j]
A[index_min] = A[i]
A[i] = value_min
return A
def insertionS... | def selection_sort(A):
for i in range(len(A) - 1):
index_min = i
value_min = A[i]
for j in range(i + 1, len(A)):
if A[j] < value_min:
index_min = j
value_min = A[j]
A[index_min] = A[i]
A[i] = value_min
return A
def insertion_so... |
#
# LeetCode
#
# Problem - 386
# URL - https://leetcode.com/problems/lexicographical-numbers/
#
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
ans = []
for i in range(1, n+1):
ans.insert(bisect.bisect_left(ans, str(i)), str(i))
return ans
| class Solution:
def lexical_order(self, n: int) -> List[int]:
ans = []
for i in range(1, n + 1):
ans.insert(bisect.bisect_left(ans, str(i)), str(i))
return ans |
def _method(f): return lambda *l, **d: f(i, *l, **d)
class o:
def __init__(i, **d): i.__dict__.update(**d)
def __repr__(i): return str(
{k: (v.__name__ + "()" if callable(v) else v)
for k, v in sorted(i.__dict__.items()) if k[0] != "_"})
def of(i, **methods):
for k, f in methods.items():
i.__di... | def _method(f):
return lambda *l, **d: f(i, *l, **d)
class O:
def __init__(i, **d):
i.__dict__.update(**d)
def __repr__(i):
return str({k: v.__name__ + '()' if callable(v) else v for (k, v) in sorted(i.__dict__.items()) if k[0] != '_'})
def of(i, **methods):
for (k, f) in methods.ite... |
class Solution(object):
def minCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if not costs:
return 0
dp = [0] * (len(costs[0]))
dp[:] = costs[0]
for i in xrange(1, len(costs)):
d0 = d1 = d2 = 0
... | class Solution(object):
def min_cost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if not costs:
return 0
dp = [0] * len(costs[0])
dp[:] = costs[0]
for i in xrange(1, len(costs)):
d0 = d1 = d2 = 0
f... |
class Solution:
def romanToInt(self, s: str) -> int:
romanMap = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
prev = 1000
for c in s:
curr = romanMap[c]
if curr > prev:
result += curr - prev*2
else:
... | class Solution:
def roman_to_int(self, s: str) -> int:
roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
prev = 1000
for c in s:
curr = romanMap[c]
if curr > prev:
result += curr - prev * 2
el... |
'''
Design a calculator which will solve all the problems correctly except for
1. 45*3 = 555
2. 56+9 = 77
3. 56/6 = 4
Your program should take two numbers, operator as input and show the output.
'''
def add(n1,n2):
''' To add the given numbers '''
result = n1+n2
return result
def sub(n1,n2):
''' To ... | """
Design a calculator which will solve all the problems correctly except for
1. 45*3 = 555
2. 56+9 = 77
3. 56/6 = 4
Your program should take two numbers, operator as input and show the output.
"""
def add(n1, n2):
""" To add the given numbers """
result = n1 + n2
return result
def sub(n1, n2):
"""... |
'''
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . f . f
gggg .... gggg gggg ....
... | """
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . f . f
gggg .... gggg gggg ....
5: ... |
# Convert to str
number = 18
number_string = str(number)
print(type(number_string)) # 'str' | number = 18
number_string = str(number)
print(type(number_string)) |
n = int(input("Informe a quantidade de caracteres: "))
caracteres = []
consoantes = 0
i = 1
while i <= n:
c = input("Informe o %d caracter: " %i)
caracteres.append(c)
i += 1
i = 0
while i < n:
if caracteres[i] not in "aeiou":
consoantes += 1
i += 1
print("O total de consoantes eh: ", consoan... | n = int(input('Informe a quantidade de caracteres: '))
caracteres = []
consoantes = 0
i = 1
while i <= n:
c = input('Informe o %d caracter: ' % i)
caracteres.append(c)
i += 1
i = 0
while i < n:
if caracteres[i] not in 'aeiou':
consoantes += 1
i += 1
print('O total de consoantes eh: ', consoa... |
# Advent of Code 2019 Solutions: Day 2, Puzzle 1
# https://github.com/emddudley/advent-of-code-solutions
with open('input', 'r') as f:
program = [int(x) for x in f.read().strip().split(',')]
program[1] = 12
program[2] = 2
for opcode_index in range(0, len(program), 4):
opcode = program[opcode_index]
if ... | with open('input', 'r') as f:
program = [int(x) for x in f.read().strip().split(',')]
program[1] = 12
program[2] = 2
for opcode_index in range(0, len(program), 4):
opcode = program[opcode_index]
if opcode == 99:
break
addr_a = program[opcode_index + 1]
addr_b = program[opcode_index + 2]
... |
class Solution:
def minDeletionSize(self, A: List[str]) -> int:
minDel = m = len(A[0])
dp = [1] * m
for j in range(m):
for i in range(j):
if all(A[k][i] <= A[k][j] for k in range(len(A))):
dp[j] = max(dp[j], dp[i] + 1)
minDel = min(... | class Solution:
def min_deletion_size(self, A: List[str]) -> int:
min_del = m = len(A[0])
dp = [1] * m
for j in range(m):
for i in range(j):
if all((A[k][i] <= A[k][j] for k in range(len(A)))):
dp[j] = max(dp[j], dp[i] + 1)
min_del... |
"""
https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
"""
# time complexity: O(logn), space complexity: ... | """
https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
"""
class Solution:
def is_power_of_two(self,... |
key = int(input())
n = int(input())
message = ""
for x in range(n):
letters = input()
message += chr(ord(letters) + key)
print(message) | key = int(input())
n = int(input())
message = ''
for x in range(n):
letters = input()
message += chr(ord(letters) + key)
print(message) |
def action_sanitize():
'''Make action suitable for use as a Pose Library
'''
pass
def apply_pose(pose_index=-1):
'''Apply specified Pose Library pose to the rig
:param pose_index: Pose, Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)
:type pose_index: in... | def action_sanitize():
"""Make action suitable for use as a Pose Library
"""
pass
def apply_pose(pose_index=-1):
"""Apply specified Pose Library pose to the rig
:param pose_index: Pose, Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)
:type pose_index: int ... |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def is_same_tree(self, p, q):
if p is None or q is None:
if p != q:
return False
return True
if p.val != q.val:
... | class Treenode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def is_same_tree(self, p, q):
if p is None or q is None:
if p != q:
return False
return True
if p.val != q.val:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.