content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def normalizable_feature(mean, std): """Decorator for features to specify default normalization. Args: mean: The mean value for the feature. std: The standard deviation for the feature. """ def _normalizable_feature(func): func.normal_mean = mean func.normal_std = std ...
def normalizable_feature(mean, std): """Decorator for features to specify default normalization. Args: mean: The mean value for the feature. std: The standard deviation for the feature. """ def _normalizable_feature(func): func.normal_mean = mean func.normal_std = std ...
''' - Leetcode problem: 98 - Difficulty: Medium - Brief problem description: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nod...
""" - Leetcode problem: 98 - Difficulty: Medium - Brief problem description: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nod...
""" Write a program to accept a character from the user and display whether it is a special character, digit or an alphabet. The program should continue as long as the juser wishes to. """ x = "Y" while x == "y": check = input("Enter a character: ") if check >= 'a' and check <= 'z' or check >= 'A' and che...
""" Write a program to accept a character from the user and display whether it is a special character, digit or an alphabet. The program should continue as long as the juser wishes to. """ x = 'Y' while x == 'y': check = input('Enter a character: ') if check >= 'a' and check <= 'z' or (check >= 'A' and check...
class TapeEnvWrapper: def __init__(self, env): self.__env = env self.__factors = self.__get_factors() def reset(self): return self.__env.reset() def step(self, action): action = self.__undiscretise(action) next_state, reward, done, info = self.__env.step(action) ...
class Tapeenvwrapper: def __init__(self, env): self.__env = env self.__factors = self.__get_factors() def reset(self): return self.__env.reset() def step(self, action): action = self.__undiscretise(action) (next_state, reward, done, info) = self.__env.step(action) ...
class Solution: def solve(self, n): if n == 0: return '0' remainders = [] while n: n, r = divmod(n, 3) remainders.append(str(r)) return ''.join(reversed(remainders))
class Solution: def solve(self, n): if n == 0: return '0' remainders = [] while n: (n, r) = divmod(n, 3) remainders.append(str(r)) return ''.join(reversed(remainders))
# # PySNMP MIB module CISCO-ITP-GSP2-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-GSP2-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:03:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_range_constraint, value_size_constraint, constraints_union, single_value_constraint) ...
{ 'targets': [ { 'target_name': 'discount', 'dependencies': [ 'libmarkdown' ], 'sources': [ 'src/discount.cc' ], 'include_dirs': [ 'deps/discount' ], 'libraries': [ 'deps/disco...
{'targets': [{'target_name': 'discount', 'dependencies': ['libmarkdown'], 'sources': ['src/discount.cc'], 'include_dirs': ['deps/discount'], 'libraries': ['deps/discount/libmarkdown.a']}, {'target_name': 'libmarkdown', 'type': 'none', 'actions': [{'action_name': 'build_libmarkdown', 'inputs': ['deps/discount/Csio.c', '...
class BTNode: def __init__(self, data = -1, left = None, right = None): self.data = data self.left = left self.right = right class BTree: def __init__(self): self.root = None self.is_comp = True self.num = 0 def is_empty(self): return self.root is Non...
class Btnode: def __init__(self, data=-1, left=None, right=None): self.data = data self.left = left self.right = right class Btree: def __init__(self): self.root = None self.is_comp = True self.num = 0 def is_empty(self): return self.root is None ...
load("//dev-infra/bazel/browsers:browser_archive_repo.bzl", "browser_archive") """ Defines repositories for Firefox that can be used inside Karma unit tests and Protractor e2e tests with Bazel. """ def define_firefox_repositories(): # Instructions on updating the Firefox version can be found in the `README.md...
load('//dev-infra/bazel/browsers:browser_archive_repo.bzl', 'browser_archive') '\n Defines repositories for Firefox that can be used inside Karma unit tests\n and Protractor e2e tests with Bazel.\n' def define_firefox_repositories(): browser_archive(name='org_mozilla_firefox_amd64', licenses=['reciprocal'], sha2...
class DockablePane(object,IDisposable): """ A user interface pane that participates in Revit's docking window system. DockablePane(other: DockablePane) DockablePane(id: DockablePaneId) """ def Dispose(self): """ Dispose(self: DockablePane) """ pass def GetTitle(self): """ GetTitle(sel...
class Dockablepane(object, IDisposable): """ A user interface pane that participates in Revit's docking window system. DockablePane(other: DockablePane) DockablePane(id: DockablePaneId) """ def dispose(self): """ Dispose(self: DockablePane) """ pass def get_title(self): ""...
# Calculating Page rank. class Graph(): def __init__(self): self.linked_node_map = {} self.PR_map = {} def add_node(self, node_id): if node_id not in self.linked_node_map: self.linked_node_map[node_id] = [] self.PR_map[node_id] = 0 def add_link(self, node1, ...
class Graph: def __init__(self): self.linked_node_map = {} self.PR_map = {} def add_node(self, node_id): if node_id not in self.linked_node_map: self.linked_node_map[node_id] = [] self.PR_map[node_id] = 0 def add_link(self, node1, node2, v): if node...
class NavigationValues: navigation_distance = None navigation_time = None speed_limit = None class Movement: value = None kph = None mph = None def calculate_speed(self): self.kph = self.value * 3.6 self.mph = self.value * 2.25 def __init__(...
class Navigationvalues: navigation_distance = None navigation_time = None speed_limit = None class Movement: value = None kph = None mph = None def calculate_speed(self): self.kph = self.value * 3.6 self.mph = self.value * 2.25 def __init__(...
def generate_board(): # Generate full, randomized sudoku board pass def generate_section(): # generate a randomized, 3x3 seciont of the board pass class SudokuBoard(object): """ """ def __init__(self, difficulty): super().__init__() self._base_size = 3 self....
def generate_board(): pass def generate_section(): pass class Sudokuboard(object): """ """ def __init__(self, difficulty): super().__init__() self._base_size = 3 self._board_length = self._base_size ** 2 self._difficulty = None self.difficulty = difficulty...
""" Author: Omkar Pandit Bankar Date: 10/10/2019 Email: omkarpbankar@gmail.com """
""" Author: Omkar Pandit Bankar Date: 10/10/2019 Email: omkarpbankar@gmail.com """
def is_phone_valid(phone: str) -> bool: if ( phone.isnumeric() and phone.startswith(("6", "7", "8", "9")) and len(phone) == 10 ): return True return False
def is_phone_valid(phone: str) -> bool: if phone.isnumeric() and phone.startswith(('6', '7', '8', '9')) and (len(phone) == 10): return True return False
""" An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape. If the character read is a digit (say d), the entire current tape is repeated...
""" An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape. If the character read is a digit (say d), the entire current tape is repeated...
panjang = int(raw_input("masukan panjang: ")) lebar = int(raw_input("masukan lebar: ")) tinggi = int(raw_input("masukan tinggi: ")) volume = panjang * lebar * tinggi print(volume)
panjang = int(raw_input('masukan panjang: ')) lebar = int(raw_input('masukan lebar: ')) tinggi = int(raw_input('masukan tinggi: ')) volume = panjang * lebar * tinggi print(volume)
class Node: def __init__(self,data): self.data = data self.left = self.right = None def findPreSuc(root, key): # Base Case if root is None: return # If key is present at root if root.data == key: # the maximum value in left subtree is predecessor if ro...
class Node: def __init__(self, data): self.data = data self.left = self.right = None def find_pre_suc(root, key): if root is None: return if root.data == key: if root.left is not None: tmp = root.left while tmp.right: tmp = tmp.right ...
"""" This file stores details of the rsvp. """ RVSPS=[] class Rsvp(): class_count = 1 def __init__(self): self.meetup_id = None self.topic = None self.status = None self.rsvp_id = Rsvp.class_count self.user_id = None Rsvp.class_count +=1 def __repr__(self):...
"""" This file stores details of the rsvp. """ rvsps = [] class Rsvp: class_count = 1 def __init__(self): self.meetup_id = None self.topic = None self.status = None self.rsvp_id = Rsvp.class_count self.user_id = None Rsvp.class_count += 1 def __repr__(self)...
STUDENT_NUMBER_STOP = 999 def parse_correct_answers(record): return record.split(" ") def parse_student_answers(record): parsed = record.split(" ") student = int(parsed[0]) if len(parsed) == 1: return (student, None) else: return (student, parsed[1:]) def calculate_marks(correct,...
student_number_stop = 999 def parse_correct_answers(record): return record.split(' ') def parse_student_answers(record): parsed = record.split(' ') student = int(parsed[0]) if len(parsed) == 1: return (student, None) else: return (student, parsed[1:]) def calculate_marks(correct, ...
# Copyright 2021 The Fraud Detection Framework Authors. 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 requ...
request_timeout = (60, 180) message_type_info = 5 message_type_warning = 4 message_type_error = 3 db_connection_string = 'postgresql://postgres:password@localhost:5432/fdf' exception_wait_sec = 5 setting_status_name = 'status' setting_status_processing = 'processing' setting_status_stopped = 'stopped' setting_status_re...
def czynniki_pierwsze(num: int) -> []: factors = [] k = 2 while num > 1: while num % k == 0: factors.append(k) num = num // k k = k + 1 return factors
def czynniki_pierwsze(num: int) -> []: factors = [] k = 2 while num > 1: while num % k == 0: factors.append(k) num = num // k k = k + 1 return factors
versions = {} def get_by_vid(vid): return versions[vid] def get_by_package(package, version_mode, vid): if not in_cache(package, version_mode, vid): return None return versions[vid][package + version_mode] def in_cache(package, version_mode, vid): package_str = package + version_mode return vid in ve...
versions = {} def get_by_vid(vid): return versions[vid] def get_by_package(package, version_mode, vid): if not in_cache(package, version_mode, vid): return None return versions[vid][package + version_mode] def in_cache(package, version_mode, vid): package_str = package + version_mode retu...
""" @no 169 @name Majority Element """ class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ count = {} for num in nums: if count.get(str(num)): count[str(num)] += 1 else: cou...
""" @no 169 @name Majority Element """ class Solution: def majority_element(self, nums): """ :type nums: List[int] :rtype: int """ count = {} for num in nums: if count.get(str(num)): count[str(num)] += 1 else: ...
#Linear Search class LinearSerach: def __init__(self): self.elements = [10,52,14,8,1,400,900,200,2,0] def SearchEm(self,elem): y = 0 if elem in self.elements: print("{x} is in the position of {y}".format(x = elem,y = self.elements.index(elem))) else: ...
class Linearserach: def __init__(self): self.elements = [10, 52, 14, 8, 1, 400, 900, 200, 2, 0] def search_em(self, elem): y = 0 if elem in self.elements: print('{x} is in the position of {y}'.format(x=elem, y=self.elements.index(elem))) else: print('The...
for t in range(int(input())): L=list(map(int,input().split())) sum=0 for i in L: if i<40: sum+=40 else : sum+=i print(f"#{t+1} {sum//5}")
for t in range(int(input())): l = list(map(int, input().split())) sum = 0 for i in L: if i < 40: sum += 40 else: sum += i print(f'#{t + 1} {sum // 5}')
""" For strings, return its length. For None return string 'no value' For booleans return the boolean For integers return a string showing how it compares to hundred e.g. For 67 return 'less than 100' for 4034 return 'more than 100' or equal to 100 as the case may be For lists return the 3...
""" For strings, return its length. For None return string 'no value' For booleans return the boolean For integers return a string showing how it compares to hundred e.g. For 67 return 'less than 100' for 4034 return 'more than 100' or equal to 100 as the case may be For lists return the 3...
class AgeBean: def __init__(self, judgement_id=0, age=''): self._judgement_id = judgement_id self._age = age @property def judgement_id(self): return int(self.judgement_id) @judgement_id.setter def judgement_id(self, id): self._judgement_id = id ...
class Agebean: def __init__(self, judgement_id=0, age=''): self._judgement_id = judgement_id self._age = age @property def judgement_id(self): return int(self.judgement_id) @judgement_id.setter def judgement_id(self, id): self._judgement_id = id @property ...
def reverse(head): cur = head pre = None while cur: nxt = cur.next cur.next = pre cur.pre = nxt pre = cur cur = nxt return pre
def reverse(head): cur = head pre = None while cur: nxt = cur.next cur.next = pre cur.pre = nxt pre = cur cur = nxt return pre
names = ['Anddy', 'Christian', 'Lucero', 'Yamile', 'Evelyn'] print(names) print(names[0]) print(names[0:2]) # numbers = [6, 2, 3, 45, 23, 3, 4, 55, 3, 2, 4456, 7, 98, 6, 64, 4, 321, 4, 323, 6, 68, 2, 2, 12, 4, 5] largeNumber = numbers[0] for number in numbers: if number > largeNumber: largeNumber = numb...
names = ['Anddy', 'Christian', 'Lucero', 'Yamile', 'Evelyn'] print(names) print(names[0]) print(names[0:2]) numbers = [6, 2, 3, 45, 23, 3, 4, 55, 3, 2, 4456, 7, 98, 6, 64, 4, 321, 4, 323, 6, 68, 2, 2, 12, 4, 5] large_number = numbers[0] for number in numbers: if number > largeNumber: large_number = number p...
class placeholder_optimizer(object): done=False self_managing=False def __init__(self,max_iter): self.max_iter=max_iter def update(self): pass
class Placeholder_Optimizer(object): done = False self_managing = False def __init__(self, max_iter): self.max_iter = max_iter def update(self): pass
# # Copyright (c) 2017-2018 Joy Diamond. All rights reserved. # @gem('Sapphire.LineMarker') def gem(): def construct_token__line_marker__many(t, s, newlines): assert (t.ends_in_newline is t.line_marker is true) and (newlines > 1) t.s = s t.newlines = newlines class LineMarke...
@gem('Sapphire.LineMarker') def gem(): def construct_token__line_marker__many(t, s, newlines): assert t.ends_in_newline is t.line_marker is true and newlines > 1 t.s = s t.newlines = newlines class Linemarker(PearlToken): class_order = CLASS_ORDER__LINE_MARKER display_n...
casos = int(input()) dentro = 0 fora = 0 for i in range(casos): num = int(input()) if num >= 10 and num <= 20: dentro += 1 else: fora += 1 print('{} in\n{} out'.format(dentro, fora))
casos = int(input()) dentro = 0 fora = 0 for i in range(casos): num = int(input()) if num >= 10 and num <= 20: dentro += 1 else: fora += 1 print('{} in\n{} out'.format(dentro, fora))
#https://www.hackerrank.com/challenges/quicksort2 ''' def quickSort(ar): if len(ar) <2 : # 0 or 1 return(ar) else: p = ar[0] less = [] more = [] for item in ar[1:]: if item < p: less.append(item) else: m...
""" def quickSort(ar): if len(ar) <2 : # 0 or 1 return(ar) else: p = ar[0] less = [] more = [] for item in ar[1:]: if item < p: less.append(item) else: more.append(item) l = quickSort(less) m = quickS...
class User: def __init__(self,username,password): self.is_authenticated = False self.username = username self.password = password
class User: def __init__(self, username, password): self.is_authenticated = False self.username = username self.password = password
def add(x): def do_add(y): return x + y return do_add add_to_five = add(5) # print(add_to_five(7)) # print(add(5)(3)) def Person(name, age): def print_hello(): print('Hello! My name is {}'.format(name)) def get_age(): return age return {'print_hello': print_hello, 'ge...
def add(x): def do_add(y): return x + y return do_add add_to_five = add(5) def person(name, age): def print_hello(): print('Hello! My name is {}'.format(name)) def get_age(): return age return {'print_hello': print_hello, 'get_age': get_age} john = person('John', 32) john...
class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: nums.sort() n=len(nums) if n==0: return [] dp=[[i,1] for i in range(n)] last=0 maxm=0 for i in range(1,n): for j in range(i-1,-1,-1): if num...
class Solution: def largest_divisible_subset(self, nums: List[int]) -> List[int]: nums.sort() n = len(nums) if n == 0: return [] dp = [[i, 1] for i in range(n)] last = 0 maxm = 0 for i in range(1, n): for j in range(i - 1, -1, -1): ...
class Book: def __init__(self, title, author, price): self.title = title self.author = author self.price = price def __str__(self): return f'{self.title} {self.author} {self.price}' def __call__(self, title, author, price): self.title = title self.author = au...
class Book: def __init__(self, title, author, price): self.title = title self.author = author self.price = price def __str__(self): return f'{self.title} {self.author} {self.price}' def __call__(self, title, author, price): self.title = title self.author = ...
class Solution: @staticmethod def naive(nums): return nums+nums
class Solution: @staticmethod def naive(nums): return nums + nums
ISCOUNTRY = 'isCountry' def filter_country_locations(api_response, is_country=True): """ Filter the response to only include the elements that are countries. This uses the 'api_response' object as input. Plain `list`s are also valid, but they must contain the location elements, not the `items` ...
iscountry = 'isCountry' def filter_country_locations(api_response, is_country=True): """ Filter the response to only include the elements that are countries. This uses the 'api_response' object as input. Plain `list`s are also valid, but they must contain the location elements, not the `items` ...
""" ------------------------------------------------------- config flask config file ------------------------------------------------------- Author: Dallas ID: 110242560 Email: fras2560@mylaurier.ca Version: 2014-09-18 ------------------------------------------------------- """ DEBUG = True
""" ------------------------------------------------------- config flask config file ------------------------------------------------------- Author: Dallas ID: 110242560 Email: fras2560@mylaurier.ca Version: 2014-09-18 ------------------------------------------------------- """ debug = True
#!/usr/bin/env python # -*- coding: UTF-8 -*- class DFUPrefix: """Generates the DFU prefix block""" DFU_PREFIX_LENGTH = 11 DFU_PREFIX_SIZE_POS = 6 DFU_PREFIX_IMG_COUNT_POS = 10 def __init__(self, imageSize = 0, targetCount = 0): # It looks like the DFU image size includes the DFU Prefix b...
class Dfuprefix: """Generates the DFU prefix block""" dfu_prefix_length = 11 dfu_prefix_size_pos = 6 dfu_prefix_img_count_pos = 10 def __init__(self, imageSize=0, targetCount=0): if imageSize != 0: image_size += self.DFU_PREFIX_LENGTH self.data = [ord('D'), ord('f'), ord...
''' Created on 25 Mar 2020 @author: bogdan ''' class s1010hy_wiki2text(object): ''' parsing wikipedia xml, extracting textual input ''' def __init__(self): ''' Constructor '''
""" Created on 25 Mar 2020 @author: bogdan """ class S1010Hy_Wiki2Text(object): """ parsing wikipedia xml, extracting textual input """ def __init__(self): """ Constructor """
""" GCD """ # Find the greatest common denominator (GCD) of two number input by a user. Then print out 'The GCD of <first number> and <second number> is <your result>.' print('Enter two numbers to find their greatest common denominator.') user_input1 = input('First number: ') user_input2 = input('Second number: ') ...
""" GCD """ print('Enter two numbers to find their greatest common denominator.') user_input1 = input('First number: ') user_input2 = input('Second number: ') a = int(user_input1) b = int(user_input2) print(f'The GCD of {a} and {b} is: ') while b != 0: (a, b) = (b, a % b) print(a)
# # PySNMP MIB module CISCO-HSRP-EXT-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HSRP-EXT-CAPABILITY # Produced by pysmi-0.3.4 at Mon Apr 29 17:42:35 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) ...
"""Compute the square root of a number.""" def sqrt(x): y = (1 + x)/2 tolerance = 1.0e-10 for i in range(10): error = abs(y*y - x) print(i, y, y*y, error) if error <= tolerance: break # improve the accuracy of y y = (y + x/y)/2 return y
"""Compute the square root of a number.""" def sqrt(x): y = (1 + x) / 2 tolerance = 1e-10 for i in range(10): error = abs(y * y - x) print(i, y, y * y, error) if error <= tolerance: break y = (y + x / y) / 2 return y
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ ...
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def find_target(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ result = self.helper_find_targe...
master_doc = 'index' project = u'Infrastructure-Components' copyright = '2019, Frank Zickert' htmlhelp_basename = 'Infrastructure-Components-Doc' language = 'en' gettext_compact = False html_theme = 'sphinx_rtd_theme' #html_logo = 'img/logo.svg' html_theme_options = { 'logo_only': True, 'display_version': F...
master_doc = 'index' project = u'Infrastructure-Components' copyright = '2019, Frank Zickert' htmlhelp_basename = 'Infrastructure-Components-Doc' language = 'en' gettext_compact = False html_theme = 'sphinx_rtd_theme' html_theme_options = {'logo_only': True, 'display_version': False} notfound_context = {'title': 'Page ...
a, b = input().split() a = int(a[::-1]) b = int(b[::-1]) print(a if a > b else b)
(a, b) = input().split() a = int(a[::-1]) b = int(b[::-1]) print(a if a > b else b)
ENDCODER_BANK_CONTROL1 = ['ModDevice_knob0', 'ModDevice_knob1', 'ModDevice_knob2', 'ModDevice_knob3'] ENDCODER_BANK_CONTROL2 = ['ModDevice_knob4', 'ModDevice_knob5', 'ModDevice_knob6', 'ModDevice_knob7'] ENDCODER_BANKS = {'NoDevice':[ENDCODER_BANK_CONTROL1 + ['CustomParameter_'+str(index+(bank*24)) for index in range(...
endcoder_bank_control1 = ['ModDevice_knob0', 'ModDevice_knob1', 'ModDevice_knob2', 'ModDevice_knob3'] endcoder_bank_control2 = ['ModDevice_knob4', 'ModDevice_knob5', 'ModDevice_knob6', 'ModDevice_knob7'] endcoder_banks = {'NoDevice': [ENDCODER_BANK_CONTROL1 + ['CustomParameter_' + str(index + bank * 24) for index in ra...
# Time: O(nlogk) # Space: O(k) # You have k lists of sorted integers in ascending order. # Find the smallest range that includes at least one number from each of the k lists. # # We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c. # # Example 1: # Input:[[4,10,15,24,26], [0,9,12...
class Solution(object): def smallest_range(self, nums): """ :type nums: List[List[int]] :rtype: List[int] """ (left, right) = (float('inf'), float('-inf')) min_heap = [] for row in nums: left = min(left, row[0]) right = max(right, row[...
""" This script is used for course notes. Author: Erick Marin Date: 10/05/2020 """ # Arithemtic Operators print(4 + 5) # Addition print(9 * 7) # Multiplication print(-1 / 4) # Divsion # Division with repeating or periodic numbers print(1 / 3) # Floor division "//" rounds the result down to the nearest whol...
""" This script is used for course notes. Author: Erick Marin Date: 10/05/2020 """ print(4 + 5) print(9 * 7) print(-1 / 4) print(1 / 3) print(1 // 3) print(((1 + 2) * 3 / 4) ** 5)
# -*- coding: utf-8 -*- class LoginError(Exception): pass
class Loginerror(Exception): pass
''' maze block counts for horizontal and vertical dimensions''' HN = 25 VN = 25 ''' screen width and height ''' WIDTH = 600 HEIGHT = 600 ''' configurations to fit the maze size regarding the block counts and its ratio with respect to the screen size ''' HSIZE = int(WIDTH*2./3.) VSIZE = int(HEIGHT*2./3.) HOFFSET = ...
""" maze block counts for horizontal and vertical dimensions""" hn = 25 vn = 25 ' screen width and height ' width = 600 height = 600 ' configurations to fit the maze size regarding the block counts and its ratio with respect to the screen size ' hsize = int(WIDTH * 2.0 / 3.0) vsize = int(HEIGHT * 2.0 / 3.0) hoffset = i...
# -*- coding: utf-8 -*- """Top-level package for Needlestack.""" __author__ = """Cung Tran""" __email__ = "minishcung@gmail.com" __version__ = "0.1.0"
"""Top-level package for Needlestack.""" __author__ = 'Cung Tran' __email__ = 'minishcung@gmail.com' __version__ = '0.1.0'
# md5 : 506fc4d9b83c53f867e483f9235de8f3 # sha1 : 0e90c892528abee5127e047b6ca037991267b9e0 # sha256 : 04deb949dd7601ee92a1868b2591c2829ff8d80e42511691bad64fd01374d7fe ord_names = { 733: b'mF_ld_load_ldnames', 734: b'mFt_os_mm_set_cushion', 735: b'mFt_os_resource_delete_ru_entry', 795: b'mFt_os_thread_i...
ord_names = {733: b'mF_ld_load_ldnames', 734: b'mFt_os_mm_set_cushion', 735: b'mFt_os_resource_delete_ru_entry', 795: b'mFt_os_thread_id_valid', 796: b'ASCII2HEX', 797: b'ASCII2OCTAL', 798: b'CBL_ABORT_RUN_UNIT', 799: b'CBL_ALLOC_DYN_MEM', 800: b'CBL_ALLOC_MEM', 801: b'CBL_ALLOC_SHMEM', 802: b'CBL_ALLOC_THREAD_MEM', 80...
people = int(input()) name_doc = input() grade_sum = 0 average_grade = 0 total_grade = 0 numbers = 0 while name_doc != "Finish": for x in range(people): grade = float(input()) grade_sum += grade average_grade = grade_sum / people print(f"{name_doc} - {average_grade:.2f}.") name_doc ...
people = int(input()) name_doc = input() grade_sum = 0 average_grade = 0 total_grade = 0 numbers = 0 while name_doc != 'Finish': for x in range(people): grade = float(input()) grade_sum += grade average_grade = grade_sum / people print(f'{name_doc} - {average_grade:.2f}.') name_doc =...
neopixel = Runtime.createAndStart("neopixel","NeoPixel") def startNeopixel(): neopixel.attach(i01.arduinos.get(rightPort),23,16) neopixel.setAnimation("Ironman",0,0,255,1) pinocchioLying = False def onStartSpeaking(data): if (pinocchioLying): neopixel.setAnimation("Ironman",0,255,0,1) else: ...
neopixel = Runtime.createAndStart('neopixel', 'NeoPixel') def start_neopixel(): neopixel.attach(i01.arduinos.get(rightPort), 23, 16) neopixel.setAnimation('Ironman', 0, 0, 255, 1) pinocchio_lying = False def on_start_speaking(data): if pinocchioLying: neopixel.setAnimation('Ironman', 0, 255, 0, 1)...
def pprint_matcher(node, *args, **kwargs): print(matcher_to_str(node, *args, **kwargs)) def matcher_to_str( node, indent_nr: int = 0, indent: str = " ", first_line_prefix=None ) -> str: ind = indent * indent_nr ind1 = indent * (indent_nr + 1) if first_line_prefix is None: first_line_pref...
def pprint_matcher(node, *args, **kwargs): print(matcher_to_str(node, *args, **kwargs)) def matcher_to_str(node, indent_nr: int=0, indent: str=' ', first_line_prefix=None) -> str: ind = indent * indent_nr ind1 = indent * (indent_nr + 1) if first_line_prefix is None: first_line_prefix = ind ...
class model4: def __getattr__(self,x): var_name = 'var_'+x v = self.__dict__[var_name] if var_name in self.__dict__ else self.__dict__[x] return v() if callable(v) else v def chain(self,other): for k,v in other.__dict__.items(): self.__dict__[k]=v return self if __name__=="__main__": x = model4() x.va...
class Model4: def __getattr__(self, x): var_name = 'var_' + x v = self.__dict__[var_name] if var_name in self.__dict__ else self.__dict__[x] return v() if callable(v) else v def chain(self, other): for (k, v) in other.__dict__.items(): self.__dict__[k] = v r...
ACTION_GOAL = "goal" ACTION_RED_CARD = "red-card" ACTION_YELLOW_RED_CARD = "yellow-red-card" actions = {ACTION_GOAL: "GOAL", ACTION_RED_CARD: "RED CARD", ACTION_YELLOW_RED_CARD: "RED CARD"} class PlayerAction(object): def __init__(self, player, action): if not type(player) == dict...
action_goal = 'goal' action_red_card = 'red-card' action_yellow_red_card = 'yellow-red-card' actions = {ACTION_GOAL: 'GOAL', ACTION_RED_CARD: 'RED CARD', ACTION_YELLOW_RED_CARD: 'RED CARD'} class Playeraction(object): def __init__(self, player, action): if not type(player) == dict: player = di...
def main(): # Open file for output outfile = open("Presidents.txt", "w") # Write data to the file outfile.write("Bill Clinton\n") outfile.write("George Bush\n") outfile.write("Barack Obama") outfile.close() # Close the output file main() # Call the main function
def main(): outfile = open('Presidents.txt', 'w') outfile.write('Bill Clinton\n') outfile.write('George Bush\n') outfile.write('Barack Obama') outfile.close() main()
class NoCurrentVersionFound(KeyError): """ No version node of the a particular parent node could be found """ pass class VersionDoesNotBelongToNode(AssertionError): """ The version that is trying to be attached does not belong to the parent node """ pass
class Nocurrentversionfound(KeyError): """ No version node of the a particular parent node could be found """ pass class Versiondoesnotbelongtonode(AssertionError): """ The version that is trying to be attached does not belong to the parent node """ pass
def fb_python_library(name, **kwargs): native.python_library( name = name, **kwargs )
def fb_python_library(name, **kwargs): native.python_library(name=name, **kwargs)
class Solution(object): def findLUSlength(self, a, b): """ :type a: str :type b: str :rtype: int """ if len(a) > len(b): return len(a) elif len(a) < len(b): return len(b) elif a == b: return -1 else: ...
class Solution(object): def find_lu_slength(self, a, b): """ :type a: str :type b: str :rtype: int """ if len(a) > len(b): return len(a) elif len(a) < len(b): return len(b) elif a == b: return -1 else: ...
def square_of_two_count(num): if(num == 2): return 0 num //= 2 print("num is now", num) return square_of_two_count(num) + 1 count = square_of_two_count(512) print("final count:", count) # That was a brief refresher because recursion can be messy # : Define a function called multiply. Have it ...
def square_of_two_count(num): if num == 2: return 0 num //= 2 print('num is now', num) return square_of_two_count(num) + 1 count = square_of_two_count(512) print('final count:', count) def multiply(a, b): """ :param a: A non-negative number :param b: A non-negative number :retur...
#program to display your details like name, age, address in three different lines. name = 'Chibuzor darlington' age = '19yrs' address = 'imsu junction' print(f'Name:{name}') print(f'Age:{age}') print(f'Address:{address}') def personal_details(): name, age = "Chibuzor Darlington", '19yrs' address = "imsu junctio...
name = 'Chibuzor darlington' age = '19yrs' address = 'imsu junction' print(f'Name:{name}') print(f'Age:{age}') print(f'Address:{address}') def personal_details(): (name, age) = ('Chibuzor Darlington', '19yrs') address = 'imsu junction' print('Name: {}\nAge: {}\nAddress: {}'.format(name, age, address)) pers...
cache = {} def get_page(url): if cache.get(url): return cache[url] else: data = get_data_from_server(url) cache[url] = data return data
cache = {} def get_page(url): if cache.get(url): return cache[url] else: data = get_data_from_server(url) cache[url] = data return data
"""This file contains all the code required to use the POSTGRES server so that bot has access to permanent storage""" def createTable(cursor): """Creates specified table if it does not exist""" command = "CREATE TABLE IF NOT EXISTS leaderboard (username varchar(50) NOT NULL, score INT NOT NULL)" curso...
"""This file contains all the code required to use the POSTGRES server so that bot has access to permanent storage""" def create_table(cursor): """Creates specified table if it does not exist""" command = 'CREATE TABLE IF NOT EXISTS leaderboard (username varchar(50) NOT NULL, score INT NOT NULL)' cursor.ex...
##write a program that will print the song "99 bottles of beer on the wall". ##for extra credit, do not allow the program to print each loop on a new line. bottles = 99 while bottles > 0: if bottles == 1: print(str(bottles) + " bottles of beer on the wall, " + str(bottles) + " bottle of beer.", end="...
bottles = 99 while bottles > 0: if bottles == 1: print(str(bottles) + ' bottles of beer on the wall, ' + str(bottles) + ' bottle of beer.', end=' ') else: print(str(bottles) + ' bottles of beer on the wall, ' + str(bottles) + ' bottles of beer.', end=' ') bottles -= 1 if bottles == 1: ...
#!/usr/bin/env python """credentials - the login credentials for all of the modules are stored here and imported into each module. Please be sure that you are using restricted accounts (preferably with read-only access) to your servers. """ __author__ = 'scott@flakshack.com (Scott Vintinner)' # VMware VMWARE_VCEN...
"""credentials - the login credentials for all of the modules are stored here and imported into each module. Please be sure that you are using restricted accounts (preferably with read-only access) to your servers. """ __author__ = 'scott@flakshack.com (Scott Vintinner)' vmware_vcenter_username = 'domain\\username' v...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class Tree: def __init__(self): self.head = None def bft(self): if self.head == None: return print("Bredth First Traversal") ptr = self.head ...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class Tree: def __init__(self): self.head = None def bft(self): if self.head == None: return print('Bredth First Traversal') ptr = self.head ...
"""Embed utils.""" def recurse_while_none(element): """Recursively find the leaf node with the ``href`` attribute.""" if element.text is None and element.getchildren(): return recurse_while_none(element.getchildren()[0]) href = element.attrib.get('href') if not href: href = element.at...
"""Embed utils.""" def recurse_while_none(element): """Recursively find the leaf node with the ``href`` attribute.""" if element.text is None and element.getchildren(): return recurse_while_none(element.getchildren()[0]) href = element.attrib.get('href') if not href: href = element.attr...
# Each frame has a name, and various associated roles. These roles have facet(s?) which take on values which are themselves sets of one or more frames. class Frame: # relations: a dictionary, key is role, value is other frames def __init__(self, name, isstate=False, iscenter=False): self.name = name ...
class Frame: def __init__(self, name, isstate=False, iscenter=False): self.name = name self.isstate = isstate self.iscenter = iscenter self.roles = {} class Role: def __init__(self): self.facetvalue = [] self.facetrelation = []
class Contact: def __init__(self, firstname, middlename, address, mobile, email): self.firstname = firstname self.middlename = middlename self.address = address self.mobile = mobile self.email = email
class Contact: def __init__(self, firstname, middlename, address, mobile, email): self.firstname = firstname self.middlename = middlename self.address = address self.mobile = mobile self.email = email
""" Remove duplicates from Sorted Array Given a sorted array, remove the duplicates in place such that each element appears only once and return the new length. Note that even though we want you to return the new length, make sure to change the original array as well in place Do not allocate extra space for another a...
""" Remove duplicates from Sorted Array Given a sorted array, remove the duplicates in place such that each element appears only once and return the new length. Note that even though we want you to return the new length, make sure to change the original array as well in place Do not allocate extra space for another a...
# Copyright 2021 Edoardo Riggio # # 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 law or agreed to in writin...
def minimal_contiguous_sum(A): if len(A) < 1: return None dp = A[0] m_sum = A[0] for i in range(len(A) - 1): dp = min(dp + A[i + 1], A[i + 1]) m_sum = min(dp, m_sum) return m_sum array = [-1, 2, -2, -4, 1, -2, 5, -2, -3, 1, 2, -1] print(minimal_contiguous_sum(array))
class Path(object): @staticmethod def db_dir(database): if database == 'ucf101': # folder that contains class labels # root_dir = '/data/dataset/ucf101/UCF-101/' root_dir = '/data/dataset/ucf101/UCF-5/' # Save preprocess data into output_dir ou...
class Path(object): @staticmethod def db_dir(database): if database == 'ucf101': root_dir = '/data/dataset/ucf101/UCF-5/' output_dir = '/data/dataset/VAR/UCF-5/' bbox_output_dir = '/data/dataset/UCF-101-result/UCF-5-20/' return (root_dir, output_dir, bbox...
HEALTH_CHECKS_ERROR_CODE = 503 HEALTH_CHECKS = { 'db': 'django_healthchecks.contrib.check_database', }
health_checks_error_code = 503 health_checks = {'db': 'django_healthchecks.contrib.check_database'}
DEFAULT_STEMMER = 'snowball' DEFAULT_TOKENIZER = 'word' DEFAULT_TAGGER = 'pos' TRAINERS = ['news', 'editorial', 'reviews', 'religion', 'learned', 'science_fiction', 'romance', 'humor'] DEFAULT_TRAIN = 'news'
default_stemmer = 'snowball' default_tokenizer = 'word' default_tagger = 'pos' trainers = ['news', 'editorial', 'reviews', 'religion', 'learned', 'science_fiction', 'romance', 'humor'] default_train = 'news'
def check(kwds, name): if kwds: msg = ', '.join('"%s"' % s for s in sorted(kwds)) s = '' if len(kwds) == 1 else 's' raise ValueError('Unknown attribute%s for %s: %s' % (s, name, msg)) def set_reserved(value, section, name=None, data=None, **kwds): check(kwds, '%s %s' % (section, value....
def check(kwds, name): if kwds: msg = ', '.join(('"%s"' % s for s in sorted(kwds))) s = '' if len(kwds) == 1 else 's' raise value_error('Unknown attribute%s for %s: %s' % (s, name, msg)) def set_reserved(value, section, name=None, data=None, **kwds): check(kwds, '%s %s' % (section, valu...
# Copyright (C) 2016 The Android Open Source Project # # 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 law or ag...
load('//tools/bzl:java.bzl', 'java_library2') def gwt_module(gwt_xml=None, resources=[], srcs=[], **kwargs): if gwt_xml: resources += [gwt_xml] java_library2(srcs=srcs, resources=resources, **kwargs)
''' changes to both lists that means, they point to same object once and then thrice ''' ''' a = [1,2,3] b = ([a]*3) print(a) print(b) # same effect # a[0]=11 b[0][0] = 9 print(a) print(b) #''' ''' a = [1,2,3] b = (a,) print(a) print(b) #'''
""" changes to both lists that means, they point to same object once and then thrice """ '\na = [1,2,3]\nb = ([a]*3)\nprint(a)\nprint(b)\n\n# same effect\n# a[0]=11\nb[0][0] = 9\nprint(a)\nprint(b)\n#' '\na = [1,2,3]\nb = (a,)\nprint(a)\nprint(b) \n#'
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class BotAssert(object): @staticmethod def activity_not_null(activity): if not activity: raise TypeError() @staticmethod def context_not_null(context): if not context: ...
class Botassert(object): @staticmethod def activity_not_null(activity): if not activity: raise type_error() @staticmethod def context_not_null(context): if not context: raise type_error() @staticmethod def conversation_reference_not_null(reference): ...
CHIP8_STANDARD_FONT = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0, 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, 0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, 0xF0, 0x90, 0xF0, 0x...
chip8_standard_font = [240, 144, 144, 144, 240, 32, 96, 32, 32, 112, 240, 16, 240, 128, 240, 240, 16, 240, 16, 240, 144, 144, 240, 16, 16, 240, 128, 240, 16, 240, 240, 128, 240, 144, 240, 240, 16, 32, 64, 64, 240, 144, 240, 144, 240, 240, 144, 240, 16, 240, 240, 144, 240, 144, 144, 224, 144, 224, 144, 224, 240, 128, 12...
with open('pi_digits.txt') as file_object: contnts = file_object.read() print(contnts.rstrip())
with open('pi_digits.txt') as file_object: contnts = file_object.read() print(contnts.rstrip())
class Solution: def _lengthOfLastWord(self, s): """ :type s: str :rtype: int """ temp = s.split(" ") arr = list(filter(lambda x: x != '', temp)) if not arr: return 0 return len(arr[-1]) def lengthOfLastWord(self, s): l, r = len(...
class Solution: def _length_of_last_word(self, s): """ :type s: str :rtype: int """ temp = s.split(' ') arr = list(filter(lambda x: x != '', temp)) if not arr: return 0 return len(arr[-1]) def length_of_last_word(self, s): (l,...
f=open('T.txt') fw=open('foursquare.embedding.update.2SameAnchor.1.foldtrain.twodirectionContext.number.100_dim.10000000','w') for i in f: ii=i.split() strt=ii[0]+'_foursquare'+' ' for iii in ii[1:]: strt=strt+iii+'|' fw.write(strt+'\n')
f = open('T.txt') fw = open('foursquare.embedding.update.2SameAnchor.1.foldtrain.twodirectionContext.number.100_dim.10000000', 'w') for i in f: ii = i.split() strt = ii[0] + '_foursquare' + ' ' for iii in ii[1:]: strt = strt + iii + '|' fw.write(strt + '\n')
a = int(input("Enter a number1: ")) b = int(input("Enter a number2: ")) temp = b b = a a = temp print("Value of number1: ", a , " Value of number2: ",b)
a = int(input('Enter a number1: ')) b = int(input('Enter a number2: ')) temp = b b = a a = temp print('Value of number1: ', a, ' Value of number2: ', b)
""" Initializes the view_helpers package """
""" Initializes the view_helpers package """
""" Each module provides a `Simulation` class based on `sapphire.Simulation`, but with specified governing equations. The mesh, initial values, and boundary conditions are unspecified. Therefore, the constructors have those as required arguments. """
""" Each module provides a `Simulation` class based on `sapphire.Simulation`, but with specified governing equations. The mesh, initial values, and boundary conditions are unspecified. Therefore, the constructors have those as required arguments. """
"""Dependency specific initialization.""" load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@com_github_3rdparty_eventuals//bazel:deps.bzl", eventuals_deps = "deps") load("@com_github_3rdparty_stout_borrowed_ptr//bazel:deps....
"""Dependency specific initialization.""" load('@bazel_tools//tools/build_defs/repo:git.bzl', 'git_repository') load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') load('@com_github_3rdparty_eventuals//bazel:deps.bzl', eventuals_deps='deps') load('@com_github_3rdparty_stout_borrowed_ptr//bazel:deps.bzl...
# Created by MechAviv # Kinesis Introduction # Map ID :: 331003200 # Subway :: Subway Car #3 GIRL = 1531067 sm.removeNpc(GIRL) sm.warpInstanceIn(331003300, 0)
girl = 1531067 sm.removeNpc(GIRL) sm.warpInstanceIn(331003300, 0)
model_parallel_size = 1 pipe_parallel_size = 0 distributed_backend = "nccl" DDP_impl = "local" # local / torch local_rank = None lazy_mpu_init = False use_cpu_initialization = False
model_parallel_size = 1 pipe_parallel_size = 0 distributed_backend = 'nccl' ddp_impl = 'local' local_rank = None lazy_mpu_init = False use_cpu_initialization = False
""" WaveletNode class represents one node in Wavelet tree data structure. """ class WaveletNode: def __init__(self, alphabet, parent=None): self.bit_vector = '' self.alphabet = alphabet self.left = None self.right = None self.parent = parent """ Method for adding n...
""" WaveletNode class represents one node in Wavelet tree data structure. """ class Waveletnode: def __init__(self, alphabet, parent=None): self.bit_vector = '' self.alphabet = alphabet self.left = None self.right = None self.parent = parent ' Method for adding new ...
#Kunal Gautam #Codewars : @Kunalpod #Problem name: Mumbling #Problem level: 7 kyu def accum(s): li = [] for i in range(len(s)): li.append(s[i].upper() + s[i].lower()*i) return '-'.join(li)
def accum(s): li = [] for i in range(len(s)): li.append(s[i].upper() + s[i].lower() * i) return '-'.join(li)
# 0. Paste the code in the Jupyter QtConsole # 1. Execute: bfs_tree( root ) # 2. Execute: dfs_tree( root ) root = {'value': 1, 'depth': 1} def successors(node): if node['value'] == 5: return [] elif node['value'] == 4: return [{'value': 5, 'depth': node['depth']+1}] else: return...
root = {'value': 1, 'depth': 1} def successors(node): if node['value'] == 5: return [] elif node['value'] == 4: return [{'value': 5, 'depth': node['depth'] + 1}] else: return [{'value': node['value'] + 1, 'depth': node['depth'] + 1}, {'value': node['value'] + 2, 'depth': node['depth...
AUTHOR = 'Zachary Priddy. (me@zpriddy.com)' TITLE = 'Event Automation' METADATA = { 'title': TITLE, 'author': AUTHOR, 'commands': ['execute'], 'interface': { 'trigger_types': { 'index_1': { 'context': 'and / or' }, 'index_3': { 'context': 'and / or' }, ...
author = 'Zachary Priddy. (me@zpriddy.com)' title = 'Event Automation' metadata = {'title': TITLE, 'author': AUTHOR, 'commands': ['execute'], 'interface': {'trigger_types': {'index_1': {'context': 'and / or'}, 'index_3': {'context': 'and / or'}, 'index_2': {'context': 'and / or'}}, 'trigger_devices': {'index_1': {'cont...
#Y for row in range(11): for col in range(11): if (row==col) or (row==0 and col==10)or (row==1 and col==9)or (row==2 and col==8)or (row==3 and col==7)or (row==4 and col==6): print("*",end=" ") else: print(" ",end=" ") print()
for row in range(11): for col in range(11): if row == col or (row == 0 and col == 10) or (row == 1 and col == 9) or (row == 2 and col == 8) or (row == 3 and col == 7) or (row == 4 and col == 6): print('*', end=' ') else: print(' ', end=' ') print()
def can_send(user, case): return user.is_superuser or user == case.created_by def nl2br(text): return text.replace("\n", "\n<br>")
def can_send(user, case): return user.is_superuser or user == case.created_by def nl2br(text): return text.replace('\n', '\n<br>')