content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" The main init module """ __version__ = "1.1.0"
""" The main init module """ __version__ = '1.1.0'
class Todo: """ Implement the Todo Class """ def __init__(self, name, description, points, completed=False): self.name = name self.description = description self.points = points self.completed = completed def __repr__(self): return (f" Task Nam...
class Todo: """ Implement the Todo Class """ def __init__(self, name, description, points, completed=False): self.name = name self.description = description self.points = points self.completed = completed def __repr__(self): return f' Task Name: {self.name} ...
# Special Pythagorean triplet # Problem 9 # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. # # First, we recognize that i...
initial_c_value = 334 def run(): c = INITIAL_C_VALUE for c in range(INITIAL_C_VALUE, 1000): diff = 1000 - c a = diff // 2 b = diff - a sum_of_squares = a * a + b * b c_squared = c * c while sum_of_squares < c_squared: a -= 1 b += 1 ...
print('hello') """ Visible to students editEdit lab (Links to an external site.)noteNote Write a program that removes all digits from the given input. I like purple socks. Ex: If the input is: 1244Crescent the output is: Crescent The program must define and call the following function that takes a string as paramete...
print('hello') '\nVisible to students\neditEdit lab (Links to an external site.)noteNote\nWrite a program that removes all digits from the given input.\nI like purple socks.\nEx: If the input is:\n\n1244Crescent\nthe output is:\n\nCrescent\nThe program must define and call the following function that takes a string as ...
# This Script for generating Tables # Steps: # [1] Get The Table Title # [2] Get The Table Cells width # [3] Get The Table Column Names # [4] Get The Table Cells Data # ========================================================== def calc_space_before(word,cell_length): # Get Total width of ...
def calc_space_before(word, cell_length): return int((cell_length - len(word)) / 2) def cells__line(columns_width, cell_line='-', cells_seperator='+'): for i in columns_width: print(cells_seperator + cell_line * i, end='') print(cells_seperator) def calc_space_after(word, cell_length): return ...
# ch18/example4.py def read_data(): for i in range(5): print('Inside the inner for loop...') yield i * 2 result = read_data() for i in range(6): print('Inside the outer for loop...') print(next(result)) print('Finished.')
def read_data(): for i in range(5): print('Inside the inner for loop...') yield (i * 2) result = read_data() for i in range(6): print('Inside the outer for loop...') print(next(result)) print('Finished.')
class Location: def __init__(self, lat: float, lon: float): self.lat = lat self.lon = lon def __repr__(self) -> str: return f"({self.lat}, {self.lon})" def str_between(input_str: str, left: str, right: str) -> str: return input_str.split(left)[1].split(right)[0]
class Location: def __init__(self, lat: float, lon: float): self.lat = lat self.lon = lon def __repr__(self) -> str: return f'({self.lat}, {self.lon})' def str_between(input_str: str, left: str, right: str) -> str: return input_str.split(left)[1].split(right)[0]
# Consume: CONSUMER_KEY = '' CONSUMER_SECRET = '' # Access: ACCESS_TOKEN = '' ACCESS_SECRET = ''
consumer_key = '' consumer_secret = '' access_token = '' access_secret = ''
# Title : Queue implementation using lists # Author : Kiran Raj R. # Date : 03:11:2020 class Queue: def __init__(self): self._queue = [] self.head = self.length() def length(self): return len(self._queue) def print_queue(self): if self.length == self.head: p...
class Queue: def __init__(self): self._queue = [] self.head = self.length() def length(self): return len(self._queue) def print_queue(self): if self.length == self.head: print('The queue is empty') return else: print('[', end='')...
# -*- coding: utf-8 -*- target_cancer = "PANCANCER" input_file1 = [] input_file2 = [] output_tumor1 = open(target_cancer + ".SEP_8.Tumor_Cor_CpGsite&CytAct_pearson.txt", 'w') output_tumor2 = open(target_cancer + ".SEP_8..Tumor_Cor_CpGSite&CytAct_spearman.txt", 'w') for i in range(0, 10) : name = str(i) inp...
target_cancer = 'PANCANCER' input_file1 = [] input_file2 = [] output_tumor1 = open(target_cancer + '.SEP_8.Tumor_Cor_CpGsite&CytAct_pearson.txt', 'w') output_tumor2 = open(target_cancer + '.SEP_8..Tumor_Cor_CpGSite&CytAct_spearman.txt', 'w') for i in range(0, 10): name = str(i) input_file1.append(open(target_ca...
openers_by_closer = { ')': '(', '}': '{', ']': '[', '>': '<', } closers_by_opener = {v: k for k, v in openers_by_closer.items()} part1_points = { ')': 3, ']': 57, '}': 1197, '>': 25137, } part2_points = { ')': 1, ']': 2, '}': 3, '>': 4, } def part1(input): stack ...
openers_by_closer = {')': '(', '}': '{', ']': '[', '>': '<'} closers_by_opener = {v: k for (k, v) in openers_by_closer.items()} part1_points = {')': 3, ']': 57, '}': 1197, '>': 25137} part2_points = {')': 1, ']': 2, '}': 3, '>': 4} def part1(input): stack = [] corrupted = 0 for char in input: if op...
""" MangaDex API wrapper for Python :copyright: (c), 2021 Mansuf :license: MIT, see LICENSE for more details. """ __version__ = 'v0.0.1'
""" MangaDex API wrapper for Python :copyright: (c), 2021 Mansuf :license: MIT, see LICENSE for more details. """ __version__ = 'v0.0.1'
class TaskException(Exception): """ Like classic Exception, but we keep the task result, which gets spoiled by celery cache result backend. The kwargs parameter is used for passing custom metadata. """ obj = None def __init__(self, result, msg=None, **kwargs): if msg: resul...
class Taskexception(Exception): """ Like classic Exception, but we keep the task result, which gets spoiled by celery cache result backend. The kwargs parameter is used for passing custom metadata. """ obj = None def __init__(self, result, msg=None, **kwargs): if msg: resul...
def minimumNumber(n, password): # Return the minimum number of characters to make the password strong # Its length is at least 6. # It contains at least one digit. # It contains at least one lowercase English character. # It contains at least one uppercase English character. # It contains at lea...
def minimum_number(n, password): numbers = '0123456789' lower_case = 'abcdefghijklmnopqrstuvwxyz' upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' special_characters = '!@#$%^&*()-+' miss = 0 if any((character in numbers for character in password)) == False: miss += 1 if any((character in l...
# -*- coding: utf-8 -*- def get_site_id(domain_name, sites): ''' Accepts a domain name and a list of sites. sites is assumed to be the return value of ZoneSerializer.get_basic_info() This function will return the CloudFlare ID of the given domain name. ''' site_id = None match = fi...
def get_site_id(domain_name, sites): """ Accepts a domain name and a list of sites. sites is assumed to be the return value of ZoneSerializer.get_basic_info() This function will return the CloudFlare ID of the given domain name. """ site_id = None match = filter(lambda x: x['name']...
#encoding:utf-8 subreddit = '00ag9603' t_channel = '@r_00ag9603' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = '00ag9603' t_channel = '@r_00ag9603' def send_post(submission, r2t): return r2t.send_simple(submission)
names = ['Cecil', 'Brian', 'Michael', 'Edna', 'Gertrude', 'Lily', 'Beverly'] #result = [] # for name in names: # result.append(len(name)) def cap(name): up = name.upper() reversed_list = list(reversed(up)) return "".join(reversed_list) result = [cap(name) for name in names] print(result)
names = ['Cecil', 'Brian', 'Michael', 'Edna', 'Gertrude', 'Lily', 'Beverly'] def cap(name): up = name.upper() reversed_list = list(reversed(up)) return ''.join(reversed_list) result = [cap(name) for name in names] print(result)
# [Copyright] # SmartPath v1.0 # Copyright 2014-2015 Mountain Pass Solutions, Inc. # This unpublished material is proprietary to Mountain Pass Solutions, Inc. # [End Copyright] manage_joint_promotions = { "code": "manage_joint_promotions", "descr": "Manage Joint Secondary Promotions", "header": "Manage Joint Second...
manage_joint_promotions = {'code': 'manage_joint_promotions', 'descr': 'Manage Joint Secondary Promotions', 'header': 'Manage Joint Secondary Promotions', 'componentType': 'Task', 'affordanceType': 'Item', 'optional': True, 'enabled': True, 'accessPermissions': ['dept_task'], 'viewPermissions': ['ofa_task', 'dept_task'...
# # This is the Robotics Language compiler # # Parameters.py: Definition of the parameters for this package # # Created on: 08 October, 2018 # Author: Gabriel Lopes # Licence: license # Copyright: copyright # parameters = { 'globalIncludes': set(), 'localIncludes': set() } command_line_fl...
parameters = {'globalIncludes': set(), 'localIncludes': set()} command_line_flags = {'globalIncludes': {'suppress': True}, 'localIncludes': {'suppress': True}}
x = 1000000 while True: y = x z = x + 1 x = z + 1
x = 1000000 while True: y = x z = x + 1 x = z + 1
"""Implementation of basic templating engine.""" FORM_POST = """<html> <head> <title>Submit This Form</title> </head> <body onload="javascript:document.forms[0].submit()"> <form method="post" action="{action}"> {html_inputs} </form> </body> </html>""" VERIFY_LOGOUT = """<html> <head> ...
"""Implementation of basic templating engine.""" form_post = '<html>\n <head>\n <title>Submit This Form</title>\n </head>\n <body onload="javascript:document.forms[0].submit()">\n <form method="post" action="{action}">\n {html_inputs}\n </form>\n </body>\n</html>' verify_logout = '<html>\n <head>\n...
# -*- coding: UTF-8 -*- logger.info("Loading 0 objects to table cal_subscription...") # fields: id, user, calendar, is_hidden loader.flush_deferred_objects()
logger.info('Loading 0 objects to table cal_subscription...') loader.flush_deferred_objects()
def extended_euclidean_gcd(a, b): """Copied from http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm""" x,y, u,v = 0,1, 1,0 while a != 0: q,r = b//a,b%a; m,n = x-u*q,y-v*q b,a, x,y, u,v = a,r, u,v, m,n return b, x, y
def extended_euclidean_gcd(a, b): """Copied from http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm""" (x, y, u, v) = (0, 1, 1, 0) while a != 0: (q, r) = (b // a, b % a) (m, n) = (x - u * q, y - v * q) (b, a, x, y, u, v) = (a, r, u, v, ...
class n_X(flatdata.archive.Archive): _SCHEMA = """namespace n { archive X { payload : raw_data; } } """ _PAYLOAD_SCHEMA = """namespace n { archive X { payload : raw_data; } } """ _PAYLOAD_DOC = """""" _NAME = "X" _RESOURCES = { "X.archive" : flatdata.archive.ResourceSignature( ...
class N_X(flatdata.archive.Archive): _schema = 'namespace n {\narchive X\n{\n payload : raw_data;\n}\n}\n\n' _payload_schema = 'namespace n {\narchive X\n{\n payload : raw_data;\n}\n}\n\n' _payload_doc = '' _name = 'X' _resources = {'X.archive': flatdata.archive.ResourceSignature(container=fla...
# TODO(mihaibojin): WIP; finish writing a javadoc -> target plugin def _javadoc(ctx): """ Rule implementation for generating javadoc for the specified sources """ target_name = ctx.label.name output_jar = ctx.actions.declare_file("{}:{}-javadoc.jar".format(ctx.attr.group_id, ctx.attr.artifact_id)) ...
def _javadoc(ctx): """ Rule implementation for generating javadoc for the specified sources """ target_name = ctx.label.name output_jar = ctx.actions.declare_file('{}:{}-javadoc.jar'.format(ctx.attr.group_id, ctx.attr.artifact_id)) src_list = [] for src in ctx.files.srcs: src_list +=...
class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """
class Solution: def search_matrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """
def is_immutable(new, immutable_attrs): sub = new() it = iter(immutable_attrs) for atr in it: try: setattr(sub, atr, getattr(sub, atr, None)) except AttributeError: continue else: raise AssertionError( f"attribute `{sub.__class__.__...
def is_immutable(new, immutable_attrs): sub = new() it = iter(immutable_attrs) for atr in it: try: setattr(sub, atr, getattr(sub, atr, None)) except AttributeError: continue else: raise assertion_error(f'attribute `{sub.__class__.__qualname__}.{atr...
# Copyright 2017 Brocade Communications Systems, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
""" IANA Private Enterprise Numbers See: https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers """ brocade_pen = 1588 valid_pens = {BROCADE_PEN} def assert_valid_pen(pen): assert pen in VALID_PENS
# Str! API_TOKEN = 'YOUR TOKEN GOES HERE' # Int! ADMIN_ID = 'USER_ID OF PERSON(s) DESIGNATED AS ADMINS'
api_token = 'YOUR TOKEN GOES HERE' admin_id = 'USER_ID OF PERSON(s) DESIGNATED AS ADMINS'
model_space_filename = 'path/to/metrics.json' model_sampling_rules = dict( type='sequential', rules=[ # 1. select model with best performance, could replace with your own metrics dict( type='sample', operation='top', # replace with customized metric in your o...
model_space_filename = 'path/to/metrics.json' model_sampling_rules = dict(type='sequential', rules=[dict(type='sample', operation='top', key='metric.finetune.coco_bbox_mAP', value=1, mode='number')])
""" variable [operator]= value/variable_2 i += 1 result += 1 result /= 10 result *= t result += 4/3 prod %= 10 """
""" variable [operator]= value/variable_2 i += 1 result += 1 result /= 10 result *= t result += 4/3 prod %= 10 """
group_count = 0 count = 0 group = {} with open("input.txt") as f: lines = f.readlines() for line in lines: line = line.strip("\n") if line: group_count += 1 for letter in line: group[letter] = 1 if letter not in group else group[letter] + 1 else: ...
group_count = 0 count = 0 group = {} with open('input.txt') as f: lines = f.readlines() for line in lines: line = line.strip('\n') if line: group_count += 1 for letter in line: group[letter] = 1 if letter not in group else group[letter] + 1 else: ...
with open('input.txt') as f: graph = f.readlines() tree_count = 0 x = 0 for line in graph: if line[x] == '#': tree_count += 1 x += 3 x %= len(line.strip()) print('Part one: ', tree_count) slopes = (1, 3, 5, 7) mult_count = 1 for slope in slopes: tree_count = 0 x = 0 for line in gr...
with open('input.txt') as f: graph = f.readlines() tree_count = 0 x = 0 for line in graph: if line[x] == '#': tree_count += 1 x += 3 x %= len(line.strip()) print('Part one: ', tree_count) slopes = (1, 3, 5, 7) mult_count = 1 for slope in slopes: tree_count = 0 x = 0 for line in graph...
""" Shortest Remaining Time First Scheduler process format: python dict{ 'name':str 'burst_time':int 'arrival_time':int 'remaining_time':int } """ def sort_by(processes, key, reverse=False): """ sorts the given processes list according to the key specified """ return sorted(processes, ...
""" Shortest Remaining Time First Scheduler process format: python dict{ 'name':str 'burst_time':int 'arrival_time':int 'remaining_time':int } """ def sort_by(processes, key, reverse=False): """ sorts the given processes list according to the key specified """ return sorted(processes, ...
class Vector(object): def __init__(self, p0, p1): self.x = p1[0] - p0[0] self.y = p1[1] - p0[1] def is_vertical(self, other): return not self.dot(other) def dot(self, other): return self.x * other.x + self.y * other.y def norm_square(self): return self.dot(self...
class Vector(object): def __init__(self, p0, p1): self.x = p1[0] - p0[0] self.y = p1[1] - p0[1] def is_vertical(self, other): return not self.dot(other) def dot(self, other): return self.x * other.x + self.y * other.y def norm_square(self): return self.dot(sel...
def normalize(df, features): for f in features: range = df[f].max() - df[f].min() df[f] = df[f] / range
def normalize(df, features): for f in features: range = df[f].max() - df[f].min() df[f] = df[f] / range
dt = {} def solve(a, b): if a == b: return True if len(a) <= 1: return False flag = False temp = a + '-' + 'b' if temp in dt: return dt[temp] for i in range(1, len(a)): temp1 = solve(a[:i], b[-i:]) and solve(a[i:], b[:-i]) # swapped temp2 = solve(a[:i]...
dt = {} def solve(a, b): if a == b: return True if len(a) <= 1: return False flag = False temp = a + '-' + 'b' if temp in dt: return dt[temp] for i in range(1, len(a)): temp1 = solve(a[:i], b[-i:]) and solve(a[i:], b[:-i]) temp2 = solve(a[:i], b[:i]) and ...
''' Author: ZHAO Zinan Created: 06-Nov-2018 75. Sort Colors https://leetcode.com/problems/sort-colors/description/ ''' class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ ...
""" Author: ZHAO Zinan Created: 06-Nov-2018 75. Sort Colors https://leetcode.com/problems/sort-colors/description/ """ class Solution: def sort_colors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ zero = 0 ...
n = int(input()) uid_list = [] for i in range(1,n+1): uid = input() uid_list.append(uid) alpha = '''abcdefghijklmnopqrstuvwxyz''' Alpha = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' numeric = '0123456789' N = 0 A = 0 a = 0 valid = [] rep = 0 for i in uid_list: for j in i: if j in Alpha: ...
n = int(input()) uid_list = [] for i in range(1, n + 1): uid = input() uid_list.append(uid) alpha = 'abcdefghijklmnopqrstuvwxyz' alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' numeric = '0123456789' n = 0 a = 0 a = 0 valid = [] rep = 0 for i in uid_list: for j in i: if j in Alpha: a += 1 e...
# 350111 # a3 p10.py # Tibebu T.Biru # t.biru@jacobs-university.de #function definition def print_frame(n, m, c): print(c * m) for i in range(1, n - 1): print(c, ' ' * (m - 2), c, sep='') print(c * m) """ Basically, we print the first and last lines by using repetition which is mult...
def print_frame(n, m, c): print(c * m) for i in range(1, n - 1): print(c, ' ' * (m - 2), c, sep='') print(c * m) ' Basically, we print the first and last lines by using repetition\n which is multiplying the character m-times. Then, for the second \n and third row, we print one character first ...
Clock.bpm=144; Scale.default="lydianMinor" d1 >> play("x-o{-[-(-o)]}", sample=0).every([28,4], "trim", 3) d2 >> play("(X )( X)N{ xv[nX]}", drive=0.2, lpf=var([0,40],[28,4]), rate=PStep(P[5:8],[-1,-2],1)).sometimes("sample.offadd", 1, 0.75) d3 >> play("e", amp=var([0,1],[PRand(8,16)/2,1.5]), dur=PRand([1/2,1/4]), pan=va...
Clock.bpm = 144 Scale.default = 'lydianMinor' d1 >> play('x-o{-[-(-o)]}', sample=0).every([28, 4], 'trim', 3) d2 >> play('(X )( X)N{ xv[nX]}', drive=0.2, lpf=var([0, 40], [28, 4]), rate=p_step(P[5:8], [-1, -2], 1)).sometimes('sample.offadd', 1, 0.75) d3 >> play('e', amp=var([0, 1], [p_rand(8, 16) / 2, 1.5]), dur=p_rand...
# -*- mode: python -*- # vi: set ft=python : # Copyright (c) 2018-2019, Toyota Research Institute. # 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...
def _impl(repository_ctx): vars = repository_ctx.attr._vars bzl_content = [] for key in vars: value = repository_ctx.os.environ.get(key, '') bzl_content.append("{}='{}'\n".format(key, value)) repository_ctx.file('BUILD.bazel', content='\n', executable=False) repository_ctx.file('envi...
s = input() count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in s : if(i == '0') : count[0]+=1 elif(i == '1') : count[1]+=1 elif(i == '2') : count[2]+=1 elif(i == '3') : count[3]+=1 elif(i == '4') : count[4]+=1 elif(i == '5') : count[5]+=1 elif(i =...
s = input() count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in s: if i == '0': count[0] += 1 elif i == '1': count[1] += 1 elif i == '2': count[2] += 1 elif i == '3': count[3] += 1 elif i == '4': count[4] += 1 elif i == '5': count[5] += 1 elif i ==...
# # PySNMP MIB module Wellfleet-IFWALL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-IFWALL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:33:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, single_value_constraint, constraints_union, value_range_constraint) ...
# The observer pattern is a software design pattern in which an object, called the subject, # maintains a list of its dependents, called observers, and notifies them automatically of # any state changes, usually by calling one of their methods. # See more in wiki: https://en.wikipedia.org/wiki/Observer_pattern # # We w...
class Observer(object): def __init__(self, id): self._id = id def update(self, message): print('Observer %d get the update : %s' % (self._id, message)) class Subject(object): def __init__(self): self._observer_list = [] self._message = '' def add_observer(self, obser...
DEBUG = True ADMINS = frozenset([ "yourname@yourdomain.com" ])
debug = True admins = frozenset(['yourname@yourdomain.com'])
magic_square = [ [8, 3, 4], [1, 5, 9], [6, 7, 2] ] print("Row") print(magic_square[0][0]+magic_square[0][1]+magic_square[0][2]) print(magic_square[1][0]+magic_square[1][1]+magic_square[1][2]) print(magic_square[2][0]+magic_square[2][1]+magic_square[2][2]) print("colume") print(magic_square[0][0]+magic_squa...
magic_square = [[8, 3, 4], [1, 5, 9], [6, 7, 2]] print('Row') print(magic_square[0][0] + magic_square[0][1] + magic_square[0][2]) print(magic_square[1][0] + magic_square[1][1] + magic_square[1][2]) print(magic_square[2][0] + magic_square[2][1] + magic_square[2][2]) print('colume') print(magic_square[0][0] + magic_squar...
#!/usr/bin/python3 """a class empty""" class BaseGeometry(): """create class""" pass def area(self): """area""" raise Exception("area() is not implemented")
"""a class empty""" class Basegeometry: """create class""" pass def area(self): """area""" raise exception('area() is not implemented')
class UserImporter: def __init__(self, api): self.api = api self.users = {} def run(self): users = self.api.GetPersons() def save_site_privs(self, user): # update site roles pass def save_slice_privs(self, user): # update slice roles pass ...
class Userimporter: def __init__(self, api): self.api = api self.users = {} def run(self): users = self.api.GetPersons() def save_site_privs(self, user): pass def save_slice_privs(self, user): pass
def I(d,i,v):d[i]=d.setdefault(i,0)+v L=open("inputday14").readlines();t,d,p=L[0],dict([l.strip().split(' -> ')for l in L[2:]]),{};[I(p,t[i:i+2],1)for i in range(len(t)-2)] def E(P):o=dict(P);[(I(P,p,-o[p]),I(P,p[0]+n,o[p]),I(P,n+p[1],o[p]))for p,n in d.items()if p in o.keys()];return P def C(P):e={};[I(e,c,v)for p,v i...
def i(d, i, v): d[i] = d.setdefault(i, 0) + v l = open('inputday14').readlines() (t, d, p) = (L[0], dict([l.strip().split(' -> ') for l in L[2:]]), {}) [i(p, t[i:i + 2], 1) for i in range(len(t) - 2)] def e(P): o = dict(P) [(i(P, p, -o[p]), i(P, p[0] + n, o[p]), i(P, n + p[1], o[p])) for (p, n) in d.items(...
N,M=map(int,input().split()) edges=[list(map(int,input().split())) for i in range(M)] ans=0 for x in edges: l=list(range(N)) for y in edges: if y!=x:l=[l[y[0]-1] if l[i]==l[y[1]-1] else l[i] for i in range(N)] if len(set(l))!=1:ans+=1 print(ans)
(n, m) = map(int, input().split()) edges = [list(map(int, input().split())) for i in range(M)] ans = 0 for x in edges: l = list(range(N)) for y in edges: if y != x: l = [l[y[0] - 1] if l[i] == l[y[1] - 1] else l[i] for i in range(N)] if len(set(l)) != 1: ans += 1 print(ans)
def initialize_weights_normal(network): pass def initialize_weights_xavier(network): pass
def initialize_weights_normal(network): pass def initialize_weights_xavier(network): pass
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: def kSum(nums: List[int], target: int, k: int) -> List[List[int]]: res = [] # If we have run out of numbers to add, return res. if not nums: return res ...
class Solution: def four_sum(self, nums: List[int], target: int) -> List[List[int]]: def k_sum(nums: List[int], target: int, k: int) -> List[List[int]]: res = [] if not nums: return res average_value = target // k if average_value < nums[0] o...
class Employee: def __init__(self, first, last, sex): self.first = first self.last = last self.sex = sex self.email = first + '.' + last + '@company.com' def fullname(self): return "{} {}".format(self.first, self.last) def main(): emp_1 = Employee('prajesh', 'anant...
class Employee: def __init__(self, first, last, sex): self.first = first self.last = last self.sex = sex self.email = first + '.' + last + '@company.com' def fullname(self): return '{} {}'.format(self.first, self.last) def main(): emp_1 = employee('prajesh', 'anant...
class Solution: def lowestCommonAncestor(self, root: 'TreeNode', nodes: 'List[TreeNode]') -> 'TreeNode': nodes = set(nodes) return self._lca(root, nodes) def _lca(self, root, nodes): if not root or root in nodes: return root l = self._lca(root.left, nodes) ...
class Solution: def lowest_common_ancestor(self, root: 'TreeNode', nodes: 'List[TreeNode]') -> 'TreeNode': nodes = set(nodes) return self._lca(root, nodes) def _lca(self, root, nodes): if not root or root in nodes: return root l = self._lca(root.left, nodes) ...
# # PySNMP MIB module EMC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EMC-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:02:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, value_range_constraint, constraints_union, value_size_constraint) ...
class IrisAbstract(metaclass=ABCMeta): @abstractmethod def mean(self) -> float: ... @abstractmethod def sum(self) -> float: ... @abstractmethod def len(self) -> int: ...
class Irisabstract(metaclass=ABCMeta): @abstractmethod def mean(self) -> float: ... @abstractmethod def sum(self) -> float: ... @abstractmethod def len(self) -> int: ...
"""https://open.kattis.com/problems/planina""" def mid(n): if n == 0: return 2 else: return 2 * mid(n-1) - 1 n = int(input()) print(mid(n)**2)
"""https://open.kattis.com/problems/planina""" def mid(n): if n == 0: return 2 else: return 2 * mid(n - 1) - 1 n = int(input()) print(mid(n) ** 2)
class Solution: def rob(self, nums: List[int]) -> int: def recur(arr): memo = {} def dfs(i): if i in memo: return memo[i] if i >= len(arr): return 0 ...
class Solution: def rob(self, nums: List[int]) -> int: def recur(arr): memo = {} def dfs(i): if i in memo: return memo[i] if i >= len(arr): return 0 cur = max(arr[i] + dfs(i + 2), dfs(i + 1)) ...
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0]*(len(text2)+1) for _ in range(len(text1)+1)] m, n = len(text1), len(text2) for i in range(1, m+1): for j in range(1, n+1): if text1[i-1] == text2[j-1]: ...
class Solution: def longest_common_subsequence(self, text1: str, text2: str) -> int: dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)] (m, n) = (len(text1), len(text2)) for i in range(1, m + 1): for j in range(1, n + 1): if text1[i - 1] == text2[j - 1]...
tail = input() body = input() head = input() animal = [head, body, tail] print(animal)
tail = input() body = input() head = input() animal = [head, body, tail] print(animal)
ngroups = int(input()) for i in range(ngroups): bef = '0.0' while True: act = input() if act == '0': break if act.find('.') == -1: act += '.0' nDecAct = len(act) - act.find('.') - 1 nDecBef = len(bef) - bef.find('.') - 1 decima...
ngroups = int(input()) for i in range(ngroups): bef = '0.0' while True: act = input() if act == '0': break if act.find('.') == -1: act += '.0' n_dec_act = len(act) - act.find('.') - 1 n_dec_bef = len(bef) - bef.find('.') - 1 decimals_after ...
def part1(): Input = [int(x) for x in open("input.txt").read().split("\n")] Start = 0 Jumps = {} while len(Input) != 0: Smallest = float("inf") for x in Input: Smallest = min(Smallest, x-Start) if Smallest not in Jumps: Jumps[Smallest] = 1 else:...
def part1(): input = [int(x) for x in open('input.txt').read().split('\n')] start = 0 jumps = {} while len(Input) != 0: smallest = float('inf') for x in Input: smallest = min(Smallest, x - Start) if Smallest not in Jumps: Jumps[Smallest] = 1 else: ...
# Adapted from: http://jared.geek.nz/2013/feb/linear-led-pwm INPUT_SIZE = 255 # Input integer size OUTPUT_SIZE = 255 # Output integer size INT_TYPE = 'uint8_t' TABLE_NAME = 'cie'; def cie1931(L): L = L*100.0 if L <= 8: return (L/902.3) else: return ((L+16.0)/116.0)**3 x = range...
input_size = 255 output_size = 255 int_type = 'uint8_t' table_name = 'cie' def cie1931(L): l = L * 100.0 if L <= 8: return L / 902.3 else: return ((L + 16.0) / 116.0) ** 3 x = range(0, int(INPUT_SIZE + 1)) brightness = [cie1931(float(L) / INPUT_SIZE) for l in x] numerator = 1 denominator = ...
class ImportBuilder(): def __init__(self, file_type: str) -> None: self.allowed_file_types = [ 'xlsx', 'json', 'pbix', 'rdl', 'onedrive' ] if file_type not in self.allowed_file_types: raise ValueError( ...
class Importbuilder: def __init__(self, file_type: str) -> None: self.allowed_file_types = ['xlsx', 'json', 'pbix', 'rdl', 'onedrive'] if file_type not in self.allowed_file_types: raise value_error('File type not supported, please provide file types that are supported.') _conten...
# # PySNMP MIB module HPN-ICF-NVGRE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-NVGRE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:40:39 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint) ...
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ # Idea: preorder recursive traversal; add number of children after root val, in order to know when to terminate. class Codec: def serialize(self, root): """E...
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str """ node_list = []...
image = [] with open('conv0.bb','rb') as f: pixels = f.read(320 * 160 * 4 * 2) print(type(pixels)) for pixel in pixels: image.append(pixel) print(len(image)) print(max(image)) print(min(image))
image = [] with open('conv0.bb', 'rb') as f: pixels = f.read(320 * 160 * 4 * 2) print(type(pixels)) for pixel in pixels: image.append(pixel) print(len(image)) print(max(image)) print(min(image))
print ("Hello world ....! Hi") count = 10 print("I am at break-point ",count); count=10*2 print("end ",count) print ("Hello world") pr = input("enter your name .!!") print ("Hello world",pr) for hooray_counter in range(1, 10): for hip_counter in range(1, 3): print ("Hip") print ("Hooray!!") while Tr...
print('Hello world ....! Hi') count = 10 print('I am at break-point ', count) count = 10 * 2 print('end ', count) print('Hello world') pr = input('enter your name .!!') print('Hello world', pr) for hooray_counter in range(1, 10): for hip_counter in range(1, 3): print('Hip') print('Hooray!!') while True:...
class Solution(object): def intToRoman(self, num): """ :type num: int :rtype: str """ exchange = [['I', 1], ['V', 5], ['X', 10], ['L', 50], ['C', 100], ['D', 500], ['M', 1000]] exchange = exchange[::-1] roman = "" index = 0 while num >...
class Solution(object): def int_to_roman(self, num): """ :type num: int :rtype: str """ exchange = [['I', 1], ['V', 5], ['X', 10], ['L', 50], ['C', 100], ['D', 500], ['M', 1000]] exchange = exchange[::-1] roman = '' index = 0 while num > 0: ...
ofd1 = open('D:\\MyGit\\ML\Data\\x_y_seqindex.csv','r') ofd2 = open('D:\\MyGit\\ML\Data\\OrderSeq.csv','r') nfd = open('D:\\MyGit\\ML\Data\\OrderClassificationCheck.txt','w') orders = [] for i in ofd2: t = i.strip().split(',') order,design,classification,seq = t orders.append(t) dic = {} dic[0]='Complex'...
ofd1 = open('D:\\MyGit\\ML\\Data\\x_y_seqindex.csv', 'r') ofd2 = open('D:\\MyGit\\ML\\Data\\OrderSeq.csv', 'r') nfd = open('D:\\MyGit\\ML\\Data\\OrderClassificationCheck.txt', 'w') orders = [] for i in ofd2: t = i.strip().split(',') (order, design, classification, seq) = t orders.append(t) dic = {} dic[0] =...
# from flask import Blueprint, request # from app.api.utils import good_json_response, bad_json_response # import requests # blueprint.route('/add', methods=['POST']) def test_register(): pass # url = 'http://localhost:5000/json' # resp = requests.get(url) # assert resp.status_code == 200 # assert...
def test_register(): pass def test_delete(): pass def f(): return 4 def test_function(): assert f() == 4 __all__ = 'blueprint'
# -*- coding: utf-8 -*- class AgendamentoExistenteError(Exception): def __init__(self, *args, **kwargs): super(AgendamentoExistenteError, self).__init__(*args, **kwargs)
class Agendamentoexistenteerror(Exception): def __init__(self, *args, **kwargs): super(AgendamentoExistenteError, self).__init__(*args, **kwargs)
""" Parameters for tf.function decorators that need be defined before importing the model file""" # used by RADU_NN*.py, defaults to four amplitude images INPUT_FEATURES_SHAPE = [None, 512, 512, 4]
""" Parameters for tf.function decorators that need be defined before importing the model file""" input_features_shape = [None, 512, 512, 4]
class Slot: def __init__(self, x, y, paint=False): self.x = x self.y = y self.paint = paint self.painted = False self.neigh = set() self.neigh_count = 0 def __str__(self): return "%d %d" % (self.x, self.y) class Grid: def __init__(self, n_rows, n_col...
class Slot: def __init__(self, x, y, paint=False): self.x = x self.y = y self.paint = paint self.painted = False self.neigh = set() self.neigh_count = 0 def __str__(self): return '%d %d' % (self.x, self.y) class Grid: def __init__(self, n_rows, n_c...
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0]*(len(text1)+1) for _ in range(len(text2)+1)] for i in range(1, len(text2)+1): for j in range(1, len(text1)+1): if text2[i - 1] == text1[j - 1]: dp[i][j] = 1 +...
class Solution: def longest_common_subsequence(self, text1: str, text2: str) -> int: dp = [[0] * (len(text1) + 1) for _ in range(len(text2) + 1)] for i in range(1, len(text2) + 1): for j in range(1, len(text1) + 1): if text2[i - 1] == text1[j - 1]: dp...
""" Reversed from binary_search. Given a item, if the item in the list, return its index. If not in the list, return the index of the first item that is larger than the the given item If all items in the list are less then the given item, return -1 """ def binary_search_fuzzy(a...
""" Reversed from binary_search. Given a item, if the item in the list, return its index. If not in the list, return the index of the first item that is larger than the the given item If all items in the list are less then the given item, return -1 """ def binary_search_fuzzy(al...
SCRIPT=""" #!/bin/bash # Generate train/test script for scenario "{scenario}" using the faster-rcnn "alternating optimization" method set -x set -e rm -f $CAFFE_ROOT/data/cache/*.pkl rm -f {scenarios_dir}/{scenario}/output/*.pkl DIR=`pwd` function quit {{ cd $DIR exit 0 }} export PYTHONUNBUFFERED="True" TRA...
script = '\n#!/bin/bash\n# Generate train/test script for scenario "{scenario}" using the faster-rcnn "alternating optimization" method\n\nset -x\nset -e\n\nrm -f $CAFFE_ROOT/data/cache/*.pkl\nrm -f {scenarios_dir}/{scenario}/output/*.pkl\n\nDIR=`pwd`\n\nfunction quit {{\n cd $DIR\n exit 0\n}}\n\nexport PYTHONUNBUF...
#test for primality def IsPrime(x): x = abs(int(x)) if x < 2: return False if x == 2: return True if not x & 1: return False for y in range(3, int(x**0.5)+1, 2): if x % y == 0: return False return True def QuadatricAnswer(a, b, n): return n**2 + a...
def is_prime(x): x = abs(int(x)) if x < 2: return False if x == 2: return True if not x & 1: return False for y in range(3, int(x ** 0.5) + 1, 2): if x % y == 0: return False return True def quadatric_answer(a, b, n): return n ** 2 + a * n + b de...
class NoRecordsFoundError(Exception): pass class J2XException(Exception): pass
class Norecordsfounderror(Exception): pass class J2Xexception(Exception): pass
""" Profile ../profile-datasets-py/div52_zen50deg/038.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div52_zen50deg/038.py" self["Q"] = numpy.array([ 1.619327, 5.956785, 4.367512, 5.966544, 5.988635, 7.336613, 6.150054, 10.02425 , ...
""" Profile ../profile-datasets-py/div52_zen50deg/038.py file automaticaly created by prof_gen.py script """ self['ID'] = '../profile-datasets-py/div52_zen50deg/038.py' self['Q'] = numpy.array([1.619327, 5.956785, 4.367512, 5.966544, 5.988635, 7.336613, 6.150054, 10.02425, 7.748795, 6.746565, 7.848652, 8.14...
n = int(input()) tl = list(map(int, input().split())) m = int(input()) sum_time = sum(tl) for _ in range(m): p, x = map(int, input().split()) print(sum_time - tl[p-1] + x)
n = int(input()) tl = list(map(int, input().split())) m = int(input()) sum_time = sum(tl) for _ in range(m): (p, x) = map(int, input().split()) print(sum_time - tl[p - 1] + x)
class Solution: def reverseWords(self, s: str) -> str: list_s = s.split(' ') for i in range(len(list_s)): list_s[i] = list_s[i][::-1] return ' '.join(list_s) print(Solution().reverseWords("Let's take LeetCode contest"))
class Solution: def reverse_words(self, s: str) -> str: list_s = s.split(' ') for i in range(len(list_s)): list_s[i] = list_s[i][::-1] return ' '.join(list_s) print(solution().reverseWords("Let's take LeetCode contest"))
class XmlConverter: def __init__(self, prefix, method, params): self.text = '' self.prefix = prefix self.method = method self.params = params def create_tag(self, parent, elem): if isinstance(elem, dict): for key, value in elem.items(): self.t...
class Xmlconverter: def __init__(self, prefix, method, params): self.text = '' self.prefix = prefix self.method = method self.params = params def create_tag(self, parent, elem): if isinstance(elem, dict): for (key, value) in elem.items(): sel...
print('-------------------------------------------------------------------------') family=['me','sis','Papa','Mummy','Chacha'] print('Now, we will copy family list to a another list') for i in range(len(family)): cpy_family=family[1:4] print(family) print('--------------------------------------') print(cpy_fa...
print('-------------------------------------------------------------------------') family = ['me', 'sis', 'Papa', 'Mummy', 'Chacha'] print('Now, we will copy family list to a another list') for i in range(len(family)): cpy_family = family[1:4] print(family) print('--------------------------------------') print(cpy_...
num = 1 num1 = 10 num2 = 20 num3 = 40 num3 = 30 num4 = 50
num = 1 num1 = 10 num2 = 20 num3 = 40 num3 = 30 num4 = 50
# example_traceback.py def loader(filename): fin = open(filenam) loader("data/result_ab.txt")
def loader(filename): fin = open(filenam) loader('data/result_ab.txt')
#%% #https://leetcode.com/problems/divide-two-integers/ #%% dividend = -2147483648 dividend = -10 divisor = -1 divisor = 3 def divideInt(dividend, divisor): sign = -1 if dividend * divisor < 0 else 1 if dividend == 0: return 0 dividend = abs(dividend) divisor = abs(divisor) if divisor == ...
dividend = -2147483648 dividend = -10 divisor = -1 divisor = 3 def divide_int(dividend, divisor): sign = -1 if dividend * divisor < 0 else 1 if dividend == 0: return 0 dividend = abs(dividend) divisor = abs(divisor) if divisor == 1: return sign * dividend remainder = dividend ...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Counter(object): ''' Stores all the samples for a given counter. ''' def __init__(self, parent, category, name): self.parent = parent sel...
class Counter(object): """ Stores all the samples for a given counter. """ def __init__(self, parent, category, name): self.parent = parent self.full_name = category + '.' + name self.category = category self.name = name self.samples = [] self.timestamps = [] ...
'''<yasir_ahmad> WAP to create a function which takes 3 arguments (say a,b,ch) where a is length ;b is breadth and ch is choice whether to compute area or perimeter. Note:- By default is should find area. ''' def Area_Perimeter(a,b,ch=1): """ a(int): Length of the rectangle b(int): Breadth o...
"""<yasir_ahmad> WAP to create a function which takes 3 arguments (say a,b,ch) where a is length ;b is breadth and ch is choice whether to compute area or perimeter. Note:- By default is should find area. """ def area__perimeter(a, b, ch=1): """ a(int): Length of the rectangle b(int): Breadth of t...
load("@com_github_reboot_dev_pyprotoc_plugin//:rules.bzl", "create_protoc_plugin_rule") cc_eventuals_library = create_protoc_plugin_rule( "@com_github_3rdparty_eventuals_grpc//protoc-gen-eventuals:protoc-gen-eventuals", extensions=(".eventuals.h", ".eventuals.cc") )
load('@com_github_reboot_dev_pyprotoc_plugin//:rules.bzl', 'create_protoc_plugin_rule') cc_eventuals_library = create_protoc_plugin_rule('@com_github_3rdparty_eventuals_grpc//protoc-gen-eventuals:protoc-gen-eventuals', extensions=('.eventuals.h', '.eventuals.cc'))
class GUIComponent: def get_surface(self): return None def get_position(self): return None def initialize(self): pass
class Guicomponent: def get_surface(self): return None def get_position(self): return None def initialize(self): pass
__author__ = 'Chirag' '''iter(<iterable>) = iterator converts iterable object into in 'iterator' so that we use can use the next(<iterator>)''' string = "Hello" for letter in string: print(letter) string_iter = iter(string) print(next(string_iter))
__author__ = 'Chirag' "iter(<iterable>) = iterator converts \niterable object into in 'iterator' so that \nwe use can use the next(<iterator>)" string = 'Hello' for letter in string: print(letter) string_iter = iter(string) print(next(string_iter))
def val_to_list(val): """ Convert a single value string or number to a list :param val: :return: """ if val is not None: if not isinstance(val, (list, tuple)): val = [val] if isinstance(val, tuple): val = list(val) return val def one_list_to_val(val)...
def val_to_list(val): """ Convert a single value string or number to a list :param val: :return: """ if val is not None: if not isinstance(val, (list, tuple)): val = [val] if isinstance(val, tuple): val = list(val) return val def one_list_to_val(val):...
class InfrastructureException(Exception): """ Custom exception to be raised to indicate a infrastructure function has failed its checks. You should be explicit in such checks. """ pass
class Infrastructureexception(Exception): """ Custom exception to be raised to indicate a infrastructure function has failed its checks. You should be explicit in such checks. """ pass
x = int (input('Digite um numero :')) for x in range (0,x): print (x) if x % 4 == 0: print ('[{}]'.format(x))
x = int(input('Digite um numero :')) for x in range(0, x): print(x) if x % 4 == 0: print('[{}]'.format(x))
#try out file I/O myfile=open("example.txt", "a+") secondfile=open("python.txt", "r") for _ in range(4): print(secondfile.read())
myfile = open('example.txt', 'a+') secondfile = open('python.txt', 'r') for _ in range(4): print(secondfile.read())
""" Non Leetcode Question: https://www.educative.io/courses/grokking-the-coding-interview/YQQwQMWLx80 Given a string, find the length of the longest substring in it with no more than K distinct characters. Example 1: Input: String="araaci", K=2 Output: 4 Explanation: The lo...
""" Non Leetcode Question: https://www.educative.io/courses/grokking-the-coding-interview/YQQwQMWLx80 Given a string, find the length of the longest substring in it with no more than K distinct characters. Example 1: Input: String="araaci", K=2 Output: 4 Explanation: The lo...
def nth_sevenish_number(n): answer, bit_place = 0, 0 while n > 0: if n & 1 == 1: answer += 7 ** bit_place n >>= 1 bit_place += 1 return answer # n = 1 # print(nth_sevenish_number(n)) for n in range(1, 10): print(nth_sevenish_number(n))
def nth_sevenish_number(n): (answer, bit_place) = (0, 0) while n > 0: if n & 1 == 1: answer += 7 ** bit_place n >>= 1 bit_place += 1 return answer for n in range(1, 10): print(nth_sevenish_number(n))
""" creates decorator for class that counts instances and allows to return and reset this value """ def instances_counter(cls): """Some code""" setattr(cls, 'ins_cnt', 0) def __init__(self): cls.ins_cnt += 1 cls.__init__ def get_created_instances(self=None): return cls.ins_cn...
""" creates decorator for class that counts instances and allows to return and reset this value """ def instances_counter(cls): """Some code""" setattr(cls, 'ins_cnt', 0) def __init__(self): cls.ins_cnt += 1 cls.__init__ def get_created_instances(self=None): return cls.ins_cnt...