content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env prey async def main(): count = int(await x("ls -1 | wc -l")) print(f"Files count: {count}")
async def main(): count = int(await x('ls -1 | wc -l')) print(f'Files count: {count}')
g = int(input()) if g%2 == 0: print("no. even") else: print("no. is odd")
g = int(input()) if g % 2 == 0: print('no. even') else: print('no. is odd')
def soma_elementos(lista): soma = 0 for i in lista: soma = soma + i return soma lista = [1,2,3,4,5,6] print(soma_elementos(lista))
def soma_elementos(lista): soma = 0 for i in lista: soma = soma + i return soma lista = [1, 2, 3, 4, 5, 6] print(soma_elementos(lista))
class str(object): def __new__(self, *args): if ___delta("num=", args.__len__(), 0): return "" else: first_arg = ___delta("tuple-getitem", args, 0) return first_arg.__str__() def __init__(self, *args): pass def __len__(self): int = ___id("%int") return ___delta("strlen", se...
class Str(object): def __new__(self, *args): if ___delta('num=', args.__len__(), 0): return '' else: first_arg = ___delta('tuple-getitem', args, 0) return first_arg.__str__() def __init__(self, *args): pass def __len__(self): int = ___id...
#!/usr/bin/python35 fp = open('hello.txt') print('fp.tell = %s' % (fp.tell())) fp.seek(10, SEEK_SET) print('fp.seek(10), fp.tell() = %s' % (fp.tell())) # only do zero cur-relative seeks fp.seek(0, SEEK_CUR) print('fp.seek(0, 1), fp.tell() = %s' % (fp.tell())) fp.seek(0, SEEK_END) print('fp.seek(0, 2), fp.tell() = ...
fp = open('hello.txt') print('fp.tell = %s' % fp.tell()) fp.seek(10, SEEK_SET) print('fp.seek(10), fp.tell() = %s' % fp.tell()) fp.seek(0, SEEK_CUR) print('fp.seek(0, 1), fp.tell() = %s' % fp.tell()) fp.seek(0, SEEK_END) print('fp.seek(0, 2), fp.tell() = %s' % fp.tell())
''' Created on 02-06-2011 @author: Piotr ''' class GeneratorInterval(object): ''' Describes the interval in for generating the image. @attention: DTO ''' def __init__(self, start, stop, step=0): ''' Constructor. @param start: starting point of the interval ...
""" Created on 02-06-2011 @author: Piotr """ class Generatorinterval(object): """ Describes the interval in for generating the image. @attention: DTO """ def __init__(self, start, stop, step=0): """ Constructor. @param start: starting point of the interval @param s...
with open('8.input') as inputFile: data = [b.split(' ') for b in [a.rstrip('\n').split(' | ')[1] for a in inputFile.readlines()]] result = 0 for d in data: for e in d: if len(e) in [2,3,4,7]: result += 1 print(result)
with open('8.input') as input_file: data = [b.split(' ') for b in [a.rstrip('\n').split(' | ')[1] for a in inputFile.readlines()]] result = 0 for d in data: for e in d: if len(e) in [2, 3, 4, 7]: result += 1 print(result)
def main(): message = input("Introducir Mensaje: ") key = int(input("Key [1-26]: ")) mode = input("Cifrar o Descifrar [c/d]: ") if mode.lower().startswith('c'): mode = "cifrar" elif mode.lower().startswith('d'): mode = "descifrar" translated = encdec(message, key, mode) ...
def main(): message = input('Introducir Mensaje: ') key = int(input('Key [1-26]: ')) mode = input('Cifrar o Descifrar [c/d]: ') if mode.lower().startswith('c'): mode = 'cifrar' elif mode.lower().startswith('d'): mode = 'descifrar' translated = encdec(message, key, mode) if mo...
# Problem statement # write a program to swap two numbers without using third variable x = input() y = input() print ("Before swapping: ") print("Value of x : ", x, " and y : ", y) x, y = y, x print ("After swapping: ") print("Value of x : ", x, " and y : ", y) # sample input # 10 # 20 # sample output...
x = input() y = input() print('Before swapping: ') print('Value of x : ', x, ' and y : ', y) (x, y) = (y, x) print('After swapping: ') print('Value of x : ', x, ' and y : ', y)
#!/bin/zsh ''' Table Printer Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this: tableData = [['ap...
""" Table Printer Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this: tableData = [['apples', 'oran...
def stable_match(a_pref: dict, b_pref: dict) -> set: a_list = list(a_pref.keys()) match_dict = {} while len(match_dict) != len(a_pref): print(a_list) for ai in a_list: if ai in match_dict.values(): continue print(f"{ai}") # obtengo mejor c...
def stable_match(a_pref: dict, b_pref: dict) -> set: a_list = list(a_pref.keys()) match_dict = {} while len(match_dict) != len(a_pref): print(a_list) for ai in a_list: if ai in match_dict.values(): continue print(f'{ai}') bi = a_pref[ai].po...
#!/usr/bin/env python3 #errors.py class ParserTongueError(Exception): pass ######################## ### Tokenizer Errors ### ######################## class TokenizerError(ParserTongueError): pass class TokenInstantiationTypeError(TokenizerError): def __init__(self, message): self.message = me...
class Parsertongueerror(Exception): pass class Tokenizererror(ParserTongueError): pass class Tokeninstantiationtypeerror(TokenizerError): def __init__(self, message): self.message = message class Unknowntokentypeerror(TokenizerError): def __init__(self, message): self.message = mess...
# Escreva um programa que leia um valor em metros e o exiba convertido em # centimetros e milimetros. n = float(input('Valor em metros: ')) cm = n * 100 mm = n * 1000 print('\033[7mCentimetros:{}cm\033[m\n\033[7mMilimetros:{}mm\033[m'.format(cm,mm))
n = float(input('Valor em metros: ')) cm = n * 100 mm = n * 1000 print('\x1b[7mCentimetros:{}cm\x1b[m\n\x1b[7mMilimetros:{}mm\x1b[m'.format(cm, mm))
# config.py cfg_mnet = { 'name': 'mobilenet0.25', 'in_channels': 3, 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 64, 'ngpu': 1, 'epoch': 200, 'decay1': 190...
cfg_mnet = {'name': 'mobilenet0.25', 'in_channels': 3, 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 64, 'ngpu': 1, 'epoch': 200, 'decay1': 190, 'decay2': 220, 'image_size': 480, 'pretrain': './weights/pre...
l = list(map(int, input().split())) minT = l[0] maxT = l[0] maxI = 0 minI = 0 for i in range(0, len(l)): if minT > l[i]: minT = l[i] minI = i for i in range(0, len(l)): if maxT < l[i]: maxT = l[i] maxI = i t = l[maxI] l[maxI] = l[minI] l[minI] = t print(' '.join(map(str, l)))
l = list(map(int, input().split())) min_t = l[0] max_t = l[0] max_i = 0 min_i = 0 for i in range(0, len(l)): if minT > l[i]: min_t = l[i] min_i = i for i in range(0, len(l)): if maxT < l[i]: max_t = l[i] max_i = i t = l[maxI] l[maxI] = l[minI] l[minI] = t print(' '.join(map(str, ...
# Didn't event attempt pt 2. Here's a solution cribbed from https://www.reddit.com/r/adventofcode/comments/7irzg5/2017_day_10_solutions/dr1095j/ f = "165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153" lengths1 = [int(x) for x in f.strip().split(",")] lengths2 = [ord(x) for x in f.strip()] + [17, 31, 73, 47, 23] de...
f = '165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153' lengths1 = [int(x) for x in f.strip().split(',')] lengths2 = [ord(x) for x in f.strip()] + [17, 31, 73, 47, 23] def run(lengths, times): position = 0 skip = 0 sequence = list(range(256)) for _ in range(times): for l in lengths: ...
def getMoneySpent(keyboards, drives, b): keyboards.sort(reverse = True) drives.sort(reverse = True) cost = -1 for k in keyboards: for d in drives: _cost = k + d if _cost <= b: if _cost > cost: cost = _cost break...
def get_money_spent(keyboards, drives, b): keyboards.sort(reverse=True) drives.sort(reverse=True) cost = -1 for k in keyboards: for d in drives: _cost = k + d if _cost <= b: if _cost > cost: cost = _cost break if...
# Python - 2.7.6 Test.describe('Basic Tests') Test.assert_equals(my_first_kata(3, 5), (3 % 5 + 5 % 3)) Test.assert_equals(my_first_kata('hello', 3), False) Test.assert_equals(my_first_kata(67, 'bye'), False) Test.assert_equals(my_first_kata(True, True), False) Test.assert_equals(my_first_kata(314, 107), (107 % 314 + 3...
Test.describe('Basic Tests') Test.assert_equals(my_first_kata(3, 5), 3 % 5 + 5 % 3) Test.assert_equals(my_first_kata('hello', 3), False) Test.assert_equals(my_first_kata(67, 'bye'), False) Test.assert_equals(my_first_kata(True, True), False) Test.assert_equals(my_first_kata(314, 107), 107 % 314 + 314 % 107) Test.assert...
DOMAIN = 'api.dkc.ru' VERSION_API = 'v1' URL_DOMAIN = f"https://{DOMAIN}/{VERSION_API}" DEFAULT_HEADERS = { "Accept": "*/*", }
domain = 'api.dkc.ru' version_api = 'v1' url_domain = f'https://{DOMAIN}/{VERSION_API}' default_headers = {'Accept': '*/*'}
def strip_react(polymer_fn): polymer = polymer_fn() result = {} letters = list(set(polymer.lower())) for letter in letters: stripped = polymer.replace(letter, "").replace(letter.upper(), "") result[letter] = react(stripped) return min(result.values()) def react(stripped): i ...
def strip_react(polymer_fn): polymer = polymer_fn() result = {} letters = list(set(polymer.lower())) for letter in letters: stripped = polymer.replace(letter, '').replace(letter.upper(), '') result[letter] = react(stripped) return min(result.values()) def react(stripped): i = 0 ...
''' twitter API keys ''' API_KEY = '' API_SECRET = '' ACCESS_TOKEN = '' ACCESS_SECRET = ''
""" twitter API keys """ api_key = '' api_secret = '' access_token = '' access_secret = ''
class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: count = collections.Counter(words) count_i = collections.defaultdict(list) for c in count: count_i[count[c]].append(c) large = list( sorted(count_i.keys()) ) ...
class Solution: def top_k_frequent(self, words: List[str], k: int) -> List[str]: count = collections.Counter(words) count_i = collections.defaultdict(list) for c in count: count_i[count[c]].append(c) large = list(sorted(count_i.keys())) total = 0 ans = []...
name='green' def get_line(in_f,num=1): line = in_f.readline() obj = line.split(' ') if len(obj) != num and -1 != num: print('ERROR') for i in range(len(obj)): obj[i] = int(obj[i]) return obj def check_in_file(in_f): [T,n] = get_line(in_f,2) LJ = True LJ1 = True for i in range(T): L = get_line(in_f,n) ...
name = 'green' def get_line(in_f, num=1): line = in_f.readline() obj = line.split(' ') if len(obj) != num and -1 != num: print('ERROR') for i in range(len(obj)): obj[i] = int(obj[i]) return obj def check_in_file(in_f): [t, n] = get_line(in_f, 2) lj = True lj1 = True ...
# # PySNMP MIB module INNOVX-DTE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INNOVX-DTE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:42:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: summ = 0 def helper(self, root: TreeNode) -> TreeNode: if not root: return None root.r...
class Solution: summ = 0 def helper(self, root: TreeNode) -> TreeNode: if not root: return None root.right = self.helper(root.right) Solution.summ += root.val root.val = Solution.summ root.left = self.helper(root.left) return root def bst_to_gst(...
class Parent1: def __call__(self): return 'parent1' class Parent2: def foo(self): return 'parent2' class Child1(Parent1): pass
class Parent1: def __call__(self): return 'parent1' class Parent2: def foo(self): return 'parent2' class Child1(Parent1): pass
class PyCharm: def execute(self): print("Compiling") print("Running") class MyCharm: def execute(self): print("Spell Check") print("Convention Check") print("Compiling") print("Running") class Laptop: def code(self, ide): ide.execute() ide = PyCh...
class Pycharm: def execute(self): print('Compiling') print('Running') class Mycharm: def execute(self): print('Spell Check') print('Convention Check') print('Compiling') print('Running') class Laptop: def code(self, ide): ide.execute() ide = py_ch...
def load_data(file_name: str = "sample"): file = open(file_name) data, result = [], [] try: for line in file.read().splitlines(): data.append(line.split(" ")) except Exception as e: print(e) finally: file.close() for line in data: result.append([i for ...
def load_data(file_name: str='sample'): file = open(file_name) (data, result) = ([], []) try: for line in file.read().splitlines(): data.append(line.split(' ')) except Exception as e: print(e) finally: file.close() for line in data: result.append([i fo...
coordinates = (1, 2, 3) # coordinates[0] * coordinates[1] * coordinates[2] # x = coordinates[0] # y = coordinates[1] # z = coordinates[2] # x * y * z # better way x, y, z = coordinates # works with lists too
coordinates = (1, 2, 3) (x, y, z) = coordinates
class Node: def __init__(self,info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) class BinarySearchTree: def __init__(self): self.root = None def create(self, val): if self.root ...
class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) class Binarysearchtree: def __init__(self): self.root = None def create(self, val): if self.ro...
class Character: def __init__(self, gear: int, name: str, relic: int = 0) -> None: self.__gear: int = gear self.__relic = relic self.__name: str = name @property def gear(self) -> int: return self.__gear @property def relic(self): return self.__relic @p...
class Character: def __init__(self, gear: int, name: str, relic: int=0) -> None: self.__gear: int = gear self.__relic = relic self.__name: str = name @property def gear(self) -> int: return self.__gear @property def relic(self): return self.__relic @pr...
'''Example Lambda package file''' def lambda_handler(event, context): '''Example lambda function''' return 'Hello from Cloudify & Lambda'
"""Example Lambda package file""" def lambda_handler(event, context): """Example lambda function""" return 'Hello from Cloudify & Lambda'
def foo(): bar("some string", s2="another_string") def bar(s: str, s2: str): print("bar(s) here: ", s) a = 1 + 2 return
def foo(): bar('some string', s2='another_string') def bar(s: str, s2: str): print('bar(s) here: ', s) a = 1 + 2 return
if __name__ == "__main__": f = open('val_files.txt', 'w') for i in range(108): f.writelines(['2011_09_26/2011_09_26_drive_0001_sync ', str(i).zfill(10), ' l\n']) f.close() print('done')
if __name__ == '__main__': f = open('val_files.txt', 'w') for i in range(108): f.writelines(['2011_09_26/2011_09_26_drive_0001_sync ', str(i).zfill(10), ' l\n']) f.close() print('done')
print('-=-' * 30) termo = int(input('Termo: ')) razao = int(input('Razao ')) c = 1 while c <= 10: print('{}'.format(termo), end=' -> ') termo += razao c += 1 print('Fim')
print('-=-' * 30) termo = int(input('Termo: ')) razao = int(input('Razao ')) c = 1 while c <= 10: print('{}'.format(termo), end=' -> ') termo += razao c += 1 print('Fim')
# Created by MechAviv # Map ID :: 931050940 # Classified Lab : Silo OBJECT_1 = sm.sendNpcController(2159377, -700, 30) sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0) OBJECT_2 = sm.sendNpcController(2159378, -800, 30) sm.showNpcSpecialActionByObjectId(OBJECT_2, "summon", 0) sm.setSpeakerID(2159383) sm.removeEs...
object_1 = sm.sendNpcController(2159377, -700, 30) sm.showNpcSpecialActionByObjectId(OBJECT_1, 'summon', 0) object_2 = sm.sendNpcController(2159378, -800, 30) sm.showNpcSpecialActionByObjectId(OBJECT_2, 'summon', 0) sm.setSpeakerID(2159383) sm.removeEscapeButton() sm.setPlayerAsSpeaker() sm.setSpeakerType(3) sm.sendNex...
train_1 = [[[('AUTHOR_FIRST_NAME', u'J.D.'), ('AUTHOR_LAST_NAME', u'Adams'), ('AUTHOR_FIRST_NAME', u'T.L.'), ('AUTHOR_LAST_NAME', u'Herter'), ('AUTHOR_FIRST_NAME', u'G.E.'), ('AUTHOR_LAST_NAME', u'Gull'), ('AUTHOR_FIRST_NAME', u'J.'), ('AUTHOR_LAST_NAME', u'Shoenwald'), ('AUTHOR_FIRST_NAME', u'C.P.'), ('AUTHOR_LAST_N...
train_1 = [[[('AUTHOR_FIRST_NAME', u'J.D.'), ('AUTHOR_LAST_NAME', u'Adams'), ('AUTHOR_FIRST_NAME', u'T.L.'), ('AUTHOR_LAST_NAME', u'Herter'), ('AUTHOR_FIRST_NAME', u'G.E.'), ('AUTHOR_LAST_NAME', u'Gull'), ('AUTHOR_FIRST_NAME', u'J.'), ('AUTHOR_LAST_NAME', u'Shoenwald'), ('AUTHOR_FIRST_NAME', u'C.P.'), ('AUTHOR_LAST_NAM...
# numbers assert 2+2==4 assert (50-5*6)/4 == 5.0 assert 8/5 == 1.6 assert 7//3 == 2 assert 7//-3 == -3 width=20 height=5*9 assert width*height == 900 x=y=z=0 assert x == 0 assert y == 0 assert z == 0 assert 3 * 3.75 / 1.5 == 7.5 assert 7.0 / 2 == 3.5 # complex numbers x = 8j y = 8.3j z = 3.2e6j a = 4+2j b = 2-3j c = ...
assert 2 + 2 == 4 assert (50 - 5 * 6) / 4 == 5.0 assert 8 / 5 == 1.6 assert 7 // 3 == 2 assert 7 // -3 == -3 width = 20 height = 5 * 9 assert width * height == 900 x = y = z = 0 assert x == 0 assert y == 0 assert z == 0 assert 3 * 3.75 / 1.5 == 7.5 assert 7.0 / 2 == 3.5 x = 8j y = 8.3j z = 3200000j a = 4 + 2j b = 2 - 3...
# OBJECT_TYPES VIPREQUEST_OBJ_TYPE = 'VipRequest' SERVERPOOL_OBJ_TYPE = 'ServerPool' VLAN_OBJ_TYPE = 'Vlan'
viprequest_obj_type = 'VipRequest' serverpool_obj_type = 'ServerPool' vlan_obj_type = 'Vlan'
class Header: def __init__(self, opcode, src_addr="127.0.0.1", dest_addr="127.0.0.1"): self.opcode = str(opcode) self.src_addr = src_addr self.dest_addr = dest_addr def encrypt(self, cipher): return type(self)( opcode=cipher.encrypt(self.opcode), src_addr...
class Header: def __init__(self, opcode, src_addr='127.0.0.1', dest_addr='127.0.0.1'): self.opcode = str(opcode) self.src_addr = src_addr self.dest_addr = dest_addr def encrypt(self, cipher): return type(self)(opcode=cipher.encrypt(self.opcode), src_addr=cipher.encrypt(self.src...
#!/usr/bin/python ROS_VISION_NODE_NAME = 'vision' ROS_BRIDGE_ENCODING = "bgr8" ROS_CONFIG_FILE_PATH = '/vision/config_folder' ROS_IS_RECONFIGURE = '/vision/reconfigure' ROS_SUBSCRIBER_WEBCAM_TOPIC_NAME = "/usb_cam/image_raw" ROS_SUBSCRIBER_MOUSE_EVENT_TOPIC_NAME = "/ui/mouse_event" ROS_SUBSCRIBER_CONFIG_START_TOPIC_...
ros_vision_node_name = 'vision' ros_bridge_encoding = 'bgr8' ros_config_file_path = '/vision/config_folder' ros_is_reconfigure = '/vision/reconfigure' ros_subscriber_webcam_topic_name = '/usb_cam/image_raw' ros_subscriber_mouse_event_topic_name = '/ui/mouse_event' ros_subscriber_config_start_topic_name = '/vision/recon...
n = int(input()) s = 0 for i in range(1,n+1): if i%3 !=0 and i%5 !=0: s += i print(s)
n = int(input()) s = 0 for i in range(1, n + 1): if i % 3 != 0 and i % 5 != 0: s += i print(s)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-07-10 15:18:29 # @Author : Lewis Tian (taseikyo@gmail.com) # @Link : github.com/taseikyo # @Version : Python3.7 # https://projecteuler.net/problem=6 # (1 + 2 + ... 100)^2 - (1^2 + 2^2 + ... 100^2) = # 2 * [(1*2 + 1*3 + ... 1*100) + (2*3 + 2*4 + ... 2...
def main(): return 2 * sum((x * y for x in range(1, 101) for y in range(x + 1, 101))) if __name__ == '__main__': print(main())
# Write a Python program to test whether a number is within 100 of 1000 or 2000. n = int(input("Enter a number: ")) def near_thousand(x): return ((abs(1000 - x) <= 100) or (abs(2000 - x) <= 100)) print(near_thousand(n))
n = int(input('Enter a number: ')) def near_thousand(x): return abs(1000 - x) <= 100 or abs(2000 - x) <= 100 print(near_thousand(n))
class Char: def __init__(self): self.name = "" self.max_health = 100 class Attributes: def __init__(self): self.str = 0 self.agi = 0 self.dex = 0 self.lck = 0 self.chr = 0 self.end = 0 self.spr = 0 self.wis = 0
class Char: def __init__(self): self.name = '' self.max_health = 100 class Attributes: def __init__(self): self.str = 0 self.agi = 0 self.dex = 0 self.lck = 0 self.chr = 0 self.end = 0 self.spr = 0 self.wis = 0
class app: def __init__(self): print('test') if __name__ == '__main__': app()
class App: def __init__(self): print('test') if __name__ == '__main__': app()
class InvalidRequestMethodErr(Exception): pass class InvalidDownloadMiddlewareErr(Exception): pass class InvalidMiddlewareErr(Exception): pass class QueueEmptyErr(Exception): pass class InvalidDownloaderErr(Exception): pass class UnhandledDownloadErr(Exception): pass
class Invalidrequestmethoderr(Exception): pass class Invaliddownloadmiddlewareerr(Exception): pass class Invalidmiddlewareerr(Exception): pass class Queueemptyerr(Exception): pass class Invaliddownloadererr(Exception): pass class Unhandleddownloaderr(Exception): pass
load("@bazel_skylib//lib:unittest.bzl", "asserts", "analysistest") load("cppwinrt.bzl", "cppwinrt") def _test_impl(ctx): env = analysistest.begin(ctx) target_under_test = analysistest.target_under_test(env) actions = analysistest.target_actions(env) header_output = actions[0].outputs.to_list()[0] a...
load('@bazel_skylib//lib:unittest.bzl', 'asserts', 'analysistest') load('cppwinrt.bzl', 'cppwinrt') def _test_impl(ctx): env = analysistest.begin(ctx) target_under_test = analysistest.target_under_test(env) actions = analysistest.target_actions(env) header_output = actions[0].outputs.to_list()[0] a...
(day, month, year) = input().strip().split() day = int(day); month = int(month); year = int(year) if month < 3: month += 12 year -= 1 c = year / 100 k = year % 100 day + 26 * (m + 1) / 10 + k + k/4 week_day_name = '' # 1. Follow from flowchart if 0 == week_day: week_day_name = 'SAT' elif 1 == week_day...
(day, month, year) = input().strip().split() day = int(day) month = int(month) year = int(year) if month < 3: month += 12 year -= 1 c = year / 100 k = year % 100 day + 26 * (m + 1) / 10 + k + k / 4 week_day_name = '' if 0 == week_day: week_day_name = 'SAT' elif 1 == week_day: week_day_name = 'SUN' elif ...
#using strings myString ="my time is longer" myInteger= 23 int =455 print(int) print(myString.upper()) #all in capital letters print(myString.lower()) #all in lowercase print(myString.capitalize()) # the first letter is in capital letter print(myString.swapcase()) #change all in capital letters because the original s...
my_string = 'my time is longer' my_integer = 23 int = 455 print(int) print(myString.upper()) print(myString.lower()) print(myString.capitalize()) print(myString.swapcase()) print(myString.count('i')) print(myString.replace('time', 'computer')) print(myString.startswith('me')) print(myString.endswith('longer')) print(my...
class Animal(): def __init__(self,name): self.name =name #a = Animal("dog") #print(a.name)
class Animal: def __init__(self, name): self.name = name
# # Copyright 2022 Embedded Systems Unit, Fondazione Bruno Kessler # # 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 # # Unl...
""" Module for all PyVmt exceptions """ class Pyvmtexception(Exception): """ Base exception for pyvmt """ class Unexpectedstatevariableerror(PyvmtException): """ Raised when a formula which shouldn't have next/prev state variables has one """ class Statevariableerror(PyvmtExceptio...
def save_color_image(db, data): db.update_snapshot(data['user'], data['timestamp'], data['result']) def save_depth_image(db, data): db.update_snapshot(data['user'], data['timestamp'], data['result'])
def save_color_image(db, data): db.update_snapshot(data['user'], data['timestamp'], data['result']) def save_depth_image(db, data): db.update_snapshot(data['user'], data['timestamp'], data['result'])
class Solution: def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: r = [] for row in range(len(matrix)): m = min(matrix[row]) i = matrix[row].index(m) flag = True for k in range(len(matrix)): if matrix[k][i]>m: ...
class Solution: def lucky_numbers(self, matrix: List[List[int]]) -> List[int]: r = [] for row in range(len(matrix)): m = min(matrix[row]) i = matrix[row].index(m) flag = True for k in range(len(matrix)): if matrix[k][i] > m: ...
## scale and fit on the scaled data scaler = StandardScaler() X_scaled = scaler.fit_transform(X) pred = KMeans(4).fit_predict(X_scaled) # plotting xmin,ymin,xmax,ymax = *X_scaled.min(0), *X_scaled.max(0) # the "*" just unpacks the values, not multiplication plt.scatter(X_scaled[:,0],X_scaled[:,1], c=pred) plt.xlim(xm...
scaler = standard_scaler() x_scaled = scaler.fit_transform(X) pred = k_means(4).fit_predict(X_scaled) (xmin, ymin, xmax, ymax) = (*X_scaled.min(0), *X_scaled.max(0)) plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=pred) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.title('KMeans with scaling')
class BreakoutException(Exception): pass class FunctionThrownException(Exception): def __init__(self, outer, step): self.outer = outer self.step = step def o_add(input_list, position, param1, param2, param3): param3(input_list, input_list[position+3], True, param1(input_list, input_lis...
class Breakoutexception(Exception): pass class Functionthrownexception(Exception): def __init__(self, outer, step): self.outer = outer self.step = step def o_add(input_list, position, param1, param2, param3): param3(input_list, input_list[position + 3], True, param1(input_list, input_list...
for i in range(0, 9): if i == 5: continue print(i) print("Loop is end.")
for i in range(0, 9): if i == 5: continue print(i) print('Loop is end.')
# -*- coding: utf-8 -*- def factorial_func(n: int): if isinstance(n, int) and n < 0: raise ValueError('Number n must be an integer and n is not an negative!') res = 1 while n >= 2: res *= n n -= 1 return res def fib_func(n): if isinstance(n, int) and n < 1: raise...
def factorial_func(n: int): if isinstance(n, int) and n < 0: raise value_error('Number n must be an integer and n is not an negative!') res = 1 while n >= 2: res *= n n -= 1 return res def fib_func(n): if isinstance(n, int) and n < 1: raise value_error('Number n must...
fuel_type = input() fuel_amount = float(input()) club_card = input() gasoline_price = 2.22 diesel_price = 2.33 gas_price = 0.93 if fuel_type == "Gas": if club_card == "Yes": if 20 <= fuel_amount <= 25: fuel_price = fuel_amount * (gas_price - 0.08) fuel_price = fuel_price - (fuel_pr...
fuel_type = input() fuel_amount = float(input()) club_card = input() gasoline_price = 2.22 diesel_price = 2.33 gas_price = 0.93 if fuel_type == 'Gas': if club_card == 'Yes': if 20 <= fuel_amount <= 25: fuel_price = fuel_amount * (gas_price - 0.08) fuel_price = fuel_price - fuel_price...
#Kunal Gautam #Codewars : @Kunalpod #Problem name: Complete The Pattern #6 - Odd Ladder #Problem level: 7 kyu def pattern(n): return "\n".join(str(i)*i for i in range(1, n+1) if i%2)
def pattern(n): return '\n'.join((str(i) * i for i in range(1, n + 1) if i % 2))
def power_iteration(A, m0=1, u0=None, eps=1e-8, max_steps=500, verbose=False): m = m0 u = u0 for k in range(int(max_steps)): if verbose: print(k, m, u) m_prev = m v = dot(A, u) mi = argmax(abs(v)) m = v[mi] u = v / m ...
def power_iteration(A, m0=1, u0=None, eps=1e-08, max_steps=500, verbose=False): m = m0 u = u0 for k in range(int(max_steps)): if verbose: print(k, m, u) m_prev = m v = dot(A, u) mi = argmax(abs(v)) m = v[mi] u = v / m if abs(m - m_prev) <= ...
try: pass except: pass
try: pass except: pass
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def freeGLUT(): http_archive( name="FreeGLUT" , build_file="//bazel/deps/FreeGLUT:build.BUILD" , sha256="90828907e...
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def free_glut(): http_archive(name='FreeGLUT', build_file='//bazel/deps/FreeGLUT:build.BUILD', sha256='90828907ea4e30a79ce7f36c5b3e4d60039912d92ec17788fd709c955f4d0a04', strip_prefix='FreeGLUT-349a23dcc1264a76deb79962d1c90462ad0c6f50', urls=['htt...
def comb(bam_file,fq_start,fq_end): fq={} with open(fq_start) as f: lines = f.readlines() for i in range(1,len(lines),4): l = len(lines[i].strip()) name = lines[i-1].strip()[1:] fq[name]=[str(l)] with open(fq_end) as f: lines = f.readlines() for i in range(1,l...
def comb(bam_file, fq_start, fq_end): fq = {} with open(fq_start) as f: lines = f.readlines() for i in range(1, len(lines), 4): l = len(lines[i].strip()) name = lines[i - 1].strip()[1:] fq[name] = [str(l)] with open(fq_end) as f: lines = f.readlines() for i in...
# TODO: *3 @task def setupNetwork(ifaces): interfaces = '''auto lo iface lo inet loopback ''' for iface, config in ifaces.items(): interfaces += ''' auto %s iface %s inet static address %s netmask %s ''' % (iface, iface, config[0], config[1]) if iface == 'eth1': interfaces ...
@task def setup_network(ifaces): interfaces = 'auto lo\niface lo inet loopback\n' for (iface, config) in ifaces.items(): interfaces += '\nauto %s\niface %s inet static\n address %s\n netmask %s\n' % (iface, iface, config[0], config[1]) if iface == 'eth1': interfaces += ' gat...
class LexpyError(Exception): pass class InvalidWildCardExpressionError(LexpyError): def __init__(self, expr, message): self.expr = expr self.message = message def __str__(self): return repr(': '.join([self.message, self.expr]))
class Lexpyerror(Exception): pass class Invalidwildcardexpressionerror(LexpyError): def __init__(self, expr, message): self.expr = expr self.message = message def __str__(self): return repr(': '.join([self.message, self.expr]))
# Python program to create a bytearray from a list nums = [10, 20, 56, 35, 17, 99] values = bytearray(nums) for x in values: print(x)
nums = [10, 20, 56, 35, 17, 99] values = bytearray(nums) for x in values: print(x)
#!/usr/bin/env python3 x = 0 y = (-1/4)*(x-1)+3 print(y)
x = 0 y = -1 / 4 * (x - 1) + 3 print(y)
class American(object): pass class NewYorker(American): pass anAmerican = American() aNewYorker = NewYorker()
class American(object): pass class Newyorker(American): pass an_american = american() a_new_yorker = new_yorker()
# [7 kyu] Descending Order # # Author: Hsins # Date: 2019/12/31 def descending_order(num): return int("".join(sorted(str(num), reverse=True)))
def descending_order(num): return int(''.join(sorted(str(num), reverse=True)))
def minimum_bracket_reversals(input_string): if len(input_string) % 2 == 1: return -1 stack = Stack() count = 0 for bracket in input_string: if stack.is_empty(): stack.push(bracket) else: top = stack.top() if top != bracket: if...
def minimum_bracket_reversals(input_string): if len(input_string) % 2 == 1: return -1 stack = stack() count = 0 for bracket in input_string: if stack.is_empty(): stack.push(bracket) else: top = stack.top() if top != bracket: if ...
def intercalaEmOrdem(lista1, lista2): intercalada = [] lista1.sort() lista2.sort() while len(lista1) > 0 and len(lista2) > 0: if lista1[0] < lista2[0]: intercalada.append(lista1.pop(0)) else: intercalada.append(lista2.pop(0)) if len(lista1) > 0: inte...
def intercala_em_ordem(lista1, lista2): intercalada = [] lista1.sort() lista2.sort() while len(lista1) > 0 and len(lista2) > 0: if lista1[0] < lista2[0]: intercalada.append(lista1.pop(0)) else: intercalada.append(lista2.pop(0)) if len(lista1) > 0: inte...
def f2(a): global b print(a) print(b) b = 9 print(b) b = 5 f2(3)
def f2(a): global b print(a) print(b) b = 9 print(b) b = 5 f2(3)
# # PySNMP MIB module CPQCLUSTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQCLUSTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:27:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, constraints_intersection, single_value_constraint, value_range_constraint) ...
#!/usr/bin/env python f = open('/Users/kosta/dev/advent-of-code-17/day10/input.txt') lengths = list(map(int, f.readline().split(','))) hash_list = list(range(256)) skip = 0 cur_index = 0 for length in lengths: if cur_index + length > len(hash_list): sub_list = hash_list[cur_index:] sub_list.exten...
f = open('/Users/kosta/dev/advent-of-code-17/day10/input.txt') lengths = list(map(int, f.readline().split(','))) hash_list = list(range(256)) skip = 0 cur_index = 0 for length in lengths: if cur_index + length > len(hash_list): sub_list = hash_list[cur_index:] sub_list.extend(hash_list[:cur_index + ...
def softmax(x): t = np.exp(x) return t/t.sum() q_relu = softmax(C @ relu(A @ x + b) + d) q_sigmoid = softmax(C @ sigmoid(A @ x + b) + d)
def softmax(x): t = np.exp(x) return t / t.sum() q_relu = softmax(C @ relu(A @ x + b) + d) q_sigmoid = softmax(C @ sigmoid(A @ x + b) + d)
# Filters and the expression register are two really cool ways of calling arbitrary code from vim. # Filters are just anything that takes your text via stdin and gives you something via stdout # Filters can be invoked via `!{motion}` or `!` while selecting, and can call arbitrary scripts # Examples with either `!}` or...
"""The quick brown fox jumps over the lazy dog""" 'The quick brown fox jumps over the lazy dog' 'The quick brown fox jumps over the lazy cat' 'The quick brown fox jumps over the lazy dog'
#encoding:utf-8 subreddit = 'india' t_channel = '@r_indiaa' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'india' t_channel = '@r_indiaa' def send_post(submission, r2t): return r2t.send_simple(submission)
microcode = ''' def macroop VCVTSD2SS_XMM_XMM { cvtf2f xmm0, xmm0m, destSize=4, srcSize=8, ext=Scalar movfph2h xmm0, xmm0v, dataSize=4 movfp xmm1, xmm1v, dataSize=8 vclear dest=xmm2, destVL=16 }; def macroop VCVTSD2SS_XMM_M { ldfp ufp1, seg, sib, disp, dataSize=8 cvtf2f xmm0, ufp1, destSize=4...
microcode = '\n\ndef macroop VCVTSD2SS_XMM_XMM {\n cvtf2f xmm0, xmm0m, destSize=4, srcSize=8, ext=Scalar\n movfph2h xmm0, xmm0v, dataSize=4\n movfp xmm1, xmm1v, dataSize=8\n vclear dest=xmm2, destVL=16\n};\n\ndef macroop VCVTSD2SS_XMM_M {\n ldfp ufp1, seg, sib, disp, dataSize=8\n cvtf2f xmm0, ufp1, d...
# --- Day 2: I Was Told There Would Be No Math --- def createLineList(input): lineList = [line.rstrip('\r\n') for line in open(input)] return lineList def createDimList(lines): dimList = [] for L in lines: dim = L.split("x") for i in range(0, len(dim)): dim[i] = int(dim[i]) dimList.append(dim) return di...
def create_line_list(input): line_list = [line.rstrip('\r\n') for line in open(input)] return lineList def create_dim_list(lines): dim_list = [] for l in lines: dim = L.split('x') for i in range(0, len(dim)): dim[i] = int(dim[i]) dimList.append(dim) return dimLis...
__author__ = 'burakks41' line1 = input().split() line2 = input().split() flowers = int(line1[0]) persons = int(line1[1]) person = [0] * persons flowers_cost = sorted([int(n) for n in line2],reverse=True) sum = 0 for i in range(flowers): x, person[i % persons] = person[i % persons], person[i % persons] + 1 su...
__author__ = 'burakks41' line1 = input().split() line2 = input().split() flowers = int(line1[0]) persons = int(line1[1]) person = [0] * persons flowers_cost = sorted([int(n) for n in line2], reverse=True) sum = 0 for i in range(flowers): (x, person[i % persons]) = (person[i % persons], person[i % persons] + 1) ...
# You are given an array of non-negative integers numbers. You are allowed to choose any number from this array and swap any two digits in it. If after the swap operation the number contains leading zeros, they can be omitted and not considered (eg: 010 will be considered just 10). # Your task is to check whether it...
def compare(arr1, arr2): store = [] for i in range(len(arr1)): if arr1[i] != arr2[i]: store.append(i) return store def get_options(str): store = [] for i in range(len(str) - 1): store.append(int(str[i + 1:] + str[:i + 1])) return store def check(i, arr): curr = ...
def balanced_split_exists(arr): if len(arr) < 2 or sum(arr) % 2 != 0: return False arr.sort() # n log n l, r = 0, len(arr) - 1 left_sum, right_sum = arr[l], arr[r] while l <= r: if arr[l] >= arr[r]: return False if left_sum < right_sum: l += 1 ...
def balanced_split_exists(arr): if len(arr) < 2 or sum(arr) % 2 != 0: return False arr.sort() (l, r) = (0, len(arr) - 1) (left_sum, right_sum) = (arr[l], arr[r]) while l <= r: if arr[l] >= arr[r]: return False if left_sum < right_sum: l += 1 ...
def get_hours_since_midnight(total_seconds): hours = total_seconds // 3600 return hours total_seconds = int(input('Enter a number of seconds: ')) hours = get_hours_since_midnight(total_seconds) format(hours,'02d') def get_minutes(total_seconds): minutes = ( total_seconds % 3600) minutes //= 60 re...
def get_hours_since_midnight(total_seconds): hours = total_seconds // 3600 return hours total_seconds = int(input('Enter a number of seconds: ')) hours = get_hours_since_midnight(total_seconds) format(hours, '02d') def get_minutes(total_seconds): minutes = total_seconds % 3600 minutes //= 60 return...
brd = { 'name': ('Raspberry Pi B+/2'), 'port': { 'rpigpio': { 'gpio' : { # BCM/Functional RPi pin names. 'bcm2_sda' : '3', 'bcm3_scl' : '5', 'bcm4_gpclk0': '7', 'bcm17' : '11', ...
brd = {'name': 'Raspberry Pi B+/2', 'port': {'rpigpio': {'gpio': {'bcm2_sda': '3', 'bcm3_scl': '5', 'bcm4_gpclk0': '7', 'bcm17': '11', 'bcm27_pcm_d': '13', 'bcm22': '15', 'bcm10_mosi': '19', 'bcm9_miso': '21', 'bcm11_sclk': '23', 'bcm5': '29', 'bcm6': '31', 'bcm13': '33', 'bcm19_miso': '35', 'bcm26': '37', 'bcm21_sclk'...
n = int(input()) X = list(map(int, input().split())) X.sort() def median(n, X): if n % 2 == 0: numerator = X[int(n / 2)] + X[int(n / 2 - 1)] median_value = numerator / 2 else: median_value = X[int(n / 2)] return int(median_value) print(median(int(n / 2), X[: int(n / 2)])) prin...
n = int(input()) x = list(map(int, input().split())) X.sort() def median(n, X): if n % 2 == 0: numerator = X[int(n / 2)] + X[int(n / 2 - 1)] median_value = numerator / 2 else: median_value = X[int(n / 2)] return int(median_value) print(median(int(n / 2), X[:int(n / 2)])) print(media...
{ 'includes': [ '../common.gyp' ], 'targets': [ { 'target_name': 'libzxing', 'type': 'static_library', 'include_dirs': [ 'core/src', ], 'sources': [ 'core/src/bigint/BigInteger.cc', 'core/src/bigint/BigIntegerAlgorithms.cc', 'core/src/bigint/BigInteg...
{'includes': ['../common.gyp'], 'targets': [{'target_name': 'libzxing', 'type': 'static_library', 'include_dirs': ['core/src'], 'sources': ['core/src/bigint/BigInteger.cc', 'core/src/bigint/BigIntegerAlgorithms.cc', 'core/src/bigint/BigIntegerUtils.cc', 'core/src/bigint/BigUnsigned.cc', 'core/src/bigint/BigUnsignedInAB...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = (class_1 + class_2) print (new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_c...
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) courses = {'Math': 65, 'English...
def increment(x, by=1): return x + by def tokenize(sentence): return pos_tag(word_tokenize(sentence)) def synsets(sentence): tokens = tokenize(sentence) return remove_none(tagged_to_synset(*t) for t in tokens) def remove_none(xs): return [x for x in xs if x is not None] def score(synset, syn...
def increment(x, by=1): return x + by def tokenize(sentence): return pos_tag(word_tokenize(sentence)) def synsets(sentence): tokens = tokenize(sentence) return remove_none((tagged_to_synset(*t) for t in tokens)) def remove_none(xs): return [x for x in xs if x is not None] def score(synset, synse...
s1 = input() s2 = input() pairs = set() for i in range(len(s2) - 1): pairs.add(s2[i:i + 2]) ans = 0 for i in range(len(s1) - 1): if s1[i: i + 2] in pairs: ans += 1 print(ans)
s1 = input() s2 = input() pairs = set() for i in range(len(s2) - 1): pairs.add(s2[i:i + 2]) ans = 0 for i in range(len(s1) - 1): if s1[i:i + 2] in pairs: ans += 1 print(ans)
# makes a BST from an array class Node: def __init__(self, value, left, right): self.value = value self.left = left self.right = right def bst_from_array(array, start, end): if start >= end: return None mid = (start + end) // 2 value = array[mid] left = bst_from_arra...
class Node: def __init__(self, value, left, right): self.value = value self.left = left self.right = right def bst_from_array(array, start, end): if start >= end: return None mid = (start + end) // 2 value = array[mid] left = bst_from_array(array, start, mid) ri...
''' Created on 24.05.2011 @author: Sergey Khayrulin ''' class Position(object): ''' Definition for position of point ''' def __init__(self,proximal_point=None,distal_point=None): ''' Constructor ''' self.distal_point = distal_point self.pr...
""" Created on 24.05.2011 @author: Sergey Khayrulin """ class Position(object): """ Definition for position of point """ def __init__(self, proximal_point=None, distal_point=None): """ Constructor """ self.distal_point = distal_point self.proximal_point = prox...
sum_counter = 0 # 600851475143 number = 600851475143 for i in range(2, 10000): for j in range(1, i + 1): if i % j == 0: sum_counter += 1 if sum_counter == 2: # print(i, end= " ") if number % i == 0: print() print(f"prime factors for {number} : {i}", ...
sum_counter = 0 number = 600851475143 for i in range(2, 10000): for j in range(1, i + 1): if i % j == 0: sum_counter += 1 if sum_counter == 2: if number % i == 0: print() print(f'prime factors for {number} : {i}', end=' ') print() sum_counter =...
class MemoryItem: def __init__(self, observation, action, next_observation, reward, done, info): self.observation = observation self.action = action self.next_observation = next_observation self.reward = reward self.done = done self.info = info
class Memoryitem: def __init__(self, observation, action, next_observation, reward, done, info): self.observation = observation self.action = action self.next_observation = next_observation self.reward = reward self.done = done self.info = info
class Queen: def __init__(self, pos, visited): self.pos = pos self.visited = visited
class Queen: def __init__(self, pos, visited): self.pos = pos self.visited = visited
VALID_USER = { "username": "Test", "email": "test@email.com", "password": "Test@123", "password2": "Test@123", }
valid_user = {'username': 'Test', 'email': 'test@email.com', 'password': 'Test@123', 'password2': 'Test@123'}
class Solution: def minJumps(self, arr, n): jumps = [-1] * n jumps[0] = 0 front = 0 rear = 0 while rear < n : remaining_jumps = arr[rear] - (front - rear) while remaining_jumps > 0 and front < n-1: front += 1 j...
class Solution: def min_jumps(self, arr, n): jumps = [-1] * n jumps[0] = 0 front = 0 rear = 0 while rear < n: remaining_jumps = arr[rear] - (front - rear) while remaining_jumps > 0 and front < n - 1: front += 1 j = jump...
# # Copyright (c) 2013-2014, PagerDuty, Inc. <info@pagerduty.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notic...
class Mockqueue: def __init__(self, event=None, status=None, detailed_snapshot=None, cleanup_age_secs=None): self.event = event self.status = status self.expected_detailed_snapshot = detailed_snapshot self.expected_cleanup_age = cleanup_age_secs self.consume_code = None ...
# 3. File Writer # Create a program that creates a file called my_first_file.txt. # In that file write a single line with the content: 'I just created my first file!' # file = open("my_first_file.txt", "w") # # file.write('I just created my first file!') # # file.close() # With manager is better than just open as it ...
with open('my_first_file.txt', 'w') as file: file.write('I just created my first file!')
# 4-5. Summing a Million: Make a list of the numbers from one to one million, and then use min() and max() # to make sure your list actually starts at one and ends at one million. # Also, use the sum() function to see how quickly Python can add a million numbers. numbers = list(range(1, 1000001)) print(min(numbers)) ...
numbers = list(range(1, 1000001)) print(min(numbers)) print(max(numbers)) print(sum(numbers))