content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
SOURCE = [ [41, -61, 41, 98, -74, -66, -61, -75, -44, 93, 99, -57, -11, 41, 44, -64, 52, 27, -87, -85], ] DESTINATION = [ [-87, -85, -75, -74, -66, -64, -61, -61, -57, -44, -11, 27, 41, 41, 41, 44, 52, 93, 98, 99], ] def validate(func): for n, data in enumerate(SOURCE): data_copy = data[:] ...
source = [[41, -61, 41, 98, -74, -66, -61, -75, -44, 93, 99, -57, -11, 41, 44, -64, 52, 27, -87, -85]] destination = [[-87, -85, -75, -74, -66, -64, -61, -61, -57, -44, -11, 27, 41, 41, 41, 44, 52, 93, 98, 99]] def validate(func): for (n, data) in enumerate(SOURCE): data_copy = data[:] assert func(...
# DROP TABLES songplay_table_drop = "DROP TABLE IF EXISTS songplays;" user_table_drop = "DROP TABLE IF EXISTS users;" song_table_drop = "DROP TABLE IF EXISTS songs;" artist_table_drop = "DROP TABLE IF EXISTS artists;" time_table_drop = "DROP TABLE IF EXISTS time;" # CREATE TABLES songplay_table_create = (""" CRE...
songplay_table_drop = 'DROP TABLE IF EXISTS songplays;' user_table_drop = 'DROP TABLE IF EXISTS users;' song_table_drop = 'DROP TABLE IF EXISTS songs;' artist_table_drop = 'DROP TABLE IF EXISTS artists;' time_table_drop = 'DROP TABLE IF EXISTS time;' songplay_table_create = '\n CREATE TABLE IF NOT EXISTS songplays (...
x = [()] x = [(a)] x = [(a,)] x = [(a)] x = [(a,)] x = [a, b] x = [(a, b)] x = [(a, b, c)]
x = [()] x = [a] x = [(a,)] x = [a] x = [(a,)] x = [a, b] x = [(a, b)] x = [(a, b, c)]
# https://leetcode.com/problems/find-the-difference/description/ # # algorithms # Easy (52.06%) # Total Accepted: 124.1k # Total Submissions: 238.4k class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ length = l...
class Solution(object): def find_the_difference(self, s, t): """ :type s: str :type t: str :rtype: str """ length = len(t) bit = 0 for i in xrange(length): bit ^= ord(t[i]) if i == length - 1: break ...
class Solution: def XXX(self, x: int) -> int: if x != 0: if x > 0: num = str(x)[::-1] else: num = '-' + str(-x)[::-1] num = int(num) return num if num < 2 ** 31 and num >= - 2 ** 31 else 0 return 0
class Solution: def xxx(self, x: int) -> int: if x != 0: if x > 0: num = str(x)[::-1] else: num = '-' + str(-x)[::-1] num = int(num) return num if num < 2 ** 31 and num >= -2 ** 31 else 0 return 0
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Breakout 6.4 Check digits # Suggested Activities - EAN-8 barcodes def extractDigit(i, n): """Extract the ith digit from n The rightmost digit is at position 0 ...
def extract_digit(i, n): """Extract the ith digit from n The rightmost digit is at position 0 Digit positions are 76543210 """ if i < 0: return -1 return n // pow(10, i) % 10 def is_valid_ean8(n): sum = 0 for i in range(9): digit = extract_digit(i, n) ...
def is_a_url(path): return (path is not None and isinstance(path, str) and (path.startswith('http://') or path.startswith('https://')) ) def tabular(descriptor): return 'schema' in descriptor def streaming(descriptor): return descriptor.get(PROP_STREAMING) def stre...
def is_a_url(path): return path is not None and isinstance(path, str) and (path.startswith('http://') or path.startswith('https://')) def tabular(descriptor): return 'schema' in descriptor def streaming(descriptor): return descriptor.get(PROP_STREAMING) def streamable(descriptor): return PROP_STREAME...
class Users: def __init__(self, first_name, last_name, user_name, credential): self.first_name = first_name self.last_name = last_name self.user_name = user_name self.credential = credential user_users = [] def save_user(self): ''' this is a save function th...
class Users: def __init__(self, first_name, last_name, user_name, credential): self.first_name = first_name self.last_name = last_name self.user_name = user_name self.credential = credential user_users = [] def save_user(self): """ this is a save function th...
# This file is Copyright 2015, Will Bond <will@wbond.net>, licensed to Google # under the terms of the Google Inbound Service Agreement, signed August 15 2015 def data(provider_method, first_param_name_suffix=False): """ A method decorator for unittest.TestCase classes that configured a static method to b...
def data(provider_method, first_param_name_suffix=False): """ A method decorator for unittest.TestCase classes that configured a static method to be used to provide multiple sets of test data to a single test :param provider_method: The name of the staticmethod of the class to use as the da...
message_id_example = 'f1392251-db64-4f6c-acb3-73b64aa79d9d' timestamp_example = '2016-03-23 12:15:22.62027' current_articles_example = open("dashboard/tests/json/current_articles_example.json", "r").read() article_detail_example = open("dashboard/tests/json/article_detail_example.json", "r").read() article_ids_exampl...
message_id_example = 'f1392251-db64-4f6c-acb3-73b64aa79d9d' timestamp_example = '2016-03-23 12:15:22.62027' current_articles_example = open('dashboard/tests/json/current_articles_example.json', 'r').read() article_detail_example = open('dashboard/tests/json/article_detail_example.json', 'r').read() article_ids_example ...
class Const: @property def GUROBI(self): return "GUROBI"
class Const: @property def gurobi(self): return 'GUROBI'
''' ''' # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License");...
""" """ Test.Summary = 'Testing ATS TCP handshake timeout' ts = Test.MakeATSProcess('ts') server = Test.MakeOriginServer('server', delay=15) dns = Test.MakeDNServer('dns', ip='127.0.0.1', default=['127.0.0.1']) request_header = {'headers': 'GET /file HTTP/1.1\r\nHost: *\r\n\r\n', 'timestamp': '5678', 'body': ''} respon...
__title__ = 'hermes_python' __version__ = '0.8.1' __description__ = 'Python bindings for Snips Hermes Protocol' __url__ = { 'Documentation': 'https://hermespython.readthedocs.io/en/latest/', 'Source': 'https://github.com/snipsco/hermes-protocol/tree/develop/platforms/hermes-python', 'Tracker': 'https://gith...
__title__ = 'hermes_python' __version__ = '0.8.1' __description__ = 'Python bindings for Snips Hermes Protocol' __url__ = {'Documentation': 'https://hermespython.readthedocs.io/en/latest/', 'Source': 'https://github.com/snipsco/hermes-protocol/tree/develop/platforms/hermes-python', 'Tracker': 'https://github.com/snipsc...
class Vehiculo: def __init__(self, velocidad_maxima, kilometraje, capacidad): self.velocidad_maxima = velocidad_maxima self.kilometraje = kilometraje self.capacidad = capacidad def set_capacidad(self, capacidad): self.capacidad = capacidad def get_capacidad(self...
class Vehiculo: def __init__(self, velocidad_maxima, kilometraje, capacidad): self.velocidad_maxima = velocidad_maxima self.kilometraje = kilometraje self.capacidad = capacidad def set_capacidad(self, capacidad): self.capacidad = capacidad def get_capacidad(sel...
load("//:plugin.bzl", "ProtoPluginInfo") load("//:compile.bzl", "ProtoCompileInfo") load( "//:compile.bzl", # "ProtoCompileInfo", # "get_plugin_out_arg", # "get_plugin_outputs", "objc_upper_segments", "rust_keywords", ) def proto_compile_impl(ctx): files = [] for dep in ctx.attr.deps: ...
load('//:plugin.bzl', 'ProtoPluginInfo') load('//:compile.bzl', 'ProtoCompileInfo') load('//:compile.bzl', 'objc_upper_segments', 'rust_keywords') def proto_compile_impl(ctx): files = [] for dep in ctx.attr.deps: aspect = dep[ProtoLibraryAspectNodeInfo] files += aspect.outputs return [proto...
""" [05/30/13] Challenge #126 [Intermediate] Perfect P'th Powers https://www.reddit.com/r/dailyprogrammer/comments/1fcpnx/053013_challenge_126_intermediate_perfect_pth/ # [](#IntermediateIcon) *(Intermediate)*: Perfect P'th Powers An integer X is a "perfect square power" if there is some integer Y such that Y^2 = X. ...
""" [05/30/13] Challenge #126 [Intermediate] Perfect P'th Powers https://www.reddit.com/r/dailyprogrammer/comments/1fcpnx/053013_challenge_126_intermediate_perfect_pth/ # [](#IntermediateIcon) *(Intermediate)*: Perfect P'th Powers An integer X is a "perfect square power" if there is some integer Y such that Y^2 = X. ...
class PlanTopology(APIObject,IDisposable): """ An object that represents a Plan Topology within the Autodesk Revit project. """ def Dispose(self): """ Dispose(self: APIObject,A_0: bool) """ pass def GetRoomIds(self): """ GetRoomIds(self: PlanTopology) -> ICollection[ElementId] Retrieves room...
class Plantopology(APIObject, IDisposable): """ An object that represents a Plan Topology within the Autodesk Revit project. """ def dispose(self): """ Dispose(self: APIObject,A_0: bool) """ pass def get_room_ids(self): """ GetRoomIds(self: PlanTopology) -> ICollection[ElementId]...
def integrity_query(t_from, t_to, period, table, test_column, time_column='time', return_epoch=True): return f'''WITH RECURSIVE input (t_from, t_to, t_interval) AS ( VALUES (to_timestamp({t_from}), to_timestamp({t_to}), interval \'{period} s\') ), filled AS ( SELECT ser.tm as time, {test_column} ...
def integrity_query(t_from, t_to, period, table, test_column, time_column='time', return_epoch=True): return f"WITH RECURSIVE\ninput (t_from, t_to, t_interval) AS (\n VALUES (to_timestamp({t_from}), to_timestamp({t_to}), interval '{period} s')\n), filled AS (\n SELECT\n ser.tm as time, {test_column}\n ...
""" Deleting objects in VNC should also delete it's back-ref objects. """ def test_delete_vmi(vnc_api_client, vnc_lib, vnc_vmi_1): vnc_vmi_1.get_instance_ip_back_refs.return_value = [{'uuid': 'instance-ip-uuid'}] vnc_lib.virtual_machine_interface_read.return_value = vnc_vmi_1 vnc_api_client.delete_vmi('v...
""" Deleting objects in VNC should also delete it's back-ref objects. """ def test_delete_vmi(vnc_api_client, vnc_lib, vnc_vmi_1): vnc_vmi_1.get_instance_ip_back_refs.return_value = [{'uuid': 'instance-ip-uuid'}] vnc_lib.virtual_machine_interface_read.return_value = vnc_vmi_1 vnc_api_client.delete_vmi('vmi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Animal(object): def run(self): print('Animal running...') class Dog(Animal): def run(self): print('Dog running...') def shout(self): print('Dog wang wang...') class Cat(Animal): def run(self): print('Cat running...') def shout(self): print('Cat mi...
class Animal(object): def run(self): print('Animal running...') class Dog(Animal): def run(self): print('Dog running...') def shout(self): print('Dog wang wang...') class Cat(Animal): def run(self): print('Cat running...') def shout(self): print('Cat mi...
# Python function that checks whether a passed string is palindrome or not. def isPalindrome(string): left_pos = 0 right_pos = len(string) - 1 while right_pos >= left_pos: if not string[left_pos] == string[right_pos]: return False left_pos += 1 right_pos -= 1 return True print(isPalindrome('aza'))
def is_palindrome(string): left_pos = 0 right_pos = len(string) - 1 while right_pos >= left_pos: if not string[left_pos] == string[right_pos]: return False left_pos += 1 right_pos -= 1 return True print(is_palindrome('aza'))
def bubbleSort(alist): t = 0 for passnum in range(len(alist) - 1, 0, -1): for i in range(passnum): if alist[i] < alist[i + 1]: temp = alist[i] alist[i] = alist[i + 1] alist[i + 1] = temp elif alist[i] == alist[i + 1]: ...
def bubble_sort(alist): t = 0 for passnum in range(len(alist) - 1, 0, -1): for i in range(passnum): if alist[i] < alist[i + 1]: temp = alist[i] alist[i] = alist[i + 1] alist[i + 1] = temp elif alist[i] == alist[i + 1]: ...
num=300 num2=14 num3=100 num4=111
num = 300 num2 = 14 num3 = 100 num4 = 111
command = input().split(": ") products = {} while "statistics" not in command: key = command[0] value = command[1] if key in products: products[key] += int(value) else: products[key] = int(value) command = input().split(": ") print("Products in stock:") [print(f"- {product}: {quan...
command = input().split(': ') products = {} while 'statistics' not in command: key = command[0] value = command[1] if key in products: products[key] += int(value) else: products[key] = int(value) command = input().split(': ') print('Products in stock:') [print(f'- {product}: {quantit...
def can_build(env, platform): return True def configure(env): pass def has_custom_iterator(): return True def has_custom_physics_iterator(): return True def has_custom_audio_iterator(): # TODO enable custom iterator once the audio process system is integrated return False def get_doc_p...
def can_build(env, platform): return True def configure(env): pass def has_custom_iterator(): return True def has_custom_physics_iterator(): return True def has_custom_audio_iterator(): return False def get_doc_path(): return 'doc_classes' def get_doc_classes(): return ['Component', 'D...
#-*- coding: utf-8 -*- """ This package is an implementation of the OpenID specification in Python. It contains code for both server and consumer implementations. For information on implementing an OpenID consumer, see the C{L{openid.consumer.consumer}} module. For information on implementing an OpenID server, see t...
""" This package is an implementation of the OpenID specification in Python. It contains code for both server and consumer implementations. For information on implementing an OpenID consumer, see the C{L{openid.consumer.consumer}} module. For information on implementing an OpenID server, see the C{L{openid.server.se...
class dotSetProperty_t(object): # no doc aName=None aStringValue=None DoubleValue=None FatherId=None IntValue=None Source=None Type=None
class Dotsetproperty_T(object): a_name = None a_string_value = None double_value = None father_id = None int_value = None source = None type = None
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE.txt in the project root for # license information. # ------------------------------------------------------------------------- def assert...
def assert_with_message(param_name, expected_value, actual_value): assert expected_value == actual_value, "Expected '{}' to be '{}', got '{}'".format(param_name, expected_value, actual_value) __all__ = ['assert_with_message']
# -*- coding: utf-8 -*- """ Created on Sun Dec 5 19:14:22 2021 @author: catal """ """please see https://holypython.com/ for original exercises""" """ Place a curly bracket "{}" in the appropriate place and fill inside .format()'s parenthesis so that "Hello!, Name" is printed. """ def printGreeting(): """take...
""" Created on Sun Dec 5 19:14:22 2021 @author: catal """ 'please see https://holypython.com/ for original exercises' '\nPlace a curly bracket "{}" in the appropriate place\nand fill inside .format()\'s parenthesis so that "Hello!, Name" is printed.\n' def print_greeting(): """takes user input and prints a greet...
# # PySNMP MIB module RIVERSTONE-RS94X-AGENTCAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RIVERSTONE-RS94X-AGENTCAP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:49:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ve...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ...
class GameOfLifeDivTwo: def theSimulation(self, init, T): s, l = init, len(init) def r(i): def rr(ls): return '1' if ls.count('1') >= 2 else '0' if i == 0: return rr(s[-1:] + s[:2]) elif i == l-1: return rr(s[-2:] + ...
class Gameoflifedivtwo: def the_simulation(self, init, T): (s, l) = (init, len(init)) def r(i): def rr(ls): return '1' if ls.count('1') >= 2 else '0' if i == 0: return rr(s[-1:] + s[:2]) elif i == l - 1: return rr...
#Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. # #For example, #Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ mx=...
class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ mx = lt = rt = 0 (left_trap, right_trap) = ([], []) for i in xrange(len(height)): left_trap.append(lt) if height[i] > lt: lt = height[i] ...
class Animal: def __init__(self, name1, age1): self.name = name1 self.age = age1 def eat(self): print("The {} can eat".format(self.name)) def run(self): print(self.age) def active(self): print("All animals are active") mamal = Animal("Dog", [34,5,2]) mamal....
class Animal: def __init__(self, name1, age1): self.name = name1 self.age = age1 def eat(self): print('The {} can eat'.format(self.name)) def run(self): print(self.age) def active(self): print('All animals are active') mamal = animal('Dog', [34, 5, 2]) mamal.r...
class Solution: def nearestValidPoint(self, x: int, y: int, points) -> int: # not a good idea to iniatilze prev_min this way. prev_min, index = 10 << 10, -1 abs_ = abs for i, (xi, yi) in enumerate(points): if xi == x: dst = y - yi elif yi == y:...
class Solution: def nearest_valid_point(self, x: int, y: int, points) -> int: (prev_min, index) = (10 << 10, -1) abs_ = abs for (i, (xi, yi)) in enumerate(points): if xi == x: dst = y - yi elif yi == y: dst = x - xi else: ...
''' modifier: 01 eqtime: 12 ''' def main(): info('Jan microbone blank analysis') if analysis_type=='blank': info('is blank. not heating') close(name="L", description="Microbone to Minibone") close(name="A", description="CO2 Laser to Jan") open(name="T", description="Mi...
""" modifier: 01 eqtime: 12 """ def main(): info('Jan microbone blank analysis') if analysis_type == 'blank': info('is blank. not heating') close(name='L', description='Microbone to Minibone') close(name='A', description='CO2 Laser to Jan') open(name='T', description='Microbone...
n = 1 while n < 5: print(n * "*") n = n + 1 while n > 0: print(n * "*") n = n - 1
n = 1 while n < 5: print(n * '*') n = n + 1 while n > 0: print(n * '*') n = n - 1
### Cell class for 2-D maze module ### Author: gdgrant ### Date: 11/6/2018 class Cell: """ Unit cell for a square grid graph """ def __init__(self, id, adj, acc): """ Set the cell's ID, adjacent cells, and accessible cells """ self.id = id # Number of this cell ...
class Cell: """ Unit cell for a square grid graph """ def __init__(self, id, adj, acc): """ Set the cell's ID, adjacent cells, and accessible cells """ self.id = id self.adj = adj self.acc = acc self._validate_id(self.id, *self.adj, *self.acc) self._validate_acc(...
''' @Date: 2019-12-02 20:59:38 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors: ywyz @LastEditTime: 2019-12-02 21:34:50 ''' class Account: def __init__(self, id=0, balance=100.0, annualInterestRate=0.0): self.__id = id self.__balance = balance self.__annua...
""" @Date: 2019-12-02 20:59:38 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors: ywyz @LastEditTime: 2019-12-02 21:34:50 """ class Account: def __init__(self, id=0, balance=100.0, annualInterestRate=0.0): self.__id = id self.__balance = balance self.__annua...
class Solution: def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: ans = 0 maxDepth = 0 def dfs(root: Optional[TreeNode], depth: int) -> None: nonlocal ans nonlocal maxDepth if not root: return if depth > maxDepth: maxDepth = depth ans = root.v...
class Solution: def find_bottom_left_value(self, root: Optional[TreeNode]) -> int: ans = 0 max_depth = 0 def dfs(root: Optional[TreeNode], depth: int) -> None: nonlocal ans nonlocal maxDepth if not root: return if depth > maxD...
MESSAGE_CONTENTS_FILENAME = "text_messages/message.txt" ORDERS_FILENAME = "user_data/orders.csv" API_KEY = "" ORDER_NUMBER_ROW = "Order Number" ORDER_STATUS_ROW = "Order Status" FIRST_NAME_ROW = "First Name (Billing)" ORDER_ITEM_ROW = "Item Name" NUMBER_OF_ITEMS_ROW = "Quantity" PHONE_NUMBER_ROW = "Phone (Billing)" wi...
message_contents_filename = 'text_messages/message.txt' orders_filename = 'user_data/orders.csv' api_key = '' order_number_row = 'Order Number' order_status_row = 'Order Status' first_name_row = 'First Name (Billing)' order_item_row = 'Item Name' number_of_items_row = 'Quantity' phone_number_row = 'Phone (Billing)' wit...
@auth.requires_login() @auth.requires_membership('Super-Administrator') def audit_academic(): db.academic_log.id_period.readable = False db.academic_log.id_academic.readable = False query = ((db.academic_log)) grid = SQLFORM.grid(query, exportclasses = None, orderby=db.academic_log.date_log...
@auth.requires_login() @auth.requires_membership('Super-Administrator') def audit_academic(): db.academic_log.id_period.readable = False db.academic_log.id_academic.readable = False query = db.academic_log grid = SQLFORM.grid(query, exportclasses=None, orderby=db.academic_log.date_log, deletable=False, ...
#### # FOR # for iterador in range(inicio, fim, passo): ### """ for number in range(1, 11, 1): print(number) """ for i in range (1, 11, 1): idade = float (input ( "informe uma idade: ")) if idade >= 18: print ("voce ja pode beber") else: print(" voce nao pode beber")
""" for number in range(1, 11, 1): print(number) """ for i in range(1, 11, 1): idade = float(input('informe uma idade: ')) if idade >= 18: print('voce ja pode beber') else: print(' voce nao pode beber')
def replace_element(iterable_object: (list, dict), old_value: (str, int, float, list, tuple, dict), new_value: (str, int, float, list, tuple, dict) ) -> (list, dict): ''' This function takes an iterable object and two values, and returns the ...
def replace_element(iterable_object: (list, dict), old_value: (str, int, float, list, tuple, dict), new_value: (str, int, float, list, tuple, dict)) -> (list, dict): """ This function takes an iterable object and two values, and returns the same object with the first value replaced by the first. It is t...
n = int(input()) s = input() t = list(s) s1 = [] s2 = [] for i in range(n): s1.append([]) s2.append([]) for i in range(n): for j in range(n): if j < i: s1[i].append(t[j]) else: s2[i].append(t[j]) count = 0 com = [] slv = [] for i in range(n): for j in range(i...
n = int(input()) s = input() t = list(s) s1 = [] s2 = [] for i in range(n): s1.append([]) s2.append([]) for i in range(n): for j in range(n): if j < i: s1[i].append(t[j]) else: s2[i].append(t[j]) count = 0 com = [] slv = [] for i in range(n): for j in range(i): ...
def for_n(): """printing small 'n' using for loop""" for row in range(6): for col in range(4): if col==0 or col==3 and row not in (0,1) or row==1 and col!=3: print("*",end=" ") else: print(" ",end=" ") print() def while_n(): ...
def for_n(): """printing small 'n' using for loop""" for row in range(6): for col in range(4): if col == 0 or (col == 3 and row not in (0, 1)) or (row == 1 and col != 3): print('*', end=' ') else: print(' ', end=' ') print() def while_n():...
def selection_sort(arr, n): for i in range(0, n - 1): min_idx = i for j in range(i, n): if (arr[min_idx] > arr[j]): min_idx = j if min_idx != i: arr[min_idx], arr[i] = arr[i], arr[min_idx] def print_array(arr, n): for i in range(0, n): pr...
def selection_sort(arr, n): for i in range(0, n - 1): min_idx = i for j in range(i, n): if arr[min_idx] > arr[j]: min_idx = j if min_idx != i: (arr[min_idx], arr[i]) = (arr[i], arr[min_idx]) def print_array(arr, n): for i in range(0, n): p...
BEST_PARAMS = { "boosting_type": "dart", "learning_rate": 0.2, "num_leaves": 64, "min_child_samples": 5, "n_estimators": 5000, "drop_rate": 0.015, "feature_fraction": 0.7, "bagging_fraction": 0.8, "n_jobs": -2, }
best_params = {'boosting_type': 'dart', 'learning_rate': 0.2, 'num_leaves': 64, 'min_child_samples': 5, 'n_estimators': 5000, 'drop_rate': 0.015, 'feature_fraction': 0.7, 'bagging_fraction': 0.8, 'n_jobs': -2}
def pega_id(*args): try: telaAtualizarProdutos = args[0] telaErro = args[1] cursor = args[2] id = telaAtualizarProdutos.cod_atualizar.text() if telaAtualizarProdutos.broto_atualizar.isChecked(): cursor.execute("select * from broto where id = %s" % id) ...
def pega_id(*args): try: tela_atualizar_produtos = args[0] tela_erro = args[1] cursor = args[2] id = telaAtualizarProdutos.cod_atualizar.text() if telaAtualizarProdutos.broto_atualizar.isChecked(): cursor.execute('select * from broto where id = %s' % id) ...
class PetrolPump(object): def __init__(self, petrol, distance): self.petrol = petrol self.distance = distance self.nextPP = None class CyclicLinkedList(object): def __init__(self): self.list = [] def add(self, petrol, distance): newPP = PetrolPump(petrol, distance) ...
class Petrolpump(object): def __init__(self, petrol, distance): self.petrol = petrol self.distance = distance self.nextPP = None class Cycliclinkedlist(object): def __init__(self): self.list = [] def add(self, petrol, distance): new_pp = petrol_pump(petrol, distan...
def greet(name): print(f'Hello, {name}!') def test_prints(capsys): # call the function greet('Escape School 2021') # test that it wrote what we expect to stdout captured = capsys.readouterr() # .err would be the stderr output assert captured.out == 'Hello, Escape School 2021!\n'
def greet(name): print(f'Hello, {name}!') def test_prints(capsys): greet('Escape School 2021') captured = capsys.readouterr() assert captured.out == 'Hello, Escape School 2021!\n'
major = "0" minor = "0" patch = "0" release = "dev0" if release != "": __version__ = f"{major}.{minor}.{patch}.{release}" else: __version__ = f"{major}.{minor}.{patch}"
major = '0' minor = '0' patch = '0' release = 'dev0' if release != '': __version__ = f'{major}.{minor}.{patch}.{release}' else: __version__ = f'{major}.{minor}.{patch}'
""" Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2: Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4 """ __a...
""" Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2: Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4 """ __au...
def test_features(api, wiki): assert len(api.features) == 9 assert len(api.features['GB021'].domain) == 2 f = api.features['GB021'] assert f.description assert f.name assert f.patrons assert f.id assert 'Documentation' in api.features['GB020'].description def test_bib(api): assert...
def test_features(api, wiki): assert len(api.features) == 9 assert len(api.features['GB021'].domain) == 2 f = api.features['GB021'] assert f.description assert f.name assert f.patrons assert f.id assert 'Documentation' in api.features['GB020'].description def test_bib(api): assert l...
''' Description: Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3. You are given the total volume m of the building. Being given m can you find ...
""" Description: Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3. You are given the total volume m of the building. Being given m can you find ...
class TaskStates(object): ENQUEUED = 'enqueued' SUCCEEDED = 'succeeded' FAILED = 'failed' DELETED = 'deleted' CHOICES = ( (ENQUEUED, 'Enqueued'), (SUCCEEDED, 'Succeeded'), (FAILED, 'Failed'), (DELETED, 'Deleted'), ) class QueueType(object): SNS = 'sns' ...
class Taskstates(object): enqueued = 'enqueued' succeeded = 'succeeded' failed = 'failed' deleted = 'deleted' choices = ((ENQUEUED, 'Enqueued'), (SUCCEEDED, 'Succeeded'), (FAILED, 'Failed'), (DELETED, 'Deleted')) class Queuetype(object): sns = 'sns' celery = 'celery' choices = ((SNS, 'S...
names = ['H','E','L','L','O'] message = f"hello {names[0]}" print(message) message = f"hello {names[1]}" print(message) message = f"hello {names[2]}" print(message) message = f"hello {names[3]}" print(message) message = f"hello {names[4]}" print(message)
names = ['H', 'E', 'L', 'L', 'O'] message = f'hello {names[0]}' print(message) message = f'hello {names[1]}' print(message) message = f'hello {names[2]}' print(message) message = f'hello {names[3]}' print(message) message = f'hello {names[4]}' print(message)
#!/usr/bin/env python # -*- coding: utf-8 -*- class State(object): def __init__(self): self.states = ['search_enemy_distance', 'get_time_left', 'get_enemy_pose','get_nearest_target', 'search_near_target','get_highest_target','go_to_target','escape'] self.transitions = [ {'t...
class State(object): def __init__(self): self.states = ['search_enemy_distance', 'get_time_left', 'get_enemy_pose', 'get_nearest_target', 'search_near_target', 'get_highest_target', 'go_to_target', 'escape'] self.transitions = [{'trigger': 'enemy_far', 'source': 'search_enemy_distance', 'dest': 'ge...
class Solution: # O(n) time | O(n) space def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: originalColor = image[sr][sc] if originalColor == newColor: return image self.dfs(image, sr, sc, originalColor, newColor) return i...
class Solution: def flood_fill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: original_color = image[sr][sc] if originalColor == newColor: return image self.dfs(image, sr, sc, originalColor, newColor) return image def dfs(self, im...
ctx.addWire(name="BEL_A0", type="WIRE", x=0, y=0) ctx.addWire(name="BEL_A1", type="WIRE", x=0, y=0) ctx.addWire(name="BEL_Q", type="WIRE", x=0, y=0) ctx.addPip(name="Q->A0", type="PIP", srcWire="BEL_Q", dstWire="BEL_A0", delay=ctx.getDelayFromNS(0.05), loc=Loc(0, 0, 0)) ctx.addPip(name="Q->A1", type="PIP", srcWire="BE...
ctx.addWire(name='BEL_A0', type='WIRE', x=0, y=0) ctx.addWire(name='BEL_A1', type='WIRE', x=0, y=0) ctx.addWire(name='BEL_Q', type='WIRE', x=0, y=0) ctx.addPip(name='Q->A0', type='PIP', srcWire='BEL_Q', dstWire='BEL_A0', delay=ctx.getDelayFromNS(0.05), loc=loc(0, 0, 0)) ctx.addPip(name='Q->A1', type='PIP', srcWire='BEL...
def main(): for x in range(4): if x == 5: break else: print("Well of course that didn't happen") for x in range(7): if x == 5: break else: print("H-hey wait!") i = 0 while i < 3: print("Works with while too") for x in rang...
def main(): for x in range(4): if x == 5: break else: print("Well of course that didn't happen") for x in range(7): if x == 5: break else: print('H-hey wait!') i = 0 while i < 3: print('Works with while too') for x in range(...
# -*- coding: utf-8 -*- name = 'ic_shared' version = '1.1.9' description = 'Icarus Shared Libraries' authors = ['mjbonnington'] requires = [ 'python-2.7+', 'plyer', ] build_requires = [ 'rezlib', ] build_command = 'python -m build {install}' def commands(): env.PYTHONPATH.append('{root}')
name = 'ic_shared' version = '1.1.9' description = 'Icarus Shared Libraries' authors = ['mjbonnington'] requires = ['python-2.7+', 'plyer'] build_requires = ['rezlib'] build_command = 'python -m build {install}' def commands(): env.PYTHONPATH.append('{root}')
m=int(input()) ms=set(map(int,input().split())) n=int(input()) ns=set(map(int,input().split())) mns=sorted((ms.difference(ns)).union((ns.difference(ms)))) print(*mns,sep='\n')
m = int(input()) ms = set(map(int, input().split())) n = int(input()) ns = set(map(int, input().split())) mns = sorted(ms.difference(ns).union(ns.difference(ms))) print(*mns, sep='\n')
"""Settings for the of_lldp NApp.""" FLOW_VLAN_VID = 3799 FLOW_PRIORITY = 1000 TABLE_ID = 0 POLLING_TIME = 3 FLOW_MANAGER_URL = 'http://localhost:8181/api/kytos/flow_manager/v2' # Prefix this NApp has when using cookies COOKIE_PREFIX = 0xab
"""Settings for the of_lldp NApp.""" flow_vlan_vid = 3799 flow_priority = 1000 table_id = 0 polling_time = 3 flow_manager_url = 'http://localhost:8181/api/kytos/flow_manager/v2' cookie_prefix = 171
def save_queens(board, col, size): if col >= size: return True for i in range(size): if is_safe(board, i, col, size): board[i][col] = 1 if save_queens(board, col+1,size): return True #backtrack board[i][col] = 0 return Fa...
def save_queens(board, col, size): if col >= size: return True for i in range(size): if is_safe(board, i, col, size): board[i][col] = 1 if save_queens(board, col + 1, size): return True board[i][col] = 0 return False def is_safe(board, row...
class Solution: def minPartitions(self, n: str) -> int: ''' 32 = 11 22 = 11 11 = 82734 = 11111 71623 = 11111 60512 = 10111 50401 = 10101 40300 = 10100 30200 = 10100 20100 = 10100 10000 = 10000 ''' # coun...
class Solution: def min_partitions(self, n: str) -> int: """ 32 = 11 22 = 11 11 = 82734 = 11111 71623 = 11111 60512 = 10111 50401 = 10101 40300 = 10100 30200 = 10100 20100 = 10100 10000 = 10000 """ coun...
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ # Using Boyer-Moore Majority Vote Algorithm # Since we only use equality comparison, and cnt_a and cnt_b are initialized to 0 # thus initializing a and b t...
class Solution(object): def majority_element(self, nums): """ :type nums: List[int] :rtype: List[int] """ a = b = 0 cnt_a = cnt_b = 0 for e in nums: if a == e: cnt_a += 1 elif b == e: cnt_b += 1 ...
def BF_iszscored(x): numericThreshold = 2.2204E-16 iszscored = ((np.absolute(np.mean(x)) < numericThreshold) & (np.absolute(np.std(x)-1) < numericThreshold)) return(iszscored)
def bf_iszscored(x): numeric_threshold = 2.2204e-16 iszscored = (np.absolute(np.mean(x)) < numericThreshold) & (np.absolute(np.std(x) - 1) < numericThreshold) return iszscored
# terrascript/resource/poseidon/ct.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:14:51 UTC) __all__ = []
__all__ = []
#Author: ahmelq - github.com/ahmedelq #License: MIT def compareTriplets(a, b): """Rate two tuples, if a[i] > b[i] give a 1 point, b[i] > a[i] give b 1 point, give 0 otherwise""" cmp = lambda x,y: x > y return [sum(map(cmp, a,b)), sum(map(cmp, b, a))] def compareTripletsSFW(a, b): """Same as compareTr...
def compare_triplets(a, b): """Rate two tuples, if a[i] > b[i] give a 1 point, b[i] > a[i] give b 1 point, give 0 otherwise""" cmp = lambda x, y: x > y return [sum(map(cmp, a, b)), sum(map(cmp, b, a))] def compare_triplets_sfw(a, b): """Same as compareTriplets, implemented strightforwardlly""" resu...
def getResNet50Init(): string = '\ layer {\n\ bottom: "image"\n\ top: "conv1"\n\ name: "conv1"\n\ type: "Convolution"\n\ convolution_param {\n\ num_output: 64\n\ kernel_size: 7\n\ pad: 3\n\ stride: 2\n\ }\n\ }\n\ \n\ layer {\n\ bottom: "conv1"\n\ top: ...
def get_res_net50_init(): string = 'layer {\n bottom: "image"\n top: "conv1"\n name: "conv1"\n type: "Convolution"\n convolution_param {\n num_output: 64\n kernel_size: 7\n pad: 3\n stride: 2\n }\n}\n\nlayer {\n bottom: "conv1"\n top: "conv1"\n name: "bn_conv1"...
favorite_places = { 'znn': ['chengdu', 'shanghai', 'hangzhou'], 'yl': ['chengdu', 'huang montains'], 'other': ['xian', 'xinjiang', 'nanji'] } for name, places in favorite_places.items(): print("\n" + name.title() + " likes the following places:") for place in places: print("- " + place....
favorite_places = {'znn': ['chengdu', 'shanghai', 'hangzhou'], 'yl': ['chengdu', 'huang montains'], 'other': ['xian', 'xinjiang', 'nanji']} for (name, places) in favorite_places.items(): print('\n' + name.title() + ' likes the following places:') for place in places: print('- ' + place.title())
"""Provides an indirection layer to bazel cc_rules""" load( "//tensorflow/core/platform/default:rules_cc.bzl", _cc_binary = "cc_binary", _cc_import = "cc_import", _cc_library = "cc_library", _cc_shared_library = "cc_shared_library", _cc_test = "cc_test", ) cc_binary = _cc_binary cc_import = _c...
"""Provides an indirection layer to bazel cc_rules""" load('//tensorflow/core/platform/default:rules_cc.bzl', _cc_binary='cc_binary', _cc_import='cc_import', _cc_library='cc_library', _cc_shared_library='cc_shared_library', _cc_test='cc_test') cc_binary = _cc_binary cc_import = _cc_import cc_library = _cc_library cc_sh...
def _get_method(method): router = globals()['router'] if method.lower() == 'get': return router.get elif method.lower() == 'post': return router.post elif method.lower() == 'put': return router.put elif method.lower() == 'delete': return router.delete def register_e...
def _get_method(method): router = globals()['router'] if method.lower() == 'get': return router.get elif method.lower() == 'post': return router.post elif method.lower() == 'put': return router.put elif method.lower() == 'delete': return router.delete def register_en...
# # PySNMP MIB module CISCO-TAP2-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TAP2-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:49:44 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) ...
fibo = [1, 1] indices = range(2,10,1) print("indices elements manquants", list(indices)) for indice in indices: element = fibo[indice - 1] + fibo[indice - 2] fibo.append(element) print("suite fibonacci : " , fibo) #affichage indice = 0 for elem in fibo: print("U" + str(indice), "=", elem) indice += 1
fibo = [1, 1] indices = range(2, 10, 1) print('indices elements manquants', list(indices)) for indice in indices: element = fibo[indice - 1] + fibo[indice - 2] fibo.append(element) print('suite fibonacci : ', fibo) indice = 0 for elem in fibo: print('U' + str(indice), '=', elem) indice += 1
"""Python code/sdk/common/constants.py.""" DEFAULT_DOMAIN = "https://api.fyndx0.de" APPLICATION_MIN_TOKEN_LENGTH = 5 HTTP_TIMEOUT = 15 TIMEZONE = "Asia/Kolkata"
"""Python code/sdk/common/constants.py.""" default_domain = 'https://api.fyndx0.de' application_min_token_length = 5 http_timeout = 15 timezone = 'Asia/Kolkata'
# @desc Evaluate the overengineered XOR gate. By Benji '24 def XOR(bool1, bool2): value1 = bool1 or bool2 value2 = not (bool1 and bool2) return value1 and value2 def main(): print(XOR(False, False)) print(XOR(False, True)) print(XOR(True, False)) print(XOR(True, True)) if __name__ == '_...
def xor(bool1, bool2): value1 = bool1 or bool2 value2 = not (bool1 and bool2) return value1 and value2 def main(): print(xor(False, False)) print(xor(False, True)) print(xor(True, False)) print(xor(True, True)) if __name__ == '__main__': main()
# list in python item1 = "python" item2 = "go" item3 = "kotlin" item4 = "java" myList = [item1, item2, item3, item4] print(myList[2]) print(len(myList)) print(len(myList) -1) isKotlinInList = "kotlin" in myList print(isKotlinInList) print("---------------") myRange = range(30) print(list(myRa...
item1 = 'python' item2 = 'go' item3 = 'kotlin' item4 = 'java' my_list = [item1, item2, item3, item4] print(myList[2]) print(len(myList)) print(len(myList) - 1) is_kotlin_in_list = 'kotlin' in myList print(isKotlinInList) print('---------------') my_range = range(30) print(list(myRange))
pkgname = "rhash" pkgver = "1.4.2" pkgrel = 0 build_style = "configure" configure_args = [ "--prefix=/usr", "--sysconfdir=/etc", "--enable-openssl", "--disable-openssl-runtime", "--enable-lib-static", "--enable-lib-shared", ] make_build_target = "all" make_build_args = ["lib-shared"] make_install_target = "...
pkgname = 'rhash' pkgver = '1.4.2' pkgrel = 0 build_style = 'configure' configure_args = ['--prefix=/usr', '--sysconfdir=/etc', '--enable-openssl', '--disable-openssl-runtime', '--enable-lib-static', '--enable-lib-shared'] make_build_target = 'all' make_build_args = ['lib-shared'] make_install_target = 'install' make_i...
class FileHandler: """Class for handling all IO/file handling tasks.""" @staticmethod def read_file(file_path): """Reads a specified file. Args: file_path (string): The path to the input file. Raises: FileNotFoundError: If file not found. IsADi...
class Filehandler: """Class for handling all IO/file handling tasks.""" @staticmethod def read_file(file_path): """Reads a specified file. Args: file_path (string): The path to the input file. Raises: FileNotFoundError: If file not found. IsADir...
class Solution: def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ acc = collections.Counter() acc[0] = 1 total = 0 res = 0 for num in nums: total += num need = total - k ...
class Solution: def subarray_sum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ acc = collections.Counter() acc[0] = 1 total = 0 res = 0 for num in nums: total += num need = total - k ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- collect_ignore = ['setup.py']
collect_ignore = ['setup.py']
## Configuration data config = { "cvs_sites": [ 'ABINGTON', 'ACTON', 'AGAWAM', 'ALLSTON', 'AMHERST', 'ARLINGTON', 'ASHLAND', 'ATHOL', 'ATTLEBORO', ...
config = {'cvs_sites': ['ABINGTON', 'ACTON', 'AGAWAM', 'ALLSTON', 'AMHERST', 'ARLINGTON', 'ASHLAND', 'ATHOL', 'ATTLEBORO', 'BEDFORD', 'BELCHERTOWN', 'BELLINGHAM', 'BELMONT', 'BEVERLY', 'BILLERICA', 'BOSTON', 'BOURNE', 'BRAINTREE', 'BRIGHTON', 'BROCKTON', 'BROOKLINE', 'BURLINGTON', 'CAMBRIDGE', 'CANTON', 'CARVER', 'CHAT...
# # PySNMP MIB module INTELCORPORATION-MULTI-FLEX-SERVER-BLADES-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATION-MULTI-FLEX-SERVER-BLADES-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:54:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_union, single_value_constraint, constraints_intersection) ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2011 Cisco Systems, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache...
def get_view_builder(req): base_url = req.application_url return view_builder(base_url) class Viewbuilder(object): """ViewBuilder for QoS, derived from neutron.views.networks.""" def __init__(self, base_url): """Initialize builder. :param base_url: url of the root wsgi application ...
irint("Hello NYC") print("Hello NYC") print("Hello NYC") print("Hello NYC") print("Ola Mira") print("Ola Mira") print("Ola Mira") print("Ola Mira") print("Ola Mira") print("Ola Mira") print("Ola Mira") print("Ola Mira")
irint('Hello NYC') print('Hello NYC') print('Hello NYC') print('Hello NYC') print('Ola Mira') print('Ola Mira') print('Ola Mira') print('Ola Mira') print('Ola Mira') print('Ola Mira') print('Ola Mira') print('Ola Mira')
# for optimization def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l)//2 if arr[mid] == x: return mid elif arr[mid] < x and arr[mid + 1] > x: return mid elif arr[mid] > x and arr[mid + 1] <= x: return mid + 1 elif arr[mid] > x:...
def binary_search(arr, l, r, x): while l <= r: mid = l + (r - l) // 2 if arr[mid] == x: return mid elif arr[mid] < x and arr[mid + 1] > x: return mid elif arr[mid] > x and arr[mid + 1] <= x: return mid + 1 elif arr[mid] > x: l =...
""" 74. Write a effective algorithm that search for a target value in an m x n matrix. the matrix has the following properties. 1. Integers in each row are sorted in ascending from left to right. 2. Integers in each column are sorted in ascending from top to bottom. Example 1: 1 4 7 11 1...
""" 74. Write a effective algorithm that search for a target value in an m x n matrix. the matrix has the following properties. 1. Integers in each row are sorted in ascending from left to right. 2. Integers in each column are sorted in ascending from top to bottom. Example 1: 1 4 7 11 1...
def likes(names): # your code here textToReturn = "" if (len(names) == 0): textToReturn = "no one likes this" elif (len(names) == 1): textToReturn = str(names[0]) + " likes this" elif (len(names) > 1 and len(names) < 4): for name in range(0, len(names) - 1): tex...
def likes(names): text_to_return = '' if len(names) == 0: text_to_return = 'no one likes this' elif len(names) == 1: text_to_return = str(names[0]) + ' likes this' elif len(names) > 1 and len(names) < 4: for name in range(0, len(names) - 1): text_to_return = textToRet...
# -*- coding: utf-8 -*- # Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
"""Provides a message queue that discards all messages.""" class Discardmessagesqueue(object): """Emulates a Cloud API status queue but drops all messages. This is useful when you want to perform some operations but not have the UI thread display information about those ops (e.g. running a test or fetching ...
# Databricks notebook source # MAGIC %run ./_utility-methods $lesson="6.3L" # COMMAND ---------- DA.cleanup() DA.init() DA.paths.checkpoints = f"{DA.paths.working_dir}/_checkpoints" DA.conclude_setup() sqlContext.setConf("spark.sql.shuffle.partitions", spark.sparkContext.defaultParallelism)
DA.cleanup() DA.init() DA.paths.checkpoints = f'{DA.paths.working_dir}/_checkpoints' DA.conclude_setup() sqlContext.setConf('spark.sql.shuffle.partitions', spark.sparkContext.defaultParallelism)
class BaseData(object): def __init__(self, unit): self.unit = unit def change_units(self, new_units): self.unit = new_units
class Basedata(object): def __init__(self, unit): self.unit = unit def change_units(self, new_units): self.unit = new_units
class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ n = len(nums) self.sum = nums for i in range(1, n): self.sum[i] = self.sum[i - 1] + nums[i] def sumRange(self, i, j): """ :type i: int :type j: int...
class Numarray(object): def __init__(self, nums): """ :type nums: List[int] """ n = len(nums) self.sum = nums for i in range(1, n): self.sum[i] = self.sum[i - 1] + nums[i] def sum_range(self, i, j): """ :type i: int :type j: i...
# User values mock_user_id = 'u1' mock_manager_id = 'ma1' mock_member_id = 'me1' # Project Values mock_project_title = 'test project' mock_project_description = 'this is a test project' mock_project_tags = ['test', 'project'] # Bug Values mock_bug_title = 'test bug' mock_bug_description = 'this is a test bug' mock_bu...
mock_user_id = 'u1' mock_manager_id = 'ma1' mock_member_id = 'me1' mock_project_title = 'test project' mock_project_description = 'this is a test project' mock_project_tags = ['test', 'project'] mock_bug_title = 'test bug' mock_bug_description = 'this is a test bug' mock_bug_tags = ['test', 'bug']
# ------------------------------------------------------------------ # # Module for testing household structure # # ------------------------------------------------------------------ def print_houses_and_age(fname, agents): ''' Outputs house ID | age of every agent that lives there ''' # Dict with house ID vs. a l...
def print_houses_and_age(fname, agents): """ Outputs house ID | age of every agent that lives there """ houses = {} retirement_homes = {} for agent in agents: if agent['RetirementHome'] == True: if str(agent['houseID']) in retirement_homes: retirement_homes[str(agent[...
# -*- coding: utf-8 -*- # # Copyright (C) 2019 John J. Rofrano <rofrano@gmail.com> # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/L...
""" Module Release Report """ class Releasereport: """ Release Reports --------------- Create a Release Report POST /p1/repositories/:repo_id/reports/release Get a Release Report GET /p1/reports/release/:release_id Get Release Reports for a Repository GET /p1/rep...
""" Image/shape pixel constants """ DIM = 64 X_MIN, X_MAX = (8, 56) ONE_QUARTER = (X_MAX - X_MIN) // 3 X_MIN_34, X_MAX_34 = (X_MIN + ONE_QUARTER, X_MAX - ONE_QUARTER) BUFFER = 8 SIZE_MIN, SIZE_MAX = (2, 5) MAX_PLACEMENT_ATTEMPTS = 20 MAX_DISTRACTOR_PLACEMENT_ATTEMPTS = 100 MAX_INVALIDATE_ATTEMPTS = 100
""" Image/shape pixel constants """ dim = 64 (x_min, x_max) = (8, 56) one_quarter = (X_MAX - X_MIN) // 3 (x_min_34, x_max_34) = (X_MIN + ONE_QUARTER, X_MAX - ONE_QUARTER) buffer = 8 (size_min, size_max) = (2, 5) max_placement_attempts = 20 max_distractor_placement_attempts = 100 max_invalidate_attempts = 100
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Submission file for the python anagram exercise. # # v1: use sorted strings, and append anagrams to a pre-defined list def detect_anagrams(word, candidates): """ Return all correct anagrams of a given word from a list of words. Anagrams are case insensiti...
def detect_anagrams(word, candidates): """ Return all correct anagrams of a given word from a list of words. Anagrams are case insensitive, and differ from the original word. """ anagrams = [] for candidate in candidates: c = candidate.lower() w = word.lower() if sorted(...
text_file = open("test.txt", "w") text_file.write("Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\n") text_file.close()
text_file = open('test.txt', 'w') text_file.write('Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\n') text_file.close()
# Class ccontaining parsed input for a command class CmdInfo: def __init__(self, name, args, instream, outstream, background): self.name = name self. args = args self.instream = instream self.outstream = outstream self.background = background
class Cmdinfo: def __init__(self, name, args, instream, outstream, background): self.name = name self.args = args self.instream = instream self.outstream = outstream self.background = background