content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def is_host(ip):
"""
Checks whether an address is a subnet address or a single address
:param ip: ip address or subnet
:return: True if host
"""
r = ip.split("/")
if len(r) > 1:
return False
return True
| def is_host(ip):
"""
Checks whether an address is a subnet address or a single address
:param ip: ip address or subnet
:return: True if host
"""
r = ip.split('/')
if len(r) > 1:
return False
return True |
class User:
@classmethod
def deserialize(cls) -> "User":
return cls()
def do_a_user_thing(self):
print("doing a user thing")
user = User.deserialize()
user.do_a_user_thing()
class Product:
@classmethod
def deserialize(cls) -> "Product":
return cls()
def do_a_product... | class User:
@classmethod
def deserialize(cls) -> 'User':
return cls()
def do_a_user_thing(self):
print('doing a user thing')
user = User.deserialize()
user.do_a_user_thing()
class Product:
@classmethod
def deserialize(cls) -> 'Product':
return cls()
def do_a_product_... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... | def test():
assert 'reps' in __solution__, "Make sure you are naming your object 'reps'."
assert "if exercise == 'lunges':", "Make sure you are including the 'lunges' clause"
assert "elif exercise == 'squats':", "Make sure you are including the 'squats' clause"
assert "elif exercise == 'burpees':", "Mak... |
#!/usr/bin/env python3
# coding=utf-8
#
# Copyright (c) 2020-2021 Huawei Device Co., Ltd.
# 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
#
#... | class Paramerror(Exception):
def __init__(self, error_msg, error_no=''):
super(ParamError, self).__init__(error_msg, error_no)
self.error_msg = error_msg
self.error_no = error_no
def __str__(self):
return str(self.error_msg)
class Litedeviceerror(Exception):
def __init__(... |
# this segment tree will support two operations:
# 1. Set element i equal to v.
# 2. Find maximum sum of subarray of
# original array (in fact we can answer this question for all subarrays, not only for original one) we will keep
# tuple (seg, pref, suf, sum) for each node
# use fast IO to get AC on PyPy27
class Segm... | class Segmenttree:
def __init__(self, n, arr, ZERO):
self.size = 1
while self.size < n:
self.size *= 2
self.T = [ZERO] * (2 * self.size - 1)
self.arr = arr
self.ZERO = ZERO
def combine(self, a, b):
return (max(a[0], b[0], a[2] + b[1]), max(a[1], a[3]... |
def _switch(app_connection, enable=None):
params = {"secret": "changeme"}
if enable is not None:
params["enable"] = "1" if enable else "0"
answer = app_connection.get_json("c2c/sql_profiler", params=params, cors=False)
assert answer["status"] == 200
return answer["enabled"]
def test_ok(app... | def _switch(app_connection, enable=None):
params = {'secret': 'changeme'}
if enable is not None:
params['enable'] = '1' if enable else '0'
answer = app_connection.get_json('c2c/sql_profiler', params=params, cors=False)
assert answer['status'] == 200
return answer['enabled']
def test_ok(app_... |
num_classes = 3
# dataset settings
dataset_type = 'UWMGITDataset'
data_root = './data/mmseg_train/'
classes = ['large_bowel', 'small_bowel', 'stomach']
palette = [[0, 0, 0], [128, 128, 128], [255, 255, 255]]
img_norm_cfg = dict(mean=[0, 0, 0], std=[1, 1, 1], to_rgb=True)
size = 256
albu_train_transforms = [
dict(ty... | num_classes = 3
dataset_type = 'UWMGITDataset'
data_root = './data/mmseg_train/'
classes = ['large_bowel', 'small_bowel', 'stomach']
palette = [[0, 0, 0], [128, 128, 128], [255, 255, 255]]
img_norm_cfg = dict(mean=[0, 0, 0], std=[1, 1, 1], to_rgb=True)
size = 256
albu_train_transforms = [dict(type='RandomBrightnessCont... |
#10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages.
#You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008... | name = raw_input('Enter file:')
if len(name) < 1:
name = 'mbox-short.txt'
handle = open(name)
d = dict()
for line in handle:
if not line.startswith('From '):
continue
else:
line = line.split()
line = line[5]
line = line[0:2]
d[line] = d.get(line, 0) + 1
lst = list()
f... |
# from .termapp import TermApp
class Display:
def __init__(self):
pass
def report(self):
pass
def __call__(self, msg):
key, status, data, err_msg = msg
getattr(self, status)(key, data, err_msg)
def __enter__(self):
pass
def __exit__(self, exc_type, exc_v... | class Display:
def __init__(self):
pass
def report(self):
pass
def __call__(self, msg):
(key, status, data, err_msg) = msg
getattr(self, status)(key, data, err_msg)
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_ty... |
def Tag(tag: str):
"""
Decorator that adds the given tag to the decorated function.
:param tag: The tag to add to the function.
"""
def apply_tag(method):
if not hasattr(method, '__tags'):
method.__tags = set()
method.__tags.add(tag)
return method
return... | def tag(tag: str):
"""
Decorator that adds the given tag to the decorated function.
:param tag: The tag to add to the function.
"""
def apply_tag(method):
if not hasattr(method, '__tags'):
method.__tags = set()
method.__tags.add(tag)
return method
return... |
# $ gyp src/iroha.gyp --depth=. -f make
# maybe with --generator-output=src
{
'make_global_settings': [
],
'target_defaults': {
'cflags': ['-fPIC', '-Wall', '-Wno-sign-compare'],
'defines': ['PACKAGE="iroha"', 'VERSION="0.0.1"'],
'xcode_settings': {
'OTHER_CFLAGS': [
... | {'make_global_settings': [], 'target_defaults': {'cflags': ['-fPIC', '-Wall', '-Wno-sign-compare'], 'defines': ['PACKAGE="iroha"', 'VERSION="0.0.1"'], 'xcode_settings': {'OTHER_CFLAGS': []}}, 'targets': [{'target_name': 'iroha', 'product_name': 'iroha', 'type': 'executable', 'include_dirs': ['./'], 'sources': ['main.cp... |
numbers = [4, 8, 2, 5, 1, 9]
numbers.sort()
''' sort modifies the existing list '''
print("Sort using sort() : ", numbers)
names = ["foo", "qux", "bar", "buz", "quux"]
''' sorted created a new list for sorted entries '''
print("Sort using sorted() : ", sorted(names))
print("Print names list : after sorting : ", names)
... | numbers = [4, 8, 2, 5, 1, 9]
numbers.sort()
' sort modifies the existing list '
print('Sort using sort() : ', numbers)
names = ['foo', 'qux', 'bar', 'buz', 'quux']
' sorted created a new list for sorted entries '
print('Sort using sorted() : ', sorted(names))
print('Print names list : after sorting : ', names)
print('S... |
TOP_LEVEL_OSM_TAGS = [
"aerialway",
"aeroway",
"amenity",
"barrier",
"boundary",
"building",
"craft",
"emergency",
"geological",
"healthcare",
"highway",
"historic",
"landuse",
"leisure",
"man_made",
"military",
"natural",
"office",
"place",
... | top_level_osm_tags = ['aerialway', 'aeroway', 'amenity', 'barrier', 'boundary', 'building', 'craft', 'emergency', 'geological', 'healthcare', 'highway', 'historic', 'landuse', 'leisure', 'man_made', 'military', 'natural', 'office', 'place', 'power', 'public_transport', 'railway', 'route', 'shop', 'sport', 'telecom', 't... |
'''
made by: Aayush 9029
created at: April 3, 2020
A module that converts string to morse code and vice versa
'''
class Morse:
def __init__(self, words):
'''
Takes in one parameter either morse code or letter / number / symbols and assings it to self.words
'''
self.codes = {
... | """
made by: Aayush 9029
created at: April 3, 2020
A module that converts string to morse code and vice versa
"""
class Morse:
def __init__(self, words):
"""
Takes in one parameter either morse code or letter / number / symbols and assings it to self.words
"""
self.codes = {'0':... |
class LineOperation:
def runOn(self, line: str) -> str:
return line
class CheckIfRead(LineOperation):
def __init__(self):
return
def runOn(self, line: str) -> str:
X = input(line)
if X == "Y":
line += " --"
return line
class BulkString(LineOperation):... | class Lineoperation:
def run_on(self, line: str) -> str:
return line
class Checkifread(LineOperation):
def __init__(self):
return
def run_on(self, line: str) -> str:
x = input(line)
if X == 'Y':
line += ' --'
return line
class Bulkstring(LineOperation... |
class Solution(object):
def generateTrees(self, n):
def generate_trees(start, end):
if start > end:
return [None,]
all_trees = []
for i in range(start, end +1):
left_trees = generate_trees(start, i-1)
right_trees =... | class Solution(object):
def generate_trees(self, n):
def generate_trees(start, end):
if start > end:
return [None]
all_trees = []
for i in range(start, end + 1):
left_trees = generate_trees(start, i - 1)
right_trees = gene... |
def print_formatted(number):
# your code goes here
width=len(str(bin(number))[2:])
for i in range(1,number+1):
print(str(i).rjust(width," "),oct(i)[2:].rjust(width," "),hex(i)[2:].upper().rjust(width," "),bin(i)[2:].rjust(width," "))
if __name__ == '__main__':
n = int(input())
print_formatt... | def print_formatted(number):
width = len(str(bin(number))[2:])
for i in range(1, number + 1):
print(str(i).rjust(width, ' '), oct(i)[2:].rjust(width, ' '), hex(i)[2:].upper().rjust(width, ' '), bin(i)[2:].rjust(width, ' '))
if __name__ == '__main__':
n = int(input())
print_formatted(n) |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: Jun 15, 2015
# Question: 155-Min-Stack
# Link: https://leetcode.com/problems/min-stack/
# ==============================================================================
... | class Minstack:
def __init__(self):
self.stack = []
self.minVal = []
def push(self, x):
self.stack.append(x)
if not self.minVal or x <= self.minVal[-1]:
self.minVal.append(x)
def pop(self):
x = self.stack.pop()
if self.minVal[-1] == x:
... |
#!/usr/bin/env python
"""
Useful utilities for IO.
"""
def read_samples_list(path, fail_on_empty=True):
with open(path, 'r') as f:
samples = f.read().splitlines()
if fail_on_empty and len(samples) == 0:
raise ValueError("Samples list empty")
return samples
def read_contig_list(path, fail... | """
Useful utilities for IO.
"""
def read_samples_list(path, fail_on_empty=True):
with open(path, 'r') as f:
samples = f.read().splitlines()
if fail_on_empty and len(samples) == 0:
raise value_error('Samples list empty')
return samples
def read_contig_list(path, fail_on_empty=True):
wi... |
# Course Schedule
class Solution:
def hasCycle(self, graph, start, checked, visited):
if checked[start]:
return False
visited[start] = True
for adj in graph[start]:
if visited[adj]:
return True
if self.hasCycle(graph, adj, checked, visit... | class Solution:
def has_cycle(self, graph, start, checked, visited):
if checked[start]:
return False
visited[start] = True
for adj in graph[start]:
if visited[adj]:
return True
if self.hasCycle(graph, adj, checked, visited):
... |
playerNamePath = "Data/Brain/playerName.txt"
assistantNamePath = "Data/Brain/assistantName.txt"
audioPath = "Audios/Audio.mp3"
quinnMail = "assistantquinn@gmail.com"
ibrahimMail = "ibrahimalbayrak812@gmail.com"
sendPassword = "jupubpuqnehtlsji"
playerName = ""
assistantName = ""
| player_name_path = 'Data/Brain/playerName.txt'
assistant_name_path = 'Data/Brain/assistantName.txt'
audio_path = 'Audios/Audio.mp3'
quinn_mail = 'assistantquinn@gmail.com'
ibrahim_mail = 'ibrahimalbayrak812@gmail.com'
send_password = 'jupubpuqnehtlsji'
player_name = ''
assistant_name = '' |
class SchemaFilesNotFound(Exception):
pass
class SchemaNotPresent(Exception):
pass
class ModuleNotPresent(Exception):
pass
class SchemaPathNotFound(Exception):
pass | class Schemafilesnotfound(Exception):
pass
class Schemanotpresent(Exception):
pass
class Modulenotpresent(Exception):
pass
class Schemapathnotfound(Exception):
pass |
total_seats = int(input("Number of seats: "))
MIN_PERCENTAGE = int(input("Minimum percentage: "))
raw_parties = []
raw_votes = []
while True:
inputs = str(input("")).split(" ")
if inputs[0] == "exit":
break
elif len(inputs) == 2:
party = inputs[0]
num_votes = int(inputs[... | total_seats = int(input('Number of seats: '))
min_percentage = int(input('Minimum percentage: '))
raw_parties = []
raw_votes = []
while True:
inputs = str(input('')).split(' ')
if inputs[0] == 'exit':
break
elif len(inputs) == 2:
party = inputs[0]
num_votes = int(inputs[1])
r... |
# Task:
#
# Determine if a string is a palindrome
#
# Examples of palindromes:
# "", "a", "madam", "Mr. Owl ate my metal worm", "Was it a car or a cat I saw?"
# Lines that are not palindromes: "london", "random", "Not a palindrome!"
class PalindromeChecker:
def check(self, line):
return False
| class Palindromechecker:
def check(self, line):
return False |
#@auth.requires_login()
def index():
form = FORM('Your name:', INPUT(_name='name'), INPUT(_type='submit'))
return dict(form=form)
| def index():
form = form('Your name:', input(_name='name'), input(_type='submit'))
return dict(form=form) |
#!/usr/bin/env python3
######################################################################################
# #
# Program purpose: Computes the area of the polygon. #
# Program Author : Happi Yva... | def poly_area(c):
add = []
for i in range(0, len(c) - 2, 2):
add.append(c[i] * c[i + 3] - c[i + 1] * c[i + 2])
add.append(c[len(c) - 2] * c[i] - c[len(c) - 1] * c[0])
return abs(sum(add) / 2)
if __name__ == '__main__':
print(poly_area([1, 0, 0, 0, 1, 1, 3, 0, -1, 1])) |
'''Settings file'''
# settings.py
# Variables definition
# SNMP Community
HOSTS = ["10.70.8.173/255.255.255.255","10.70.8.117/255.255.255.255"]
INTERFACE = "internal"
COMMUNITY = "private"
# SysInfo
LOCATION = "Company"
DESCRIPTION = "FortiSwitch device - Company property."
CONTACT = "admin@Company.pl"
# Import
PATH... | """Settings file"""
hosts = ['10.70.8.173/255.255.255.255', '10.70.8.117/255.255.255.255']
interface = 'internal'
community = 'private'
location = 'Company'
description = 'FortiSwitch device - Company property.'
contact = 'admin@Company.pl'
path = 'C:\\Temp\\FS' |
"""
LeetCode Problem: 129. Sum Root to Leaf Numbers
Link: https://leetcode.com/problems/sum-root-to-leaf-numbers/
Language: Python
Written by: Mostofa Adib Shakib
Leaf Node:
Both the left and right child is a Null Node
Algorithm:
1) Check if the node passed is a Null Node if so return from the recursive call
2) Con... | """
LeetCode Problem: 129. Sum Root to Leaf Numbers
Link: https://leetcode.com/problems/sum-root-to-leaf-numbers/
Language: Python
Written by: Mostofa Adib Shakib
Leaf Node:
Both the left and right child is a Null Node
Algorithm:
1) Check if the node passed is a Null Node if so return from the recursive call
2) Con... |
class StanModels:
hmnl = """
# Hierarchical multinomial logit model
# from https://github.com/ksvanhorn/ART-Forum-2017-Stan-Tutorial/blob/master/3_hmnl/hmnl.stan
data {
int<lower=2> C; // # of alternatives (choices) in each scenario
int<lower=1> K; // # of covariates of alte... | class Stanmodels:
hmnl = '\n # Hierarchical multinomial logit model\n # from https://github.com/ksvanhorn/ART-Forum-2017-Stan-Tutorial/blob/master/3_hmnl/hmnl.stan\n\n data {\n int<lower=2> C; // # of alternatives (choices) in each scenario\n int<lower=1> K; // # of covariates of ... |
"""
Torsion Class definition
Author: Israel Cabeza de Vaca Lopez
Email: israel.cabezadevaca@icm.uu.se
"""
class Torsion(object):
"""
Torsion Class
"""
def __init__(self, atomA, atomB, atomC, atomD, typeInitial, typeFinal, V1, V2, V3, V4, phase1, phase2, phase3, displacement, improper=False):
... | """
Torsion Class definition
Author: Israel Cabeza de Vaca Lopez
Email: israel.cabezadevaca@icm.uu.se
"""
class Torsion(object):
"""
Torsion Class
"""
def __init__(self, atomA, atomB, atomC, atomD, typeInitial, typeFinal, V1, V2, V3, V4, phase1, phase2, phase3, displacement, improper=False):
... |
# https://leetcode.com/problems/jump-game/
class Solution:
def canJump(self, nums: list[int]) -> bool:
curr_pos = len(nums) - 1
for i in reversed(range(len(nums) - 1)):
if i + nums[i] >= curr_pos:
curr_pos = i
return curr_pos == 0
| class Solution:
def can_jump(self, nums: list[int]) -> bool:
curr_pos = len(nums) - 1
for i in reversed(range(len(nums) - 1)):
if i + nums[i] >= curr_pos:
curr_pos = i
return curr_pos == 0 |
CONTINUOUS = 'Continuous'
CATEGORICAL = 'Categorical'
ORDINAL = 'Ordinal'
INTEGER = 'Integer'
FLOAT = 'Float'
STRING = 'String' | continuous = 'Continuous'
categorical = 'Categorical'
ordinal = 'Ordinal'
integer = 'Integer'
float = 'Float'
string = 'String' |
class MomentumGradientDescent(GradientDescent):
def __init__(self, params, lr=0.1, momentum=.9):
super(MomentumGradientDescent, self).__init__(params, lr)
self.momentum = momentum
self.velocities = [param.data.new(param.shape).zero_()
for param in params]
def... | class Momentumgradientdescent(GradientDescent):
def __init__(self, params, lr=0.1, momentum=0.9):
super(MomentumGradientDescent, self).__init__(params, lr)
self.momentum = momentum
self.velocities = [param.data.new(param.shape).zero_() for param in params]
def step(self):
for (... |
changes = list()
with open("input.txt", "r") as lines:
for line in lines:
if line[0] == '+':
changes.append(int(line[1:]))
elif line[0] == '-':
changes.append(-int(line[1:]))
sum = 0
frequenturies = set()
frequenturies.add(sum)
while True:
for change in changes:
sum += change
if (sum in frequenturies)... | changes = list()
with open('input.txt', 'r') as lines:
for line in lines:
if line[0] == '+':
changes.append(int(line[1:]))
elif line[0] == '-':
changes.append(-int(line[1:]))
sum = 0
frequenturies = set()
frequenturies.add(sum)
while True:
for change in changes:
s... |
people = [
{"name":"Harry", "house":"Gryffindor"},
{"name":"Cho", "house": "Ravenclaw"},
{"name":"Draco", "house":"Slytherin"}
]
#####
#def f(person):
# return person["name"]
######
people.sort(key=lambda person: person["name"])
print(people) | people = [{'name': 'Harry', 'house': 'Gryffindor'}, {'name': 'Cho', 'house': 'Ravenclaw'}, {'name': 'Draco', 'house': 'Slytherin'}]
people.sort(key=lambda person: person['name'])
print(people) |
def knapsack(items, capacity, debug=None):
values = [[0] * (capacity + 1) for _ in range(len(items)+1)]
# values[i][j] = max { values[i-1][j] if does not fit
# values[i-1][j-w] + v if w < j
rows, columns = len(values), len(values[0])
for i in range(1, rows):
value, we... | def knapsack(items, capacity, debug=None):
values = [[0] * (capacity + 1) for _ in range(len(items) + 1)]
(rows, columns) = (len(values), len(values[0]))
for i in range(1, rows):
(value, weight) = items[i - 1]
for j in range(1, columns):
if weight <= j:
values[i][... |
string_without_line_breaks = ""
with open('foo.txt', "r+") as file:
for line in file:
stripped_line = line.rstrip() + " "
string_without_line_breaks += stripped_line
with open ("oneLine.md", "w") as file:
file.write(string_without_line_breaks)
# print(string_without_line_breaks... | string_without_line_breaks = ''
with open('foo.txt', 'r+') as file:
for line in file:
stripped_line = line.rstrip() + ' '
string_without_line_breaks += stripped_line
with open('oneLine.md', 'w') as file:
file.write(string_without_line_breaks) |
class BoardError(StandardError):
pass
class tile:
"""This is the tile class.
tileType is a string designating the tile type.
health is how much health this tile is given
wallValues is a length 6 list designating
the type of walls around the tile.
This is the inde... | class Boarderror(StandardError):
pass
class Tile:
"""This is the tile class.
tileType is a string designating the tile type.
health is how much health this tile is given
wallValues is a length 6 list designating
the type of walls around the tile.
This is the inde... |
# Live Session - 5/10/2020 - 4CSE05
# Question 2
# Mark
m = int(input("Enter a mark: "))
if m < 40:
print("Fail")
else:
print("Pass")
# Temperature
temp = int(input("Temperature: "))
if temp > 19:
print("Hot")
else:
print("Cold")
# Number
n = int(input("Number: "))
if (n % 2 == 0):
print... | m = int(input('Enter a mark: '))
if m < 40:
print('Fail')
else:
print('Pass')
temp = int(input('Temperature: '))
if temp > 19:
print('Hot')
else:
print('Cold')
n = int(input('Number: '))
if n % 2 == 0:
print('Even')
else:
print('Odd') |
def chain(*iters):
for l in iters:
print(l)
print(chain([1, 2, 3, 4, 5], [5, 6, 7, 8])) | def chain(*iters):
for l in iters:
print(l)
print(chain([1, 2, 3, 4, 5], [5, 6, 7, 8])) |
#Friends Madlib Game
def madlib():
#Defining Blanks that the user has to enter
Adj1=input("Adjective = ")
Adj2=input("Adjective = ")
Adj3=input("Adjective = ")
Adj4=input("Adjective = ")
verb1=input("Verb in continuous tense = ")
verb2=input("Verb in past tense = ")
... | def madlib():
adj1 = input('Adjective = ')
adj2 = input('Adjective = ')
adj3 = input('Adjective = ')
adj4 = input('Adjective = ')
verb1 = input('Verb in continuous tense = ')
verb2 = input('Verb in past tense = ')
verb4 = input('Verb in continuous tense = ')
famous_personality = input('F... |
# Demo Python Operators
'''
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified x in y
value is present in ... | """
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified x in y
value is present in the object ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
mytext = "Hello world"
print(len(mytext))
print(mytext[0])
print(mytext[1])
num = 142
try:
print(mytext[num])
except IndexError:
print("I am so sorry, there is no character", num, "in the string")
print("end")
| mytext = 'Hello world'
print(len(mytext))
print(mytext[0])
print(mytext[1])
num = 142
try:
print(mytext[num])
except IndexError:
print('I am so sorry, there is no character', num, 'in the string')
print('end') |
"""
"""
class Stack :
def __init__(self, max = -1):
self._list = []
self._max = max
def get(self) :
if 0 == len(self._list):
raise IndexError()
return self._list.pop()
def put(self, *values):
if self._max > 0 and self.size() + len(values) > self._m... | """
"""
class Stack:
def __init__(self, max=-1):
self._list = []
self._max = max
def get(self):
if 0 == len(self._list):
raise index_error()
return self._list.pop()
def put(self, *values):
if self._max > 0 and self.size() + len(values) > self._max:
... |
# Copyright (c) 2012 Adi Roiban.
# See LICENSE for details.
"""
Tests executed under elevated accounts.
"""
| """
Tests executed under elevated accounts.
""" |
'''
Created on Jul. 4, 2019
@author: kjnether
'''
| """
Created on Jul. 4, 2019
@author: kjnether
""" |
def HexBlock(data, width=8):
i = 0
count = 0
result = ''
currentHexLine = ''
currentChrLine = ''
for byte in data:
# next line, if required
if (i == width):
result += f'{currentHexLine} {currentChrLine}\n'
currentHexLine = ''
currentChrLine =... | def hex_block(data, width=8):
i = 0
count = 0
result = ''
current_hex_line = ''
current_chr_line = ''
for byte in data:
if i == width:
result += f'{currentHexLine} {currentChrLine}\n'
current_hex_line = ''
current_chr_line = ''
i = 0
... |
def generate_multiple_datasets_for_multiple_epochs(tabGAN, dataset_dir, n_synthetic_datasets, n_epochs_vec,
restart = False, path_finished_epochs_counter = None,
redo_n_epochs_vec = [], plot_only_new_progress = True,... | def generate_multiple_datasets_for_multiple_epochs(tabGAN, dataset_dir, n_synthetic_datasets, n_epochs_vec, restart=False, path_finished_epochs_counter=None, redo_n_epochs_vec=[], plot_only_new_progress=True, progress_bar=True, progress_bar_subprocess=True, progress_bar_subsubprocess=None, **kwargs):
if progress_ba... |
def check(s):
idx1, idx2 = s.find("@"), s.find(".")
ok = idx1>0 and all(it.isalnum() or it=="@" or it=="-" or it=="_" for it in s[:idx1])
ok &= ~idx2 and idx2-idx1>1 and all(it.isalnum() for it in s[idx1+1:idx2])
ok &= ~idx2 and 1<=len(s[idx2+1:])<=3 and s.count("@")==1 and s.count(".")==1
return ok... | def check(s):
(idx1, idx2) = (s.find('@'), s.find('.'))
ok = idx1 > 0 and all((it.isalnum() or it == '@' or it == '-' or (it == '_') for it in s[:idx1]))
ok &= ~idx2 and idx2 - idx1 > 1 and all((it.isalnum() for it in s[idx1 + 1:idx2]))
ok &= ~idx2 and 1 <= len(s[idx2 + 1:]) <= 3 and (s.count('@') == 1)... |
"""
037
Ask the user to enter their name and display each letter in
their name on a separate line.
"""
i = "0"
name = input("Enter your name please : ")
name = list(name)
#print(name)
for i in list(name):
print(i) | """
037
Ask the user to enter their name and display each letter in
their name on a separate line.
"""
i = '0'
name = input('Enter your name please : ')
name = list(name)
for i in list(name):
print(i) |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftOROleftANDOleftNOIGUALIGUALIGUALleftMAYORMENORMAYORIGUALMENORIGUALleftMAYMAYMENMENleftMASMENOSleftMULTDIVleftNOTOGNOTleftPARIZQPARDRADD ALTER AND ANDO AS BETWEEN BI... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftOROleftANDOleftNOIGUALIGUALIGUALleftMAYORMENORMAYORIGUALMENORIGUALleftMAYMAYMENMENleftMASMENOSleftMULTDIVleftNOTOGNOTleftPARIZQPARDRADD ALTER AND ANDO AS BETWEEN BIGINT BOOLEAN CADENA CHAR CHARACTER CHECK COMA CONSTRAINT CRDR CREATE CRIZQ DATABASE DATE DAY D... |
load("//bloop/private:bloop_target.bzl", "bloop_target_test")
def bloop_target(**kwargs):
bloop_target_test(
name = "%s.bloop" % kwargs["name"],
target = kwargs["name"],
tags = ["manual"],
)
| load('//bloop/private:bloop_target.bzl', 'bloop_target_test')
def bloop_target(**kwargs):
bloop_target_test(name='%s.bloop' % kwargs['name'], target=kwargs['name'], tags=['manual']) |
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
# Time complexity O(n)
# Iterate over the list and check matches
matches = 0
rule = {"type": 0, "color": 1, "name": 2}
for item in items:
if item[rule[ruleKey]] ==... | class Solution:
def count_matches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
matches = 0
rule = {'type': 0, 'color': 1, 'name': 2}
for item in items:
if item[rule[ruleKey]] == ruleValue:
matches += 1
return matches |
def load(h):
return (88.288379267609017,
86.071116222001365,
83.840759055046817,
81.607443388287237,
79.373005516593935,
77.138024633267776,
74.902740311570923,
72.667269403298718,
70.431675646397252,
68.1959... | def load(h):
return (88.28837926760902, 86.07111622200136, 83.84075905504682, 81.60744338828724, 79.37300551659393, 77.13802463326778, 74.90274031157092, 72.66726940329872, 70.43167564639725, 68.19599674828635, 65.96025643870419, 63.724470396021154, 61.488649395194386, 59.252801086410926, 57.01693105216993, 54.7810... |
numbers=input(); n=int(input())
numbersList=[]
k=0; output=""
while k<len(numbers):
num=""
if numbers[k]!=" ":
for j in range(k,len(numbers)):
if numbers[j]==" ":
k+=1
break
else:
k+=1
num+=numbers[j]
... | numbers = input()
n = int(input())
numbers_list = []
k = 0
output = ''
while k < len(numbers):
num = ''
if numbers[k] != ' ':
for j in range(k, len(numbers)):
if numbers[j] == ' ':
k += 1
break
else:
k += 1
num += nu... |
# Copyright Notice:
# Copyright 2018 Dell, Inc. All rights reserved.
# License: BSD License. For full license text see link: https://github.com/RedDrum-Redfish-Project/RedDrum-Simulator/LICENSE.txt
# BullRed-RackManager chassisBackend resources
#
class RdChassisBackend():
# class for backend chassis resou... | class Rdchassisbackend:
def __init__(self, rdr):
self.version = 1
self.rdr = rdr
def update_resource_dbs(self, chassisid, updateStaticProps=False, updateNonVols=True):
return (0, False)
def do_chassis_reset(self, chassisid, resetType):
self.rdr.logMsg('DEBUG', '--------BAC... |
class IMachineWorker(object):
"""
Base class for objects that provide pluggable service to others.
"""
def boot(self, *args):
"""
Prepare for providing the service. After this call, it may be requested
by others.
"""
pass
def run(self):
"""
Called by reactor's loop when this obj... | class Imachineworker(object):
"""
Base class for objects that provide pluggable service to others.
"""
def boot(self, *args):
"""
Prepare for providing the service. After this call, it may be requested
by others.
"""
pass
def run(self):
"""
Called by reactor's l... |
# -*- coding: utf-8 -*-
"""five: six, redux"""
PY2 = (str is bytes)
PY3 = (str is not bytes)
# provide a symettrical `text` type to `bytes`
if PY2: # pragma: no cover
text = unicode # noqa
def n(s):
if isinstance(s, bytes):
return s
else:
return s.encode('UTF-8')
els... | """five: six, redux"""
py2 = str is bytes
py3 = str is not bytes
if PY2:
text = unicode
def n(s):
if isinstance(s, bytes):
return s
else:
return s.encode('UTF-8')
else:
text = str
def n(s):
if isinstance(s, text):
return s
else:
... |
# flake8: noqa
class STALibValidationError(Exception):
"""
Algorithm data validation raised Error.
if the data is not homogenous.
"""
def __init__(self, _type: str = None) ->None:
self._type = _type
super().__init__()
def __str__(self):
return "For Algorithms Data sh... | class Stalibvalidationerror(Exception):
"""
Algorithm data validation raised Error.
if the data is not homogenous.
"""
def __init__(self, _type: str=None) -> None:
self._type = _type
super().__init__()
def __str__(self):
return 'For Algorithms Data should be homogenous... |
t=int(input())
while(t):
t-=1
n=int(input())
if(n%6==0):
print("Misha")
else:
print("Chef") | t = int(input())
while t:
t -= 1
n = int(input())
if n % 6 == 0:
print('Misha')
else:
print('Chef') |
"""Backwards compat aliases for rules_proto_grpc Node.js rules."""
load("//js:defs.bzl", "js_grpc_node_compile", "js_grpc_node_library", "js_proto_compile", "js_proto_library")
def nodejs_proto_compile(**kwargs):
print("Rule nodejs_proto_compile from @rules_proto_grpc//nodejs:defs.bzl has been deprecated, please ... | """Backwards compat aliases for rules_proto_grpc Node.js rules."""
load('//js:defs.bzl', 'js_grpc_node_compile', 'js_grpc_node_library', 'js_proto_compile', 'js_proto_library')
def nodejs_proto_compile(**kwargs):
print('Rule nodejs_proto_compile from @rules_proto_grpc//nodejs:defs.bzl has been deprecated, please u... |
def product(arr):
prods = [1] * len(arr)
temp = 1
for i in range(len(arr)):
prods[i] = temp
temp = temp * prods[i]
temp = 1
for i in reversed(range(len(arr))):
prods[i] = prods[i] * temp
temp = temp * arr[i]
| def product(arr):
prods = [1] * len(arr)
temp = 1
for i in range(len(arr)):
prods[i] = temp
temp = temp * prods[i]
temp = 1
for i in reversed(range(len(arr))):
prods[i] = prods[i] * temp
temp = temp * arr[i] |
# Copyright 2020 by Christophe Lambin
# All rights reserved.
# dummy file to test RPi.GPIO functions on Mac
BCM = 0
IN = 0
OUT = 1
def setwarnings(set):
pass
def setmode(mode):
pass
def setup(pin, mode):
if pin == -1:
raise RuntimeError
pass
def input(pin):
return 0
| bcm = 0
in = 0
out = 1
def setwarnings(set):
pass
def setmode(mode):
pass
def setup(pin, mode):
if pin == -1:
raise RuntimeError
pass
def input(pin):
return 0 |
# Explore the data
print(cellphone.head())
# Create a scatter plot of the data from the DataFrame cellphone
plt.scatter(cellphone.x, cellphone.y)
# Add labels
plt.ylabel('Latitude')
plt.xlabel('Longitude')
# Display the plot
plt.show()
# Change the marker color to red
plt.scatter(cellphone.x, cellph... | print(cellphone.head())
plt.scatter(cellphone.x, cellphone.y)
plt.ylabel('Latitude')
plt.xlabel('Longitude')
plt.show()
plt.scatter(cellphone.x, cellphone.y, color='red')
plt.ylabel('Latitude')
plt.xlabel('Longitude')
plt.show()
plt.scatter(cellphone.x, cellphone.y, color='red', marker='s')
plt.ylabel('Latitude')
plt.x... |
class ShotgunError(Exception):
"""Exception for all server logic."""
pass
class Fault(ShotgunError):
"""Exception for all remote API logic; unused in this mock."""
_default_code = 999
@property
def code(self):
try:
return self.args[1]
except IndexError:
... | class Shotgunerror(Exception):
"""Exception for all server logic."""
pass
class Fault(ShotgunError):
"""Exception for all remote API logic; unused in this mock."""
_default_code = 999
@property
def code(self):
try:
return self.args[1]
except IndexError:
... |
def solution(l, t):
for i in range(len(l) + 1):
for j in range(i+1, len(l)+1):
s = sum(l[i:j])
if s == t:
return [i, j-1]
if s > t:
break
return [-1, -1]
data = [4, 3, 10, 2, 8]
n = 12
print(solution(data, n))
| def solution(l, t):
for i in range(len(l) + 1):
for j in range(i + 1, len(l) + 1):
s = sum(l[i:j])
if s == t:
return [i, j - 1]
if s > t:
break
return [-1, -1]
data = [4, 3, 10, 2, 8]
n = 12
print(solution(data, n)) |
#!/usr/bin/env python3
def generator(factor, seed=0, modulus=2147483647, multiple_of=1):
assert multiple_of != 0
while True:
seed *= factor
seed %= modulus
if multiple_of == 1 or seed % multiple_of == 0:
yield seed
def judge(gen_a, gen_b, num_comparisons, bits=16):
ma... | def generator(factor, seed=0, modulus=2147483647, multiple_of=1):
assert multiple_of != 0
while True:
seed *= factor
seed %= modulus
if multiple_of == 1 or seed % multiple_of == 0:
yield seed
def judge(gen_a, gen_b, num_comparisons, bits=16):
matched = 0
mask = (1 <<... |
info = []
with open("AoC2.txt", 'r') as File1:
for line in File1:
info.append([int(line[:-1].split("-")[0]),
int(line[:-1].split(" ")[0].split("-")[1]),
line[:-1].split(":")[0][-1],
line[:-1].split(" ")[-1]])
i = 0
print(info)
for password in info:... | info = []
with open('AoC2.txt', 'r') as file1:
for line in File1:
info.append([int(line[:-1].split('-')[0]), int(line[:-1].split(' ')[0].split('-')[1]), line[:-1].split(':')[0][-1], line[:-1].split(' ')[-1]])
i = 0
print(info)
for password in info:
try:
if password[3][password[0] - 1] == passwor... |
class QLayer():
def get_quant_weight(self):
raise NotImplementedError
def set_quant_weight(self):
raise NotImplementedError
def restore_weight(self):
raise NotImplementedError | class Qlayer:
def get_quant_weight(self):
raise NotImplementedError
def set_quant_weight(self):
raise NotImplementedError
def restore_weight(self):
raise NotImplementedError |
#PROGRAM TO WRITE INTO A FILE
text = "SAMPLE FOR A TESTING \n NEW LINE"
SaveFile = open("exampleFile.txt","w")
SaveFile.write(text)
SaveFile.close
| text = 'SAMPLE FOR A TESTING \n NEW LINE'
save_file = open('exampleFile.txt', 'w')
SaveFile.write(text)
SaveFile.close |
d = 1000
b = bin(d).replace('0b','')
h = hex(int(b))
c = 0
for i in b:
if i=='1':
c+=1
print(c)
# list comprehension
print(sum(1 for x in b if x=='1')) | d = 1000
b = bin(d).replace('0b', '')
h = hex(int(b))
c = 0
for i in b:
if i == '1':
c += 1
print(c)
print(sum((1 for x in b if x == '1'))) |
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man, that's enough for a party!")
print("Get a blanket.\n")
def calculate_area(x, y):
area = x * y
print(f"Given lengths of {x} and {y}, the ... | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f'You have {cheese_count} cheeses!')
print(f'You have {boxes_of_crackers} boxes of crackers!')
print("Man, that's enough for a party!")
print('Get a blanket.\n')
def calculate_area(x, y):
area = x * y
print(f'Given lengths of {x} a... |
# -*- coding: utf-8 -*-
def chainable(items):
class Chain(object):
def __init__(self, items):
self._items = items
def map(self, a):
return Chain(map(a, self._items))
def filter(self, a):
return Chain(filter(a, self._items))
def reduce(self, a)... | def chainable(items):
class Chain(object):
def __init__(self, items):
self._items = items
def map(self, a):
return chain(map(a, self._items))
def filter(self, a):
return chain(filter(a, self._items))
def reduce(self, a):
return red... |
shopping_list = ['milk', 'eggs', 'pasta', 'spam', 'bread', 'rice', 'pasta']
item_to_find = "spam"
found_at = None
for index in range(len(shopping_list)):
if shopping_list[index] != item_to_find:
continue
if shopping_list[index] == item_to_find:
found_at = index
break
if found_at != No... | shopping_list = ['milk', 'eggs', 'pasta', 'spam', 'bread', 'rice', 'pasta']
item_to_find = 'spam'
found_at = None
for index in range(len(shopping_list)):
if shopping_list[index] != item_to_find:
continue
if shopping_list[index] == item_to_find:
found_at = index
break
if found_at != None:... |
#!/usr/bin/env python
def look_for_key(main_box):
"""Non-recursive code example."""
pile = main_box.make_a_pile_to_look_through()
while pile is not pile.is_empty():
box = pile.grab_a_box()
for item in box:
if item.is_a_box():
pile.append(item)
elif i... | def look_for_key(main_box):
"""Non-recursive code example."""
pile = main_box.make_a_pile_to_look_through()
while pile is not pile.is_empty():
box = pile.grab_a_box()
for item in box:
if item.is_a_box():
pile.append(item)
elif item.is_a_key():
... |
TEST( """ . [ . 2 * 3 * 4 ] evaluate ( ) == 24 """ )
TEST( """ . [ ( . 11 * 2 ) 12 ] flatten ( ) value == 22 """ )
TEST( """ . [ f ] evaluate ( Function @ f ( Closure @ () [ . 1313 ] ) ) == 1313 """ )
TEST( """ . [ f ] evaluate ( Union @ ( . [ ( Function @ f ( Closure @ () [ . 1414 ] ) ) ] flatten () ) ) == 1414 """... | test(' . [ . 2 * 3 * 4 ] evaluate ( ) == 24 ')
test(' . [ ( . 11 * 2 ) 12 ] flatten ( ) value == 22 ')
test(' . [ f ] evaluate ( Function @ f ( Closure @ () [ . 1313 ] ) ) == 1313 ')
test(' . [ f ] evaluate ( Union @ ( . [ ( Function @ f ( Closure @ () [ . 1414 ] ) ) ] flatten () ) ) == 1414 ')
test(' . [ f + ( . 2828 ... |
#
# pystylus/ast/conditional.py
#
"""
Contains the ConditionalNode element of the pystylus AST - handling if
statements
"""
class ConditionalNode:
"""
Node handling an if statement or if+elif+else chain of statements. The
object is constructed from a 'conditional statement' and the node to be run
if t... | """
Contains the ConditionalNode element of the pystylus AST - handling if
statements
"""
class Conditionalnode:
"""
Node handling an if statement or if+elif+else chain of statements. The
object is constructed from a 'conditional statement' and the node to be run
if the conditional is later analyzed as... |
#!/usr/bin/env python3
'''
Implement and algorithm to determine if a string has all unique characters.
What if you cannot use additional data structures?
'''
def is_unique(string): # O(n)
s = set()
for c in string: # go through characters
if c in s: # if character already seen
return False... | """
Implement and algorithm to determine if a string has all unique characters.
What if you cannot use additional data structures?
"""
def is_unique(string):
s = set()
for c in string:
if c in s:
return False
s.add(c)
return True
def is_unique_1(string):
for (i, c1) in enum... |
"""
Implement an union find data structure.
"""
class UnionFind:
"""An union find data structure.
Args:
n (int): Number of items in the union find object.
"""
def __init__(self, n: int) -> None:
self.parent = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
def fi... | """
Implement an union find data structure.
"""
class Unionfind:
"""An union find data structure.
Args:
n (int): Number of items in the union find object.
"""
def __init__(self, n: int) -> None:
self.parent = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
def fin... |
def check_roles(msg, roles):
if not roles:
return True
for role in msg.author.roles:
if role.id in roles:
return True
return False
def check_scope(msg, channels, categories):
if not channels and not categories:
return True
if channels and msg.channel.id in channels:
return True
category_id = geta... | def check_roles(msg, roles):
if not roles:
return True
for role in msg.author.roles:
if role.id in roles:
return True
return False
def check_scope(msg, channels, categories):
if not channels and (not categories):
return True
if channels and msg.channel.id in chan... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
... | class Solution(object):
def average_of_levels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
info = []
def dfs(node, depth=0):
if not node:
return
if len(info) <= depth:
info.append([0, 0])
... |
"""Module containing an implementation of a priority queue"""
def _parent(i):
return (i - 1) // 2
def _right_child(i):
return 2*i + 2
def _left_child(i):
return 2*i + 1
class PriorityQueue():
"""This class represents a priority queue"""
def __init__(self):
self.items = []
def __l... | """Module containing an implementation of a priority queue"""
def _parent(i):
return (i - 1) // 2
def _right_child(i):
return 2 * i + 2
def _left_child(i):
return 2 * i + 1
class Priorityqueue:
"""This class represents a priority queue"""
def __init__(self):
self.items = []
def __l... |
origins = set()
with open('cars.csv') as f:
next(f), next(f)
for row in f:
origin = row.strip('\n').split(';')[-1]
origins.add(origin)
print(origins)
| origins = set()
with open('cars.csv') as f:
(next(f), next(f))
for row in f:
origin = row.strip('\n').split(';')[-1]
origins.add(origin)
print(origins) |
#
# #
# # #
# # # #
for i in range(4):
for j in range(4):
if j<=i:
print("#", end=" ")
print()
# second method
for i in range(4):
for j in range(i+1):
print("#", end=" ")
print()
| for i in range(4):
for j in range(4):
if j <= i:
print('#', end=' ')
print()
for i in range(4):
for j in range(i + 1):
print('#', end=' ')
print() |
'''
Created on Apr 12, 2011
@author: svenkratz
'''
Triangle = [-11.6989,66.1471,0,-16.7297,53.6023,0,-20.9605,40.2224,0,-25.1012,26.8512,0,-30.375,14.6689,0,-36.3905,3.62857,0,-42.5839,-7.21708,0,-48.2647,-18.8834,0,-48.5197,-26.3401,0,-39.7211,-27.1884,0,-30.9196,-28.0427,0,-22.1053,-28.1357,0,-13.2896,-28.1357,0,-4... | """
Created on Apr 12, 2011
@author: svenkratz
"""
triangle = [-11.6989, 66.1471, 0, -16.7297, 53.6023, 0, -20.9605, 40.2224, 0, -25.1012, 26.8512, 0, -30.375, 14.6689, 0, -36.3905, 3.62857, 0, -42.5839, -7.21708, 0, -48.2647, -18.8834, 0, -48.5197, -26.3401, 0, -39.7211, -27.1884, 0, -30.9196, -28.0427, 0, -22.1053, ... |
def main(request, response):
if request.method == "OPTIONS" and request.cookies.get("foo"):
response.status = 400
else:
response.headers.set("Cache-Control", "no-store")
response.headers.set("Access-Control-Allow-Origin", request.headers.get("origin"))
response.headers.set("Acces... | def main(request, response):
if request.method == 'OPTIONS' and request.cookies.get('foo'):
response.status = 400
else:
response.headers.set('Cache-Control', 'no-store')
response.headers.set('Access-Control-Allow-Origin', request.headers.get('origin'))
response.headers.set('Acces... |
def reverse(st):
word = st.split()
st_reversed = " ".join(word[::-1])
return st_reversed
| def reverse(st):
word = st.split()
st_reversed = ' '.join(word[::-1])
return st_reversed |
# Create a set of all pairs of similar words. Then iterate of zip(S1, S2) and all pairs should be in the set or w1==w2.
class Solution:
def areSentencesSimilar(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool:
if len(words1)!=len(words2):
return False
pairs ... | class Solution:
def are_sentences_similar(self, words1: List[str], words2: List[str], pairs: List[List[str]]) -> bool:
if len(words1) != len(words2):
return False
pairs = set(map(tuple, pairs))
return all([w1 == w2 or (w1, w2) in pairs or (w2, w1) in pairs for (w1, w2) in zip(wo... |
class BinTreeNode(object):
def __init__(self, data, left=None, right=None):
self.data, self.left, self.right = data, left, right
class BinTree(object):
def __init__(self, root=None):
self.root = root
@classmethod
def build_from(cls, node_list):
"""
param node_list: a li... | class Bintreenode(object):
def __init__(self, data, left=None, right=None):
(self.data, self.left, self.right) = (data, left, right)
class Bintree(object):
def __init__(self, root=None):
self.root = root
@classmethod
def build_from(cls, node_list):
"""
param node_list... |
class TeleinfoError(Exception):
"""Basic exception for errors raised by teleinfo"""
class BaseFormatError(TeleinfoError):
"""The format of a frame is invalid"""
def __init__(self, string_verified, object_type_verified: str,
errors: str = None):
if isinstance(string_verified, str)... | class Teleinfoerror(Exception):
"""Basic exception for errors raised by teleinfo"""
class Baseformaterror(TeleinfoError):
"""The format of a frame is invalid"""
def __init__(self, string_verified, object_type_verified: str, errors: str=None):
if isinstance(string_verified, str):
string... |
# Copyright (c) 2021 Qianyun, Inc. All rights reserved.
# common
NODE_INSTANCE = 'node-instance'
RELATIONSHIP_INSTANCE = 'relationship-instance'
COMPUTE_CONNECTED_TO_NETWORK = 'cloudchef.abstract.relationships.compute_connected_to_network'
VOLUME_CONTAINED_IN_COMPUTE = 'cloudchef.abstract.relationships.volume_containe... | node_instance = 'node-instance'
relationship_instance = 'relationship-instance'
compute_connected_to_network = 'cloudchef.abstract.relationships.compute_connected_to_network'
volume_contained_in_compute = 'cloudchef.abstract.relationships.volume_contained_in_compute'
network_connected_to_security_group = 'cloudchef.abs... |
reference_profiles = {
"naval": {
"name": "Naval Ravikant",
"birthDate": "1980-01-01"
},
"ryan": {
"bio": "Co-founder of Onename (YC S14, USV). Working on decentralized identity.",
"account": [{
"identifier": "c7520f2e8553df62c5353a84a662d060714c3ad3",
... | reference_profiles = {'naval': {'name': 'Naval Ravikant', 'birthDate': '1980-01-01'}, 'ryan': {'bio': 'Co-founder of Onename (YC S14, USV). Working on decentralized identity.', 'account': [{'identifier': 'c7520f2e8553df62c5353a84a662d060714c3ad3', '@type': 'Account', 'service': 'openbazaar'}], 'facebook': {'username': ... |
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
| def fun():
print('Welcome to GFG')
fun() |
class Solution:
def XXX(self, s: str) -> int:
newlist = s.split(" ")
newlist.reverse()
for i in newlist:
if(i != ""):
return(len(i))
| class Solution:
def xxx(self, s: str) -> int:
newlist = s.split(' ')
newlist.reverse()
for i in newlist:
if i != '':
return len(i) |
while True:
try: input()
except: break
v = [int(x) for x in input().split()]
v = sorted(v)
t = len(v) // 2
print(t, v[t]-v[t-1])
| while True:
try:
input()
except:
break
v = [int(x) for x in input().split()]
v = sorted(v)
t = len(v) // 2
print(t, v[t] - v[t - 1]) |
for k in range(int(input())):
T = input()
tiros = tuple(map(int,input().split()))
pulos = input()
tot = 0
for t,p in zip(tiros,pulos):
if p == 'S' and t <= 2:
tot += 1
elif p == 'J' and t > 2:
tot += 1
print(tot)
| for k in range(int(input())):
t = input()
tiros = tuple(map(int, input().split()))
pulos = input()
tot = 0
for (t, p) in zip(tiros, pulos):
if p == 'S' and t <= 2:
tot += 1
elif p == 'J' and t > 2:
tot += 1
print(tot) |
n = int(input())
swifts = [int(s) for s in input().split()]
semaphores = [int(s) for s in input().split()]
def sum_of_arr(arr, stop_idx):
sum = 0
for i in range(stop_idx+1):
sum += arr[i]
return sum
k = 0
for i in range(len(swifts)):
if sum_of_arr(swifts, i) == sum_of_arr(semaphores, i):... | n = int(input())
swifts = [int(s) for s in input().split()]
semaphores = [int(s) for s in input().split()]
def sum_of_arr(arr, stop_idx):
sum = 0
for i in range(stop_idx + 1):
sum += arr[i]
return sum
k = 0
for i in range(len(swifts)):
if sum_of_arr(swifts, i) == sum_of_arr(semaphores, i):
... |
def valores(num):
a = sorted(num)
print(f"O menor valor digitado foi {a[0]}")
print(f"O maior valor digitado foi {a[-1]}")
def estruc():
cont = 0
num = list()
while True:
num.append(int(input("Digite um numero: ").strip()))
cont+=1
if cont % 3 ==0:
decida ... | def valores(num):
a = sorted(num)
print(f'O menor valor digitado foi {a[0]}')
print(f'O maior valor digitado foi {a[-1]}')
def estruc():
cont = 0
num = list()
while True:
num.append(int(input('Digite um numero: ').strip()))
cont += 1
if cont % 3 == 0:
decida ... |
"""
Prime power triples
"""
def prime(n):
array = [True] * n
array[0] = array[1] = False
for i in range(2, int(n ** 0.5) + 1):
if array[i]:
for j in range(2 * i, n, i):
array[j] = False
p = []
for i in range(n):
if array[i]:
p.append(i)
r... | """
Prime power triples
"""
def prime(n):
array = [True] * n
array[0] = array[1] = False
for i in range(2, int(n ** 0.5) + 1):
if array[i]:
for j in range(2 * i, n, i):
array[j] = False
p = []
for i in range(n):
if array[i]:
p.append(i)
re... |
# -*- coding: utf-8 -*-
def decorator(aClass):
class newClass: # Returns a new class newClass in the decorator
def __init__(self, age):
self.total_display = 0
self.wrapped = aClass(age) # Record the object in the original object
def display(self):
self... | def decorator(aClass):
class Newclass:
def __init__(self, age):
self.total_display = 0
self.wrapped = a_class(age)
def display(self):
self.total_display += 1
print('total display', self.total_display)
self.wrapped.display()
return ne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.