content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def is_all_strings(iterable): return all(isinstance(string, str) for string in iterable) print(['a', 'b', 'c']) print([2, 'a', 'b', 'c'])
def is_all_strings(iterable): return all((isinstance(string, str) for string in iterable)) print(['a', 'b', 'c']) print([2, 'a', 'b', 'c'])
""" You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and ...
""" You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and ...
def concat_multiples(num, multiples): return int("".join([str(num*multiple) for multiple in range(1,multiples+1)])) def is_pandigital(num): return sorted([int(digit) for digit in str(num)]) == list(range(1,10)) def solve_p038(): # retrieve only 9 digit concatinations of multiples where n = (1,2,..n) ...
def concat_multiples(num, multiples): return int(''.join([str(num * multiple) for multiple in range(1, multiples + 1)])) def is_pandigital(num): return sorted([int(digit) for digit in str(num)]) == list(range(1, 10)) def solve_p038(): n6 = [concat_multiples(num, 6) for num in [3]] n5 = [concat_multipl...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'targets': [ { # GN version: //ui/aura_extra 'target_name': 'aura_extra', 'type': '<(...
{'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'aura_extra', 'type': '<(component)', 'dependencies': ['../../base/base.gyp:base', '../../skia/skia.gyp:skia', '../aura/aura.gyp:aura', '../base/ui_base.gyp:ui_base', '../events/events.gyp:events', '../gfx/gfx.gyp:gfx', '../gfx/gfx.gyp:gfx_geometry'], 'def...
class Env: __table = None _prev = None def __init__(self, n): self.__table = {} self._prev = n def put(self, w, i): self.__table[w] = i def get(self, w): e = self while e is not None: found = e.__table.get(w) if found is not None: ...
class Env: __table = None _prev = None def __init__(self, n): self.__table = {} self._prev = n def put(self, w, i): self.__table[w] = i def get(self, w): e = self while e is not None: found = e.__table.get(w) if found is not None: ...
def foo(*args, **kwargs): pass fo<caret>o(1, 2, 3, x = 4)
def foo(*args, **kwargs): pass fo < caret > o(1, 2, 3, x=4)
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # 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 ...
__all__ = ['logging', 'lang', 'data', 'utils'] __name__ = 'bbutils' __author__ = 'Kai Raphahn' __email__ = 'kai.raphahn@laburec.de' __year__ = 2020 __copyright__ = 'Copyright (C) {0:d}, {1:s} <{2:s}>'.format(__year__, __author__, __email__) __description__ = 'Small collection of stuff for all my other python projects (...
class physics:#universal physics(excluding projectiles because i hate them) def __init__(self,world,gravity = 2): self.gravity = gravity self.world = world def isAtScreenBottom(self,obj):#unused if obj.y + obj.size[1] <= screenSize[1]: return True else: ...
class Physics: def __init__(self, world, gravity=2): self.gravity = gravity self.world = world def is_at_screen_bottom(self, obj): if obj.y + obj.size[1] <= screenSize[1]: return True else: return False def colliding(self, xy1, size1, xy2, size2): ...
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class EnvironmentListProtectionSourcesEnum(object): """Implementation of the 'environment_ListProtectionSources' enum. TODO: type enum description here. Attributes: K_VMWARE: TODO: type description here. KSQL: TODO: type description ...
class Environmentlistprotectionsourcesenum(object): """Implementation of the 'environment_ListProtectionSources' enum. TODO: type enum description here. Attributes: K_VMWARE: TODO: type description here. KSQL: TODO: type description here. KVIEW: TODO: type description here. ...
class DoublyNode: def __init__(self, data): self.data = data self.leftlink = None self.rightlink = None def __str__(self): return '| {0} |'.format(self.data) def __repr__(self): return "Node('{0}')".format(self.data) def getdata(self): return self.data...
class Doublynode: def __init__(self, data): self.data = data self.leftlink = None self.rightlink = None def __str__(self): return '| {0} |'.format(self.data) def __repr__(self): return "Node('{0}')".format(self.data) def getdata(self): return self.data...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """Hash table. Running time: O(n) where n == len(nums). """ d = {nums[0]: 0} for i in range(1, len(nums)): if target - nums[i] in d: return [i, d[target - nums[i]]] ...
class Solution: def two_sum(self, nums: List[int], target: int) -> List[int]: """Hash table. Running time: O(n) where n == len(nums). """ d = {nums[0]: 0} for i in range(1, len(nums)): if target - nums[i] in d: return [i, d[target - nums[i]]] ...
def distinct_values_bt(bin_tree): """Find distinct values in a binary tree.""" distinct = {} result = [] def _walk(node=None): if node is None: return if node.left is not None: _walk(node.left) if distinct.get(node.val): distinct[node.val] =...
def distinct_values_bt(bin_tree): """Find distinct values in a binary tree.""" distinct = {} result = [] def _walk(node=None): if node is None: return if node.left is not None: _walk(node.left) if distinct.get(node.val): distinct[node.val] = d...
{ 'variables': { 'SMRF_LIB_DIR': '/usr/local/lib', 'SMRF_INCLUDE_DIR': '/usr/local/include' }, 'targets': [ { 'target_name': 'smrf-native-cpp', 'sources': [ 'src/smrf.cpp' ], 'cflags_cc': [ '-std=c++14' ], 'cflags!': [ '-fno-exceptions'], 'cflags_cc!': [ '-fno-exceptions'], 'incl...
{'variables': {'SMRF_LIB_DIR': '/usr/local/lib', 'SMRF_INCLUDE_DIR': '/usr/local/include'}, 'targets': [{'target_name': 'smrf-native-cpp', 'sources': ['src/smrf.cpp'], 'cflags_cc': ['-std=c++14'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'include_dirs': ['<!(node -e "require(\'nan\')")', '<@(S...
# Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): root = UndirectedG...
class Solution: def clone_graph(self, node): root = undirected_graph_node(node.label) node.clone = root stack = [(root, x) for x in node.neighbors] while stack: (connectee, node) = stack.pop() if hasattr(node, 'clone'): connectee.neighbors.app...
class ApplicationId(object): """ Contains information used to uniquely identify a manifest-based application. This class cannot be inherited. ApplicationId(publicKeyToken: Array[Byte],name: str,version: Version,processorArchitecture: str,culture: str) """ def ZZZ(self): """hardcoded/mock instance of t...
class Applicationid(object): """ Contains information used to uniquely identify a manifest-based application. This class cannot be inherited. ApplicationId(publicKeyToken: Array[Byte],name: str,version: Version,processorArchitecture: str,culture: str) """ def zzz(self): """hardcoded/mock instanc...
#!/usr/bin/env python # encoding: utf-8 # This file is made available under Elastic License 2.0 # This file is based on code available under the Apache license here: # https://github.com/apache/incubator-doris/blob/master/gensrc/script/doris_builtins_functions.py # Licensed to the Apache Software Foundation (ASF) u...
visible_functions = [[['bitand'], 'TINYINT', ['TINYINT', 'TINYINT'], '_ZN9starrocks9Operators32bitand_tiny_int_val_tiny_int_valEPN13starrocks_udf15FunctionContextERKNS1_10TinyIntValES6_'], [['bitand'], 'SMALLINT', ['SMALLINT', 'SMALLINT'], '_ZN9starrocks9Operators34bitand_small_int_val_small_int_valEPN13starrocks_udf15...
#!/usr/bin/env python """ sample data for persistence/serialization examples this version is flat for saving in CSV, ini, etc. """ AddressBook = [ {'first_name': "Chris", 'last_name': "Barker", 'address_line_1':"835 NE 33rd St", 'address_line_2' : "", ...
""" sample data for persistence/serialization examples this version is flat for saving in CSV, ini, etc. """ address_book = [{'first_name': 'Chris', 'last_name': 'Barker', 'address_line_1': '835 NE 33rd St', 'address_line_2': '', 'address_city': 'Seattle', 'address_state': 'WA', 'address_zip': '96543', 'email': 'Python...
def test_get_empty_collection(client): empty_response = client.get('/data') assert empty_response.status_code == 200 assert 'json' in empty_response.content_type assert empty_response.is_json assert empty_response.json['href'].startswith('http') assert empty_response.json['href'].endswith('/data...
def test_get_empty_collection(client): empty_response = client.get('/data') assert empty_response.status_code == 200 assert 'json' in empty_response.content_type assert empty_response.is_json assert empty_response.json['href'].startswith('http') assert empty_response.json['href'].endswith('/data...
""" @file @brief `c3 <http://c3js.org/gettingstarted.html>`_ """ def version(): "version" return "0.4.2"
""" @file @brief `c3 <http://c3js.org/gettingstarted.html>`_ """ def version(): """version""" return '0.4.2'
#!/usr/bin/env python3 def next_nums(): A = 703 B = 516 for _ in range(40000000): A *= 16807 A %= 2147483647 B *= 48271 B %= 2147483647 yield (A, B) count = 0 for newA, newB in next_nums(): if newA % 65536 == newB % 65536: count += 1 print(count)
def next_nums(): a = 703 b = 516 for _ in range(40000000): a *= 16807 a %= 2147483647 b *= 48271 b %= 2147483647 yield (A, B) count = 0 for (new_a, new_b) in next_nums(): if newA % 65536 == newB % 65536: count += 1 print(count)
class ApiConfig: def __init__(self, environment: str = None, name: str = None, is_debug: bool = None, port: int = None, root_directory: str = None): self.port = port self.is_debug = is_debug self.name = name...
class Apiconfig: def __init__(self, environment: str=None, name: str=None, is_debug: bool=None, port: int=None, root_directory: str=None): self.port = port self.is_debug = is_debug self.name = name self.environment = environment self.root_directory = root_directory
data = ( 'Mang ', # 0x00 'Zhu ', # 0x01 'Utsubo ', # 0x02 'Du ', # 0x03 'Ji ', # 0x04 'Xiao ', # 0x05 'Ba ', # 0x06 'Suan ', # 0x07 'Ji ', # 0x08 'Zhen ', # 0x09 'Zhao ', # 0x0a 'Sun ', # 0x0b 'Ya ', # 0x0c 'Zhui ', # 0x0d 'Yuan ', # 0x0e 'Hu ', # 0x0f 'Gang ', # 0x10 ...
data = ('Mang ', 'Zhu ', 'Utsubo ', 'Du ', 'Ji ', 'Xiao ', 'Ba ', 'Suan ', 'Ji ', 'Zhen ', 'Zhao ', 'Sun ', 'Ya ', 'Zhui ', 'Yuan ', 'Hu ', 'Gang ', 'Xiao ', 'Cen ', 'Pi ', 'Bi ', 'Jian ', 'Yi ', 'Dong ', 'Shan ', 'Sheng ', 'Xia ', 'Di ', 'Zhu ', 'Na ', 'Chi ', 'Gu ', 'Li ', 'Qie ', 'Min ', 'Bao ', 'Tiao ', 'Si ', 'Fu ...
"""739. Daily Temperatures""" class Solution(object): def dailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """ ## R2: res = [0 for _ in range(len(T))] stack = [] for pos, tem in enumerate(T): while stack and T[stack[-1...
"""739. Daily Temperatures""" class Solution(object): def daily_temperatures(self, T): """ :type T: List[int] :rtype: List[int] """ res = [0 for _ in range(len(T))] stack = [] for (pos, tem) in enumerate(T): while stack and T[stack[-1]] < tem: ...
# Python 3.6.1 with open("input.txt", "r") as f: puzzle_input = [int(i) for i in f.read()[0:-1]] total = 0 for cur_index in range(len(puzzle_input)): next_index = cur_index + 1 if not cur_index == len(puzzle_input) - 1 else 0 puz_cur = puzzle_input[cur_index] pnext = puzzle_input[next_index] if p...
with open('input.txt', 'r') as f: puzzle_input = [int(i) for i in f.read()[0:-1]] total = 0 for cur_index in range(len(puzzle_input)): next_index = cur_index + 1 if not cur_index == len(puzzle_input) - 1 else 0 puz_cur = puzzle_input[cur_index] pnext = puzzle_input[next_index] if puz_cur == pnext: ...
s = input() y = int(input()) n = int(input()) c = 0 for i in s: if int(i) <= y: c += 1 for i in range(n): for j in range(2, n-1): if int(s[i:j+i]) <= y: c += 1 print(c) ''' qx = [i for i in range(input1)] for i, j in input3: if i == 1: qx = qx[1:] i...
s = input() y = int(input()) n = int(input()) c = 0 for i in s: if int(i) <= y: c += 1 for i in range(n): for j in range(2, n - 1): if int(s[i:j + i]) <= y: c += 1 print(c) '\nqx = [i for i in range(input1)]\nfor i, j in input3:\n if i == 1:\n qx = qx[1:]\n if i == 2:\n ...
def to_braket(array): """ helper for pretty printing """ state = [] basis = ('|00>', '|10>', '|01>', '|11>') for im, base_state in zip(array, basis): if im: if abs(im.imag)>0.001: state.append(f'{im.real:.1f}{base_state}') else: state.appen...
def to_braket(array): """ helper for pretty printing """ state = [] basis = ('|00>', '|10>', '|01>', '|11>') for (im, base_state) in zip(array, basis): if im: if abs(im.imag) > 0.001: state.append(f'{im.real:.1f}{base_state}') else: state.a...
def is_balanced(s): pairs = {"(": ")", "[": "]", "{": "}"} stack = [] for ch in s: if ch in pairs: stack.append(ch) else: if len(stack) == 0: return False if pairs[stack.pop()] != ch: return False return len(stack) == ...
def is_balanced(s): pairs = {'(': ')', '[': ']', '{': '}'} stack = [] for ch in s: if ch in pairs: stack.append(ch) else: if len(stack) == 0: return False if pairs[stack.pop()] != ch: return False return len(stack) == 0
def generate(label): ( bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax, img_width, img_height ) = ( label.get('xmin'), label.get('ymin'), label.get('xmax'), label.get('ymax'), label.get('img_width'), label.get('img_height...
def generate(label): (bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax, img_width, img_height) = (label.get('xmin'), label.get('ymin'), label.get('xmax'), label.get('ymax'), label.get('img_width'), label.get('img_height')) dw = 1.0 / img_width dh = 1.0 / img_height x = (bbox_xmin + bbox_xmax) / 2.0 y = (b...
""" A solution should include: 1. Benchmark scenario; 2. get_actions() method; 3. get_states() method. """ # Specify benchmark scenario below. BENCHMARK = "" # Benchmark name goes here... # Specify get_action() method below. def get_actions(state): # get_actions() code goes here... return # Sp...
""" A solution should include: 1. Benchmark scenario; 2. get_actions() method; 3. get_states() method. """ benchmark = '' def get_actions(state): return def get_states(env, **kwargs): return
print("hello") count=1 if count<1: print("yes") else: print("no")
print('hello') count = 1 if count < 1: print('yes') else: print('no')
# functions print("Demonstrating functions....") def fun(): print("Printing my function: fun") def fun1(): print("Printing my function: fun1") def multiply(x, y): z = x * y return z mulnum = multiply(150, 160) print(f"The return value is {mulnum}") # Demonstrating lambda functions # Lambda functi...
print('Demonstrating functions....') def fun(): print('Printing my function: fun') def fun1(): print('Printing my function: fun1') def multiply(x, y): z = x * y return z mulnum = multiply(150, 160) print(f'The return value is {mulnum}') x = lambda a: a + 10 print(f'The value of x is {x}') y = x(5) pr...
class MCP3008(): def __init__(self, channel): self.fake_val = 0 def value(self, pin=None): return self.fake_val
class Mcp3008: def __init__(self, channel): self.fake_val = 0 def value(self, pin=None): return self.fake_val
firt_tuple = (5,5,4,6,1,2,3) new_list = list(firt_tuple) new_tuple = tuple(new_list) print(len(firt_tuple)) print(max(new_list)) print(min(new_tuple))
firt_tuple = (5, 5, 4, 6, 1, 2, 3) new_list = list(firt_tuple) new_tuple = tuple(new_list) print(len(firt_tuple)) print(max(new_list)) print(min(new_tuple))
# Please note that if you uncomment and press multiple times, the program will keep appending to the file. def cap_four(name): new_name = name[0].upper() + name[1:3] + name[3].upper() + name[4:] return new_name # Check answer = cap_four('macdonald') print(answer)
def cap_four(name): new_name = name[0].upper() + name[1:3] + name[3].upper() + name[4:] return new_name answer = cap_four('macdonald') print(answer)
class Solution: def isPalindrome(self, s: str) -> bool: s=s.lower() s=[x for x in s if x.isalnum() ] return s==s[::-1]
class Solution: def is_palindrome(self, s: str) -> bool: s = s.lower() s = [x for x in s if x.isalnum()] return s == s[::-1]
if _: l = 2 else: l = []
if _: l = 2 else: l = []
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ substring = [] substrings = [] self.recursive(s, substring, substrings) return substrings def recursive(self, s, substring, substrings): if not s...
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ substring = [] substrings = [] self.recursive(s, substring, substrings) return substrings def recursive(self, s, substring, substrings): if not s...
MONTHS = { 'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6, 'july': 7, 'august': 8, 'september': 9, 'october': 10, 'november': 11, 'december': 12, } SHORT_MONTH = [ '', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep...
months = {'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6, 'july': 7, 'august': 8, 'september': 9, 'october': 10, 'november': 11, 'december': 12} short_month = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# Iterative approach - Time-Complexity = O(k), Space-Complexity = O(1) # k is the no of digits def replaceZeros(num): num += calculateAddedValue(num) return num def calculateAddedValue(num): decimal_place = 1 result = 0 if num == 0: result += decimal_place * 5 while num > 0: ...
def replace_zeros(num): num += calculate_added_value(num) return num def calculate_added_value(num): decimal_place = 1 result = 0 if num == 0: result += decimal_place * 5 while num > 0: if num % 10 == 0: result += 5 * decimal_place num = num // 10 dec...
# Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'subdir_file', 'type': 'none', 'msvs_cygwin_shell': 0, 'actions': [ { '...
{'targets': [{'target_name': 'subdir_file', 'type': 'none', 'msvs_cygwin_shell': 0, 'actions': [{'action_name': 'make-subdir-file', 'inputs': ['make-subdir-file.py'], 'outputs': ['<(PRODUCT_DIR)/subdir_file.out'], 'action': ['python', '<(_inputs)', '<@(_outputs)'], 'process_outputs_as_sources': 1}]}]}
"""Project Euler problem 3""" def sqrt(number): """Returns the square root of the specified number as an int, rounded down""" assert number >= 0 offset = 1 while offset ** 2 <= number: offset *= 2 count = 0 while offset > 0: if (count + offset) ** 2 <= number: count...
"""Project Euler problem 3""" def sqrt(number): """Returns the square root of the specified number as an int, rounded down""" assert number >= 0 offset = 1 while offset ** 2 <= number: offset *= 2 count = 0 while offset > 0: if (count + offset) ** 2 <= number: count ...
# nCk n, m = map(int, input().split(' ')) # numerator numerator = 1 for i in range(0, m): numerator *= n n -= 1 # denominator denominator = 1 for i in range(m, 0, -1): denominator *= i print(numerator // denominator)
(n, m) = map(int, input().split(' ')) numerator = 1 for i in range(0, m): numerator *= n n -= 1 denominator = 1 for i in range(m, 0, -1): denominator *= i print(numerator // denominator)
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 16:26:56 2018 @author: joshu """ letter_z = 'z' num_3 = '3' a_space = ' ' # Check if all characters are numbers print("Is z a letter or number: ", letter_z.isalnum()) # Checks if all characters are alphabetical print("Is z a letter: ", letter_z.isalpha()) # Check...
""" Created on Sun Jun 24 16:26:56 2018 @author: joshu """ letter_z = 'z' num_3 = '3' a_space = ' ' print('Is z a letter or number: ', letter_z.isalnum()) print('Is z a letter: ', letter_z.isalpha()) print('Is 3 a number: ', num_3.isdigit()) print('Is z a lowercase: ', letter_z.islower()) print('Is z a uppercase: ', l...
''' Problem Statement: ----------------- Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array. Example 1: --------- Input: N = 6 A[] = {3, 2, 1, 56, 10000, 167} Output: min = 1, max = 10000 Example 2: ---------- Input: N = 5 A[] = {1, 345, 234, 21, 56789} Output: ...
""" Problem Statement: ----------------- Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array. Example 1: --------- Input: N = 6 A[] = {3, 2, 1, 56, 10000, 167} Output: min = 1, max = 10000 Example 2: ---------- Input: N = 5 A[] = {1, 345, 234, 21, 56789} Output: ...
class Enum(object): def __init__(self, plugin, node): if node.tag != 'enum': raise ValueError('expected <enum>, got <%s>' % node.tag) self.plugin = plugin self.name = node.attrib['name'] self.item_prefix = node.attrib.get('item-prefix', '') self.base = int(node.at...
class Enum(object): def __init__(self, plugin, node): if node.tag != 'enum': raise value_error('expected <enum>, got <%s>' % node.tag) self.plugin = plugin self.name = node.attrib['name'] self.item_prefix = node.attrib.get('item-prefix', '') self.base = int(node....
connChoices = ( {'name': 'automatic', 'rate': {'min': 0, 'max': 5000, 'def': 0}, 'conn': {'min': 0, 'max': 100, 'def': 0}, 'automatic': 1}, {'name': 'unlimited', 'rate': {'min': 0, 'max': 5000, 'def': 0, 'div': 50}, 'conn': {'min': 4, 'max': 100, 'def': 4}}, {'name': 'dialup/isdn'...
conn_choices = ({'name': 'automatic', 'rate': {'min': 0, 'max': 5000, 'def': 0}, 'conn': {'min': 0, 'max': 100, 'def': 0}, 'automatic': 1}, {'name': 'unlimited', 'rate': {'min': 0, 'max': 5000, 'def': 0, 'div': 50}, 'conn': {'min': 4, 'max': 100, 'def': 4}}, {'name': 'dialup/isdn', 'rate': {'min': 3, 'max': 8, 'def': 5...
# # PySNMP MIB module HUAWEI-MA5200-DEVICE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-MA5200-DEVICE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:46:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ...
BOT_NAME = 'podcast_scraper' SPIDER_MODULES = ['podcast_scraper.spiders'] NEWSPIDER_MODULE = 'podcast_scraper.spiders' SCHEDULER_DEBUG = 'True' LOG_LEVEL = 'DEBUG' # LOG_FILE = './logs/log.txt' # app.py will use OUTPUT_BUCKET to generate an OUTPUT_URI # using OUTPUT_BUCKET and spider_name. OUTPUT_BUCKET = 'output-rs...
bot_name = 'podcast_scraper' spider_modules = ['podcast_scraper.spiders'] newspider_module = 'podcast_scraper.spiders' scheduler_debug = 'True' log_level = 'DEBUG' output_bucket = 'output-rss-bucket-name' item_pipelines = {'scrapy_podcast_rss.pipelines.PodcastPipeline': 300}
"""3. Inference with Quantized Models ===================================== This is a tutorial which illustrates how to use quantized GluonCV models for inference on Intel Xeon Processors to gain higher performance. The following example requires ``GluonCV>=0.4`` and ``MXNet-mkl>=1.6.0b20190829``. Please follow `our ...
"""3. Inference with Quantized Models ===================================== This is a tutorial which illustrates how to use quantized GluonCV models for inference on Intel Xeon Processors to gain higher performance. The following example requires ``GluonCV>=0.4`` and ``MXNet-mkl>=1.6.0b20190829``. Please follow `our ...
def fib(n_max): n, a, b = 0, 0, 1 while n < n_max: yield b a, b = b, a + b n = n + 1 list = fib(int(input("Input a number:"))) print(next(list)) for o in list: print(o)
def fib(n_max): (n, a, b) = (0, 0, 1) while n < n_max: yield b (a, b) = (b, a + b) n = n + 1 list = fib(int(input('Input a number:'))) print(next(list)) for o in list: print(o)
""" Universidad del Valle de Guatemala CC---- thompson.py Proposito: AFN ya establecido """ class AFN: def __init__(self, start, end): self.start = start self.end = end # start and end states end.is_end = True self.text = "State Inicial: {}| State Final: {}".format(self.start,self....
""" Universidad del Valle de Guatemala CC---- thompson.py Proposito: AFN ya establecido """ class Afn: def __init__(self, start, end): self.start = start self.end = end end.is_end = True self.text = 'State Inicial: {}| State Final: {}'.format(self.start, self.end) def addstat...
"""Sparse Array""" def sparse_array(): r"""https://www.hackerrank.com/challenges/sparse-arrays? There are $N$ strings. Each string's length is no more than 20 characters. There are also $Q$ queries. For each query, you are given a string, and you need to find out how many times this string occurred pr...
"""Sparse Array""" def sparse_array(): """https://www.hackerrank.com/challenges/sparse-arrays? There are $N$ strings. Each string's length is no more than 20 characters. There are also $Q$ queries. For each query, you are given a string, and you need to find out how many times this string occurred pre...
def mostFrequentDigitSum(n): ''' A step(x) operation works like this: it changes a number x into x - s(x), where s(x) is the sum of x's digits. You like applying functions to numbers, so given the number n, you decide to build a decreasing sequence of numbers: n, step(n), step(step(n)), etc., with 0 as the last...
def most_frequent_digit_sum(n): """ A step(x) operation works like this: it changes a number x into x - s(x), where s(x) is the sum of x's digits. You like applying functions to numbers, so given the number n, you decide to build a decreasing sequence of numbers: n, step(n), step(step(n)), etc., with 0 as the l...
"""DTE Energy Bridge Exceptions.""" class DteEnergyBridgeError(Exception): """Base class for all DTE Energy Bridge exceptions""" class InvalidResponseError(DteEnergyBridgeError): """Response from DTE Energy Bridge was invalid""" class InvalidArgumentError(DteEnergyBridgeError): """Invalid argument"""
"""DTE Energy Bridge Exceptions.""" class Dteenergybridgeerror(Exception): """Base class for all DTE Energy Bridge exceptions""" class Invalidresponseerror(DteEnergyBridgeError): """Response from DTE Energy Bridge was invalid""" class Invalidargumenterror(DteEnergyBridgeError): """Invalid argument"""
# x=int(input("enter the number")) # print("factors of ",x,"is:") # for i in range (1,x+1): # if X%i==0: # print(i) n=int(input("enter factors number=")) i=1 while i<=n: if n%i==0: print(i) i+=1
n = int(input('enter factors number=')) i = 1 while i <= n: if n % i == 0: print(i) i += 1
''' Created on Feb 20, 2013 @author: gorgolewski, steele ''' #import os #subjects = os.listdir("/scr/namibia1/baird/MPI_Project/Neuroimaging_Data/") working_dir = "/scr/alaska1/steele/BSL_IHI/processing/cmt" results_dir = "/scr/alaska1/steele/BSL_IHI/processing/cmt/results" freesurfer_dir = '/scr/alaska1/steele/BSL_I...
""" Created on Feb 20, 2013 @author: gorgolewski, steele """ working_dir = '/scr/alaska1/steele/BSL_IHI/processing/cmt' results_dir = '/scr/alaska1/steele/BSL_IHI/processing/cmt/results' freesurfer_dir = '/scr/alaska1/steele/BSL_IHI/processing/freesurfer/' subjects_m = ['KCDT100819_T1.TRIO', 'JA7T100824_T1.TRIO', '172...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) def get_counter(check, metric_name, modifiers, global_options): """ https://prometheus.io/docs/concepts/metric_types/#counter https://github.com/OpenObservability/OpenMetrics/blob/master/spec...
def get_counter(check, metric_name, modifiers, global_options): """ https://prometheus.io/docs/concepts/metric_types/#counter https://github.com/OpenObservability/OpenMetrics/blob/master/specification/OpenMetrics.md#counter-1 """ monotonic_count_method = check.monotonic_count metric_name = f'{me...
class ShortCodeError(Exception): """Base exception raised when some unexpected event occurs in the shortcode OAuth flow.""" pass class UnknownShortCodeError(ShortCodeError): """Exception raised when an unknown error happens while running shortcode OAuth. """ pass class Short...
class Shortcodeerror(Exception): """Base exception raised when some unexpected event occurs in the shortcode OAuth flow.""" pass class Unknownshortcodeerror(ShortCodeError): """Exception raised when an unknown error happens while running shortcode OAuth. """ pass class Shortcodeaccessdenie...
class Empty(Exception): """Use this class to raise exception if a container is empty.""" pass class CircularQueue: """Queue implemented using cicrcularly linked list for storage.""" class _Node: """Lightweight, nonpublic class for storing a singly linked node.""" __slots__ = ["_elemen...
class Empty(Exception): """Use this class to raise exception if a container is empty.""" pass class Circularqueue: """Queue implemented using cicrcularly linked list for storage.""" class _Node: """Lightweight, nonpublic class for storing a singly linked node.""" __slots__ = ['_elemen...
def szyfr(ciag, k): nowy_ciag = "" for lit in ciag: nowy_ord = 65+(ord(lit)-65+k) % 26 nowy_ciag += chr(nowy_ord) return nowy_ciag def odszyfr(ciag, k): nowy_ciag = "" for lit in ciag: nowy_ord = 65+(ord(lit)-65-k) % 26 nowy_ciag += chr(nowy_ord) return nowy_cia...
def szyfr(ciag, k): nowy_ciag = '' for lit in ciag: nowy_ord = 65 + (ord(lit) - 65 + k) % 26 nowy_ciag += chr(nowy_ord) return nowy_ciag def odszyfr(ciag, k): nowy_ciag = '' for lit in ciag: nowy_ord = 65 + (ord(lit) - 65 - k) % 26 nowy_ciag += chr(nowy_ord) retu...
#! python3 # __author__ = "YangJiaHao" # date: 2018/2/3 class Solution: def myAtoi(self, str): """ :type str: str :rtype: int """ str = str.strip() if str == "": return 0 num = '' symbol = 1 if str[0] == '-': symbol = -1...
class Solution: def my_atoi(self, str): """ :type str: str :rtype: int """ str = str.strip() if str == '': return 0 num = '' symbol = 1 if str[0] == '-': symbol = -1 str = str[1:] elif str[0] == '+':...
#!/usr/bin/python patch_size = [11, 15, 21] detector = ["FeatureDetectorHarrisCV", "FeatureDetectorUniform"] filter_size = [1, 3] max_disparity = [140, 160, 180, 200] fp_runscript = open("/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_grid_search_stage2.sh", 'w') fp_runscript.write("#!/bin/bash\n\n") cnt = 0 ...
patch_size = [11, 15, 21] detector = ['FeatureDetectorHarrisCV', 'FeatureDetectorUniform'] filter_size = [1, 3] max_disparity = [140, 160, 180, 200] fp_runscript = open('/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_grid_search_stage2.sh', 'w') fp_runscript.write('#!/bin/bash\n\n') cnt = 0 for i in range(len(pa...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isMirror(self, r1: TreeNode, r2: TreeNode) -> bool: if r1 == None and r2 == None: re...
class Solution: def is_mirror(self, r1: TreeNode, r2: TreeNode) -> bool: if r1 == None and r2 == None: return True if r1 == None or r2 == None: return False return r1.val == r2.val and self.isMirror(r1.left, r2.right) and self.isMirror(r1.right, r2.left) def is_...
class Passenger: def __init__(self, name): self.name = name def selectTrip(self, tripOptions): ''' Given a list of trip options, a passenger may select a trip This trip is then added to the trip queue, which allows for later return pricing tripOptions: the queue of give...
class Passenger: def __init__(self, name): self.name = name def select_trip(self, tripOptions): """ Given a list of trip options, a passenger may select a trip This trip is then added to the trip queue, which allows for later return pricing tripOptions: the queue of gi...
# A file containing mappings of CC -> MC file names # Pack version 3 VER3 = { 'char.png': 'minecraft/textures/entity/steve.png', 'chicken.png': 'minecraft/textures/entity/chicken.png', 'creeper.png': 'minecraft/textures/entity/creeper/creeper.png', 'pig.png': 'minecraft/textures/entity/pig/pig.png', ...
ver3 = {'char.png': 'minecraft/textures/entity/steve.png', 'chicken.png': 'minecraft/textures/entity/chicken.png', 'creeper.png': 'minecraft/textures/entity/creeper/creeper.png', 'pig.png': 'minecraft/textures/entity/pig/pig.png', 'sheep.png': 'minecraft/textures/entity/sheep/sheep.png', 'sheep_fur.png': 'minecraft/tex...
# output: ok assert(max(1, 2, 3) == 3) assert(max(1, 3, 2) == 3) assert(max(3, 2, 1) == 3) assert(min([1]) == 1) assert(min([1, 2, 3]) == 1) assert(min([1, 3, 2]) == 1) assert(min([3, 2, 1]) == 1) exception = False try: min() except TypeError: exception = True assert(exception) exception = False try: max...
assert max(1, 2, 3) == 3 assert max(1, 3, 2) == 3 assert max(3, 2, 1) == 3 assert min([1]) == 1 assert min([1, 2, 3]) == 1 assert min([1, 3, 2]) == 1 assert min([3, 2, 1]) == 1 exception = False try: min() except TypeError: exception = True assert exception exception = False try: max() except TypeError: ...
# Hack 1: InfoDB lists. Build your own/personalized InfoDb with a list length > 3, create list within a list as illustrated with Owns_Cars blue = "\033[34m" white = "\033[37m" InfoDb = [] # List with dictionary records placed in a list InfoDb.append({ "FirstName": "Michael", "Las...
blue = '\x1b[34m' white = '\x1b[37m' info_db = [] InfoDb.append({'FirstName': 'Michael', 'LastName': 'Chen', 'DOB': 'December 1', 'Residence': 'San Diego', 'Email': 'michaelc57247@stu.powayusd.com', 'Owns_Cars': ['2016 Ford Focus EV', '2019 Honda Pilot']}) InfoDb.append({'FirstName': 'Ethan', 'LastName': 'Vo', 'DOB': '...
x,y,z = map(int,input().split(' ')) a,b,c = map(int,input().split(' ')) if (x, y, z) == (a, b, c): print("0") elif (y, z) == (b, c): print(15 * (x - a)) elif z==c: if y<=b and x<=a: print("0") else: print(500 * (y - b)) elif z>c: print("10000") else: print("0")
(x, y, z) = map(int, input().split(' ')) (a, b, c) = map(int, input().split(' ')) if (x, y, z) == (a, b, c): print('0') elif (y, z) == (b, c): print(15 * (x - a)) elif z == c: if y <= b and x <= a: print('0') else: print(500 * (y - b)) elif z > c: print('10000') else: print('0')
def get_sum(arr,i,j): sum = 0 sum += arr[i-1][j-1] sum += arr[i-1][j] sum += arr[i - 1][j+1] sum += arr[i][j] sum += arr[i+1][j-1] sum += arr[i+1][j] sum += arr[i+1][j+1] return sum if __name__ == '__main__': arr = [] for _ in range(6): arr.append(list(map(int, inp...
def get_sum(arr, i, j): sum = 0 sum += arr[i - 1][j - 1] sum += arr[i - 1][j] sum += arr[i - 1][j + 1] sum += arr[i][j] sum += arr[i + 1][j - 1] sum += arr[i + 1][j] sum += arr[i + 1][j + 1] return sum if __name__ == '__main__': arr = [] for _ in range(6): arr.append(...
""" The exceptions here tries to follow PEP249 (https://www.python.org/dev/peps/pep-0249/#exceptions) """ class Warning(Exception): """Exception raised for important warnings like data truncations while inserting, etc.""" pass class Error(Exception): """Exception that is the base class of all other error ...
""" The exceptions here tries to follow PEP249 (https://www.python.org/dev/peps/pep-0249/#exceptions) """ class Warning(Exception): """Exception raised for important warnings like data truncations while inserting, etc.""" pass class Error(Exception): """Exception that is the base class of all other error ...
BROKER_URL = "redis://localhost:6379/0" CELERY_RESULT_BACKEND = "redis://localhost:6379/0" CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT=['json'] CELERY_ENABLE_UTC = True CELERY_TRACK_STARTED=True
broker_url = 'redis://localhost:6379/0' celery_result_backend = 'redis://localhost:6379/0' celery_task_serializer = 'json' celery_result_serializer = 'json' celery_accept_content = ['json'] celery_enable_utc = True celery_track_started = True
def substring (Str,n): for i in range(n): print(i) #0 #1 for j in range(i ,n): #0 to 3 #1 to 3 for k in range(i, (j + 1)): #0 to 1 => 0 #1 to 2 => 1 print(Str[k], end="") #print 0th element of the string. #print 0th and 1st element side by side. pr...
def substring(Str, n): for i in range(n): print(i) for j in range(i, n): for k in range(i, j + 1): print(Str[k], end='') print() str = 'abc' n = len(Str) substring(Str, n)
class MockPresenterFactory: def __init__(self): self.__presented_logs = [] def register_presenter(self, presenter): pass def present(self, obj): text = "" if isinstance(obj, str): text = obj elif isinstance(obj, list): if len(obj) > 0: ...
class Mockpresenterfactory: def __init__(self): self.__presented_logs = [] def register_presenter(self, presenter): pass def present(self, obj): text = '' if isinstance(obj, str): text = obj elif isinstance(obj, list): if len(obj) > 0: ...
def is_growth(numbers): for i in range(1, len(numbers)): if numbers[i] <= numbers[i - 1]: return False return True def main(): numbers = list(map(int, input().split())) if is_growth(numbers): print('YES') else: print('NO') if __name__ == '__main__': main()...
def is_growth(numbers): for i in range(1, len(numbers)): if numbers[i] <= numbers[i - 1]: return False return True def main(): numbers = list(map(int, input().split())) if is_growth(numbers): print('YES') else: print('NO') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization...
def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simply replace the two lines below with: return auth.wiki() """ response.flash = t('Welcome to web2py!') return dict(m...
a="#" b="@" c=1 d=int(input("Enter Number:")) if d%2==0: f=d/2 else: f=d//2+1 h=f-3 e=1 g=2 while c<=d: if c<=2 or c==f: print (a*c) c+=1 elif c>2 and c<f: print (a+(b*e)+a) c+=1 e+=1 elif c>f and c<d-1: print (a+(b*h)+a) c+=1 h=h-1 ...
a = '#' b = '@' c = 1 d = int(input('Enter Number:')) if d % 2 == 0: f = d / 2 else: f = d // 2 + 1 h = f - 3 e = 1 g = 2 while c <= d: if c <= 2 or c == f: print(a * c) c += 1 elif c > 2 and c < f: print(a + b * e + a) c += 1 e += 1 elif c > f and c < d - 1: ...
# substitution ciphers # or, how to transform data from one thing to another encode_table = { 'A': 'H', 'B': 'Z', 'C': 'Y', 'D': 'W', 'E': 'O', 'F': 'R', 'G': 'J', 'H': 'D', 'I': 'P', 'J': 'T', 'K': 'I', 'L': 'G', 'M': 'L', 'N': 'C', 'O': 'E', 'P': 'X', ...
encode_table = {'A': 'H', 'B': 'Z', 'C': 'Y', 'D': 'W', 'E': 'O', 'F': 'R', 'G': 'J', 'H': 'D', 'I': 'P', 'J': 'T', 'K': 'I', 'L': 'G', 'M': 'L', 'N': 'C', 'O': 'E', 'P': 'X', 'Q': 'K', 'R': 'U', 'S': 'N', 'T': 'F', 'U': 'A', 'V': 'M', 'W': 'B', 'X': 'Q', 'Y': 'V', 'Z': 'S'} decode_table = {value: key for (key, value) ...
class Color: pass class rgb(Color): "A representation of an RGBA color" def __init__(self, r, g, b, a=1.0): self.r = r self.g = g self.b = b self.a = a def __repr__(self): return "rgba({}, {}, {}, {})".format(self.r, self.g, self.b, self.a) @property ...
class Color: pass class Rgb(Color): """A representation of an RGBA color""" def __init__(self, r, g, b, a=1.0): self.r = r self.g = g self.b = b self.a = a def __repr__(self): return 'rgba({}, {}, {}, {})'.format(self.r, self.g, self.b, self.a) @property ...
aggregate_genres = [{"rock": ["symphonic rock", "jazz-rock", "heartland rock", "rap rock", "garage rock", "folk-rock", "roots rock", "adult alternative pop rock", "rock roll", "punk rock", "arena rock", "pop-rock", "glam rock", "southern rock", "indie rock", "funk rock", "country rock", "piano rock", "art rock", "rocka...
aggregate_genres = [{'rock': ['symphonic rock', 'jazz-rock', 'heartland rock', 'rap rock', 'garage rock', 'folk-rock', 'roots rock', 'adult alternative pop rock', 'rock roll', 'punk rock', 'arena rock', 'pop-rock', 'glam rock', 'southern rock', 'indie rock', 'funk rock', 'country rock', 'piano rock', 'art rock', 'rocka...
""" Mock module for _luastack C++ extension. Behaves like true _luastack module, but operates an imaginary Lua stack represented by a list. """ class StackPad: """Stub for padding the stack to make indexing start at 1.""" def __repr__(self): return "<StackPad>" stack = [StackPad()] # Imaginary Lua...
""" Mock module for _luastack C++ extension. Behaves like true _luastack module, but operates an imaginary Lua stack represented by a list. """ class Stackpad: """Stub for padding the stack to make indexing start at 1.""" def __repr__(self): return '<StackPad>' stack = [stack_pad()] references = {} d...
# Number of images used for training (rest goes for validation) train_size = 55000 # Image width and height of mnist width = 28 height = 28 # The total number of labels num_labels = 10 # The number of batches to prefetch when training on GPU num_prefetch = 5 # Number of neurons the weight matrices as specified in t...
train_size = 55000 width = 28 height = 28 num_labels = 10 num_prefetch = 5 num_neurons = [1000, 1000, 500, 200] prune_k = [0.0, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.97, 0.99] prune_types = [None, 'weight_pruning', 'unit_pruning']
#recursive solution def fib(n): if (n<=2): return 1 return fib(n-1)+fib(n-2) #print(fib(6)) #should be 8 #dp solution def fib_dp(n): a = [0]*n a[0] = a[1] = 1 for i in range(2, n): a[i] = a[i-1] + a[i-2] #print(a) return a fib_dp(6)
def fib(n): if n <= 2: return 1 return fib(n - 1) + fib(n - 2) def fib_dp(n): a = [0] * n a[0] = a[1] = 1 for i in range(2, n): a[i] = a[i - 1] + a[i - 2] return a fib_dp(6)
## configuration settings c = get_config() ## Configure SSL ----------------------------------------------- c.JupyterHub.ssl_key = "/srv/jupyterhub/ssl/jhub.privkey.pem" c.JupyterHub.ssl_cert = "/srv/jupyterhub/ssl/jhub.fullchain.pem" c.JupyterHub.ip = '128.59.232.200' c.JupyterHub.port = 443 ## Configure OAuth ----...
c = get_config() c.JupyterHub.ssl_key = '/srv/jupyterhub/ssl/jhub.privkey.pem' c.JupyterHub.ssl_cert = '/srv/jupyterhub/ssl/jhub.fullchain.pem' c.JupyterHub.ip = '128.59.232.200' c.JupyterHub.port = 443 c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator' c.Authenticator.oauth_callback_url = 'https:...
class Config(object): DEBUG = True DEVELOPMENT = True class ProductionConfig(Config): DEBUG = False DEVELOPMENT = False
class Config(object): debug = True development = True class Productionconfig(Config): debug = False development = False
N, M = map(int, input().split()) G = [[] for _ in range(N)] for _ in range(M): A, B = map(int, input().split()) G[A].append(B) G[B].append(A) dist = [-1] * N nodes = [[] for _ in range(N)] dist[0] = 0 nodes[0] = [0] for k in range(1, N): for v in nodes[k-1]: for next_v in G[v]: ...
(n, m) = map(int, input().split()) g = [[] for _ in range(N)] for _ in range(M): (a, b) = map(int, input().split()) G[A].append(B) G[B].append(A) dist = [-1] * N nodes = [[] for _ in range(N)] dist[0] = 0 nodes[0] = [0] for k in range(1, N): for v in nodes[k - 1]: for next_v in G[v]: ...
def store_value(redis_client,key_name,value): redis_client.setnx(key_name,value) return True def get_key_value(redis_client,key_name): return redis_client.get(key_name)
def store_value(redis_client, key_name, value): redis_client.setnx(key_name, value) return True def get_key_value(redis_client, key_name): return redis_client.get(key_name)
class HTTPException(Exception): def __init__(self, status: int, reason: str): self.status = status self.reason = reason def __str__(self): return "HTTPException: {}: {}".format(self.status, self.reason)
class Httpexception(Exception): def __init__(self, status: int, reason: str): self.status = status self.reason = reason def __str__(self): return 'HTTPException: {}: {}'.format(self.status, self.reason)
#!/usr/bin/env python3 def find_root(n, m): r = int(pow(m, 1 / n)) if r**n == m: return r if (r + 1)**n == m: return r + 1 return -1 for t in range(int(input())): print(find_root(*map(int, input().split())))
def find_root(n, m): r = int(pow(m, 1 / n)) if r ** n == m: return r if (r + 1) ** n == m: return r + 1 return -1 for t in range(int(input())): print(find_root(*map(int, input().split())))
class QuantumProcessor: """A class for defining a quantum processor""" def __init__(self, qubit_num=1, execution_time=0.1): """Define a quantum processor Args: qubit_num (int, optional): The number of qubits. Defaults to 1. execution_time (float, optional): The executi...
class Quantumprocessor: """A class for defining a quantum processor""" def __init__(self, qubit_num=1, execution_time=0.1): """Define a quantum processor Args: qubit_num (int, optional): The number of qubits. Defaults to 1. execution_time (float, optional): The executio...
hooked_function = None def set_hook(hook): global hooked_function hooked_function = hook hooked_function def do_it(): if hooked_function != None: hooked_function() else: print("Did not get hooked")
hooked_function = None def set_hook(hook): global hooked_function hooked_function = hook hooked_function def do_it(): if hooked_function != None: hooked_function() else: print('Did not get hooked')
# assign first item to dictionary, give value of 1 # go through items # if item name isn't equal to any dictionary, set it to a new dictionary # if item name equals existing dictionary, set that dictionary's value to +=1 # after everything, print dictionaries people = {} with open('tweeters.txt') as file: for line...
people = {} with open('tweeters.txt') as file: for line in file: person = line.strip() people[person] = people.get(person, 0) + 1 with open('tweets.txt', 'a') as file: for i in people: file.write(str(i) + ': ' + str(people[i]) + '\n')
#! /usr/bin/env python """ Some type definitions for metadata extraction """ class MetadataError(RuntimeError): pass
""" Some type definitions for metadata extraction """ class Metadataerror(RuntimeError): pass
class PyginationError(Exception): pass class PaginationError(Exception): pass
class Pyginationerror(Exception): pass class Paginationerror(Exception): pass
## CLASSES class NamedThing(object): """ a databased entity or concept/class """ def __init__(self, id=None, label=None): self.id=id self.label=label def __str__(self): return "id={} label={} ".format(self.id,self.label) def __repr__(...
class Namedthing(object): """ a databased entity or concept/class """ def __init__(self, id=None, label=None): self.id = id self.label = label def __str__(self): return 'id={} label={} '.format(self.id, self.label) def __repr__(self): return self.__str__() cla...
#!/usr/bin/env python3 def part_one(file): return(min(main(file))) def part_two(file): return(max(main(file))) def main(file): distances = dict() cities = set([s.strip().split(" ")[0] for s in open(file)]) cities.update([s.strip().split(" ")[2] for s in open(file)]) for city in cities: ...
def part_one(file): return min(main(file)) def part_two(file): return max(main(file)) def main(file): distances = dict() cities = set([s.strip().split(' ')[0] for s in open(file)]) cities.update([s.strip().split(' ')[2] for s in open(file)]) for city in cities: distances[city] = dict()...
#Handling Exceptions try: age = int(input("Enter your age:")) except ValueError as ex: print(ex) print(type(ex)) print("Please enter valid age!") else: print("else part executed")
try: age = int(input('Enter your age:')) except ValueError as ex: print(ex) print(type(ex)) print('Please enter valid age!') else: print('else part executed')
def uncycle(list): if len(list) <= 3: return max(list) m = int(len(list) / 2) if list[0] < list[m]: return uncycle(list[m:]) else: return uncycle(list[:m])
def uncycle(list): if len(list) <= 3: return max(list) m = int(len(list) / 2) if list[0] < list[m]: return uncycle(list[m:]) else: return uncycle(list[:m])
def _build_csv_path(target:str, directory:str, cell_line:str): return "{target}/{directory}/{cell_line}.csv".format( target=target, directory=directory, cell_line=cell_line ) def get_raw_epigenomic_data_path(target:str, cell_line:str): return _build_csv_path(target, "epigenomic_data...
def _build_csv_path(target: str, directory: str, cell_line: str): return '{target}/{directory}/{cell_line}.csv'.format(target=target, directory=directory, cell_line=cell_line) def get_raw_epigenomic_data_path(target: str, cell_line: str): return _build_csv_path(target, 'epigenomic_data', cell_line) def get_ra...
# -*- coding: utf-8 -*- # Copyright: (c) 2017, Wayne Witzel III <wayne@riotousliving.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Ansible Tower documentation fragment DOCUMENTATION = r''' options: tower_host: descr...
class Moduledocfragment(object): documentation = '\noptions:\n tower_host:\n description:\n - URL to your Tower instance.\n type: str\n tower_username:\n description:\n - Username for your Tower instance.\n type: str\n tower_password:\n description:\n - Password for your Tower instance.\n...
def main(): question = input("Please what type of variation is it ... |> ") if question == "direct": question = input("Please what is the value of the initial 1st variable => ").isdigit() if question: int(question) another_question = input("Please what is the value of the...
def main(): question = input('Please what type of variation is it ... |> ') if question == 'direct': question = input('Please what is the value of the initial 1st variable => ').isdigit() if question: int(question) another_question = input('Please what is the value of the ini...