content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python
"""
CREATED AT: 2021/8/1
Des:
https://leetcode.com/contest/weekly-contest-252/problems/three-divisors/
GITHUB: https://github.com/Jiezhi/myleetcode
"""
class Solution:
def isThree(self, n: int) -> bool:
cnt = 0
for i in range(2, int(n / 2) + 1):
if n % i == 0:
... | """
CREATED AT: 2021/8/1
Des:
https://leetcode.com/contest/weekly-contest-252/problems/three-divisors/
GITHUB: https://github.com/Jiezhi/myleetcode
"""
class Solution:
def is_three(self, n: int) -> bool:
cnt = 0
for i in range(2, int(n / 2) + 1):
if n % i == 0:
cnt += ... |
try:
var1 += 1
except:
var1 = 1
def __quick_unload_script():
print("Unloaded: %s" % str(var1))
print(f"Just edit and save! {var1}")
| try:
var1 += 1
except:
var1 = 1
def __quick_unload_script():
print('Unloaded: %s' % str(var1))
print(f'Just edit and save! {var1}') |
class MissingKeyError(Exception):
pass
class NoneError(Exception):
pass
| class Missingkeyerror(Exception):
pass
class Noneerror(Exception):
pass |
def print_lol(the_list, indent = False, level = 0):
"""This function ..."""
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item, indent, level + 1)
else:
if indent:
for tab_stop in range(level):
print("\t", e... | def print_lol(the_list, indent=False, level=0):
"""This function ..."""
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item, indent, level + 1)
else:
if indent:
for tab_stop in range(level):
print('\t', end=''... |
# Copyright 2018 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.
"""Enforces luci-milo.cfg consistency.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API bui... | """Enforces luci-milo.cfg consistency.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""
presubmit_version = '2.0.0'
use_python3 = True
_ignore_freeze_footer = 'Ignore-Freeze'
_freeze_start = 1639641600
_freeze_end = 1641196800... |
#Also called as Circular Queue
class Queue:
def __init__(self, maxSize):
self.items = maxSize * [None] # To initialize a list with a limit set make a list with the size u want and make all the elements None
self.maxSize = maxSize
self.start = -1
self.top = -1
def __str__(self)... | class Queue:
def __init__(self, maxSize):
self.items = maxSize * [None]
self.maxSize = maxSize
self.start = -1
self.top = -1
def __str__(self):
values = [str(x) for x in self.items]
return ' '.join(values)
def is_full(self):
if self.top + 1 == self.... |
def checkorders(orders: [str]) -> [bool]:
results = []
for i in orders:
flag = True
stock = []
for j in i:
if j in '([{':
stock.append(j)
else:
if stock == []:
flag = False
break
... | def checkorders(orders: [str]) -> [bool]:
results = []
for i in orders:
flag = True
stock = []
for j in i:
if j in '([{':
stock.append(j)
else:
if stock == []:
flag = False
break
... |
a = int(input())
b = int(input())
if a > b:
print(a)
else:
print(b)
| a = int(input())
b = int(input())
if a > b:
print(a)
else:
print(b) |
a,b = map(int,input().split())
ans=0
k=1
while a or b:
ans+=k*(((b%3)-(a%3))%3)
a//=3
b//=3
k*=3
print(ans) | (a, b) = map(int, input().split())
ans = 0
k = 1
while a or b:
ans += k * ((b % 3 - a % 3) % 3)
a //= 3
b //= 3
k *= 3
print(ans) |
# Minimum Remove to Make Valid Parentheses: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
# Given a string s of '(' , ')' and lowercase English characters.
# Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is ... | class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
stack = []
for index in range(len(s)):
char = s[index]
if char == ')':
if len(stack) == 0:
stack.append(index)
elif s[stack[-1]] == '(':
... |
#!user/bin/python
class MyEnv:
"""
"""
def __init__(self):
self.my_env = {
"subnet": "<your_lab_subnet/mask>",
"gateway": "<your_lab_gateway_ip_address>",
"ansible_addr": "<ansible_container_ip_address>",
"web_addr": "<wev_container_ip_address>",
... | class Myenv:
"""
"""
def __init__(self):
self.my_env = {'subnet': '<your_lab_subnet/mask>', 'gateway': '<your_lab_gateway_ip_address>', 'ansible_addr': '<ansible_container_ip_address>', 'web_addr': '<wev_container_ip_address>', 'db_addr': '<db_container_ip_address>', 'phsical_nic': '<NIC name of do... |
app_name = "users"
urlpatterns = [
]
| app_name = 'users'
urlpatterns = [] |
#def divisor is from:
#https://www.w3resource.com/python-exercises/basic/python-basic-1-exercise-24.php
def divisor(n):
for i in range(n):
x = len([i for i in range(1, n+1) if not n % i])
return x
nums = []
i = 0
while i < 20:
preNum = int(input())
if(preNum > 0):
nums.append([diviso... | def divisor(n):
for i in range(n):
x = len([i for i in range(1, n + 1) if not n % i])
return x
nums = []
i = 0
while i < 20:
pre_num = int(input())
if preNum > 0:
nums.append([divisor(preNum), preNum])
i += 1
nums.sort()
f = nums[len(nums) - 1]
x = f.copy()
y = x[::-1]
print(*y, ... |
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high)//2
if nums[mid] == target:
... | class Solution:
def search_insert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
... |
s, t = 7, 11
a, b = 5, 15
m, n = 3, 2
apple = [-2, 2, 1]
orange = [5, -6]
a_score, b_score = 0, 0
''' too slow
for i in apple:
if (a + i) in list(range(s, t+1)):
a_score +=1
for i in orange:
if (b + i) in list(range(s, t+1)):
b_score +=1
'''
for i in apple:
if (a+i >= s) and (a+i <= t):
... | (s, t) = (7, 11)
(a, b) = (5, 15)
(m, n) = (3, 2)
apple = [-2, 2, 1]
orange = [5, -6]
(a_score, b_score) = (0, 0)
' too slow\nfor i in apple:\n if (a + i) in list(range(s, t+1)):\n a_score +=1\n\nfor i in orange:\n if (b + i) in list(range(s, t+1)):\n b_score +=1\n\n'
for i in apple:
if a + i >=... |
class Customer:
id = 1
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
self.id = Customer.id
Customer.id += 1
def __repr__(self):
return f"Customer <{self.id}> {self.name}; Address: {self.address}; Email: ... | class Customer:
id = 1
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
self.id = Customer.id
Customer.id += 1
def __repr__(self):
return f'Customer <{self.id}> {self.name}; Address: {self.address}; Email: ... |
SECRET_KEY = "abc"
FILEUPLOAD_ALLOWED_EXTENSIONS = ["png"]
# FILEUPLOAD_PREFIX = "/cool/upload"
# FILEUPLOAD_LOCALSTORAGE_IMG_FOLDER = "images/boring/"
FILEUPLOAD_RANDOM_FILE_APPENDIX = True
FILEUPLOAD_CONVERT_TO_SNAKE_CASE = True
| secret_key = 'abc'
fileupload_allowed_extensions = ['png']
fileupload_random_file_appendix = True
fileupload_convert_to_snake_case = True |
"""
Exercise 5
Write a program to read through the mail box data and when you find line that
starts with "From", you will split the line into words using the split
function. We are interested in who sent the message which is the second word
on the From line.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
You w... | """
Exercise 5
Write a program to read through the mail box data and when you find line that
starts with "From", you will split the line into words using the split
function. We are interested in who sent the message which is the second word
on the From line.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
You w... |
# 6. Math Power
def math_power(n, p):
power_output = n ** p
print(power_output)
number = float(input())
power = float(input())
math_power(number, power) | def math_power(n, p):
power_output = n ** p
print(power_output)
number = float(input())
power = float(input())
math_power(number, power) |
# https://atcoder.jp/contests/math-and-algorithm/tasks/math_and_algorithm_bj
n = int(input())
xx = [0] * n
yy = [0] * n
for i in range(n):
xx[i], yy[i] = map(int, input().split())
xx.sort()
yy.sort()
ax = 0
ay = 0
cx = 0
cy = 0
for i in range(n):
ax += xx[i] * i - cx
cx += xx[i]
ay += yy[i] * i - cy
... | n = int(input())
xx = [0] * n
yy = [0] * n
for i in range(n):
(xx[i], yy[i]) = map(int, input().split())
xx.sort()
yy.sort()
ax = 0
ay = 0
cx = 0
cy = 0
for i in range(n):
ax += xx[i] * i - cx
cx += xx[i]
ay += yy[i] * i - cy
cy += yy[i]
print(ax + ay) |
"""Defines a rule for runtime test targets."""
load("@io_bazel_rules_go//go:def.bzl", "go_test")
# runtime_test is a macro that will create targets to run the given test target
# with different runtime options.
def runtime_test(
lang,
image,
shard_count = 50,
size = "enormous",
... | """Defines a rule for runtime test targets."""
load('@io_bazel_rules_go//go:def.bzl', 'go_test')
def runtime_test(lang, image, shard_count=50, size='enormous', blacklist_file=''):
args = ['--lang', lang, '--image', image]
data = [':runner']
if blacklist_file != '':
args += ['--blacklist_file', 'tes... |
_version_major = 0
_version_minor = 1
_version_micro = 0
__version__ = "{0:d}.{1:d}.{2:d}".format(
_version_major, _version_minor, _version_micro)
| _version_major = 0
_version_minor = 1
_version_micro = 0
__version__ = '{0:d}.{1:d}.{2:d}'.format(_version_major, _version_minor, _version_micro) |
def troca(i,j,lista):
if (i >= 0 and j >= 0) and (i <= (len(lista) - 1) and j <= (len(lista) - 1)):
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
return lista
def main():
n = int(input())
lista = []
for k in range(n):
lista.append(int(input()))
i = int(input(... | def troca(i, j, lista):
if (i >= 0 and j >= 0) and (i <= len(lista) - 1 and j <= len(lista) - 1):
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
return lista
def main():
n = int(input())
lista = []
for k in range(n):
lista.append(int(input()))
i = int(input())... |
# test
def addTwoNumbers(a, b):
sum = a + b
return sum
def addList(l1):
sum = 0
for i in l1:
sum += i
return sum
add = lambda x, y : x + y
num1 = 1
num2 = 2
print("The sum is ", addTwoNumbers(num1, num2))
numlist = (1, 2, 3)
print(add(10, 20))
print("The sum is ", addList(numlist)... | def add_two_numbers(a, b):
sum = a + b
return sum
def add_list(l1):
sum = 0
for i in l1:
sum += i
return sum
add = lambda x, y: x + y
num1 = 1
num2 = 2
print('The sum is ', add_two_numbers(num1, num2))
numlist = (1, 2, 3)
print(add(10, 20))
print('The sum is ', add_list(numlist))
for i in r... |
#
# PySNMP MIB module MITEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
#!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
"prints a matrix of integers"
row_len = len(matrix)
col_len = len(matrix[0])
for i in range(row_len):
for j in range(col_len):
if j != col_len - 1:
print("{:d}".format(matrix[i][j]), end=' ')
else... | def print_matrix_integer(matrix=[[]]):
"""prints a matrix of integers"""
row_len = len(matrix)
col_len = len(matrix[0])
for i in range(row_len):
for j in range(col_len):
if j != col_len - 1:
print('{:d}'.format(matrix[i][j]), end=' ')
else:
... |
def sum_of_squares(n):
total = 0
for i in range(n):
if i * i < n:
total += i * i
else:
break
return total
| def sum_of_squares(n):
total = 0
for i in range(n):
if i * i < n:
total += i * i
else:
break
return total |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Fireclaw the Fox"
__license__ = """
Simplified BSD (BSD 2-Clause) License.
See License.txt or http://opensource.org/licenses/BSD-2-Clause for more info
"""
| __author__ = 'Fireclaw the Fox'
__license__ = '\nSimplified BSD (BSD 2-Clause) License.\nSee License.txt or http://opensource.org/licenses/BSD-2-Clause for more info\n' |
_base_ = [
'../_base_/models/fcn_r50-d8.py', '../_base_/datasets/pascal_context.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py'
]
model = dict(
decode_head=dict(num_classes=60),
auxiliary_head=dict(num_classes=60),
test_cfg=dict(mode='slide', crop_size=(480, 480), stride=(... | _base_ = ['../_base_/models/fcn_r50-d8.py', '../_base_/datasets/pascal_context.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py']
model = dict(decode_head=dict(num_classes=60), auxiliary_head=dict(num_classes=60), test_cfg=dict(mode='slide', crop_size=(480, 480), stride=(320, 320)))
optimizer =... |
_base_ = [
'../_base_/models/irrpwc.py',
'../_base_/datasets/flyingthings3d_subset_bi_with_occ_384x768.py',
'../_base_/schedules/schedule_s_fine_half.py',
'../_base_/default_runtime.py'
]
custom_hooks = [dict(type='EMAHook')]
data = dict(
train_dataloader=dict(
samples_per_gpu=1, workers_p... | _base_ = ['../_base_/models/irrpwc.py', '../_base_/datasets/flyingthings3d_subset_bi_with_occ_384x768.py', '../_base_/schedules/schedule_s_fine_half.py', '../_base_/default_runtime.py']
custom_hooks = [dict(type='EMAHook')]
data = dict(train_dataloader=dict(samples_per_gpu=1, workers_per_gpu=5, drop_last=True), val_dat... |
class Solution:
def isAlienSorted(self, words, order):
lookup = {c: i for i, c in enumerate(order)}
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
... | class Solution:
def is_alien_sorted(self, words, order):
lookup = {c: i for (i, c) in enumerate(order)}
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
... |
#!/usr/bin/python
# sorting.py
items = { "coins": 7, "pens": 3, "cups": 2,
"bags": 1, "bottles": 4, "books": 5 }
for key in sorted(items.keys()):
print ("%s: %s" % (key, items[key]))
print ("####### #######")
for key in sorted(items.keys(), reverse=True):
print ("%s: %s" % (key, items[key]))
| items = {'coins': 7, 'pens': 3, 'cups': 2, 'bags': 1, 'bottles': 4, 'books': 5}
for key in sorted(items.keys()):
print('%s: %s' % (key, items[key]))
print('####### #######')
for key in sorted(items.keys(), reverse=True):
print('%s: %s' % (key, items[key])) |
# variants
model_type = 'SepDisc'
runner = 'SepDiscRunner01'
lambda_img = 0.001
lambda_lidar = 0.001
src_acc_threshold = 0.6
tgt_acc_threshold = 0.6
img_disc = dict(type='FCDiscriminatorCE', in_dim=64)
img_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
lidar_disc = dict(type='FCDiscriminatorCE', in_dim=64)
lid... | model_type = 'SepDisc'
runner = 'SepDiscRunner01'
lambda_img = 0.001
lambda_lidar = 0.001
src_acc_threshold = 0.6
tgt_acc_threshold = 0.6
img_disc = dict(type='FCDiscriminatorCE', in_dim=64)
img_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
lidar_disc = dict(type='FCDiscriminatorCE', in_dim=64)
lidar_opt = dic... |
def debug(x):
print(x)
### Notebook Magics
# %matplotlib inline
def juptyerConfig(pd, max_columns=500, max_rows = 500, float_format = '{:,.6f}', max_info_rows = 1000, max_categories = 500):
pd.options.display.max_columns = 500
pd.options.display.max_rows = 500
pd.options.display.float_format = float_f... | def debug(x):
print(x)
def juptyer_config(pd, max_columns=500, max_rows=500, float_format='{:,.6f}', max_info_rows=1000, max_categories=500):
pd.options.display.max_columns = 500
pd.options.display.max_rows = 500
pd.options.display.float_format = float_format.format
pd.options.display.max_info_rows... |
# Scores old stuff
#
# Helper functions
#
# FIXME: use ticks instead, teams are either up for the whole tick or down for the whole tick
def _get_uptime_for_team(team_id, cursor):
"""Calculate the uptime for a team.
The uptime is normalized to 0 to 100. An uptime of 100 means the team was
online for the ent... | def _get_uptime_for_team(team_id, cursor):
"""Calculate the uptime for a team.
The uptime is normalized to 0 to 100. An uptime of 100 means the team was
online for the entire tick, while an uptime of 0 means it was not online
at all.
:param int team_id: ID of the team.
:param cursor: Cursor th... |
# Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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... | """A module to handle different character widths on the console.
Some East Asian characters have width of two on console, and combining
characters themselves take no extra space.
See issue 604 [1] for more details about East Asian characters. The issue also
contains `generate_wild_chars.py` script that was originally... |
"""
PASSENGERS
"""
numPassengers = 435
passenger_arriving = (
(2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0), # 0
(1, 5, 1, 0, 0, 0, 2, 2, 0, 1, 0, 0), # 1
(1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0), # 2
(0, 2, 1, 1, 1, 0, 3, 2, 1, 0, 0, 0), # 3
(0, 1, 1, 1, 0, 0, 4, 1, 0, 0, 0, 0), # 4
(1, 0, 0, 1, 0, 0, 1, 3, 0, 1, 0, ... | """
PASSENGERS
"""
num_passengers = 435
passenger_arriving = ((2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0), (1, 5, 1, 0, 0, 0, 2, 2, 0, 1, 0, 0), (1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0), (0, 2, 1, 1, 1, 0, 3, 2, 1, 0, 0, 0), (0, 1, 1, 1, 0, 0, 4, 1, 0, 0, 0, 0), (1, 0, 0, 1, 0, 0, 1, 3, 0, 1, 0, 0), (2, 2, 1, 0, 0, 0, 2, 1, 1, 0,... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class ZookeeperBenchmark(MavenPackage):
"""It is designed to measure the per-request latency of a ZooKeeper
ensem... | class Zookeeperbenchmark(MavenPackage):
"""It is designed to measure the per-request latency of a ZooKeeper
ensemble for a predetermined length of time"""
homepage = 'http://zookeeper.apache.org'
git = 'https://github.com/brownsys/zookeeper-benchmark.git'
version('master', branch='master')
depen... |
n = [ 1 ] + [ 50 ] * 10 + [ 1 ]
with open('8.in', 'r') as f:
totn, m, k, op = [ int(x) for x in f.readline().split() ]
for i in range(m):
f.readline()
for i, v in enumerate(n):
with open('p%d.in' % i, 'w') as o:
o.write('%d 0 %d 2\n' % (v, k))
for j in range(v):
... | n = [1] + [50] * 10 + [1]
with open('8.in', 'r') as f:
(totn, m, k, op) = [int(x) for x in f.readline().split()]
for i in range(m):
f.readline()
for (i, v) in enumerate(n):
with open('p%d.in' % i, 'w') as o:
o.write('%d 0 %d 2\n' % (v, k))
for j in range(v):
... |
# Configuration file for ipython-console.
c = get_config()
#------------------------------------------------------------------------------
# ZMQTerminalIPythonApp configuration
#------------------------------------------------------------------------------
# ZMQTerminalIPythonApp will inherit config from: TerminalIP... | c = get_config() |
"""Constants for the WLED integration."""
# Integration domain
DOMAIN = "wled"
# Attributes
ATTR_COLOR_PRIMARY = "color_primary"
ATTR_DURATION = "duration"
ATTR_FADE = "fade"
ATTR_INTENSITY = "intensity"
ATTR_LED_COUNT = "led_count"
ATTR_MAX_POWER = "max_power"
ATTR_ON = "on"
ATTR_PALETTE = "palette"
ATTR_PLAYLIST = ... | """Constants for the WLED integration."""
domain = 'wled'
attr_color_primary = 'color_primary'
attr_duration = 'duration'
attr_fade = 'fade'
attr_intensity = 'intensity'
attr_led_count = 'led_count'
attr_max_power = 'max_power'
attr_on = 'on'
attr_palette = 'palette'
attr_playlist = 'playlist'
attr_preset = 'preset'
at... |
"""Wrapper macro around parcel cli"""
load("@aspect_bazel_lib//lib:utils.bzl", "path_to_workspace_root")
load("@npm//parcel-bundler:index.bzl", _parcel = "parcel")
def parcel(name, entry_html, data = [], **kwargs):
"""Wrapper macro around parcel cli"""
_parcel(
name = name,
args = [
... | """Wrapper macro around parcel cli"""
load('@aspect_bazel_lib//lib:utils.bzl', 'path_to_workspace_root')
load('@npm//parcel-bundler:index.bzl', _parcel='parcel')
def parcel(name, entry_html, data=[], **kwargs):
"""Wrapper macro around parcel cli"""
_parcel(name=name, args=['build', '%s/$(execpath %s)' % (path_... |
def fib(n):
'''Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,...'''
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
| def fib(n):
"""Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,..."""
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2) |
class Column(object):
def __init__(self, name, dataType):
self._number = 0
self._name = name
self._dataType = dataType
self._length = None
self._default = None
self._notNull = False
self._unique = False
self._constraint = None
self._check = []
... | class Column(object):
def __init__(self, name, dataType):
self._number = 0
self._name = name
self._dataType = dataType
self._length = None
self._default = None
self._notNull = False
self._unique = False
self._constraint = None
self._check = []... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return Non... | class Solution(object):
def middle_node(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
(fast_runer, slow_runer) = (head, head)
while fastRuner and fastRuner.next:
fast_runer = fastRuner.next.next
... |
""" author:
name : Do Viet Chinh
personal email: dovietchinh1998@mgail.com
personal facebook: https://www.facebook.com/profile.php?id=100005935236259
VNOpenAI team: vnopenai@gmail.com
via team :
date:
26.3.2021
""" | """ author:
name : Do Viet Chinh
personal email: dovietchinh1998@mgail.com
personal facebook: https://www.facebook.com/profile.php?id=100005935236259
VNOpenAI team: vnopenai@gmail.com
via team :
date:
26.3.2021
""" |
# Definisikan class Karyawan
class Karyawan:
def __init__(self, nama, usia, pendapatan, insentif_lembur):
self.nama = nama
self.usia = usia
self.pendapatan = pendapatan
self.pendapatan_tambahan = 0
self.insentif_lembur = insentif_lembur
def lembur(self):
self.pend... | class Karyawan:
def __init__(self, nama, usia, pendapatan, insentif_lembur):
self.nama = nama
self.usia = usia
self.pendapatan = pendapatan
self.pendapatan_tambahan = 0
self.insentif_lembur = insentif_lembur
def lembur(self):
self.pendapatan_tambahan += self.ins... |
TEMPLATE = """import numpy as np
import unittest
from {name}.algorithm.research_algorithm import {name_upper}Estimator
class Test{name_upper}Estimator(unittest.TestCase):
def test_predict(self):
multiplier = 2
input_data = np.random.random([1, 2])
expected_result = input_data * multiplie... | template = 'import numpy as np\nimport unittest\n\nfrom {name}.algorithm.research_algorithm import {name_upper}Estimator\n\n\nclass Test{name_upper}Estimator(unittest.TestCase):\n\n def test_predict(self):\n multiplier = 2\n input_data = np.random.random([1, 2])\n expected_result = input_data * ... |
"""A module for defining WORKSPACE dependencies required for rules_foreign_cc"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load(
"//foreign_cc/private/shell_toolchain/toolchains:ws_defs.bzl",
shell_toolchain_workspace_ini... | """A module for defining WORKSPACE dependencies required for rules_foreign_cc"""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('//foreign_cc/private/shell_toolchain/toolchains:ws_defs.bzl', shell_toolchain_workspace_initalization... |
class Solution:
def wordSquares(self, words):
"""
:type words: List[str]
:rtype: List[List[str]]
"""
n = len(words[0])
pres = collections.defaultdict(list)
for word in words:
for i in range(n):
pres[word[:i]].append(word)
de... | class Solution:
def word_squares(self, words):
"""
:type words: List[str]
:rtype: List[List[str]]
"""
n = len(words[0])
pres = collections.defaultdict(list)
for word in words:
for i in range(n):
pres[word[:i]].append(word)
... |
#!/usr/bin/env python
# encoding: utf-8
name = "Non Atom Centered Platts Groups"
shortDesc = ""
longDesc = """
"""
entry(
index = -3,
label = "R",
group =
"""
1 * R u0
""",
solute = None,
shortDesc = """""",
longDesc =
"""
""",
)
entry(
index = -2,
label = "CO",
group =
"""
1 ... | name = 'Non Atom Centered Platts Groups'
short_desc = ''
long_desc = '\n\n'
entry(index=-3, label='R', group='\n1 * R u0\n', solute=None, shortDesc='', longDesc='\n\n')
entry(index=-2, label='CO', group='\n1 * CO u0\n', solute=None, shortDesc='', longDesc='\n\n')
entry(index=1, label='Oss(CdsOd)', group='\n1 * CO ... |
def permutations(arr):
arr1 = arr.copy()
print(" ".join(arr1), end=" ")
count = len(arr1)
for x in range(len(arr)):
tmp = []
for i in arr:
for k in arr1:
if i not in k:
tmp.append(k + i)
count += 1
p... | def permutations(arr):
arr1 = arr.copy()
print(' '.join(arr1), end=' ')
count = len(arr1)
for x in range(len(arr)):
tmp = []
for i in arr:
for k in arr1:
if i not in k:
tmp.append(k + i)
count += 1
print(' '.join... |
class AvailableCashError(Exception):
def __init__(self, available_amount, requested_amount):
error_message = (
'There is not enough available cash in the account. ' +
'Amount available is {available_amount}, amount requested is {requested_amount}. ' +
'\nPlease add funds ... | class Availablecasherror(Exception):
def __init__(self, available_amount, requested_amount):
error_message = ('There is not enough available cash in the account. ' + 'Amount available is {available_amount}, amount requested is {requested_amount}. ' + '\nPlease add funds or reduce the requested amount.').fo... |
# --------------
##File path for the file
file_path
#Code starts here
def read_file(path):
f=open(path,'r')
sentence=f.readline()
f.close()
return sentence
sample_message=read_file(file_path)
print(sample_message)
# --------------
#Code starts here
file_path_1
file_path_2
def fus... | file_path
def read_file(path):
f = open(path, 'r')
sentence = f.readline()
f.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
file_path_1
file_path_2
def fuse_msg(message_a, message_b):
a = int(message_a)
b = int(message_b)
quotient = b // a
return st... |
#
# Copyright SAS Institute
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | class Sasconfignotfounderror(Exception):
def __init__(self, path: str):
self.path = path
def __str__(self):
return 'Configuration path {} does not exist.'.format(self.path)
class Sasconfignotvaliderror(Exception):
def __init__(self, defn: str, msg: str=None):
self.defn = defn if ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
## Onera M6 configuration module for geoGen
#
# Adrien Crovato
def getParams():
p = {}
# Wing parameters (nP planforms for half-wing)
p['airfPath'] = '../airfoils' # path pointing the airfoils directory (relative to this config file)
p['airfName'] = ['one... | def get_params():
p = {}
p['airfPath'] = '../airfoils'
p['airfName'] = ['oneraM6.dat', 'oneraM6.dat']
p['span'] = [1.196]
p['taper'] = [0.562]
p['sweep'] = [30]
p['dihedral'] = [0]
p['twist'] = [0, 0]
p['rootChord'] = 0.8059
p['offset'] = [0.0, 0.0]
p['coWingtip'] = True
... |
# A function is a block of organized, reusable code that is used to perform a single, related action.
# Define a function.
def fun():
print("What's a Funtion ?")
# Functions with Arguments.
def funArg(arg1,arg2):
print(arg1," ",arg2)
# return(arg1," ",arg2)
#Functions that returns a value... | def fun():
print("What's a Funtion ?")
def fun_arg(arg1, arg2):
print(arg1, ' ', arg2)
def fun_x(a):
return a + a
fun()
fun_arg(50, 50)
print(fun_arg(50, 50))
print(fun_x(50)) |
"""
Contains choice collections for model fields.
Add choices here instead of writing them in models.py.
"""
# Menu Item
MENU_ITEM_CHOICES = (("VEGETARIAN", "Vegetarian"), ("ALL", "All"))
MENU_ITEM_CATEGORY = (
("CHINESE", "Chinese Food"),
("SOUTH INDIAN", "South Indian Food"),
("FAST FOOD", "Fast ... | """
Contains choice collections for model fields.
Add choices here instead of writing them in models.py.
"""
menu_item_choices = (('VEGETARIAN', 'Vegetarian'), ('ALL', 'All'))
menu_item_category = (('CHINESE', 'Chinese Food'), ('SOUTH INDIAN', 'South Indian Food'), ('FAST FOOD', 'Fast Food'), ('DRINKS', 'Drinks... |
# Frames Per Second
FPS = 60
# SCREEN
SCREEN_COLUMNS_NUMBER = 6
SCREEN_ROWS_NUMBER = 7
SCREEN_COLUMN_SIZE = 96
SCREEN_ROW_SIZE = 96
SCREEN_WIDTH = SCREEN_COLUMNS_NUMBER * SCREEN_COLUMN_SIZE
SCREEN_HEIGHT = SCREEN_ROWS_NUMBER * SCREEN_ROW_SIZE
# Colors for display.
COLOR_WHITE = (255, 255, 255)
CO... | fps = 60
screen_columns_number = 6
screen_rows_number = 7
screen_column_size = 96
screen_row_size = 96
screen_width = SCREEN_COLUMNS_NUMBER * SCREEN_COLUMN_SIZE
screen_height = SCREEN_ROWS_NUMBER * SCREEN_ROW_SIZE
color_white = (255, 255, 255)
color_black = (0, 0, 0)
color_green = (0, 128, 0)
color_blue = (0, 0, 128)
c... |
def deny(blacklist):
"""
Decorates a handler to filter out a blacklist of commands.
The decorated handler will not be called if message.command is in the
blacklist:
@deny(['A', 'B'])
def handle_everything_except_a_and_b(client, message):
pass
Single-item blacklists may... | def deny(blacklist):
"""
Decorates a handler to filter out a blacklist of commands.
The decorated handler will not be called if message.command is in the
blacklist:
@deny(['A', 'B'])
def handle_everything_except_a_and_b(client, message):
pass
Single-item blacklists may... |
class Linked_List():
def __init__(self, head):
self.head = head
class Node():
def __init__(self, data):
self.data = data
self.next = None
# O(N) space and O(N) time
def partition_linked_list(linked_list, partition):
less_than = []
greater_than_or_equal = []
next_one = linke... | class Linked_List:
def __init__(self, head):
self.head = head
class Node:
def __init__(self, data):
self.data = data
self.next = None
def partition_linked_list(linked_list, partition):
less_than = []
greater_than_or_equal = []
next_one = linked_list.head
while next_on... |
# -*- coding: utf-8 -*-
# See LICENSE file for full copyright and licensing details.
{
'name': 'Library Management system odoo',
'version': "10.0.1.0.6",
'author': "David Kimolo",
'category': 'School Management',
'website': '',
'license': "AGPL-3",
'summary': """A Module For Library Managem... | {'name': 'Library Management system odoo', 'version': '10.0.1.0.6', 'author': 'David Kimolo', 'category': 'School Management', 'website': '', 'license': 'AGPL-3', 'summary': 'A Module For Library Management For School\n Library Management\n Library\n School Library\n ... |
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# External libraries
# Markdown
'markdownx',
# Bootstrap
'bootstrap4',
# Our apps
'... | installed_apps = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'markdownx', 'bootstrap4', 'apps.blocks', 'apps.bot', 'apps.custom_admin', 'apps.lp', 'apps.results', 'apps.services', 'apps.tags', 'apps.qu... |
#!/usr/bin/python
# Copyright (c) 2010 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.
"""PyAuto Errors."""
class JSONInterfaceError(RuntimeError):
"""Represent an error in the JSON ipc interface."""
pass
class NTPT... | """PyAuto Errors."""
class Jsoninterfaceerror(RuntimeError):
"""Represent an error in the JSON ipc interface."""
pass
class Ntpthumbnailnotshownerror(RuntimeError):
"""Represent an error from attempting to manipulate a NTP thumbnail that
is not visible to a real user."""
pass |
class Sorting:
@staticmethod
def insertion_sort(arr):
for i in range(1, len(arr)):
curr = arr[i]
j = i - 1
while j >= 0 and curr < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = curr
return arr
if __name__ == "__m... | class Sorting:
@staticmethod
def insertion_sort(arr):
for i in range(1, len(arr)):
curr = arr[i]
j = i - 1
while j >= 0 and curr < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = curr
return arr
if __name__ == '__ma... |
# coding: utf-8
# (C) Copyright IBM Corp. 2018, 2019.
#
# 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... | class Synthesizecallback(object):
def __init__(self):
pass
def on_connected(self):
"""
Called when a Websocket connection was made
"""
def on_error(self, error):
"""
Called when there is an error in the Websocket connection.
"""
def on_content_... |
HERO = {'B': 'Batman', 'J': 'Joker', 'R': 'Robin'}
OUTPUT = '{}: {}'.format
class BatmanQuotes(object):
@staticmethod
def get_quote(quotes, hero):
for i, a in enumerate(hero):
if i == 0:
hero = HERO[a]
elif a.isdigit():
quotes = quotes[int(a)]
... | hero = {'B': 'Batman', 'J': 'Joker', 'R': 'Robin'}
output = '{}: {}'.format
class Batmanquotes(object):
@staticmethod
def get_quote(quotes, hero):
for (i, a) in enumerate(hero):
if i == 0:
hero = HERO[a]
elif a.isdigit():
quotes = quotes[int(a)]
... |
numBlanks = 0
golden = ["Emptiness", "fear", "mountain"]
newLines = []
with open('fill-blanks.txt', 'r') as f:
for line in f:
if '...' in line:
blank = input("Fill the blank in " + line)
if blank == golden[numBlanks]:
newLine = line.replace("...", blank)
e... | num_blanks = 0
golden = ['Emptiness', 'fear', 'mountain']
new_lines = []
with open('fill-blanks.txt', 'r') as f:
for line in f:
if '...' in line:
blank = input('Fill the blank in ' + line)
if blank == golden[numBlanks]:
new_line = line.replace('...', blank)
... |
array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
SENTINEL = 10**12
def merge(array, left, mid, right):
L = array[left:mid]
R = array[mid:right]
L.append(SENTINEL)
R.append(SENTINEL)
i = j = 0
for k in range(left, right):
if L[i] <= R[j]:
arr... | array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
sentinel = 10 ** 12
def merge(array, left, mid, right):
l = array[left:mid]
r = array[mid:right]
L.append(SENTINEL)
R.append(SENTINEL)
i = j = 0
for k in range(left, right):
if L[i] <= R[j]:
arra... |
ACTIONS = ["Attribution", "CommericalUse", "DerivativeWorks", "Distribution", "Notice", "Reproduction", "ShareAlike", "Sharing", "SourceCode", "acceptTracking", "adHocShare", "aggregate", "annotate", "anonymize", "append", "appendTo", "archive", "attachPolicy", "attachSource", "attribute", "commercialize", "compensate"... | actions = ['Attribution', 'CommericalUse', 'DerivativeWorks', 'Distribution', 'Notice', 'Reproduction', 'ShareAlike', 'Sharing', 'SourceCode', 'acceptTracking', 'adHocShare', 'aggregate', 'annotate', 'anonymize', 'append', 'appendTo', 'archive', 'attachPolicy', 'attachSource', 'attribute', 'commercialize', 'compensate'... |
_base_ = [
'../_base_/models/regnet/regnetx_400mf.py',
'../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs1024_coslr.py',
'../_base_/default_runtime.py'
]
# Precise BN hook will update the bn stats, so this hook should be executed
# before CheckpointHook, which has priority of 'NORM... | _base_ = ['../_base_/models/regnet/regnetx_400mf.py', '../_base_/datasets/imagenet_bs32.py', '../_base_/schedules/imagenet_bs1024_coslr.py', '../_base_/default_runtime.py']
custom_hooks = [dict(type='PreciseBNHook', num_samples=8192, interval=1, priority='ABOVE_NORMAL')]
optimizer = dict(lr=0.8, nesterov=True)
dataset_... |
###########################################################################
#
# Copyright 2020 Google 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
#
# https://www.apache.org/l... | conversion_status__schema = [[{'name': 'childDirectedTreatment', 'type': 'BOOLEAN', 'mode': 'NULLABLE'}, {'name': 'customVariables', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{'description': '', 'name': 'kind', 'type': 'STRING', 'mode': 'NULLABLE'}, {'description': 'U1, U10, U100, U11, U12, U13, U14, U15, U16, U... |
with open("input") as file:
lines = [line.split(" ") for line in file.read().strip().split("\n")]
register_names = set([line[0] for line in lines])
registers = {}
for name in register_names:
registers[name] = 0
operations = {
"dec": lambda r,v: r-v,
"inc": lambda r,v: r+v }
... | with open('input') as file:
lines = [line.split(' ') for line in file.read().strip().split('\n')]
register_names = set([line[0] for line in lines])
registers = {}
for name in register_names:
registers[name] = 0
operations = {'dec': lambda r, v: r - v, 'inc': lambda r, v: r + v}
compariso... |
# Source: https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/mean.py
def get_mean(norm_value=255, dataset='activitynet'):
# Below values are in RGB order
assert dataset in ['activitynet', 'kinetics', 'ucf101']
if dataset == 'activitynet':
return [114.7748/norm_value, 107.7354/norm_value... | def get_mean(norm_value=255, dataset='activitynet'):
assert dataset in ['activitynet', 'kinetics', 'ucf101']
if dataset == 'activitynet':
return [114.7748 / norm_value, 107.7354 / norm_value, 99.475 / norm_value]
elif dataset == 'kinetics':
return [110.63666788 / norm_value, 103.16065604 / n... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"say_hello": "00_core.ipynb",
"say_bye": "00_core.ipynb",
"optimize_bayes_param": "01_bayes_opt.ipynb",
"ReadTabBatchIdentity": "02_tab_ae.ipynb",
"TabularPandasIdentity": ... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'say_hello': '00_core.ipynb', 'say_bye': '00_core.ipynb', 'optimize_bayes_param': '01_bayes_opt.ipynb', 'ReadTabBatchIdentity': '02_tab_ae.ipynb', 'TabularPandasIdentity': '02_tab_ae.ipynb', 'TabDataLoaderIdentity': '02_tab_ae.ipynb', 'RecreatedLoss... |
C = "C"
CPP = "Cpp"
CSHARP = "CSharp"
GO = "Go"
JAVA = "Java"
JAVASCRIPT = "JavaScript"
OBJC = "ObjC"
PYTHON = "Python" # synonym for PYTHON3
PYTHON2 = "Python2"
PYTHON3 = "Python3"
RUST = "Rust"
SWIFT = "Swift"
def supported():
"""Returns the supported languages.
Returns:
the list of supported languag... | c = 'C'
cpp = 'Cpp'
csharp = 'CSharp'
go = 'Go'
java = 'Java'
javascript = 'JavaScript'
objc = 'ObjC'
python = 'Python'
python2 = 'Python2'
python3 = 'Python3'
rust = 'Rust'
swift = 'Swift'
def supported():
"""Returns the supported languages.
Returns:
the list of supported languages.
"""
return ... |
"""
Build rule for open source tf.text libraries.
"""
def py_tf_text_library(
name,
srcs = [],
deps = [],
visibility = None,
cc_op_defs = [],
cc_op_kernels = []):
"""Creates build rules for TF.Text ops as shared libraries.
Defines three targets:
<name>
... | """
Build rule for open source tf.text libraries.
"""
def py_tf_text_library(name, srcs=[], deps=[], visibility=None, cc_op_defs=[], cc_op_kernels=[]):
"""Creates build rules for TF.Text ops as shared libraries.
Defines three targets:
<name>
Python library that exposes all ops defined in `cc_op_d... |
list_of_numbers_as_strings = input().split(", ")
for index in range(len(list_of_numbers_as_strings)):
number = int(list_of_numbers_as_strings[index])
if number == 0:
list_of_numbers_as_strings.remove(str(0))
list_of_numbers_as_strings.append(str(0))
print(list_of_numbers_as_strings)
| list_of_numbers_as_strings = input().split(', ')
for index in range(len(list_of_numbers_as_strings)):
number = int(list_of_numbers_as_strings[index])
if number == 0:
list_of_numbers_as_strings.remove(str(0))
list_of_numbers_as_strings.append(str(0))
print(list_of_numbers_as_strings) |
##
# Copyright (c) 2006-2018 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | """
PyKerberos Function Description.
"""
class Krberror(Exception):
pass
class Basicautherror(KrbError):
pass
class Gsserror(KrbError):
pass
def check_password(user, pswd, service, default_realm):
"""
This function provides a simple way to verify that a user name and password
match those nor... |
"""
Provide friendlier Kotlin rule exports.
"""
load(
"@io_bazel_rules_kotlin//kotlin:kotlin.bzl",
_kt_jvm_binary = "kt_jvm_binary",
_kt_jvm_library = "kt_jvm_library",
)
kt_jvm_library = _kt_jvm_library
kt_jvm_binary = _kt_jvm_binary
| """
Provide friendlier Kotlin rule exports.
"""
load('@io_bazel_rules_kotlin//kotlin:kotlin.bzl', _kt_jvm_binary='kt_jvm_binary', _kt_jvm_library='kt_jvm_library')
kt_jvm_library = _kt_jvm_library
kt_jvm_binary = _kt_jvm_binary |
def query(self, sql, *args):
'''Mixin method for the XXXBase class.
conn should be a cm.db.Connection instance.'''
conn = self._get_connection()
return conn.query(sql, *args)
def get_connection(self):
'''Mixin method for the XXXBase class.
Returns a cm.db.Connection instance.'''
raise 'No i... | def query(self, sql, *args):
"""Mixin method for the XXXBase class.
conn should be a cm.db.Connection instance."""
conn = self._get_connection()
return conn.query(sql, *args)
def get_connection(self):
"""Mixin method for the XXXBase class.
Returns a cm.db.Connection instance."""
raise 'No i... |
##Config file for lifetime_spyrelet.py in spyre/spyre/spyrelet/
# Device List
devices = {
'vna':[
'lantz.drivers.VNA_Keysight.E5071B',
['TCPIP0::A-E5071B-03400::inst0::INSTR'],
{}
],
'source':[
'lantz.drivers.mwsource.SynthNVPro',
['ASRL16::INSTR'],
{}
]
... | devices = {'vna': ['lantz.drivers.VNA_Keysight.E5071B', ['TCPIP0::A-E5071B-03400::inst0::INSTR'], {}], 'source': ['lantz.drivers.mwsource.SynthNVPro', ['ASRL16::INSTR'], {}]}
spyrelets = {'freqSweep_Keysight': ['spyre.spyrelets.freqSweep_VNA_Keysight_spyrelet.Sweep', {'vna': 'vna', 'source': 'source'}, {}]} |
height = int(input())
for i in range(1, height + 1):
for j in range(1,i+1):
if(i == height or j == 1 or i == j):
print(i,end=" ")
else:
print(end=" ")
print()
# Sample Input :- 5
# Output :-
# 1
# 2 2
# 3 3
# 4 4
# 5 5 5 5 5
| height = int(input())
for i in range(1, height + 1):
for j in range(1, i + 1):
if i == height or j == 1 or i == j:
print(i, end=' ')
else:
print(end=' ')
print() |
# -*- coding:utf-8-*-
name = ["gyj","dzj","why","zz","wwb","zke","ljx","syb","yxd"]
print(name)
name.reverse()
print(name)
print(len(name))
| name = ['gyj', 'dzj', 'why', 'zz', 'wwb', 'zke', 'ljx', 'syb', 'yxd']
print(name)
name.reverse()
print(name)
print(len(name)) |
"""
Exercise 08: Write a Python program to sort a list of elements
using quick sort algorithm.
"""
def quickSort(alist):
"""
Quick sort algrithm, In-place version.
"""
def partition(alist, left, right):
pivot = alist[right - 1]
i = left - 1
for j in range(left, right):
... | """
Exercise 08: Write a Python program to sort a list of elements
using quick sort algorithm.
"""
def quick_sort(alist):
"""
Quick sort algrithm, In-place version.
"""
def partition(alist, left, right):
pivot = alist[right - 1]
i = left - 1
for j in range(left, right):
... |
def flatten(seq):
r = []
for x in seq:
if type(x) == list:
r += flatten(x)
else:
r.append(x)
return r
seq = [1,[2,3],4]
seq = [1,[2,[5,6],3],4]
print(seq, '-->', flatten(seq))
| def flatten(seq):
r = []
for x in seq:
if type(x) == list:
r += flatten(x)
else:
r.append(x)
return r
seq = [1, [2, 3], 4]
seq = [1, [2, [5, 6], 3], 4]
print(seq, '-->', flatten(seq)) |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'nonassocLESSMOREEQUALSTOMOREEQUALLESSEQUALNOTEQUALleftPLUSMINUSleftTIMESDIVIDEleftANDORrightUMINUSINT FLOAT PLUS MINUS TIMES DIVIDE EQUALS LPAREN RPAREN LCURLBRACKET RCURLBRACKET ID COMMENT ST... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'nonassocLESSMOREEQUALSTOMOREEQUALLESSEQUALNOTEQUALleftPLUSMINUSleftTIMESDIVIDEleftANDORrightUMINUSINT FLOAT PLUS MINUS TIMES DIVIDE EQUALS LPAREN RPAREN LCURLBRACKET RCURLBRACKET ID COMMENT STRING ASSIGN SEMICOLON COMMA POINT NOT EQUALSTO MORE LESS MOREEQUAL LES... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Hai-Tao Yu
# 26/09/2018
# https://y-research.github.io
"""Description
""" | """Description
""" |
class Level:
def __init__(self, current_level=1, current_xp=0, level_up_base=30, level_up_factor=30):
#Original (self, current_level=1, current_xp=0, level_up_base=200, level_up_factor=150)
self.current_level = current_level
self.current_xp = current_xp
self.level_up_base = level_up_... | class Level:
def __init__(self, current_level=1, current_xp=0, level_up_base=30, level_up_factor=30):
self.current_level = current_level
self.current_xp = current_xp
self.level_up_base = level_up_base
self.level_up_factor = level_up_factor
@property
def experience_to_next_l... |
version = 1
disable_existing_loggers = False
loggers = {
'sanic.root': {
'level': 'DEBUG',
'handlers': ['console', 'root_file'],
'propagate': True
},
'sanic.error': {
'level': 'ERROR',
'handlers': ['error_file'],
'propagate': True
},
'sanic.access': {... | version = 1
disable_existing_loggers = False
loggers = {'sanic.root': {'level': 'DEBUG', 'handlers': ['console', 'root_file'], 'propagate': True}, 'sanic.error': {'level': 'ERROR', 'handlers': ['error_file'], 'propagate': True}, 'sanic.access': {'level': 'INFO', 'handlers': ['access_file'], 'propagate': True}}
handlers... |
#Printing Stars in 'C' Shape !
'''
****
*
*
*
*
*
****
'''
for row in range(7):
for col in range(5):
if (col==0 and (row!=0 and row!=6)) or (row==0 or row==6) and (col>0):
print('*',end='')
else:
print(end=' ')
print() | """
****
*
*
*
*
*
****
"""
for row in range(7):
for col in range(5):
if col == 0 and (row != 0 and row != 6) or ((row == 0 or row == 6) and col > 0):
print('*', end='')
else:
print(end=' ')
print() |
# Copyright (c) 2019 Kevin Weiss, for HAW Hamburg <kevin.weiss@haw-hamburg.de>
#
# This file is subject to the terms and conditions of the MIT License. See the
# file LICENSE in the top level directory for more details.
# SPDX-License-Identifier: MIT
"""packet init for BPH PAL
"""
| """packet init for BPH PAL
""" |
# Copyright 2018, OpenCensus Authors
#
# 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 w... | class Tagmap(object):
""" A tag map is a map of tags from key to value
:type tags: list(:class: '~opencensus.tags.tag.Tag')
:param tags: a list of tags
"""
def __init__(self, tags=None):
self._map = {}
if tags is not None:
self.tags = tags
for tag in self.t... |
def Main():
a = 1
b = 2
c = 3
e = 4
d = a + b - c * e
return d
| def main():
a = 1
b = 2
c = 3
e = 4
d = a + b - c * e
return d |
# Parameters:
# MON_PERIOD : Number of seconds the temperature is read.
# MON_INTERVAL : Number of seconds the temperature is checked.
# TEMP_HIGH : Value in Celsius degree on that a warning e-mail is sent if temperature is above it.
# TEMP_CRITICAL : Value in Celsius degree on that the device is shutted down ... | mon_period = 1
mon_interval = 600
temp_high = 85.0
temp_critical = 90.0 |
material = []
for i in range(int(input())):
material.append(int(input()))
srted = sorted(material)
if srted == material:
print("YES")
else:
print("NO") | material = []
for i in range(int(input())):
material.append(int(input()))
srted = sorted(material)
if srted == material:
print('YES')
else:
print('NO') |
PALETTE = (
'#51A351',
'#f89406',
'#7D1935',
'#4A96AD',
'#DE1B1B',
'#E9E581',
'#A2AB58',
'#FFE658',
'#118C4E',
'#193D4F',
)
LABELS = {
'cpu_user': 'CPU time spent in user mode, %',
'cpu_nice': 'CPU time spent in user mode with low priority (nice), %',
'cpu_sys': 'CPU... | palette = ('#51A351', '#f89406', '#7D1935', '#4A96AD', '#DE1B1B', '#E9E581', '#A2AB58', '#FFE658', '#118C4E', '#193D4F')
labels = {'cpu_user': 'CPU time spent in user mode, %', 'cpu_nice': 'CPU time spent in user mode with low priority (nice), %', 'cpu_sys': 'CPU time spent in system mode, %', 'cpu_idle': 'CPU time spe... |
def alphabet_war(reinforces, airstrikes):
n=len(reinforces[0])
r=[]
for _ in range(n):
r.append([])
for reinforce in reinforces:
for i in range(n):
r[i].append(reinforce[i])
a=[]
for i in range(n):
a.append(r[i].pop(0))
for airstrike in airstrikes:
... | def alphabet_war(reinforces, airstrikes):
n = len(reinforces[0])
r = []
for _ in range(n):
r.append([])
for reinforce in reinforces:
for i in range(n):
r[i].append(reinforce[i])
a = []
for i in range(n):
a.append(r[i].pop(0))
for airstrike in airstrikes:
... |
class UnknownLogKind(ValueError):
"""Exception thrown when an unknown ``kind`` is passed."""
def __init__(self, value):
"""
Construct the exception.
:param value: The invalid kind value passed in.
"""
message = "Unknown log entry kind %r" % value
super(UnknownLo... | class Unknownlogkind(ValueError):
"""Exception thrown when an unknown ``kind`` is passed."""
def __init__(self, value):
"""
Construct the exception.
:param value: The invalid kind value passed in.
"""
message = 'Unknown log entry kind %r' % value
super(UnknownLo... |
# encoding: utf-8
"""
ordereddict.py
Created by Thomas Mangin on 2013-03-18.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
# ================================================================== OrderedDict
# This is only an hack until we drop support for python version < 2.7
class OrderedDict(dict):... | """
ordereddict.py
Created by Thomas Mangin on 2013-03-18.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
class Ordereddict(dict):
def __init__(self, args):
dict.__init__(self, args)
self._order = [_ for (_, __) in args]
def __setitem__(self, key, value):
dict.__setit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.