content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python3
# set Blinkt! brightness, IT BURNS MEEEEEE, 100 is the max
BRIGHTNESS = 10
# define colour values for Blinkt! LEDs. Edit as you please...
COLOUR_MAP = { 'level6': { 'r': 155, 'g': 0, 'b': 200, 'name': 'magenta' },
'level5': { 'r': 255, 'g': 0, 'b': 0, 'name': 'red' },
... | brightness = 10
colour_map = {'level6': {'r': 155, 'g': 0, 'b': 200, 'name': 'magenta'}, 'level5': {'r': 255, 'g': 0, 'b': 0, 'name': 'red'}, 'level4': {'r': 255, 'g': 30, 'b': 0, 'name': 'orange'}, 'level3': {'r': 180, 'g': 100, 'b': 0, 'name': 'yellow'}, 'level2': {'r': 0, 'g': 255, 'b': 0, 'name': 'green'}, 'level1'... |
class Solution:
def largestRectangleArea(self, heights: list[int]) -> int:
heights.append(0)
stack: list[int] = [-1]
ans = 0
for i, h in enumerate(heights):
while stack and h <= heights[stack[-1]]:
curH = heights[stack.pop()]
if not stack: ... | class Solution:
def largest_rectangle_area(self, heights: list[int]) -> int:
heights.append(0)
stack: list[int] = [-1]
ans = 0
for (i, h) in enumerate(heights):
while stack and h <= heights[stack[-1]]:
cur_h = heights[stack.pop()]
if not s... |
# Problem: Decode Ways
# Difficulty: Medium
# Category: String, DP
# Leetcode 91: https://leetcode.com/problems/decode-ways/discuss/
"""
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine th... | """
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The numb... |
def solve(x: int) -> int:
x = y # err
z = x + 1
return y # err
| def solve(x: int) -> int:
x = y
z = x + 1
return y |
number = int(input())
counter = int(input())
number_add = number
list_numbers = [number]
for i in range(counter - 1):
number_add += number
list_numbers.append(number_add)
print(list_numbers)
| number = int(input())
counter = int(input())
number_add = number
list_numbers = [number]
for i in range(counter - 1):
number_add += number
list_numbers.append(number_add)
print(list_numbers) |
# Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
# Example 1:
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
class Solution(object):
def reverseWords(self, s):
"""
... | class Solution(object):
def reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
list1 = [word[::-1] for word in s.split(' ')]
return ' '.join(list1) |
def plot_data(data, ax, keys=None, width=0.5, colors=None):
if keys is None:
keys = ['Latent Test error', 'Test Information Loss']
if colors is None:
colors = ['blue', 'red']
for i, entry in enumerate(data):
h1 = entry[keys[0]]
h2 = h1 + entry[keys[1]]
ax.fill_betwee... | def plot_data(data, ax, keys=None, width=0.5, colors=None):
if keys is None:
keys = ['Latent Test error', 'Test Information Loss']
if colors is None:
colors = ['blue', 'red']
for (i, entry) in enumerate(data):
h1 = entry[keys[0]]
h2 = h1 + entry[keys[1]]
ax.fill_betwe... |
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-3-Clause
#
# Constants for MIDI notes.
#
# For example:
# F# in Octave 3: O3.Fs
# C# in Octave -2: On2.Cs
# D-flat in Octave 1: O1.Db
# D in Octave 0: O0.D
# E in Octave 2: O2.E
class Octave:
def __init__(self, base):
... | class Octave:
def __init__(self, base):
self.C = base
self.Cs = base + 1
self.Db = base + 1
self.D = base + 2
self.Ds = base + 3
self.Eb = base + 3
self.E = base + 4
self.F = base + 5
self.Fs = base + 6
self.Gb = base + 6
self.... |
class Task:
def __init__(self, id, title):
self.title = title
self.id = id
self.status = "new"
| class Task:
def __init__(self, id, title):
self.title = title
self.id = id
self.status = 'new' |
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-value... | """
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-value... |
def problem(a):
try:
return float(a) * 50 + 6
except ValueError:
return "Error" | def problem(a):
try:
return float(a) * 50 + 6
except ValueError:
return 'Error' |
class AccountInfo():
def __init__(self, row_id, email, password, cookies, status_id):
self.row_id = row_id
self.email = email
self.password = password
self.cookies = cookies
self.status_id = status_id
def __repr__(self):
return f"id: {self.row_id}, email: {self... | class Accountinfo:
def __init__(self, row_id, email, password, cookies, status_id):
self.row_id = row_id
self.email = email
self.password = password
self.cookies = cookies
self.status_id = status_id
def __repr__(self):
return f'id: {self.row_id}, email: {self.em... |
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""
Given an array of integers numbers that is already
sorted in ascending order, find two numbers such that
they add up to a specific target number.
Return the indices of the two numb... | class Solution:
def two_sum(self, numbers: List[int], target: int) -> List[int]:
"""
Given an array of integers numbers that is already
sorted in ascending order, find two numbers such that
they add up to a specific target number.
Return the indices of the two numbers (1-... |
"""
coding: utf-8
Created on 17/11/2020
@author: github.com/edrmonteiro
From: Hackerrank challenges
Language: Python
Title: Sorting: Bubble Sort
Consider the following version of Bubble Sort:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in dec... | """
coding: utf-8
Created on 17/11/2020
@author: github.com/edrmonteiro
From: Hackerrank challenges
Language: Python
Title: Sorting: Bubble Sort
Consider the following version of Bubble Sort:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in dec... |
class ssdict:
def __init__(self, ss, param, collectiontype):
factory = {
'projects': self.getProjects,
'reviews': self.getReviews,
'items': self.getItems,
'comments': self.getComments,
}
func = factory[collectiontype]
self.collection = ... | class Ssdict:
def __init__(self, ss, param, collectiontype):
factory = {'projects': self.getProjects, 'reviews': self.getReviews, 'items': self.getItems, 'comments': self.getComments}
func = factory[collectiontype]
self.collection = func(ss, param)
def get_projects(self, ss, accountid)... |
#
# PySNMP MIB module CISCOSB-ippreflist-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-ippreflist-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:08:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ... |
"""
Raincoat comments that are checked in acceptance tests
"""
def simple_function():
# Raincoat: pypi package: raincoat==0.1.4 path: raincoat/_acceptance_test.py element: use_umbrella # noqa
# Raincoat: pypi package: raincoat==0.1.4 path: raincoat/_acceptance_test.py element: Umbrella.open # noqa
# Rai... | """
Raincoat comments that are checked in acceptance tests
"""
def simple_function():
pass
raise NotImplementedError |
"""
Day 3 - Maximum Subarray
LeetCode Easy Problem
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you ... | """
Day 3 - Maximum Subarray
LeetCode Easy Problem
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you ... |
class c_iterateur(object):
def __init__(self, obj):
self.obj = obj
self.length = len(obj)
self.count = 0
def __iter__(self):
return self
def next(self):
if self.count > self.length:
raise StopIteration
else:
result = self.obj[self.co... | class C_Iterateur(object):
def __init__(self, obj):
self.obj = obj
self.length = len(obj)
self.count = 0
def __iter__(self):
return self
def next(self):
if self.count > self.length:
raise StopIteration
else:
result = self.obj[self.co... |
# input number of strings in the set
N = int(input())
trie = {}
end = object()
# input the strings
for _ in range(N):
s = input()
t = trie
for c in s[:-1]:
if c in t:
t = t[c]
else:
t[c] = {}
t = t[c]
# Print GOOD SET if the set is valid else, outp... | n = int(input())
trie = {}
end = object()
for _ in range(N):
s = input()
t = trie
for c in s[:-1]:
if c in t:
t = t[c]
else:
t[c] = {}
t = t[c]
if t is end:
print('BAD SET')
print(s)
exit()
if s[-1] in t:
... |
# Google Kickstart 2019 Round: Practice
def solution(N, K, x1, y1, C, D, E1, E2, F):
alarmList = []
alarmPowermap = [[] for i in range(K)]
alarmPower = 0
# Calculate alarmList
element = (x1 + y1) % F
xPrev, yPrev = x1, y1
alarmList.append(element)
for _ in range(N-1):
xi = (C*... | def solution(N, K, x1, y1, C, D, E1, E2, F):
alarm_list = []
alarm_powermap = [[] for i in range(K)]
alarm_power = 0
element = (x1 + y1) % F
(x_prev, y_prev) = (x1, y1)
alarmList.append(element)
for _ in range(N - 1):
xi = (C * xPrev + D * yPrev + E1) % F
yi = (D * xPrev + C ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 19:22:52 2020
@author: abhi0
"""
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
temp=[]
tempPrime=[]
for ... | """
Created on Tue Aug 11 19:22:52 2020
@author: abhi0
"""
class Solution:
def set_zeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
temp = []
temp_prime = []
for i in range(len(matrix)):
if 0... |
thistuple = ("apple", "banana", "cherry")
print(thistuple)
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
x = ("apple", "banana", "che... | thistuple = ('apple', 'banana', 'cherry')
print(thistuple)
thistuple = ('apple', 'banana', 'cherry')
print(thistuple[1])
thistuple = ('apple', 'banana', 'cherry')
print(thistuple[-1])
thistuple = ('apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon', 'mango')
print(thistuple[2:5])
x = ('apple', 'banana', 'cherry')
y ... |
def test_response_protocol_with_http1_0_request_():
pass
def test_response_protocol_with_http1_1_request_():
pass
def test_response_protocol_with_http1_1_request_and_http1_0_server():
pass
def test_response_protocol_with_http0_9_request_():
pass
def test_response_protocol_with_http2_0_request_():
pass
| def test_response_protocol_with_http1_0_request_():
pass
def test_response_protocol_with_http1_1_request_():
pass
def test_response_protocol_with_http1_1_request_and_http1_0_server():
pass
def test_response_protocol_with_http0_9_request_():
pass
def test_response_protocol_with_http2_0_request_():
... |
# -*- coding: utf-8 -*-
"""Version information for :mod:`seffnet`."""
__all__ = [
'VERSION',
]
VERSION = '0.0.1-dev'
| """Version information for :mod:`seffnet`."""
__all__ = ['VERSION']
version = '0.0.1-dev' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 18:24:38 2017
@author: dhingratul
P 1.1
"""
def isUnique(s):
s2=s.upper()
l=set(list(s2))
if len(l) == len(s2):
return True
else:
return False
# Main program
print(isUnique("ABCc"))
| """
Created on Tue Apr 25 18:24:38 2017
@author: dhingratul
P 1.1
"""
def is_unique(s):
s2 = s.upper()
l = set(list(s2))
if len(l) == len(s2):
return True
else:
return False
print(is_unique('ABCc')) |
plain_text = list(input("Enter plain text:\n"))
encrypted_text = []
original_text = []
for char in plain_text:
encrypted_text.append(chr(ord(char)+5))
for char in encrypted_text:
original_text.append(chr(ord(char)-5))
print(encrypted_text)
print(original_text) | plain_text = list(input('Enter plain text:\n'))
encrypted_text = []
original_text = []
for char in plain_text:
encrypted_text.append(chr(ord(char) + 5))
for char in encrypted_text:
original_text.append(chr(ord(char) - 5))
print(encrypted_text)
print(original_text) |
'''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another sol... | """
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another sol... |
POSSIBLE_MARKS = (
("4", "4"),
("5", "5"),
("6", "6"),
("7", "7"),
("8", "8"),
("9", "9"),
("10", "10"),
)
| possible_marks = (('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10')) |
#
# PySNMP MIB module IPAD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPAD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:44:34 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:1... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint, constraints_union) ... |
distancia = float(input('Digite a distancia em KM da viagem: '))
passag1 = distancia * 0.5
passag2 = distancia * 0.45
if distancia <= 200:
print('Sua passagem vai custar R${:.2f}'.format(passag1))
else:
print('Sua passagem vai custar R${:.2f}'.format(passag2))
| distancia = float(input('Digite a distancia em KM da viagem: '))
passag1 = distancia * 0.5
passag2 = distancia * 0.45
if distancia <= 200:
print('Sua passagem vai custar R${:.2f}'.format(passag1))
else:
print('Sua passagem vai custar R${:.2f}'.format(passag2)) |
f=float(8.11)
print(f)
i=int(f)
print(i)
j=7
print(type(j))
j=f
print(j)
print(type(j))
print(int(8.6))
| f = float(8.11)
print(f)
i = int(f)
print(i)
j = 7
print(type(j))
j = f
print(j)
print(type(j))
print(int(8.6)) |
def _impl(ctx):
name = ctx.attr.name
deps = ctx.attr.deps
suites = ctx.attr.suites
visibility = None # ctx.attr.visibility
suites_mangled = [s.partition(".")[0].rpartition("/")[2] for s in suites]
for s in suites_mangled:
native.cc_test(
name = "{}-{}".format(name, s),
... | def _impl(ctx):
name = ctx.attr.name
deps = ctx.attr.deps
suites = ctx.attr.suites
visibility = None
suites_mangled = [s.partition('.')[0].rpartition('/')[2] for s in suites]
for s in suites_mangled:
native.cc_test(name='{}-{}'.format(name, s), deps=deps, visibility=visibility, args=[s])... |
while True:
budget = float(input("Enter your budget : "))
available=budget
break
d ={"name":[], "quantity":[], "price":[]}
l= list(d.values())
name = l[0]
quantity= l[1]
price = l[2]
while True:
ch = int(input("1.ADD\n2.EXIT\nEnter your choice : "))
if ch == 1 and... | while True:
budget = float(input('Enter your budget : '))
available = budget
break
d = {'name': [], 'quantity': [], 'price': []}
l = list(d.values())
name = l[0]
quantity = l[1]
price = l[2]
while True:
ch = int(input('1.ADD\n2.EXIT\nEnter your choice : '))
if ch == 1 and available > 0:
pn =... |
data="7.dat"
s=0.0
c=0
with open(data) as fp:
for line in fp:
words=line.split(':')
if(words[0]=="RMSE"):
c+=1
# print(words[1])
s+=float(words[1])
# print(s)
print("average:")
print(s/c) | data = '7.dat'
s = 0.0
c = 0
with open(data) as fp:
for line in fp:
words = line.split(':')
if words[0] == 'RMSE':
c += 1
s += float(words[1])
print('average:')
print(s / c) |
if __name__ == '__main__':
n = int(input())
for num in range(n):
print(num * num)
| if __name__ == '__main__':
n = int(input())
for num in range(n):
print(num * num) |
#
# PySNMP MIB module ONEACCESS-CONFIGMGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-CONFIGMGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:34:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
coco_keypoints = [ "nose", # 0
"left_eye", # 1
"right_eye", # 2
"left_ear", # 3
"right_ear", # 4
"left_shoulder", # 5
"right_shoulder", # 6
"left_elbow", # 7
... | coco_keypoints = ['nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle']
coco_pairs = [(0, 1), (0, 2), (1, 3), (2, 4), (5, 6), (5, 7), (6, 8), ... |
# Return tracebacks with OperationOutcomes when an exceprion occurs
DEBUG = False
# How many items should we include in budles whwn count is not specified
DEFAULT_BUNDLE_SIZE = 20
# Limit bundles to this size even if more are requested
# TODO: Disable limiting when set to 0
MAX_BUNDLE_SIZE = 100
# Path to the models... | debug = False
default_bundle_size = 20
max_bundle_size = 100
models_path = 'models'
db_backend = 'SQLAlchemy'
strict_mode = {'set_attribute_without_setter': False, 'set_non_existent_reference': False} |
peso = float(input('Digite o peso da pessoa \t'))
engorda = peso + (peso*0.15)
emagrece = peso - (peso*0.20)
print('Se engordar , peso = ',engorda)
print('Se emagrece , peso = ',emagrece)
| peso = float(input('Digite o peso da pessoa \t'))
engorda = peso + peso * 0.15
emagrece = peso - peso * 0.2
print('Se engordar , peso = ', engorda)
print('Se emagrece , peso = ', emagrece) |
#conditional tests- testing for equalities
sanrio_1 = 'keroppi'
print("Is sanrio == 'keroppi'? I predict True.")
print(sanrio_1 == 'keroppi')
sanrio_2 = 'hello kitty'
print("Is sanrio == 'Hello Kitty'? I predict True.")
print(sanrio_2 == 'hello kitty')
sanrio_3 = 'pochacco'
print("Is sanrio == 'Pochacco'? I... | sanrio_1 = 'keroppi'
print("Is sanrio == 'keroppi'? I predict True.")
print(sanrio_1 == 'keroppi')
sanrio_2 = 'hello kitty'
print("Is sanrio == 'Hello Kitty'? I predict True.")
print(sanrio_2 == 'hello kitty')
sanrio_3 = 'pochacco'
print("Is sanrio == 'Pochacco'? I predict True.")
print(sanrio_3 == 'pochacco')
sanrio_4... |
num =int(input(" Input a Number: "))
def factorsOf(num):
factors=[]
for i in range(1,num+1):
if num%i==0:
factors.append(i)
print(factors)
factorsOf(num)
| num = int(input(' Input a Number: '))
def factors_of(num):
factors = []
for i in range(1, num + 1):
if num % i == 0:
factors.append(i)
print(factors)
factors_of(num) |
# A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
# Write a function: that, given an array A consisting of N integers fulfilling t... | def odd_occurances_in_array(A):
if len(A) == 1:
return A[0]
a = sorted(A)
for i in range(0, len(A), 2):
if i + 1 == len(A):
return A[i]
if A[i] != A[i + 1]:
return A[i]
print(odd_occurances_in_array([9, 3, 9, 3, 9, 7, 9])) |
# Find which triangle numbers and which square numbers are the same
# Written: 13 Jul 2016 by Alex Vear
# Public domain. No rights reserved.
STARTVALUE = 1 # set the start value for the program to test
ENDVALUE = 1000000 # set the end value for the program to test
for num in range(STARTVALUE, ENDVALUE):
sqr... | startvalue = 1
endvalue = 1000000
for num in range(STARTVALUE, ENDVALUE):
sqr = num * num
for i in range(STARTVALUE, ENDVALUE):
tri = i * (i + 1) / 2
if sqr == tri:
print('Square Number:', sqr, ' ', 'Triangle Number:', tri, ' ', 'Squared:', num, ' ', 'Triangled:', i)
else:
... |
class Solution:
def missingNumber(self, nums: List[int]) -> int:
l = len(nums)
return l * (1 + l) // 2 - sum(nums)
| class Solution:
def missing_number(self, nums: List[int]) -> int:
l = len(nums)
return l * (1 + l) // 2 - sum(nums) |
def quick_sort(data: list, first: int, last: int):
if not isinstance(data, list):
print(f'The data {data} MUST be of type list')
return
if not isinstance(first, int) or not isinstance(last, int):
print(f'The args {first}, and {last} MUST be an index')
return
if first <... | def quick_sort(data: list, first: int, last: int):
if not isinstance(data, list):
print(f'The data {data} MUST be of type list')
return
if not isinstance(first, int) or not isinstance(last, int):
print(f'The args {first}, and {last} MUST be an index')
return
if first < last:
... |
# ------------------------------
# 42. Trapping Rain Water
#
# Description:
# 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.
# (see picture on the website)
#
# Example:
# Input: [0,1,0,2,1,0,1,3,2,1,2,1]
# Outpu... | class Solution:
def trap(self, height: List[int]) -> int:
res = 0
current = 0
stack = []
while current < len(height):
while stack and height[current] > height[stack[-1]]:
last = stack.pop()
if not stack:
break
... |
# Scaler problem
def solve(s, queries):
left_most = [-1] * len(s)
index = -1
for i in range(len(s) - 1, -1, -1):
if s[i] == '1':
index = i
left_most[i] = index
right_most = [-1] * len(s)
index = -1
for i in range(len(s)):
if s[i] == '1':
index = ... | def solve(s, queries):
left_most = [-1] * len(s)
index = -1
for i in range(len(s) - 1, -1, -1):
if s[i] == '1':
index = i
left_most[i] = index
right_most = [-1] * len(s)
index = -1
for i in range(len(s)):
if s[i] == '1':
index = i
right_mos... |
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
hashmap = {}
for num in nums:
hashmap[num] = hashmap.setdefault(num, 0) + 1
max_value = -sys.maxint
majority_element = None
for num ... | class Solution(object):
def majority_element(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
hashmap = {}
for num in nums:
hashmap[num] = hashmap.setdefault(num, 0) + 1
max_value = -sys.maxint
majority_element = None
for num... |
def getime(date):
list1=[]
for hour in range(8):
for minute in range(0,56,5):
if minute<10:
time=str(date)+'-0'+str(hour)+':0'+str(minute)+':01'
else:
time=str(date)+'-0'+str(hour)+':'+str(minute)+':01'
list1.append(time)
for hour in range(8,24):
if hour<10:
for minute in range(0,60):
if... | def getime(date):
list1 = []
for hour in range(8):
for minute in range(0, 56, 5):
if minute < 10:
time = str(date) + '-0' + str(hour) + ':0' + str(minute) + ':01'
else:
time = str(date) + '-0' + str(hour) + ':' + str(minute) + ':01'
lis... |
HASH_KEY = 55
WORDS_LENGTH = 5
REQUIRED_WORDS = 365
MAX_GAME_ATTEMPTS = 6
WORDS_PATH = 'out/palabras5.txt'
GAME_HISTORY_PATH = 'out/partidas.json'
GAME_WORDS_PATH = 'out/palabras_por_fecha.json' | hash_key = 55
words_length = 5
required_words = 365
max_game_attempts = 6
words_path = 'out/palabras5.txt'
game_history_path = 'out/partidas.json'
game_words_path = 'out/palabras_por_fecha.json' |
#hyperparameter
hidden_size = 256 # hidden size of model
layer_size = 3 # number of layers of model
dropout = 0.2 # dropout rate in training
bidirectional = True # use bidirectional RNN for encoder
use_attention = True # use attention between encoder-decoder
batch_size = 8 # batch size in training
workers = 4 # number... | hidden_size = 256
layer_size = 3
dropout = 0.2
bidirectional = True
use_attention = True
batch_size = 8
workers = 4
max_epochs = 10
lr = 0.0001
teacher_forcing = 0.9
max_len = 80
seed = 1
mode = 'train'
data_csv_path = './dataset/train/train_data/data_list.csv'
dataset_path = './dataset/train'
sample_rate = 16000
windo... |
class ProcessorResults():
"""
This class is a intended to be used as a standard results class to store
every results object to be needed in the Processor class.
"""
def __init__(self):
self.all_tracks = {}
| class Processorresults:
"""
This class is a intended to be used as a standard results class to store
every results object to be needed in the Processor class.
"""
def __init__(self):
self.all_tracks = {} |
''' write a function to sort a given list and return sorted list using sort() or sorted() functions'''
def sorted_list(alist):
return sorted(alist)
sorted_me = sorted_list([5,2,1,7,8,3,2,9,4])
print(sorted_me)
def sort_list(alist):
return alist.sort()
sort_me = sort_list([5,2,1,7,8,3,2,9,4])
print(sort_me)
| """ write a function to sort a given list and return sorted list using sort() or sorted() functions"""
def sorted_list(alist):
return sorted(alist)
sorted_me = sorted_list([5, 2, 1, 7, 8, 3, 2, 9, 4])
print(sorted_me)
def sort_list(alist):
return alist.sort()
sort_me = sort_list([5, 2, 1, 7, 8, 3, 2, 9, 4])
p... |
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
else:
p = []
placeholder = []
for _ in range(numRows):
placeholder.appe... | class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
else:
p = []
placeholder = []
for _ in range(numRows):
placeholder.app... |
class Solution:
""" Note: for UnionFind structure, see Structures/UnionFind/uf.py. """
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
# Yes, goes from 0-n+1 but we don't use 0.
uf = UnionFind(range(len(edges)+1))
last = None
for (u, v) in edges:
... | class Solution:
""" Note: for UnionFind structure, see Structures/UnionFind/uf.py. """
def find_redundant_connection(self, edges: List[List[int]]) -> List[int]:
uf = union_find(range(len(edges) + 1))
last = None
for (u, v) in edges:
if uf.find(u) == uf.find(v):
... |
def solution(A):
h = set(A)
l = len(h)
for i in range(1, l+1):
if i not in h:
return i
return -1
# final check
print(solution([1, 2, 3, 4, 6]))
| def solution(A):
h = set(A)
l = len(h)
for i in range(1, l + 1):
if i not in h:
return i
return -1
print(solution([1, 2, 3, 4, 6])) |
class BitmaskPrinter:
bitmask_object_template = '''/* Autogenerated Code - do not edit directly */
#pragma once
#include <stdint.h>
#include <jude/core/c/jude_enum.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef uint%SIZE%_t %BITMASK%_t;
extern const jude_bitmask_map_t %BITMASK%_bitmask_map[];
#ifdef __cplus... | class Bitmaskprinter:
bitmask_object_template = '/* Autogenerated Code - do not edit directly */\n#pragma once\n\n#include <stdint.h>\n#include <jude/core/c/jude_enum.h>\n\n#ifdef __cplusplus\nextern "C" {\n#endif\n\ntypedef uint%SIZE%_t %BITMASK%_t;\nextern const jude_bitmask_map_t %BITMASK%_bitmask_map[];\n\n#ifd... |
# -------------------------------------------------- class: AddonInstallSettings ------------------------------------------------- #
class AddonInstallSettings:
# --------------------------------------------------------- Init --------------------------------------------------------- #
def __init__(
s... | class Addoninstallsettings:
def __init__(self, path: str):
self.path = path
def post_install_action(self, browser, addon_id: str, internal_addon_id: str, addon_base_url: str) -> None:
return None |
'''
Description:
You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.
Any node in the binary tree can be flipped by swapping its left and right sub... | """
Description:
You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.
Any node in the binary tree can be flipped by swapping its left and right sub... |
"""
b = [int(x) for x in input().split()]
del b[0]
prefix = 0
suffix = 0
ans = 0
for n in range(len(b)):
prefix += b[n]
suffix += b[-n-1]
if prefix == suffix:
ans += 1
print(ans)
"""
a = input()
print(20156 if a.startswith('1') else 1)
| """
b = [int(x) for x in input().split()]
del b[0]
prefix = 0
suffix = 0
ans = 0
for n in range(len(b)):
prefix += b[n]
suffix += b[-n-1]
if prefix == suffix:
ans += 1
print(ans)
"""
a = input()
print(20156 if a.startswith('1') else 1) |
#!/usr/bin/env python3
"""Utilities for building services in the Ride2Rail project."""
__version__ = '0.2.0'
__all__ = ['cli_utils', 'cache_operations', 'logging', 'normalization']
| """Utilities for building services in the Ride2Rail project."""
__version__ = '0.2.0'
__all__ = ['cli_utils', 'cache_operations', 'logging', 'normalization'] |
installed_extensions = [ 'azext_identitydirmgt_v1_0',
'azext_planner_v1_0',
'azext_identitysignins_v1_0',
'azext_schemaextensions_v1_0',
'azext_mail_v1_0',
'azext_files_v1_0',
'azext_notes_v1_0',
'azext_crossdeviceexperiences_v1_0',
'azext_cloudcommunications_v1_0',
'azext_directoryobjects_v1_0',
'azext_users... | installed_extensions = ['azext_identitydirmgt_v1_0', 'azext_planner_v1_0', 'azext_identitysignins_v1_0', 'azext_schemaextensions_v1_0', 'azext_mail_v1_0', 'azext_files_v1_0', 'azext_notes_v1_0', 'azext_crossdeviceexperiences_v1_0', 'azext_cloudcommunications_v1_0', 'azext_directoryobjects_v1_0', 'azext_usersfunctions_v... |
# Fields for the tables generated from the mysql dump
table_fields = {"commits":
[
"author_id",
"committer_id",
"project_id",
"created_at"
],
"counters":
[
"id",
... | table_fields = {'commits': ['author_id', 'committer_id', 'project_id', 'created_at'], 'counters': ['id', 'date', 'commit_comments', 'commit_parents', 'commits', 'followers', 'organization_members', 'projects', 'users', 'issues', 'pull_requests', 'issue_comments', 'pull_request_comments', 'pull_request_history', 'watche... |
# Leo colorizer control file for factor mode.
# This file is in the public domain.
# Properties for factor mode.
properties = {
"commentEnd": ")",
"commentStart": "(",
"doubleBracketIndent": "true",
"indentCloseBrackets": "]",
"indentNextLines": "^(\\*<<|:).*",
"indentOpenBrackets": "... | properties = {'commentEnd': ')', 'commentStart': '(', 'doubleBracketIndent': 'true', 'indentCloseBrackets': ']', 'indentNextLines': '^(\\*<<|:).*', 'indentOpenBrackets': '[', 'lineComment': '!', 'lineUpClosingBracket': 'true', 'noWordSep': "+-*=><;.?/'"}
factor_main_attributes_dict = {'default': 'null', 'digit_re': '-?... |
#%%
"""
- Lonely Pixel I
- https://leetcode.com/problems/lonely-pixel-i/
- Medium
"""
#%%
"""
Given a picture consisting of black and white pixels, find the number of black lonely pixels.
The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.
A black... | """
- Lonely Pixel I
- https://leetcode.com/problems/lonely-pixel-i/
- Medium
"""
"\nGiven a picture consisting of black and white pixels, find the number of black lonely pixels.\n\nThe picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.\n\nA black lonel... |
"""
How to Use this File.
participants is a dictionary where a key is the name of the participant and the value is
a set of all the invalid selections for that participant.
participants = {'Bob': {'Sue', 'Jim'},
'Jim': {'Bob', 'Betty'},
} # And so on.
history is a dictionary where a key is the name of ... | """
How to Use this File.
participants is a dictionary where a key is the name of the participant and the value is
a set of all the invalid selections for that participant.
participants = {'Bob': {'Sue', 'Jim'},
'Jim': {'Bob', 'Betty'},
} # And so on.
history is a dictionary where a key is the name of ... |
# Source : https://leetcode.com/problems/find-the-highest-altitude/
# Author : foxfromworld
# Date : 13/11/2021
# First attempt
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
alt, ret = 0, 0
for g in gain:
alt = alt + g
ret = max(alt, ret)
return... | class Solution:
def largest_altitude(self, gain: List[int]) -> int:
(alt, ret) = (0, 0)
for g in gain:
alt = alt + g
ret = max(alt, ret)
return ret |
def type_I(A, i, j):
# Swap two rows
A[i], A[j] = np.copy(A[j]), np.copy(A[i])
def type_II(A, i, const):
# Multiply row j of A by const
A[i] *= const
def type_III(A, i, j, const):
# Add a constant times row j to row i
A[i] += const*A[j]
| def type_i(A, i, j):
(A[i], A[j]) = (np.copy(A[j]), np.copy(A[i]))
def type_ii(A, i, const):
A[i] *= const
def type_iii(A, i, j, const):
A[i] += const * A[j] |
class Justifier:
def justify(self, textIn):
width = max(map(len, textIn))
return map(lambda s: s.rjust(width), textIn)
| class Justifier:
def justify(self, textIn):
width = max(map(len, textIn))
return map(lambda s: s.rjust(width), textIn) |
tournament = input()
total_played = 0
total_won = 0
total_lost = 0
while tournament != "End of tournaments":
games_per_tournament = int(input())
games_counter = 0
total_played += games_per_tournament
for games in range(1, games_per_tournament + 1):
desi_team = int(input())
other_team ... | tournament = input()
total_played = 0
total_won = 0
total_lost = 0
while tournament != 'End of tournaments':
games_per_tournament = int(input())
games_counter = 0
total_played += games_per_tournament
for games in range(1, games_per_tournament + 1):
desi_team = int(input())
other_team = i... |
class Bootstrap:
'''Essential bootstrap cross validator, consistent with other splitter classes
in sklearn.model_selection.
Example:
boot = Bootstrap(n_bootstraps = 3, random_state=1)
for train, test in boot.split(X):
print("Train:", X[train]," Test:", X[test])
'''
def __ini... | class Bootstrap:
"""Essential bootstrap cross validator, consistent with other splitter classes
in sklearn.model_selection.
Example:
boot = Bootstrap(n_bootstraps = 3, random_state=1)
for train, test in boot.split(X):
print("Train:", X[train]," Test:", X[test])
"""
def __init... |
CHECKPOINT = 'model/checkpoint.bin'
MODEL_PATH = 'model/model.bin'
input_path = 'input/train.csv'
LR = 0.01
scheduler_threshold = 0.001
scheduler_patience = 2
scheduler_decay_factor = 0.5
embed_dims = 128
hidden_dims = 128
num_layers = 1
bidirectional = False
dropout = 0.2
out_dims = 128
Batch_Size = 64
Epochs = 100... | checkpoint = 'model/checkpoint.bin'
model_path = 'model/model.bin'
input_path = 'input/train.csv'
lr = 0.01
scheduler_threshold = 0.001
scheduler_patience = 2
scheduler_decay_factor = 0.5
embed_dims = 128
hidden_dims = 128
num_layers = 1
bidirectional = False
dropout = 0.2
out_dims = 128
batch__size = 64
epochs = 100
s... |
BASE_URL = "https://www.zhixue.com"
# BASE_URL = "http://localhost:8080"
INFO_URL = f"{BASE_URL}/container/container/student/account/"
# Login
SERVICE_URL = f"{BASE_URL}:443/ssoservice.jsp"
SSO_URL = f"https://open.changyan.com/sso/login?sso_from=zhixuesso&service={SERVICE_URL}"
CHANGE_PASSWORD_URL = f"{BASE_URL}/por... | base_url = 'https://www.zhixue.com'
info_url = f'{BASE_URL}/container/container/student/account/'
service_url = f'{BASE_URL}:443/ssoservice.jsp'
sso_url = f'https://open.changyan.com/sso/login?sso_from=zhixuesso&service={SERVICE_URL}'
change_password_url = f'{BASE_URL}/portalcenter/home/updatePassword/'
test_password_u... |
debug_defs = select({
"//:debug-ast": ["DEBUG_AST"],
"//conditions:default": []
}) + select({
"//:debug-bindings": ["DEBUG_BINDINGS"],
"//conditions:default": []
}) + select({
"//:debug-ctors": ["DEBUG_CTORS"],
"//conditions:default": []
}) + select({
"//:debug-filters": ["DEBUG_FILTER... | debug_defs = select({'//:debug-ast': ['DEBUG_AST'], '//conditions:default': []}) + select({'//:debug-bindings': ['DEBUG_BINDINGS'], '//conditions:default': []}) + select({'//:debug-ctors': ['DEBUG_CTORS'], '//conditions:default': []}) + select({'//:debug-filters': ['DEBUG_FILTERS'], '//conditions:default': []}) + selec... |
# -*- coding: utf-8 -*-
"""
ASGI
"""
| """
ASGI
""" |
_prefix = 'MC__'
JOB_DIR_COMPONENT_PATHS = {
'job_key': _prefix + 'JOB_KEY',
'job_meta': _prefix + 'JOB_META.json',
'job_spec': 'job_spec.json',
'entrypoint': 'entrypoint.sh',
'work_dir': 'work_dir',
'executed_checkpoint': _prefix + 'EXECUTED',
'completed_checkpoint': _prefix + 'COMPLETED',... | _prefix = 'MC__'
job_dir_component_paths = {'job_key': _prefix + 'JOB_KEY', 'job_meta': _prefix + 'JOB_META.json', 'job_spec': 'job_spec.json', 'entrypoint': 'entrypoint.sh', 'work_dir': 'work_dir', 'executed_checkpoint': _prefix + 'EXECUTED', 'completed_checkpoint': _prefix + 'COMPLETED', 'failure_checkpoint': _prefix... |
p=int(input('enter the principal amount'))
n=int(input('enter the number of year'))
r=int(input('enter the rate of interest'))
d=p*n*r/100
print('simple interest=',d)
| p = int(input('enter the principal amount'))
n = int(input('enter the number of year'))
r = int(input('enter the rate of interest'))
d = p * n * r / 100
print('simple interest=', d) |
def add_to_parser(parser):
parser.add_argument("-c", "--channel", type=str, dest="channel",
help="""
If the CAN interface supports multiple channels, select which one
you are after here. For example on linux this might be 1
... | def add_to_parser(parser):
parser.add_argument('-c', '--channel', type=str, dest='channel', help='\n If the CAN interface supports multiple channels, select which one\n you are after here. For example on linux this might be 1\n ', default='0')
... |
c = get_config()
c.NotebookApp.ip = '{{IPYTHON_NB_LISTEN_ADDR}}'
c.NotebookApp.port = {{IPYTHON_NB_LISTEN_PORT}}
c.NotebookApp.open_browser = False
c.NotebookApp.notebook_dir = u'{{IPYTHON_NB_DIR}}'
c.NotebookApp.base_url = '{{HTTP_BASE_URL}}/{{IPYTHON_NB_PREFIX}}'
c.NotebookApp.tornado_settings = {'static_url_prefix... | c = get_config()
c.NotebookApp.ip = '{{IPYTHON_NB_LISTEN_ADDR}}'
c.NotebookApp.port = {{IPYTHON_NB_LISTEN_PORT}}
c.NotebookApp.open_browser = False
c.NotebookApp.notebook_dir = u'{{IPYTHON_NB_DIR}}'
c.NotebookApp.base_url = '{{HTTP_BASE_URL}}/{{IPYTHON_NB_PREFIX}}'
c.NotebookApp.tornado_settings = {'static_url_prefix':... |
class Solution:
def XXX(self, intervals: List[List[int]]) -> List[List[int]]:
res=[]
intervals.sort()
res.append(intervals[0])
for i in range(1,len(intervals)):
t=res[-1]
if intervals[i][0]<=t[1]:
res[-1][1]=max(intervals[i][1],res[-1][1])
... | class Solution:
def xxx(self, intervals: List[List[int]]) -> List[List[int]]:
res = []
intervals.sort()
res.append(intervals[0])
for i in range(1, len(intervals)):
t = res[-1]
if intervals[i][0] <= t[1]:
res[-1][1] = max(intervals[i][1], res[-... |
#!/usr/bin/env python
print("Hello World!")
# commnads
# $python hello.py
# Hello World!
# $python hello.py > output.txt
# if file exists, old file is deleted, new file created with same name
# if file doesn't exits, then new file is created
# $python hello.py >> output.txt
# if file exists, then result is appended... | print('Hello World!') |
#!/usr/bin/env python3
def solution(n: int, a: list) -> list:
"""
>>> solution(5, [3, 4, 4, 6, 1, 4, 4])
[3, 2, 2, 4, 2]
"""
counters = [0] * n
max_counter = n + 1
cur_max = 0
for num in a:
if num == max_counter:
counters = [cur_max] * n
else:
co... | def solution(n: int, a: list) -> list:
"""
>>> solution(5, [3, 4, 4, 6, 1, 4, 4])
[3, 2, 2, 4, 2]
"""
counters = [0] * n
max_counter = n + 1
cur_max = 0
for num in a:
if num == max_counter:
counters = [cur_max] * n
else:
counters[num - 1] += 1
... |
# Separate the construction of a complex object from its
# representation so that the same construction process can create different representations.
# Parse a complex representation, create one of several targets.
# Allows you to build different kind of object by implementing the Steps,
# to build on particular objec... | class Anything(object):
def __init__(self):
self.build_step_1()
self.build_step_2()
def build_step_1(self):
raise NotImplementedError
def build_step_2(self):
raise NotImplementedError
class Anythinga(Anything):
def build_step_1(self):
pass
def build_step... |
"""
Contains modules related to the import of the data and formatting of the target
Modules :
- Start
- Encode_Target
"""
__all__ = ['Load', 'Encode_Target']
| """
Contains modules related to the import of the data and formatting of the target
Modules :
- Start
- Encode_Target
"""
__all__ = ['Load', 'Encode_Target'] |
def dict_extract(value, var, ret_dict=None):
"""Search a list of nested dictionaries
Args:
value(obj): Object being searched for
var(iterable): iterable containing dictionaries or lists
ret_dict(dict): Highest depth dictionary containing value
Yield:
Dictionary containing d... | def dict_extract(value, var, ret_dict=None):
"""Search a list of nested dictionaries
Args:
value(obj): Object being searched for
var(iterable): iterable containing dictionaries or lists
ret_dict(dict): Highest depth dictionary containing value
Yield:
Dictionary containing d... |
"""
16. 3Sum Closest
Given an array nums of n integers and an integer target,
find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
My opnion:
I searched the internet for what the problem means. I ... | """
16. 3Sum Closest
Given an array nums of n integers and an integer target,
find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
My opnion:
I searched the internet for what the problem means. I ... |
def high_and_low(numbers):
# In this little assignment you are given a string of space separated numbers,
# and have to return the highest and lowest number.
result = [int(x) for x in numbers.split()]
string = str(max(result)) + " " + str(min(result))
return string
print(high_and_low("4 5 29 54 4 ... | def high_and_low(numbers):
result = [int(x) for x in numbers.split()]
string = str(max(result)) + ' ' + str(min(result))
return string
print(high_and_low('4 5 29 54 4 0 -214 542 -64 1 -3 6 -6')) |
class Clustering:
def __init__(self):
self._cluster = {}
def _query(self, jpt):
return self._cluster[jpt] | class Clustering:
def __init__(self):
self._cluster = {}
def _query(self, jpt):
return self._cluster[jpt] |
# https://codeforces.com/problemset/problem/705/A
n = int(input())
love = 'I love it'
hate = 'I hate it'
result = ''
if n == 1:
print('I hate it')
else:
for num in range(1, n + 1):
if num == n:
if num % 2 != 0:
result += hate
else:
result += lov... | n = int(input())
love = 'I love it'
hate = 'I hate it'
result = ''
if n == 1:
print('I hate it')
else:
for num in range(1, n + 1):
if num == n:
if num % 2 != 0:
result += hate
else:
result += love
break
if num % 2 != 0:
... |
#!/usr/bin/python
S = input()
P_score= S.split(" ")
#print (S)
for i in range (0,len(P_score)):
P_score[i]= int(P_score[i])
List_J=[1 for m in range(0,len(P_score))]## set default List_J as "1"
for i in range(0,(len(P_score)-1)):
if P_score[i] < P_score[i+1]:
List_J[i+1] = List... | s = input()
p_score = S.split(' ')
for i in range(0, len(P_score)):
P_score[i] = int(P_score[i])
list_j = [1 for m in range(0, len(P_score))]
for i in range(0, len(P_score) - 1):
if P_score[i] < P_score[i + 1]:
List_J[i + 1] = List_J[i] + 1
i += 1
elif P_score[i] > P_score[i + 1]:
if... |
"""A series of modules containing dictionaries that can be used in run.py"""
def test_movie_set_1():
movie1 = {
"name": "Apollo11",
"rating": "G",
"genre": "documentary",
"length": 93
}
movie2 = {
"name": "Cars",
"rating": "G",
"genre": ... | """A series of modules containing dictionaries that can be used in run.py"""
def test_movie_set_1():
movie1 = {'name': 'Apollo11', 'rating': 'G', 'genre': 'documentary', 'length': 93}
movie2 = {'name': 'Cars', 'rating': 'G', 'genre': 'comedy', 'length': 117}
movie3 = {'name': 'Pride and Prejudice', 'rating... |
# June 2021
# Author: J. Rossbroich
"""
misc.py
Contains functions used by the adelie package
"""
def getattr_deep(obj, attrs):
"""
Like getattr(), but checks in children objects
Example:
X = object()
X.Y = childobject()
X.Y.variable = 5
getattr(X, 'Y.variable') -> Attri... | """
misc.py
Contains functions used by the adelie package
"""
def getattr_deep(obj, attrs):
"""
Like getattr(), but checks in children objects
Example:
X = object()
X.Y = childobject()
X.Y.variable = 5
getattr(X, 'Y.variable') -> AttributeError
getattr_deep(X, 'Y.v... |
'''
Contains keyword arguments and their default values
for workflows. Used to auto-complete arguments that
are missing in submitted workflows.
Workflow items with all the given arguments are then
parsed into actual Celery workflows by the workflow
designer.
2020 Benjamin Kellenberger
'''
... | """
Contains keyword arguments and their default values
for workflows. Used to auto-complete arguments that
are missing in submitted workflows.
Workflow items with all the given arguments are then
parsed into actual Celery workflows by the workflow
designer.
2020 Benjamin Kellenberger
"""
d... |
feed_template = '''
<html>
<head>
<title>Carbon Black {{integration_name}} Feed</title>
<style type="text/css">
A:link {color: black;}
A:visited {color: black;}
A:active {color: black;}
A:hover {underline; color: #d02828;}
</style>
<style>
#config
{
font-family:"Trebuchet... | feed_template = '\n<html>\n <head>\n <title>Carbon Black {{integration_name}} Feed</title>\n\n <style type="text/css">\n A:link {color: black;}\n A:visited {color: black;}\n A:active {color: black;}\n A:hover {underline; color: #d02828;}\n </style>\n\n <style>\n #config\n {\n font-fami... |
x=[9,2,10,1,-1,0,0,1]
for i in range(len(x)-1):
for j in range(len(x)-1):
if x[j] > x[j+1]:
x[j],x[j+1] = x[j+1],x[j]
print(x)
x=input()
y={}
for i in range(len(x)):
if not x[i] in y :
y[x[i]]=0
y[x[i]]+=1
print(y)
x=input()
y=len(x)
y-=1
for i in range(round(len(x)/2)):
if not ... | x = [9, 2, 10, 1, -1, 0, 0, 1]
for i in range(len(x) - 1):
for j in range(len(x) - 1):
if x[j] > x[j + 1]:
(x[j], x[j + 1]) = (x[j + 1], x[j])
print(x)
x = input()
y = {}
for i in range(len(x)):
if not x[i] in y:
y[x[i]] = 0
y[x[i]] += 1
print(y)
x = input()
y = len(x)
y -= 1
for... |
#
# PySNMP MIB module IPV4-RIP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPV4-RIP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:45:29 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,... | (ap_ipv4_rip,) = mibBuilder.importSymbols('APENT-MIB', 'apIpv4Rip')
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, valu... |
# print "Hello" N times
n=int(input())
if n>=0:
for i in range(n):
print("Hello")
else:
print("Invalid input") | n = int(input())
if n >= 0:
for i in range(n):
print('Hello')
else:
print('Invalid input') |
##############################################################################
#
# Copyright (C) BBC 2018
#
##############################################################################
events = [
{
"prodState": "Maintenance",
"firstTime": 1494707632.238,
"device_uuid": "3cb330f3-afb0-4e25... | events = [{'prodState': 'Maintenance', 'firstTime': 1494707632.238, 'device_uuid': '3cb330f3-afb0-4e25-99ef-1902403b9be1', 'eventClassKey': null, 'severity': 5, 'agent': 'zenperfsnmp', 'dedupid': 'rpm01.rbsov.bbc.co.uk||/Status/Snmp|snmp_error|5', 'Location': [{'uid': '/zport/dmd/Locations/RBSOV', 'name': '/RBSOV'}], '... |
# Commodity and Equity Sector mappings
sectmap = {
'commodity_sector_mappings':{
'&6A_CCB':('Currencies', 'G10 Currencies', 'G10 Currencies', 'G10 Currencies', 'AUD'), # AUD
'&6B_CCB':('Currencies', 'G10 Currencies', 'G10 Currencies', 'G10 Currencies', 'GBP'), # GBP
'&6C_CCB':('Currencies',... | sectmap = {'commodity_sector_mappings': {'&6A_CCB': ('Currencies', 'G10 Currencies', 'G10 Currencies', 'G10 Currencies', 'AUD'), '&6B_CCB': ('Currencies', 'G10 Currencies', 'G10 Currencies', 'G10 Currencies', 'GBP'), '&6C_CCB': ('Currencies', 'G10 Currencies', 'G10 Currencies', 'G10 Currencies', 'CAD'), '&6E_CCB': ('Cu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.