content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution: def setZeroes(self, matrix): dummy1=[1]*len(matrix) dummy2=[1]*len(matrix[0]) for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j]==0: dummy1[i]=0 dummy2[j]=0 for i in range(len(matrix)): for j in range(len(matrix[0])): if dummy1[i]==0 or dummy2[j]==0: matrix[i][j]=0 return matrix
class Solution: def set_zeroes(self, matrix): dummy1 = [1] * len(matrix) dummy2 = [1] * len(matrix[0]) for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: dummy1[i] = 0 dummy2[j] = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if dummy1[i] == 0 or dummy2[j] == 0: matrix[i][j] = 0 return matrix
N=int(input("Enter the number of test cases:")) for i in range(0,N): L,D,S,C=map(int,input().split()) for i in range(1,D): if(S>=L): S+=C*S break if L<= S: print("ALIVE AND KICKING") else: print("DEAD AND ROTTING")
n = int(input('Enter the number of test cases:')) for i in range(0, N): (l, d, s, c) = map(int, input().split()) for i in range(1, D): if S >= L: s += C * S break if L <= S: print('ALIVE AND KICKING') else: print('DEAD AND ROTTING')
class Solution: def increasingTriplet(self, nums: List[int]) -> bool: first = second = math.inf for i in nums: if i <=first: first = i elif i<=second: second = i else: return True return False
class Solution: def increasing_triplet(self, nums: List[int]) -> bool: first = second = math.inf for i in nums: if i <= first: first = i elif i <= second: second = i else: return True return False
DynamoTable # unused import (dynamo_query/__init__.py:8) DynamoRecord # unused variable (dynamo_query/__init__.py:12) create # unused function (dynamo_query/data_table.py:119) memo # unused variable (dynamo_query/data_table.py:137) filter_keys # unused function (dynamo_query/data_table.py:299) get_column # unused function (dynamo_query/data_table.py:472) drop_duplicates # unused function (dynamo_query/data_table.py:734) sanitize_key # unused function (dynamo_query/dictclasses/dictclass.py:127) compute_key # unused function (dynamo_query/dictclasses/dictclass.py:131) sanitize # unused function (dynamo_query/dictclasses/dictclass.py:351) get_field_names # unused function (dynamo_query/dictclasses/dynamo_dictclass.py:32) DynamoAutoscaler # unused class (dynamo_query/dynamo_autoscaler.py:17) deregister_auto_scaling # unused function (dynamo_query/dynamo_autoscaler.py:47) register_auto_scaling # unused function (dynamo_query/dynamo_autoscaler.py:76) get_last_evaluated_key # unused function (dynamo_query/dynamo_query_main.py:648) reset_start_key # unused function (dynamo_query/dynamo_query_main.py:677) get_raw_responses # unused function (dynamo_query/dynamo_query_main.py:684) DynamoTable # unused class (dynamo_query/dynamo_table.py:63) delete_table # unused function (dynamo_query/dynamo_table.py:232) invalidate_cache # unused function (dynamo_query/dynamo_table.py:546) cached_batch_get # unused function (dynamo_query/dynamo_table.py:552) batch_get_records # unused function (dynamo_query/dynamo_table.py:729) batch_delete_records # unused function (dynamo_query/dynamo_table.py:747) batch_upsert_records # unused function (dynamo_query/dynamo_table.py:762) cached_get_record # unused function (dynamo_query/dynamo_table.py:829) upsert_record # unused function (dynamo_query/dynamo_table.py:851) delete_record # unused function (dynamo_query/dynamo_table.py:920) clear_records # unused function (dynamo_query/dynamo_table.py:1131) NE # unused variable (dynamo_query/enums.py:58) IN # unused variable (dynamo_query/enums.py:59) EXISTS # unused variable (dynamo_query/enums.py:65) NOT_EXISTS # unused variable (dynamo_query/enums.py:66) CONTAINS # unused variable (dynamo_query/enums.py:68) default # unused function (dynamo_query/json_tools.py:40) pluralize # unused function (dynamo_query/utils.py:91) get_nested_item # unused function (dynamo_query/utils.py:112)
DynamoTable DynamoRecord create memo filter_keys get_column drop_duplicates sanitize_key compute_key sanitize get_field_names DynamoAutoscaler deregister_auto_scaling register_auto_scaling get_last_evaluated_key reset_start_key get_raw_responses DynamoTable delete_table invalidate_cache cached_batch_get batch_get_records batch_delete_records batch_upsert_records cached_get_record upsert_record delete_record clear_records NE IN EXISTS NOT_EXISTS CONTAINS default pluralize get_nested_item
preamble = [int(input()) for _ in range(25)] for _ in range(975): x = int(input()) valid = False for i, a in enumerate(preamble[:-1]): for b in preamble[i+1:]: if a + b == x: valid = True if not valid: print(x) break preamble = preamble[1:] + [x]
preamble = [int(input()) for _ in range(25)] for _ in range(975): x = int(input()) valid = False for (i, a) in enumerate(preamble[:-1]): for b in preamble[i + 1:]: if a + b == x: valid = True if not valid: print(x) break preamble = preamble[1:] + [x]
# https://www.codechef.com/AUG21C/problems/SPCTRIPS for T in range(int(input())): n,c=int(input()),0 for x in range(1,n+1): for y in range(x,n+1,x): c+=((n-(x+y))//y+1) print(c)
for t in range(int(input())): (n, c) = (int(input()), 0) for x in range(1, n + 1): for y in range(x, n + 1, x): c += (n - (x + y)) // y + 1 print(c)
class QuizBrain: def __init__(self, a_list): self.question_number = 0 self.question_list = a_list self.score = 0 def still_has_questions(self): """Checks if their still have more questions""" if self.question_number < 12: """Checks if their still have more questions""" return True else: return False def next_question(self): """Displays the question""" current_question = self.question_list[self.question_number] self.question_number += 1 user_answer = input(f"Q.{self.question_number}: {current_question.question} (True/False): ") self.check_answer(user_answer, current_question.answer) def check_answer(self, user_answer, correct_answer): """Checks if the answer is correct""" if user_answer.capitalize() == correct_answer: self.score += 1 print("Correct!") else: print("Incorrect.") print(f"The correct answer was: {correct_answer}.") print(f"Your current score is: {self.score}/{self.question_number}") print("\n")
class Quizbrain: def __init__(self, a_list): self.question_number = 0 self.question_list = a_list self.score = 0 def still_has_questions(self): """Checks if their still have more questions""" if self.question_number < 12: 'Checks if their still have more questions' return True else: return False def next_question(self): """Displays the question""" current_question = self.question_list[self.question_number] self.question_number += 1 user_answer = input(f'Q.{self.question_number}: {current_question.question} (True/False): ') self.check_answer(user_answer, current_question.answer) def check_answer(self, user_answer, correct_answer): """Checks if the answer is correct""" if user_answer.capitalize() == correct_answer: self.score += 1 print('Correct!') else: print('Incorrect.') print(f'The correct answer was: {correct_answer}.') print(f'Your current score is: {self.score}/{self.question_number}') print('\n')
ignore_validation = { "/api/v1/profile": ("POST", "PUT"), "/api/v1/exchange": "GET", "/api/v1/validation": "GET", "/api/v1/meals/search" : "GET", "/api/v1/meals/browse" : "GET" }
ignore_validation = {'/api/v1/profile': ('POST', 'PUT'), '/api/v1/exchange': 'GET', '/api/v1/validation': 'GET', '/api/v1/meals/search': 'GET', '/api/v1/meals/browse': 'GET'}
class Node(object): def __init__(self, id, x, y): self.__id = id self.__x = x self.__y = y self.reset() @property def id(self): return self.__id @property def x(self): return self.__x @property def y(self): return self.__y @property def total_distance_to_goal(self): """ Get the distance from the origin to the goal, via this node. :returns: the total distance """ return self.distance_to_here + self.distance_to_goal def reset(self): """Reset any mutable values.""" self.via = None self.visited = False self.distance_to_goal = float('inf') self.distance_to_here = float('inf')
class Node(object): def __init__(self, id, x, y): self.__id = id self.__x = x self.__y = y self.reset() @property def id(self): return self.__id @property def x(self): return self.__x @property def y(self): return self.__y @property def total_distance_to_goal(self): """ Get the distance from the origin to the goal, via this node. :returns: the total distance """ return self.distance_to_here + self.distance_to_goal def reset(self): """Reset any mutable values.""" self.via = None self.visited = False self.distance_to_goal = float('inf') self.distance_to_here = float('inf')
# -*- coding: utf-8 -*- """ Author : Chris Azzara Purpose : A simple number guessing game. This program will try to guess a secret number between 1 - 100 The user will enter whether the guess is too high or too low or correct. The program uses the binary search algorithm to narrow the search space. """ print("Number Guessing Game!") print("Think of a number between 1 and 100 and I will try to guess it!") high = 100 low = 1 mid = (high + low) // 2 while low <= high: print("Is the number you are thinking of {}?".format(mid)) print("high {} mid {} low {}".format(high, mid, low)) response = input("y = yes\nh = too high\nl = too low\n") if response[0].lower() == 'y': print("Aha! I knew it!") break elif response[0].lower() == 'h': high = mid - 1 mid = (high + low) // 2 elif response[0].lower() == 'l': low = mid + 1 mid = (high + low) // 2 else: print("Sorry I didn't understand that...Let's try again")
""" Author : Chris Azzara Purpose : A simple number guessing game. This program will try to guess a secret number between 1 - 100 The user will enter whether the guess is too high or too low or correct. The program uses the binary search algorithm to narrow the search space. """ print('Number Guessing Game!') print('Think of a number between 1 and 100 and I will try to guess it!') high = 100 low = 1 mid = (high + low) // 2 while low <= high: print('Is the number you are thinking of {}?'.format(mid)) print('high {} mid {} low {}'.format(high, mid, low)) response = input('y = yes\nh = too high\nl = too low\n') if response[0].lower() == 'y': print('Aha! I knew it!') break elif response[0].lower() == 'h': high = mid - 1 mid = (high + low) // 2 elif response[0].lower() == 'l': low = mid + 1 mid = (high + low) // 2 else: print("Sorry I didn't understand that...Let's try again")
load("//bazel/rules/image:png_to_xpm.bzl", "png_to_xpm") load("//bazel/rules/image:xpm_to_ppm.bzl", "xpm_to_ppm") load("//bazel/rules/image:ppm_to_mask.bzl", "ppm_to_mask") load("//bazel/rules/image:ppm_to_xpm.bzl", "ppm_to_xpm") load("//bazel/rules/image:xpm_to_xbm.bzl", "xpm_to_xbm") load("//bazel/rules/image:png_mirror.bzl", "png_mirror") def png_to_x11_artifacts(name): png_to_xpm(name) xpm_to_ppm(name) ppm_to_mask(name) ppm_to_xpm(name + "_mask") xpm_to_xbm(name + "_mask") png_mirror(name) png_to_xpm(name + "_mirror") xpm_to_ppm(name + "_mirror") ppm_to_mask(name + "_mirror") ppm_to_xpm(name + "_mirror_mask") xpm_to_xbm(name + "_mirror_mask") native.filegroup( name = name + "_image_data", srcs = [ name + ".xpm", name + "_mask.xbm", name + "_mirror.xpm", name + "_mirror_mask.xbm", ], )
load('//bazel/rules/image:png_to_xpm.bzl', 'png_to_xpm') load('//bazel/rules/image:xpm_to_ppm.bzl', 'xpm_to_ppm') load('//bazel/rules/image:ppm_to_mask.bzl', 'ppm_to_mask') load('//bazel/rules/image:ppm_to_xpm.bzl', 'ppm_to_xpm') load('//bazel/rules/image:xpm_to_xbm.bzl', 'xpm_to_xbm') load('//bazel/rules/image:png_mirror.bzl', 'png_mirror') def png_to_x11_artifacts(name): png_to_xpm(name) xpm_to_ppm(name) ppm_to_mask(name) ppm_to_xpm(name + '_mask') xpm_to_xbm(name + '_mask') png_mirror(name) png_to_xpm(name + '_mirror') xpm_to_ppm(name + '_mirror') ppm_to_mask(name + '_mirror') ppm_to_xpm(name + '_mirror_mask') xpm_to_xbm(name + '_mirror_mask') native.filegroup(name=name + '_image_data', srcs=[name + '.xpm', name + '_mask.xbm', name + '_mirror.xpm', name + '_mirror_mask.xbm'])
# -*- coding: utf-8 -*- """ fairsearchdeltr.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power fairsearchdeltr. """ class TrainStep(object): """The :class:`TrainStep` object, which is a representation of the parameters in each step of the training. Contains a `timestamp`, `omega`, `omega_gradient`, `loss`, `loss_standard`, `loss_exposure`. TODO: is the name of the class OK? """ def __init__(self, timestamp, omega, omega_gradient, loss_standard, loss_exposure, loss): """ Object constructor :param timestamp: timestamp of object creation :param omega: current values of model :param omega_gradient: calculated gradient :param loss_standard: represents the change in ranking of training set vs predictions for training set :param loss_exposure: represents the difference in exposures :param loss: this should decrease at each iteration of training """ self.timestamp = timestamp self.omega = omega self.omega_gradient = omega_gradient self.loss_standard = loss_standard self.loss_exposure = loss_exposure self.loss = loss def __repr__(self): return "<TrainStep [{0},{1},{2},{3},{4}]>".format(self.timestamp, self.omega, self.omega_gradient, self.loss_standard, self.loss_exposure) class FairScoreDoc(object): """The :class:`FairScoreDoc` object, which is a representation of the items in the rankings. Contains an `id`, `is_protected` attribute, `features` and a `score` """ def __init__(self, id, is_protected, features, score): self.id = id self.score = score self.features = features self.is_protected = is_protected def __repr__(self): return "<FairScoreDoc [%s]>" % ("Protected" if self.is_protected else "Nonprotected") class Query(object): """The :class:`FairScoreDoc` object, which is a representation of the items in the rankings. Contains an `id`, `is_protected` attribute, `features` and a `score` """ def __init__(self, id, docs): self.id = id self.docs = docs
""" fairsearchdeltr.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power fairsearchdeltr. """ class Trainstep(object): """The :class:`TrainStep` object, which is a representation of the parameters in each step of the training. Contains a `timestamp`, `omega`, `omega_gradient`, `loss`, `loss_standard`, `loss_exposure`. TODO: is the name of the class OK? """ def __init__(self, timestamp, omega, omega_gradient, loss_standard, loss_exposure, loss): """ Object constructor :param timestamp: timestamp of object creation :param omega: current values of model :param omega_gradient: calculated gradient :param loss_standard: represents the change in ranking of training set vs predictions for training set :param loss_exposure: represents the difference in exposures :param loss: this should decrease at each iteration of training """ self.timestamp = timestamp self.omega = omega self.omega_gradient = omega_gradient self.loss_standard = loss_standard self.loss_exposure = loss_exposure self.loss = loss def __repr__(self): return '<TrainStep [{0},{1},{2},{3},{4}]>'.format(self.timestamp, self.omega, self.omega_gradient, self.loss_standard, self.loss_exposure) class Fairscoredoc(object): """The :class:`FairScoreDoc` object, which is a representation of the items in the rankings. Contains an `id`, `is_protected` attribute, `features` and a `score` """ def __init__(self, id, is_protected, features, score): self.id = id self.score = score self.features = features self.is_protected = is_protected def __repr__(self): return '<FairScoreDoc [%s]>' % ('Protected' if self.is_protected else 'Nonprotected') class Query(object): """The :class:`FairScoreDoc` object, which is a representation of the items in the rankings. Contains an `id`, `is_protected` attribute, `features` and a `score` """ def __init__(self, id, docs): self.id = id self.docs = docs
a = {'a': 1, 'b': 2} b = a del b['a'] print(a) print(b) c = 5 del a del b, c
a = {'a': 1, 'b': 2} b = a del b['a'] print(a) print(b) c = 5 del a del b, c
class Keys(): ERROR = 'ERROR' DEBUG = 'DEBUG' WARN = 'WARN' INFO = 'INFO' URL = 'url' TAG = 'tag' MESSAGE = 'message' LOG_LEVEL = 'level' REQUEST_METHOD = 'method' RESPONSE_STATUS = 'status' PAGE = 'page' SHOW = 'show' ALL = 'all'
class Keys: error = 'ERROR' debug = 'DEBUG' warn = 'WARN' info = 'INFO' url = 'url' tag = 'tag' message = 'message' log_level = 'level' request_method = 'method' response_status = 'status' page = 'page' show = 'show' all = 'all'
# # Copyright(c) 2019-2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # class PresentationPolicy: def __init__(self, standard_log, group_begin_func): self.standard = standard_log self.group_begin = group_begin_func def std_log_entry(msg_id, msg, log_result, html_node): pass def group_log_begin(msg_id, msg, html_node): return html_node, html_node null_policy = PresentationPolicy(std_log_entry, group_log_begin)
class Presentationpolicy: def __init__(self, standard_log, group_begin_func): self.standard = standard_log self.group_begin = group_begin_func def std_log_entry(msg_id, msg, log_result, html_node): pass def group_log_begin(msg_id, msg, html_node): return (html_node, html_node) null_policy = presentation_policy(std_log_entry, group_log_begin)
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return '0' if numerator ^ denominator < 0: result = '-' else: result = '' numerator = abs(numerator) denominator = abs(denominator) integer_part = numerator // denominator result += str(integer_part) numerator = numerator - integer_part * denominator if numerator == 0: return result result += '.' rest_map = {} decimal_part_result = [] while numerator != 0 and numerator not in rest_map: rest_map[numerator] = len(decimal_part_result) numerator *= 10 decimal_part_result.append(numerator // denominator) numerator -= decimal_part_result[-1] * denominator if numerator == 0: return result + ''.join(map(str, decimal_part_result)) else: return result + ''.join(map(str, decimal_part_result[0:rest_map[numerator]])) + '(' + ''.join(map(str, decimal_part_result[rest_map[numerator]:])) + ')' if __name__ == '__main__': print(Solution().fractionToDecimal(numerator=1, denominator=2)) print(Solution().fractionToDecimal(numerator=2, denominator=1)) print(Solution().fractionToDecimal(numerator=2, denominator=3)) print(Solution().fractionToDecimal(numerator=4, denominator=333)) print(Solution().fractionToDecimal(numerator=1, denominator=5)) print(Solution().fractionToDecimal(numerator=7, denominator=30))
class Solution: def fraction_to_decimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return '0' if numerator ^ denominator < 0: result = '-' else: result = '' numerator = abs(numerator) denominator = abs(denominator) integer_part = numerator // denominator result += str(integer_part) numerator = numerator - integer_part * denominator if numerator == 0: return result result += '.' rest_map = {} decimal_part_result = [] while numerator != 0 and numerator not in rest_map: rest_map[numerator] = len(decimal_part_result) numerator *= 10 decimal_part_result.append(numerator // denominator) numerator -= decimal_part_result[-1] * denominator if numerator == 0: return result + ''.join(map(str, decimal_part_result)) else: return result + ''.join(map(str, decimal_part_result[0:rest_map[numerator]])) + '(' + ''.join(map(str, decimal_part_result[rest_map[numerator]:])) + ')' if __name__ == '__main__': print(solution().fractionToDecimal(numerator=1, denominator=2)) print(solution().fractionToDecimal(numerator=2, denominator=1)) print(solution().fractionToDecimal(numerator=2, denominator=3)) print(solution().fractionToDecimal(numerator=4, denominator=333)) print(solution().fractionToDecimal(numerator=1, denominator=5)) print(solution().fractionToDecimal(numerator=7, denominator=30))
class Tags(object): """A class to manage various AirWatch device tag functionalities""" def __init__(self, client): self.client = client def get_id_by_name(self, name, og_id): # mdm/tags/search?name={name} response = self._get(path='/tags/search', params={'name':str(name), 'organizationgroupid':str(og_id)}) return response def _get(self, module='mdm', path=None, version=None, params=None, header=None): """GET requests for the /MDM/Tags module.""" response = self.client.get(module=module, path=path, version=version, params=params, header=header) return response def _post(self, module='mdm', path=None, version=None, params=None, data=None, json=None, header=None): """POST requests for the /MDM/Tags module.""" response = self.client.post(module=module, path=path, version=version, params=params, data=data, json=json, header=header) return response
class Tags(object): """A class to manage various AirWatch device tag functionalities""" def __init__(self, client): self.client = client def get_id_by_name(self, name, og_id): response = self._get(path='/tags/search', params={'name': str(name), 'organizationgroupid': str(og_id)}) return response def _get(self, module='mdm', path=None, version=None, params=None, header=None): """GET requests for the /MDM/Tags module.""" response = self.client.get(module=module, path=path, version=version, params=params, header=header) return response def _post(self, module='mdm', path=None, version=None, params=None, data=None, json=None, header=None): """POST requests for the /MDM/Tags module.""" response = self.client.post(module=module, path=path, version=version, params=params, data=data, json=json, header=header) return response
def factors(x): result = [] i = 1 while i*i <= x: if x % i == 0: result.append(i) if x//i != i: result.append(x//i) i += 1 return result for _ in range(int(input())): a, b = [int(i) for i in input().split()] m = 0 x = 0 for i in range(a, b + 1): result = factors(i) if len(result) > m: m = len(result) x = i print(f"Between {a} and {b}, {x} has a maximum of {m} divisors.")
def factors(x): result = [] i = 1 while i * i <= x: if x % i == 0: result.append(i) if x // i != i: result.append(x // i) i += 1 return result for _ in range(int(input())): (a, b) = [int(i) for i in input().split()] m = 0 x = 0 for i in range(a, b + 1): result = factors(i) if len(result) > m: m = len(result) x = i print(f'Between {a} and {b}, {x} has a maximum of {m} divisors.')
# 92. Reverse Linked List II # Runtime: 59 ms, faster than 5.80% of Python3 online submissions for Reverse Linked List II. # Memory Usage: 14.7 MB, less than 5.82% of Python3 online submissions for Reverse Linked List II. # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: # Recursion def __init__(self) -> None: self._left_node: ListNode = None self._stop: bool = False def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: if head is None: return None self._left_node = head self._recurse_reverse(head, left, right) return head def _recurse_reverse(self, right_node: ListNode, left: int, right: int) -> None: # Base case. Don't proceed any further. if right == 1: return # Keep moving the right pointer one step forward. right_node = right_node.next # Keep moving left pointer to the right until we reach the proper node from where the reversal is to start. if left > 1: self._left_node = self._left_node.next self._recurse_reverse(right_node, left - 1, right - 1) # In case both the pointers cross each other or become equal, we stop i.e. don't swap data any further. if self._left_node == right_node or right_node.next == self._left_node: self._stop = True if not self._stop: right_node.val, self._left_node.val = self._left_node.val, right_node.val # Move left one step to the right. The right pointer moves one step back via backtracking. self._left_node = self._left_node.next
class Solution: def __init__(self) -> None: self._left_node: ListNode = None self._stop: bool = False def reverse_between(self, head: ListNode, left: int, right: int) -> ListNode: if head is None: return None self._left_node = head self._recurse_reverse(head, left, right) return head def _recurse_reverse(self, right_node: ListNode, left: int, right: int) -> None: if right == 1: return right_node = right_node.next if left > 1: self._left_node = self._left_node.next self._recurse_reverse(right_node, left - 1, right - 1) if self._left_node == right_node or right_node.next == self._left_node: self._stop = True if not self._stop: (right_node.val, self._left_node.val) = (self._left_node.val, right_node.val) self._left_node = self._left_node.next
def conta_letras(frase, contar="vogais"): ''' Account the amount of consonants or vowels that the sentence has''' lista_ord_vogais = [65, 69, 73, 79, 85, 97, 101, 105, 111, 117] lista_ord_cosoantes = [66, 67, 68, 70, 71, 72, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 98, 99, 100, 102, 103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 118, 119, 120, 121, 122] count = 0 if contar == "vogais": for letra in frase: for ord_number in lista_ord_vogais: if ord(letra) == ord_number: count = count + 1 else: for letra in frase: for ord_number in lista_ord_cosoantes: if ord(letra) == ord_number: count = count + 1 return count conta_letras("programamos em python", 'consoantes')
def conta_letras(frase, contar='vogais'): """ Account the amount of consonants or vowels that the sentence has""" lista_ord_vogais = [65, 69, 73, 79, 85, 97, 101, 105, 111, 117] lista_ord_cosoantes = [66, 67, 68, 70, 71, 72, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 98, 99, 100, 102, 103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 118, 119, 120, 121, 122] count = 0 if contar == 'vogais': for letra in frase: for ord_number in lista_ord_vogais: if ord(letra) == ord_number: count = count + 1 else: for letra in frase: for ord_number in lista_ord_cosoantes: if ord(letra) == ord_number: count = count + 1 return count conta_letras('programamos em python', 'consoantes')
class SingletonMeta(type): def __init__(cls, name, bases, namespace): super().__init__(name, bases, namespace) cls.instance = None def __call__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super().__call__(*args, **kwargs) return cls.instance class SingletonBaseMeta(metaclass=SingletonMeta): pass class A(SingletonBaseMeta): pass class B(A): pass print(A()) print(A()) print(B())
class Singletonmeta(type): def __init__(cls, name, bases, namespace): super().__init__(name, bases, namespace) cls.instance = None def __call__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super().__call__(*args, **kwargs) return cls.instance class Singletonbasemeta(metaclass=SingletonMeta): pass class A(SingletonBaseMeta): pass class B(A): pass print(a()) print(a()) print(b())
# Solution by PauloBA def digital_root(n): n = str(n) ls = [] ans = 0 for i in n: ls.append(int(i)) for i in ls: ans = ans + i if ans < 10: return ans else: return digital_root(ans) print(digital_root(24))
def digital_root(n): n = str(n) ls = [] ans = 0 for i in n: ls.append(int(i)) for i in ls: ans = ans + i if ans < 10: return ans else: return digital_root(ans) print(digital_root(24))
def gcd(a, b): if min(a, b) == 0: return max(a, b) a_1 = max(a, b) % min(a, b) return gcd(a_1, min(a, b)) def lcm(a, b): return (a * b) // gcd(a, b)
def gcd(a, b): if min(a, b) == 0: return max(a, b) a_1 = max(a, b) % min(a, b) return gcd(a_1, min(a, b)) def lcm(a, b): return a * b // gcd(a, b)
class HelloMixin: def display(self): print('HelloMixin hello') class SuperHelloMixin: def display(self): print('SuperHello hello') class A(SuperHelloMixin, HelloMixin): pass if __name__ == '__main__': a = A() a.display()
class Hellomixin: def display(self): print('HelloMixin hello') class Superhellomixin: def display(self): print('SuperHello hello') class A(SuperHelloMixin, HelloMixin): pass if __name__ == '__main__': a = a() a.display()
def isPalindrome(string): return string == string[::-1] # OR # left_pos = 0 # right_pos = len(string) - 1 # # while right_pos >= left_pos: # if(string[left_pos] != string[right_pos]): # return False # left_pos += 1 # right_pos -= 1 # # return True print(isPalindrome("aza"))
def is_palindrome(string): return string == string[::-1] print(is_palindrome('aza'))
def select_rows(df, where): """Performs a series of rows selection in a DataFrame Pandas provides several methods to select rows. Using lambdas allows to select rows in a uniform and more flexible way. Parameters ---------- df: DataFrame DataFrame whose rows should be selected where: dict Dictionary with DataFrame columns name as keys and predicates (as lambdas) as values. For instance: {'a': lambda d: d == 1, 'b': lambda d: d == 3} Returns ------- Pandas DataFrame New DataFrame with selected rows """ df = df.copy() for col, f in where.items(): df = df[df[col].apply(f)] return df def chunk(len_array, nb_chunks=3): """Chunks an array in a list of several equal (when odd) length chunks Parameters ---------- len_array: int Length of the array to be chunked nb_chunks: int Number of chunks Returns ------- Iterator e.g list(chunk(10, 3)) would return [(0, 3), (3, 6), (6, 10)] """ assert nb_chunks <= len_array, "nb_chunks should be lower or equal than len_array" step = len_array // nb_chunks bounds = [x*step for x in range(nb_chunks)] + [len_array] return zip(bounds, bounds[1:])
def select_rows(df, where): """Performs a series of rows selection in a DataFrame Pandas provides several methods to select rows. Using lambdas allows to select rows in a uniform and more flexible way. Parameters ---------- df: DataFrame DataFrame whose rows should be selected where: dict Dictionary with DataFrame columns name as keys and predicates (as lambdas) as values. For instance: {'a': lambda d: d == 1, 'b': lambda d: d == 3} Returns ------- Pandas DataFrame New DataFrame with selected rows """ df = df.copy() for (col, f) in where.items(): df = df[df[col].apply(f)] return df def chunk(len_array, nb_chunks=3): """Chunks an array in a list of several equal (when odd) length chunks Parameters ---------- len_array: int Length of the array to be chunked nb_chunks: int Number of chunks Returns ------- Iterator e.g list(chunk(10, 3)) would return [(0, 3), (3, 6), (6, 10)] """ assert nb_chunks <= len_array, 'nb_chunks should be lower or equal than len_array' step = len_array // nb_chunks bounds = [x * step for x in range(nb_chunks)] + [len_array] return zip(bounds, bounds[1:])
# Semigroup = non-empty set with an associative binary operation # using addition print((2 + 3) + 4 == 2 + (3 + 4) == 9) # We get a property of closure, because the number we get is still a number of the same set, # natural numbers, including 0 # (2 + 3) + 4 # 2 + (3 + 4) # 9
print(2 + 3 + 4 == 2 + (3 + 4) == 9)
# The MIT License # # Copyright (c) 2008 James Piechota # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class Error( Exception ): """Base exception class. Contains a string with an optional error message.""" def __init__( self, message ): self._message = message def __str__( self ): return self._message def __repr__( self ): return self._message def __unicode__( self ): return self._message def msg( self ): return self._message class UnitializedError( Error ): """Thrown when an unitialized variable is accessed.""" def __init__( self, message ): Error.__init__( self, message ) class BadArgumentError( Error ): """Thrown when an invalid argument is provided.""" def __init__( self, message ): Error.__init__( self, message ) class OutOfBoundsError( Error ): """Thrown when the value of an argument is outside the allow range.""" def __init__( self, message ): Error.__init__( self, message ) class UnsupportedError( Error ): """Thrown when an implemented feature is invoked.""" def __init__( self, message ): Error.__init__( self, message ) class ThirdPartyError( Error ): """Thrown when a third party library has an error.""" def __init__( self, message ): Error.__init__( self, message ) class SilentError( Error ): """Thrown when an error has occurred but no message should be printed. Either there's none to print or something else has already printed it.""" def __init__( self, message ): Error.__init__( self, message ) class AbortError( Error ): """Thrown when an operation has been aborted either by the user or otherwise.""" def __init__( self, message ): Error.__init__( self, message )
class Error(Exception): """Base exception class. Contains a string with an optional error message.""" def __init__(self, message): self._message = message def __str__(self): return self._message def __repr__(self): return self._message def __unicode__(self): return self._message def msg(self): return self._message class Unitializederror(Error): """Thrown when an unitialized variable is accessed.""" def __init__(self, message): Error.__init__(self, message) class Badargumenterror(Error): """Thrown when an invalid argument is provided.""" def __init__(self, message): Error.__init__(self, message) class Outofboundserror(Error): """Thrown when the value of an argument is outside the allow range.""" def __init__(self, message): Error.__init__(self, message) class Unsupportederror(Error): """Thrown when an implemented feature is invoked.""" def __init__(self, message): Error.__init__(self, message) class Thirdpartyerror(Error): """Thrown when a third party library has an error.""" def __init__(self, message): Error.__init__(self, message) class Silenterror(Error): """Thrown when an error has occurred but no message should be printed. Either there's none to print or something else has already printed it.""" def __init__(self, message): Error.__init__(self, message) class Aborterror(Error): """Thrown when an operation has been aborted either by the user or otherwise.""" def __init__(self, message): Error.__init__(self, message)
class Solution: def maxPower(self, s: str) -> int: power = [] i, temp = 1, "" for s_char in s: if s_char == temp: i += 1 else: power.append( i ) i = 1 temp = s_char power.append(i) return max(power)
class Solution: def max_power(self, s: str) -> int: power = [] (i, temp) = (1, '') for s_char in s: if s_char == temp: i += 1 else: power.append(i) i = 1 temp = s_char power.append(i) return max(power)
def multiprocess_state_generator(video_frame_generator, stream_sha256): """Returns a packaged dict object for use in frame_process""" for frame in video_frame_generator: yield {'mode': 'video', 'main_sequence': True}
def multiprocess_state_generator(video_frame_generator, stream_sha256): """Returns a packaged dict object for use in frame_process""" for frame in video_frame_generator: yield {'mode': 'video', 'main_sequence': True}
# Used Python for handling large integers for _ in range(int(input())): a,b = list(map(int,input().split())) print(a*b)
for _ in range(int(input())): (a, b) = list(map(int, input().split())) print(a * b)
def solution(a, b): answer = '' month = {0:0, 1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31} day = {1:'FRI',2:'SAT',3:'SUN', 4:'MON',5:'TUE',6:'WED', 0:'THU'} d = 0 for i in range(0, a): d += month[i] d += b answer = day[(d % 7)] return answer
def solution(a, b): answer = '' month = {0: 0, 1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} day = {1: 'FRI', 2: 'SAT', 3: 'SUN', 4: 'MON', 5: 'TUE', 6: 'WED', 0: 'THU'} d = 0 for i in range(0, a): d += month[i] d += b answer = day[d % 7] return answer
# Function to calculate median def calcMedian(arr, startIndex, endIndex): index = ( startIndex + endIndex ) // 2 if (endIndex - startIndex + 1) % 2 == 0: # return median for even no of elements return ( arr[index] + arr[index + 1] ) // 2 else: # return median for odd no of elements return arr[index] # Get n n = int(input()) # Get list array X X = list(map(int, input().split())) X.sort() q1 = calcMedian(X, 0, n//2 - 1) q2 = calcMedian(X, 0, n-1) if n % 2 == 0: q3 = calcMedian(X, n//2, n-1) else: q3 = calcMedian(X, n//2 + 1, n-1) # Print result print(q1) print(q2) print(q3)
def calc_median(arr, startIndex, endIndex): index = (startIndex + endIndex) // 2 if (endIndex - startIndex + 1) % 2 == 0: return (arr[index] + arr[index + 1]) // 2 else: return arr[index] n = int(input()) x = list(map(int, input().split())) X.sort() q1 = calc_median(X, 0, n // 2 - 1) q2 = calc_median(X, 0, n - 1) if n % 2 == 0: q3 = calc_median(X, n // 2, n - 1) else: q3 = calc_median(X, n // 2 + 1, n - 1) print(q1) print(q2) print(q3)
# -*- coding: utf-8 -*- # Initial permutation matrix PI = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7] # Initial key permutation matrix CP_1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4] # Shifted key permutation matrix to get Ki+1 CP_2 = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32] # Expanded matrix (48bits after expansion) XORed with Ki E = [32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1] # S-BOXES matrix S_BOXES = [ [[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13], ], [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5], [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15], [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9], ], [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7], [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12], ], [[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14], ], [[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9], [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14], [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3], ], [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11], [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8], [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6], [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13], ], [[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1], [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6], [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2], [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12], ], [[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7], [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2], [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8], [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11], ] ] # Permutation matrix following each S-BOX substitution for each round P = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25] # Final permutation matrix of data after the 16 rounds PI_1 = [40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25] # Matrix determining the shift for each round of keys ROUND_KEY_SHIFT = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1] ENCRYPTION = 1 DECRYPTION = 0 def string_to_bit_array(text): """Convert the string into a list of bits.""" array = list() for char in text: bin_val = bin_value(char, 8) # Get value of char in one byte array.extend([int(x) for x in list(bin_val)]) # Add the bits to the list return array def bit_array_to_string(array): """Transform bit array to string.""" result_string = ''.join( [chr(int(i, 2)) for i in [''.join([str(x) for x in s_bytes]) for s_bytes in split_into_n(array, 8)]] ) return result_string def bin_value(val, bit_size): """Return the binary value as a string of the given size.""" bin_val = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:] if len(bin_val) > bit_size: raise "Binary value larger than expected!" while len(bin_val) < bit_size: bin_val = "0" + bin_val # Add 0s to satisfy size return bin_val def split_into_n(s, n): """Split into lists - each of size 'n'.""" return [s[k:k + n] for k in range(0, len(s), n)] class Des: def __init__(self): self.text = None self.passwd = None self.keys = list() def run(self, key, text, action=ENCRYPTION, padding=False): """Run the DES algorithm.""" self.text = text self.passwd = key if padding and action == ENCRYPTION: self.add_padding() elif len(self.text) % 8 != 0: # If not padding specified data size must be multiple of 8 bytes raise "Data size should be multiple of 8" self.generate_keys() # Generate all the keys text_blocks = split_into_n(self.text, 8) # Split the text in blocks of 8 bytes so 64 bits result = list() for block in text_blocks: # Loop over all the blocks of data block = string_to_bit_array(block) # Convert the block in bit array block = self.permutation(block, PI) # Apply the initial permutation L, R = split_into_n(block, 32) # L(LEFT), R(RIGHT) temp = None for i in range(16): # Perform 16 rounds d_e = self.expansion(R, E) # Expand R to 48 bits if action == ENCRYPTION: temp = self.xor(self.keys[i], d_e) # Use the Ki when encrypting else: temp = self.xor(self.keys[15 - i], d_e) # Use the last key when decrypting temp = self.substitute(temp) # Apply the S-BOXES temp = self.permutation(temp, P) temp = self.xor(L, temp) L = R R = temp result += self.permutation(R + L, PI_1) # Perform the last permutation & append the RIGHT to LEFT final_res = bit_array_to_string(result) if padding and action == DECRYPTION: return self.remove_padding(final_res) # Remove the padding if decrypting and padding is used else: return final_res # Return the final string of processed data def substitute(self, d_e): """Substitute bytes using S-BOXES.""" sub_blocks = split_into_n(d_e, 6) # Split bit array into sub_blocks of 6 bits each result = list() for i in range(len(sub_blocks)): # For all the sub_blocks block = sub_blocks[i] row = int(str(block[0]) + str(block[5]), 2) # Find row with the first & last bit column = int(''.join([str(x) for x in block[1:][:-1]]), 2) # Column value based on 2nd, 3rd, 4th & 5th bit val = S_BOXES[i][row][column] # Resulting value in the S-BOX for specific round bin = bin_value(val, 4) # Convert decimal value to binary result += [int(x) for x in bin] # Append the binary to the resulting list return result def permutation(self, block, table): """Perform permutation of the given block using the given table.""" return [block[x - 1] for x in table] def expansion(self, block, table): """Perform expansion of d to mach the size of Ki (48 bits).""" return [block[x - 1] for x in table] def xor(self, t1, t2): """Perform XOR & return the list.""" return [x ^ y for x, y in zip(t1, t2)] def generate_keys(self): """Generate all the keys.""" self.keys = [] key = string_to_bit_array(self.passwd) key = self.permutation(key, CP_1) # Perform initial permutation on the key g, d = split_into_n(key, 28) # Split into g (LEFT) & d (RIGHT) for i in range(16): # Apply the 16 rounds g, d = self.shift(g, d, ROUND_KEY_SHIFT[i]) # Shift the key according to the round tmp = g + d # Merge them self.keys.append(self.permutation(tmp, CP_2)) # Perform the permutation to get the Ki def shift(self, g, d, n): """Shift a list of the given value.""" return g[n:] + g[:n], d[n:] + d[:n] def add_padding(self): """Add padding to the data according to PKCS5 specification.""" pad_len = 8 - (len(self.text) % 8) self.text += pad_len * chr(pad_len) def remove_padding(self, data): """Remove the padding from the data.""" pad_len = ord(data[-1]) return data[:-pad_len] def encrypt(self, key, text, padding=True): """Perform encryption.""" return self.run(key, text, ENCRYPTION, padding) def decrypt(self, key, text, padding=True): """Perform decryption.""" return self.run(key, text, DECRYPTION, padding) if __name__ == '__main__': # des_algorithm.py executed as script print("Nothing to execute!")
pi = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7] cp_1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4] cp_2 = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32] e = [32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1] s_boxes = [[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]], [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5], [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15], [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]], [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7], [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]], [[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]], [[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9], [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14], [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]], [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11], [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8], [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6], [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]], [[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1], [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6], [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2], [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]], [[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7], [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2], [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8], [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]]] p = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25] pi_1 = [40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25] round_key_shift = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1] encryption = 1 decryption = 0 def string_to_bit_array(text): """Convert the string into a list of bits.""" array = list() for char in text: bin_val = bin_value(char, 8) array.extend([int(x) for x in list(bin_val)]) return array def bit_array_to_string(array): """Transform bit array to string.""" result_string = ''.join([chr(int(i, 2)) for i in [''.join([str(x) for x in s_bytes]) for s_bytes in split_into_n(array, 8)]]) return result_string def bin_value(val, bit_size): """Return the binary value as a string of the given size.""" bin_val = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:] if len(bin_val) > bit_size: raise 'Binary value larger than expected!' while len(bin_val) < bit_size: bin_val = '0' + bin_val return bin_val def split_into_n(s, n): """Split into lists - each of size 'n'.""" return [s[k:k + n] for k in range(0, len(s), n)] class Des: def __init__(self): self.text = None self.passwd = None self.keys = list() def run(self, key, text, action=ENCRYPTION, padding=False): """Run the DES algorithm.""" self.text = text self.passwd = key if padding and action == ENCRYPTION: self.add_padding() elif len(self.text) % 8 != 0: raise 'Data size should be multiple of 8' self.generate_keys() text_blocks = split_into_n(self.text, 8) result = list() for block in text_blocks: block = string_to_bit_array(block) block = self.permutation(block, PI) (l, r) = split_into_n(block, 32) temp = None for i in range(16): d_e = self.expansion(R, E) if action == ENCRYPTION: temp = self.xor(self.keys[i], d_e) else: temp = self.xor(self.keys[15 - i], d_e) temp = self.substitute(temp) temp = self.permutation(temp, P) temp = self.xor(L, temp) l = R r = temp result += self.permutation(R + L, PI_1) final_res = bit_array_to_string(result) if padding and action == DECRYPTION: return self.remove_padding(final_res) else: return final_res def substitute(self, d_e): """Substitute bytes using S-BOXES.""" sub_blocks = split_into_n(d_e, 6) result = list() for i in range(len(sub_blocks)): block = sub_blocks[i] row = int(str(block[0]) + str(block[5]), 2) column = int(''.join([str(x) for x in block[1:][:-1]]), 2) val = S_BOXES[i][row][column] bin = bin_value(val, 4) result += [int(x) for x in bin] return result def permutation(self, block, table): """Perform permutation of the given block using the given table.""" return [block[x - 1] for x in table] def expansion(self, block, table): """Perform expansion of d to mach the size of Ki (48 bits).""" return [block[x - 1] for x in table] def xor(self, t1, t2): """Perform XOR & return the list.""" return [x ^ y for (x, y) in zip(t1, t2)] def generate_keys(self): """Generate all the keys.""" self.keys = [] key = string_to_bit_array(self.passwd) key = self.permutation(key, CP_1) (g, d) = split_into_n(key, 28) for i in range(16): (g, d) = self.shift(g, d, ROUND_KEY_SHIFT[i]) tmp = g + d self.keys.append(self.permutation(tmp, CP_2)) def shift(self, g, d, n): """Shift a list of the given value.""" return (g[n:] + g[:n], d[n:] + d[:n]) def add_padding(self): """Add padding to the data according to PKCS5 specification.""" pad_len = 8 - len(self.text) % 8 self.text += pad_len * chr(pad_len) def remove_padding(self, data): """Remove the padding from the data.""" pad_len = ord(data[-1]) return data[:-pad_len] def encrypt(self, key, text, padding=True): """Perform encryption.""" return self.run(key, text, ENCRYPTION, padding) def decrypt(self, key, text, padding=True): """Perform decryption.""" return self.run(key, text, DECRYPTION, padding) if __name__ == '__main__': print('Nothing to execute!')
""" Classes for IMPACTS P3 Instruments """ class P3(object): """ """ def __init__(self, filepath, date): pass def readfile(self, filepath, ): pass
""" Classes for IMPACTS P3 Instruments """ class P3(object): """ """ def __init__(self, filepath, date): pass def readfile(self, filepath): pass
class Solution: # @param {integer[]} nums # @return {integer} def singleNumber(self, nums): a = set(nums) a = sum(a)*2 singleNumber = a - sum(nums) return singleNumber
class Solution: def single_number(self, nums): a = set(nums) a = sum(a) * 2 single_number = a - sum(nums) return singleNumber
#!/usr/bin/env python3 # Transistors. "2N3904" "2SC1815" # NPN? "2SA9012" "2SA1015" # PNP?
"""2N3904""" '2SC1815' '2SA9012' '2SA1015'
# coding: utf-8 __all__ = ['EikonError'] class EikonError(Exception): """ Base class for exceptions specific to Eikon platform. """ def __init__(self, code, message): """ Parameters ---------- code: int message: string Indicate the sort direction. Possible values are 'asc' or 'desc'. The default value is 'asc' """ self.code = code self.message = message def __str__(self): return 'Error code {} | {}'.format(self.code, self.message)
__all__ = ['EikonError'] class Eikonerror(Exception): """ Base class for exceptions specific to Eikon platform. """ def __init__(self, code, message): """ Parameters ---------- code: int message: string Indicate the sort direction. Possible values are 'asc' or 'desc'. The default value is 'asc' """ self.code = code self.message = message def __str__(self): return 'Error code {} | {}'.format(self.code, self.message)
class Car: # constructor def __init__(self,name,fuel,consumption,passengers,capacity): self.name = name self.fuel = fuel self.consumption = consumption self.km = 0.0 self.passengers = passengers self.capacity = capacity # Behavior def print_car(self): print(f'--- Car {self.name} ---\n| km: {self.km}\n| fuel: {self.fuel}\n| Passengers: {self.passengers}') def move(self,km): if( km <= (self.fuel / self.consumption)): ## move self.km += km self.fuel -= km / self.consumption else: # move as fas as car can # calculate max km maxKm = self.fuel / self.consumption self.km += maxKm self.fuel = 0 print(f"Car {self.name} cannot move further. Please go to the nearest gas station!") def get_passenger(self,passanger): if (self.capacity > len(self.passengers)): # get passenger self.passengers.append(passanger) else: # cannot print(f"There is no space for Passenger {passanger}") def get_fuel(self,newFuel): self.fuel += newFuel def get_passengers(self,passengers): if len(passengers) < 2: # warn print("Please use approprate function") else: for passanger in passengers: self.get_passenger(passanger)
class Car: def __init__(self, name, fuel, consumption, passengers, capacity): self.name = name self.fuel = fuel self.consumption = consumption self.km = 0.0 self.passengers = passengers self.capacity = capacity def print_car(self): print(f'--- Car {self.name} ---\n| km: {self.km}\n| fuel: {self.fuel}\n| Passengers: {self.passengers}') def move(self, km): if km <= self.fuel / self.consumption: self.km += km self.fuel -= km / self.consumption else: max_km = self.fuel / self.consumption self.km += maxKm self.fuel = 0 print(f'Car {self.name} cannot move further. Please go to the nearest gas station!') def get_passenger(self, passanger): if self.capacity > len(self.passengers): self.passengers.append(passanger) else: print(f'There is no space for Passenger {passanger}') def get_fuel(self, newFuel): self.fuel += newFuel def get_passengers(self, passengers): if len(passengers) < 2: print('Please use approprate function') else: for passanger in passengers: self.get_passenger(passanger)
name = "pyilmbase" version = "2.1.0" description = \ """ IlmBase Python bindings """ variants = [ ["platform-linux"] ] requires = [ "ilmbase-%s" % (version), "python", "boost" ] uuid = "repository.pyilmbase" def commands(): env.PATH.prepend("{root}/bin") env.LD_LIBRARY_PATH.prepend("{root}/lib") env.PYTHONPATH.append("{root}/lib/python2.7/site-packages")
name = 'pyilmbase' version = '2.1.0' description = '\n IlmBase Python bindings\n ' variants = [['platform-linux']] requires = ['ilmbase-%s' % version, 'python', 'boost'] uuid = 'repository.pyilmbase' def commands(): env.PATH.prepend('{root}/bin') env.LD_LIBRARY_PATH.prepend('{root}/lib') env.PYTHONPATH.append('{root}/lib/python2.7/site-packages')
vector = [{"name": "John Doe", "age": 37}, {"name": "Anna Doe", "age": 35}] # for item in vector: # print(item["name"]) print(list(map(lambda item: item["name"], vector)))
vector = [{'name': 'John Doe', 'age': 37}, {'name': 'Anna Doe', 'age': 35}] print(list(map(lambda item: item['name'], vector)))
# -*- coding: utf-8 -*- """ Created on Sat Feb 9 19:48:15 2019 @author: Utente """ #Exercises Chapter 3 #3.2 do_four def do_twice(func, arg): func(arg) func(arg) def print_twice(arg): print(arg) print(arg) def do_four(func, arg): do_twice(func, arg) do_twice(func, arg) do_twice(print_twice, 'cazzo vuoi') print('') do_four(print_twice, 'cazzo vuoi') #3.3 grid def re_do_twice(f): f() f() def re_do_four(f): re_do_twice(f) re_do_twice(f) def print_beam(): print('+ - - - -', end=' ') def print_post(): print('| ', end=' ') def print_beams(): re_do_twice(print_beam) print('+') def print_posts(): re_do_twice(print_post) print('|') def print_row(): print_beams() re_do_four(print_posts) def print_grid(): re_do_twice(print_row) print_beams() print_grid() #3.3 grid part two def one_four_one(f, g, h): f() re_do_four(g) h() def print_A(): print('+', end=' ') def print_Z(): print('-', end=' ') def print_C(): print('|', end=' ') def print_O(): print('O', end=' ') def print_end(): print(' ') def nothing(): "do nothing" def print1beam(): one_four_one(nothing, print_Z, print_A) def print1post(): one_four_one(nothing, print_O, print_C) def print4beams(): one_four_one(print_A, print1beam, print_end) def print4posts(): one_four_one(print_C, print1post, print_end) def print_row(): one_four_one(nothing, print4posts, print4beams) def print_grid(): one_four_one(print4beams, print_row, nothing) print_grid()
""" Created on Sat Feb 9 19:48:15 2019 @author: Utente """ def do_twice(func, arg): func(arg) func(arg) def print_twice(arg): print(arg) print(arg) def do_four(func, arg): do_twice(func, arg) do_twice(func, arg) do_twice(print_twice, 'cazzo vuoi') print('') do_four(print_twice, 'cazzo vuoi') def re_do_twice(f): f() f() def re_do_four(f): re_do_twice(f) re_do_twice(f) def print_beam(): print('+ - - - -', end=' ') def print_post(): print('| ', end=' ') def print_beams(): re_do_twice(print_beam) print('+') def print_posts(): re_do_twice(print_post) print('|') def print_row(): print_beams() re_do_four(print_posts) def print_grid(): re_do_twice(print_row) print_beams() print_grid() def one_four_one(f, g, h): f() re_do_four(g) h() def print_a(): print('+', end=' ') def print_z(): print('-', end=' ') def print_c(): print('|', end=' ') def print_o(): print('O', end=' ') def print_end(): print(' ') def nothing(): """do nothing""" def print1beam(): one_four_one(nothing, print_Z, print_A) def print1post(): one_four_one(nothing, print_O, print_C) def print4beams(): one_four_one(print_A, print1beam, print_end) def print4posts(): one_four_one(print_C, print1post, print_end) def print_row(): one_four_one(nothing, print4posts, print4beams) def print_grid(): one_four_one(print4beams, print_row, nothing) print_grid()
class FormattedWord: def __init__(self, word, capitalize=False) -> None: self.word = word self.capitalize = capitalize class Sentence(list): def __init__(self, plain_text): for word in plain_text.split(' '): self.append(FormattedWord(word)) def __str__(self) -> str: return ' '.join([ formatted.word.upper() if formatted.capitalize else formatted.word for formatted in self ]) if __name__ == '__main__': sentence = Sentence('hello world') sentence[1].capitalize = True print(sentence)
class Formattedword: def __init__(self, word, capitalize=False) -> None: self.word = word self.capitalize = capitalize class Sentence(list): def __init__(self, plain_text): for word in plain_text.split(' '): self.append(formatted_word(word)) def __str__(self) -> str: return ' '.join([formatted.word.upper() if formatted.capitalize else formatted.word for formatted in self]) if __name__ == '__main__': sentence = sentence('hello world') sentence[1].capitalize = True print(sentence)
""" mat data format { 1989: { 'AKS': { 2: (0.0534,0.1453) # age 2 (maturation rate, adult equivalent factor), 3: (0.0534,0.1453), # same format for age 3, 4: (0.0534,0.1453) # same format for age 4 }, ... }, ... } """ def parse_mat(file): years = {} curr_year = None for line in file: if not line.startswith(" "): curr_year = int(line) years[curr_year] = {} else: row = line.split() stock = row[0].replace(",", "") years[curr_year][stock] = { 2: (float(row[1]), float(row[2])), 3: (float(row[3]), float(row[4])), 4: (float(row[5]), float(row[6])), } return years def write_mat(data, file): for yr, stocks in sorted(data.items()): file.write(f"{yr}\n") for name, stock in sorted(stocks.items()): file.write( f" {name}, {stock[2][0]:6.4f} {stock[2][1]:6.4f} {stock[3][0]:6.4f} {stock[3][1]:6.4f} {stock[4][0]:6.4f} {stock[4][1]:6.4f}\n" ) def parse_msc(file): """ format: {'maturation_file': 'input/hanford.mat', 'stocks': [('AKS', 'Alaska Spring'), ('BON', 'Bonneville'), ('CWF', 'Cowlitz Fall'), ('GSH', 'Georgia Strait Hatchery'), ('LRW', 'Lewis River Wild'), ('ORC', 'Oregon Coastal'), ('RBH', 'Robertson Creek Hatchery'), ('RBT', 'WCVI Wild'), ('SPR', 'Spring Creek'), ('URB', 'Columbia River Upriver Bright'), ('WSH', 'Willamette Spring')]} """ msc = {"maturation_file": next(file).split()[0], "stocks": []} for line in file: row = line.split(",") msc["stocks"].append((row[0], row[1].strip())) return msc def write_msc(data, file): file.write(f"{data['maturation_file']} , Name of maturation data file\n") for stock in data["stocks"]: file.write(f"{stock[0]}, {stock[1]}\n")
""" mat data format { 1989: { 'AKS': { 2: (0.0534,0.1453) # age 2 (maturation rate, adult equivalent factor), 3: (0.0534,0.1453), # same format for age 3, 4: (0.0534,0.1453) # same format for age 4 }, ... }, ... } """ def parse_mat(file): years = {} curr_year = None for line in file: if not line.startswith(' '): curr_year = int(line) years[curr_year] = {} else: row = line.split() stock = row[0].replace(',', '') years[curr_year][stock] = {2: (float(row[1]), float(row[2])), 3: (float(row[3]), float(row[4])), 4: (float(row[5]), float(row[6]))} return years def write_mat(data, file): for (yr, stocks) in sorted(data.items()): file.write(f'{yr}\n') for (name, stock) in sorted(stocks.items()): file.write(f' {name}, {stock[2][0]:6.4f} {stock[2][1]:6.4f} {stock[3][0]:6.4f} {stock[3][1]:6.4f} {stock[4][0]:6.4f} {stock[4][1]:6.4f}\n') def parse_msc(file): """ format: {'maturation_file': 'input/hanford.mat', 'stocks': [('AKS', 'Alaska Spring'), ('BON', 'Bonneville'), ('CWF', 'Cowlitz Fall'), ('GSH', 'Georgia Strait Hatchery'), ('LRW', 'Lewis River Wild'), ('ORC', 'Oregon Coastal'), ('RBH', 'Robertson Creek Hatchery'), ('RBT', 'WCVI Wild'), ('SPR', 'Spring Creek'), ('URB', 'Columbia River Upriver Bright'), ('WSH', 'Willamette Spring')]} """ msc = {'maturation_file': next(file).split()[0], 'stocks': []} for line in file: row = line.split(',') msc['stocks'].append((row[0], row[1].strip())) return msc def write_msc(data, file): file.write(f"{data['maturation_file']} , Name of maturation data file\n") for stock in data['stocks']: file.write(f'{stock[0]}, {stock[1]}\n')
casa = float(input('Valor da casa: R$')) salario = float(input('Salario do comprador R$')) anos = int(input('Quantos anos de financiamento? ')) prestacao = casa / (anos * 12) minimo = salario * 30 / 100 print('Para pagar uma casa de R${:.2f} em {} anos'.format(casa, anos)) if prestacao < minimo: print('Emprestimo pode ser CONCEDITO!') else: print('Emprestimo NEGADO!')
casa = float(input('Valor da casa: R$')) salario = float(input('Salario do comprador R$')) anos = int(input('Quantos anos de financiamento? ')) prestacao = casa / (anos * 12) minimo = salario * 30 / 100 print('Para pagar uma casa de R${:.2f} em {} anos'.format(casa, anos)) if prestacao < minimo: print('Emprestimo pode ser CONCEDITO!') else: print('Emprestimo NEGADO!')
class AutomatonListHelper: ''' ' Removes repeated elements from a list ' ' @param list array List that will be iterate ' ' @return list ''' @staticmethod def removeDuplicates(array): final_list = [] for num in array: if num not in final_list: final_list.append(num) return final_list ''' ' Returns list element of largest size without elements that have already been visited ' (if all lists have elements visited, returns None) ' If all lists are of size 1, return None and update stack of states to be processed ' ' @param list array List to be iterate ' @param dictionary visited Elements to be ignored ' @param list stackProcess Stack that will be filled if all lists are of size 1 ' ' @return string | int | float | None ''' @staticmethod def largestElementSize_NotVisited(array, visited, stackProcess): if not array: return None highestIndex = 0 highestLength = 0 for i in range(len(array)): equals = False s = '' if len(array[i]) > highestLength: for item in array[i]: s += item if visited.get(s) != None: equals = True if not equals: highestIndex = i highestLength = len(array[i]) elif len(array[i]) == highestLength: s = '' for item in array[i]: s += item if visited.get(s) != None: equals = True if not equals: highestIndex = i highestLength = len(array[i]) if highestLength == 1: for item in array: if item: item = item[0] # If the element is not in the stack and has not been processed, put it in if stackProcess.count(item) == 0 and visited.get(item) == None: stackProcess.append(item) return None elif highestLength == 0: return None else: return array[highestIndex]
class Automatonlisthelper: """ ' Removes repeated elements from a list ' ' @param list array List that will be iterate ' ' @return list """ @staticmethod def remove_duplicates(array): final_list = [] for num in array: if num not in final_list: final_list.append(num) return final_list "\n ' Returns list element of largest size without elements that have already been visited \n ' (if all lists have elements visited, returns None)\n ' If all lists are of size 1, return None and update stack of states to be processed\n '\n ' @param list array List to be iterate\n ' @param dictionary visited Elements to be ignored\n ' @param list stackProcess Stack that will be filled if all lists are of size 1\n '\n ' @return string | int | float | None\n " @staticmethod def largest_element_size__not_visited(array, visited, stackProcess): if not array: return None highest_index = 0 highest_length = 0 for i in range(len(array)): equals = False s = '' if len(array[i]) > highestLength: for item in array[i]: s += item if visited.get(s) != None: equals = True if not equals: highest_index = i highest_length = len(array[i]) elif len(array[i]) == highestLength: s = '' for item in array[i]: s += item if visited.get(s) != None: equals = True if not equals: highest_index = i highest_length = len(array[i]) if highestLength == 1: for item in array: if item: item = item[0] if stackProcess.count(item) == 0 and visited.get(item) == None: stackProcess.append(item) return None elif highestLength == 0: return None else: return array[highestIndex]
#! /usr/bin/python3 def print_sorted_dictionary_pairs(dict): for key in sorted(dict): print(key, dict[key]) def add_or_change_dictionary_value(dict, key, value): dict[key] = value def delete_dictionary_entry(dict, key): if key in dict: del dict[key] else: print(key, 'not found in dictionary') def dictionary_from_file(filename): try: file = open(filename, 'r') except: print('Cannot open file', filename) else: dict = {} for line in file: list = line.split() key = list[0] value = list[1] dict[key] = value file.close() return dict names_emails = dictionary_from_file('names_emails.txt') for key in names_emails: print(key, names_emails[key]) print_sorted_dictionary_pairs(names_emails) print() add_or_change_dictionary_value(names_emails, 'George', 'george@hotmail.com') add_or_change_dictionary_value(names_emails, 'Alan', 'alan.hurley@gmail.com') print('Entries: ', len(names_emails)) print_sorted_dictionary_pairs(names_emails) print() delete_dictionary_entry(names_emails, 'xxxx') delete_dictionary_entry(names_emails, 'George') print_sorted_dictionary_pairs(names_emails) print('Entries:', len(names_emails))
def print_sorted_dictionary_pairs(dict): for key in sorted(dict): print(key, dict[key]) def add_or_change_dictionary_value(dict, key, value): dict[key] = value def delete_dictionary_entry(dict, key): if key in dict: del dict[key] else: print(key, 'not found in dictionary') def dictionary_from_file(filename): try: file = open(filename, 'r') except: print('Cannot open file', filename) else: dict = {} for line in file: list = line.split() key = list[0] value = list[1] dict[key] = value file.close() return dict names_emails = dictionary_from_file('names_emails.txt') for key in names_emails: print(key, names_emails[key]) print_sorted_dictionary_pairs(names_emails) print() add_or_change_dictionary_value(names_emails, 'George', 'george@hotmail.com') add_or_change_dictionary_value(names_emails, 'Alan', 'alan.hurley@gmail.com') print('Entries: ', len(names_emails)) print_sorted_dictionary_pairs(names_emails) print() delete_dictionary_entry(names_emails, 'xxxx') delete_dictionary_entry(names_emails, 'George') print_sorted_dictionary_pairs(names_emails) print('Entries:', len(names_emails))
######################################################################## def clamp(value, minimum=0.0, maximum=1.0): return min(maximum, max(minimum, value)) ######################################################################## def find_all_by_name(name, list_entities): name = name.lower() for entity in list_entities: if entity.match(name): yield entity ######################################################################## def double_find_by_name(name, list_entities): """First try to find an exact match, then try to do a less exact match""" name = name.lower() for entity in list_entities: if entity.match_full(name): return entity for entity in list_entities: if entity.match(name): return entity
def clamp(value, minimum=0.0, maximum=1.0): return min(maximum, max(minimum, value)) def find_all_by_name(name, list_entities): name = name.lower() for entity in list_entities: if entity.match(name): yield entity def double_find_by_name(name, list_entities): """First try to find an exact match, then try to do a less exact match""" name = name.lower() for entity in list_entities: if entity.match_full(name): return entity for entity in list_entities: if entity.match(name): return entity
def printPacket(packet): print(packet.to_json())
def print_packet(packet): print(packet.to_json())
# -*- coding: utf-8 -*- #----------- #@utool.indent_func('[harn]') @profile def test_configurations(ibs, acfgstr_name_list, test_cfg_name_list): r""" Test harness driver function CommandLine: python -m ibeis.expt.harness --exec-test_configurations --verbtd python -m ibeis.expt.harness --exec-test_configurations --verbtd --draw-rank-cdf --show Example: >>> # SLOW_DOCTEST >>> from ibeis.expt.harness import * # NOQA >>> import ibeis >>> ibs = ibeis.opendb('PZ_MTEST') >>> acfgstr_name_list = ut.get_argval(('--aidcfg', '--acfg', '-a'), type_=list, default=['candidacy:qsize=20,dper_name=1,dsize=10', 'candidacy:qsize=20,dper_name=10,dsize=100']) >>> test_cfg_name_list = ut.get_argval('-t', type_=list, default=['custom', 'custom:fg_on=False']) >>> test_configurations(ibs, acfgstr_name_list, test_cfg_name_list) >>> ut.show_if_requested() """ testres_list = run_test_configurations2(ibs, acfgstr_name_list, test_cfg_name_list) for testres in testres_list: if testres is None: return else: experiment_printres.print_results(ibs, testres) experiment_drawing.draw_results(ibs, testres) return testres_list #def get_cmdline_testres(): # ibs, qaids, daids = main_helpers.testdata_expanded_aids(verbose=False) # test_cfg_name_list = ut.get_argval('-t', type_=list, default=['custom', 'custom:fg_on=False']) # testres = run_test_configurations(ibs, qaids, daids, test_cfg_name_list) # return ibs, testres
@profile def test_configurations(ibs, acfgstr_name_list, test_cfg_name_list): """ Test harness driver function CommandLine: python -m ibeis.expt.harness --exec-test_configurations --verbtd python -m ibeis.expt.harness --exec-test_configurations --verbtd --draw-rank-cdf --show Example: >>> # SLOW_DOCTEST >>> from ibeis.expt.harness import * # NOQA >>> import ibeis >>> ibs = ibeis.opendb('PZ_MTEST') >>> acfgstr_name_list = ut.get_argval(('--aidcfg', '--acfg', '-a'), type_=list, default=['candidacy:qsize=20,dper_name=1,dsize=10', 'candidacy:qsize=20,dper_name=10,dsize=100']) >>> test_cfg_name_list = ut.get_argval('-t', type_=list, default=['custom', 'custom:fg_on=False']) >>> test_configurations(ibs, acfgstr_name_list, test_cfg_name_list) >>> ut.show_if_requested() """ testres_list = run_test_configurations2(ibs, acfgstr_name_list, test_cfg_name_list) for testres in testres_list: if testres is None: return else: experiment_printres.print_results(ibs, testres) experiment_drawing.draw_results(ibs, testres) return testres_list
# # PySNMP MIB module IANA-PWE3-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-PWE3-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:30:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Gauge32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, IpAddress, iso, ModuleIdentity, mib_2, TimeTicks, Counter32, NotificationType, Bits, ObjectIdentity, MibIdentifier, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "IpAddress", "iso", "ModuleIdentity", "mib-2", "TimeTicks", "Counter32", "NotificationType", "Bits", "ObjectIdentity", "MibIdentifier", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") ianaPwe3MIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 174)) ianaPwe3MIB.setRevisions(('2009-06-11 00:00',)) if mibBuilder.loadTexts: ianaPwe3MIB.setLastUpdated('200906110000Z') if mibBuilder.loadTexts: ianaPwe3MIB.setOrganization('IANA') class IANAPwTypeTC(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32767)) namedValues = NamedValues(("other", 0), ("frameRelayDlciMartiniMode", 1), ("atmAal5SduVcc", 2), ("atmTransparent", 3), ("ethernetTagged", 4), ("ethernet", 5), ("hdlc", 6), ("ppp", 7), ("cem", 8), ("atmCellNto1Vcc", 9), ("atmCellNto1Vpc", 10), ("ipLayer2Transport", 11), ("atmCell1to1Vcc", 12), ("atmCell1to1Vpc", 13), ("atmAal5PduVcc", 14), ("frameRelayPortMode", 15), ("cep", 16), ("e1Satop", 17), ("t1Satop", 18), ("e3Satop", 19), ("t3Satop", 20), ("basicCesPsn", 21), ("basicTdmIp", 22), ("tdmCasCesPsn", 23), ("tdmCasTdmIp", 24), ("frDlci", 25), ("wildcard", 32767)) class IANAPwPsnTypeTC(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6)) namedValues = NamedValues(("mpls", 1), ("l2tp", 2), ("udpOverIp", 3), ("mplsOverIp", 4), ("mplsOverGre", 5), ("other", 6)) class IANAPwCapabilities(TextualConvention, Bits): status = 'current' namedValues = NamedValues(("pwStatusIndication", 0), ("pwVCCV", 1)) mibBuilder.exportSymbols("IANA-PWE3-MIB", IANAPwCapabilities=IANAPwCapabilities, IANAPwPsnTypeTC=IANAPwPsnTypeTC, ianaPwe3MIB=ianaPwe3MIB, IANAPwTypeTC=IANAPwTypeTC, PYSNMP_MODULE_ID=ianaPwe3MIB)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (gauge32, counter64, mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, ip_address, iso, module_identity, mib_2, time_ticks, counter32, notification_type, bits, object_identity, mib_identifier, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'IpAddress', 'iso', 'ModuleIdentity', 'mib-2', 'TimeTicks', 'Counter32', 'NotificationType', 'Bits', 'ObjectIdentity', 'MibIdentifier', 'Integer32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') iana_pwe3_mib = module_identity((1, 3, 6, 1, 2, 1, 174)) ianaPwe3MIB.setRevisions(('2009-06-11 00:00',)) if mibBuilder.loadTexts: ianaPwe3MIB.setLastUpdated('200906110000Z') if mibBuilder.loadTexts: ianaPwe3MIB.setOrganization('IANA') class Ianapwtypetc(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32767)) named_values = named_values(('other', 0), ('frameRelayDlciMartiniMode', 1), ('atmAal5SduVcc', 2), ('atmTransparent', 3), ('ethernetTagged', 4), ('ethernet', 5), ('hdlc', 6), ('ppp', 7), ('cem', 8), ('atmCellNto1Vcc', 9), ('atmCellNto1Vpc', 10), ('ipLayer2Transport', 11), ('atmCell1to1Vcc', 12), ('atmCell1to1Vpc', 13), ('atmAal5PduVcc', 14), ('frameRelayPortMode', 15), ('cep', 16), ('e1Satop', 17), ('t1Satop', 18), ('e3Satop', 19), ('t3Satop', 20), ('basicCesPsn', 21), ('basicTdmIp', 22), ('tdmCasCesPsn', 23), ('tdmCasTdmIp', 24), ('frDlci', 25), ('wildcard', 32767)) class Ianapwpsntypetc(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6)) named_values = named_values(('mpls', 1), ('l2tp', 2), ('udpOverIp', 3), ('mplsOverIp', 4), ('mplsOverGre', 5), ('other', 6)) class Ianapwcapabilities(TextualConvention, Bits): status = 'current' named_values = named_values(('pwStatusIndication', 0), ('pwVCCV', 1)) mibBuilder.exportSymbols('IANA-PWE3-MIB', IANAPwCapabilities=IANAPwCapabilities, IANAPwPsnTypeTC=IANAPwPsnTypeTC, ianaPwe3MIB=ianaPwe3MIB, IANAPwTypeTC=IANAPwTypeTC, PYSNMP_MODULE_ID=ianaPwe3MIB)
# expected data for tests using FBgn0031208.gff and FBgn0031208.gtf files # list the children and their expected first-order parents for the GFF test file. GFF_parent_check_level_1 = {'FBtr0300690':['FBgn0031208'], 'FBtr0300689':['FBgn0031208'], 'CG11023:1':['FBtr0300689','FBtr0300690'], 'five_prime_UTR_FBgn0031208:1_737':['FBtr0300689','FBtr0300690'], 'CDS_FBgn0031208:1_737':['FBtr0300689','FBtr0300690'], 'intron_FBgn0031208:1_FBgn0031208:2':['FBtr0300690'], 'intron_FBgn0031208:1_FBgn0031208:3':['FBtr0300689'], 'FBgn0031208:3':['FBtr0300689'], 'CDS_FBgn0031208:3_737':['FBtr0300689'], 'CDS_FBgn0031208:2_737':['FBtr0300690'], 'exon:chr2L:8193-8589:+':['FBtr0300690'], 'intron_FBgn0031208:2_FBgn0031208:4':['FBtr0300690'], 'three_prime_UTR_FBgn0031208:3_737':['FBtr0300689'], 'FBgn0031208:4':['FBtr0300690'], 'CDS_FBgn0031208:4_737':['FBtr0300690'], 'three_prime_UTR_FBgn0031208:4_737':['FBtr0300690'], } # and second-level . . . they should all be grandparents of the same gene. GFF_parent_check_level_2 = { 'CG11023:1':['FBgn0031208'], 'five_prime_UTR_FBgn0031208:1_737':['FBgn0031208'], 'CDS_FBgn0031208:1_737':['FBgn0031208'], 'intron_FBgn0031208:1_FBgn0031208:2':['FBgn0031208'], 'intron_FBgn0031208:1_FBgn0031208:3':['FBgn0031208'], 'FBgn0031208:3':['FBgn0031208'], 'CDS_FBgn0031208:3_737':['FBgn0031208'], 'CDS_FBgn0031208:2_737':['FBgn0031208'], 'exon:chr2L:8193-8589:+':['FBgn0031208'], 'intron_FBgn0031208:2_FBgn0031208:4':['FBgn0031208'], 'three_prime_UTR_FBgn0031208:3_737':['FBgn0031208'], 'FBgn0031208:4':['FBgn0031208'], 'CDS_FBgn0031208:4_737':['FBgn0031208'], 'three_prime_UTR_FBgn0031208:4_737':['FBgn0031208'], } # Same thing for GTF test file . . . GTF_parent_check_level_1 = { 'exon:chr2L:7529-8116:+':['FBtr0300689'], 'exon:chr2L:7529-8116:+_1':['FBtr0300690'], 'exon:chr2L:8193-9484:+':['FBtr0300689'], 'exon:chr2L:8193-8589:+':['FBtr0300690'], 'exon:chr2L:8668-9484:+':['FBtr0300690'], 'exon:chr2L:10000-11000:-':['transcript_Fk_gene_1'], 'exon:chr2L:11500-12500:-':['transcript_Fk_gene_2'], 'CDS:chr2L:7680-8116:+':['FBtr0300689'], 'CDS:chr2L:7680-8116:+_1':['FBtr0300690'], 'CDS:chr2L:8193-8610:+':['FBtr0300689'], 'CDS:chr2L:8193-8589:+':['FBtr0300690'], 'CDS:chr2L:8668-9276:+':['FBtr0300690'], 'CDS:chr2L:10000-11000:-':['transcript_Fk_gene_1'], 'FBtr0300689':['FBgn0031208'], 'FBtr0300690':['FBgn0031208'], 'transcript_Fk_gene_1':['Fk_gene_1'], 'transcript_Fk_gene_2':['Fk_gene_2'], 'start_codon:chr2L:7680-7682:+':['FBtr0300689'], 'start_codon:chr2L:7680-7682:+_1':['FBtr0300690'], 'start_codon:chr2L:10000-11002:-':['transcript_Fk_gene_1'], 'stop_codon:chr2L:8611-8613:+':['FBtr0300689'], 'stop_codon:chr2L:9277-9279:+':['FBtr0300690'], 'stop_codon:chr2L:11001-11003:-':['transcript_Fk_gene_1'], } GTF_parent_check_level_2 = { 'exon:chr2L:7529-8116:+':['FBgn0031208'], 'exon:chr2L:8193-9484:+':['FBgn0031208'], 'exon:chr2L:8193-8589:+':['FBgn0031208'], 'exon:chr2L:8668-9484:+':['FBgn0031208'], 'exon:chr2L:10000-11000:-':['Fk_gene_1'], 'exon:chr2L:11500-12500:-':['Fk_gene_2'], 'CDS:chr2L:7680-8116:+':['FBgn0031208'], 'CDS:chr2L:8193-8610:+':['FBgn0031208'], 'CDS:chr2L:8193-8589:+':['FBgn0031208'], 'CDS:chr2L:8668-9276:+':['FBgn0031208'], 'CDS:chr2L:10000-11000:-':['Fk_gene_1'], 'FBtr0300689':[], 'FBtr0300690':[], 'transcript_Fk_gene_1':[], 'transcript_Fk_gene_2':[], 'start_codon:chr2L:7680-7682:+':['FBgn0031208'], 'start_codon:chr2L:10000-11002:-':['Fk_gene_1'], 'stop_codon:chr2L:8611-8613:+':['FBgn0031208'], 'stop_codon:chr2L:9277-9279:+':['FBgn0031208'], 'stop_codon:chr2L:11001-11003:-':['Fk_gene_1'], } expected_feature_counts = { 'gff3':{'gene':3, 'mRNA':4, 'exon':6, 'CDS':5, 'five_prime_UTR':1, 'intron':3, 'pcr_product':1, 'protein':2, 'three_prime_UTR':2}, 'gtf':{ #'gene':3, # 'mRNA':4, 'CDS':6, 'exon':7, 'start_codon':3, 'stop_codon':3} } expected_features = {'gff3':['gene', 'mRNA', 'protein', 'five_prime_UTR', 'three_prime_UTR', 'pcr_product', 'CDS', 'exon', 'intron'], 'gtf':['gene', 'mRNA', 'CDS', 'exon', 'start_codon', 'stop_codon']}
gff_parent_check_level_1 = {'FBtr0300690': ['FBgn0031208'], 'FBtr0300689': ['FBgn0031208'], 'CG11023:1': ['FBtr0300689', 'FBtr0300690'], 'five_prime_UTR_FBgn0031208:1_737': ['FBtr0300689', 'FBtr0300690'], 'CDS_FBgn0031208:1_737': ['FBtr0300689', 'FBtr0300690'], 'intron_FBgn0031208:1_FBgn0031208:2': ['FBtr0300690'], 'intron_FBgn0031208:1_FBgn0031208:3': ['FBtr0300689'], 'FBgn0031208:3': ['FBtr0300689'], 'CDS_FBgn0031208:3_737': ['FBtr0300689'], 'CDS_FBgn0031208:2_737': ['FBtr0300690'], 'exon:chr2L:8193-8589:+': ['FBtr0300690'], 'intron_FBgn0031208:2_FBgn0031208:4': ['FBtr0300690'], 'three_prime_UTR_FBgn0031208:3_737': ['FBtr0300689'], 'FBgn0031208:4': ['FBtr0300690'], 'CDS_FBgn0031208:4_737': ['FBtr0300690'], 'three_prime_UTR_FBgn0031208:4_737': ['FBtr0300690']} gff_parent_check_level_2 = {'CG11023:1': ['FBgn0031208'], 'five_prime_UTR_FBgn0031208:1_737': ['FBgn0031208'], 'CDS_FBgn0031208:1_737': ['FBgn0031208'], 'intron_FBgn0031208:1_FBgn0031208:2': ['FBgn0031208'], 'intron_FBgn0031208:1_FBgn0031208:3': ['FBgn0031208'], 'FBgn0031208:3': ['FBgn0031208'], 'CDS_FBgn0031208:3_737': ['FBgn0031208'], 'CDS_FBgn0031208:2_737': ['FBgn0031208'], 'exon:chr2L:8193-8589:+': ['FBgn0031208'], 'intron_FBgn0031208:2_FBgn0031208:4': ['FBgn0031208'], 'three_prime_UTR_FBgn0031208:3_737': ['FBgn0031208'], 'FBgn0031208:4': ['FBgn0031208'], 'CDS_FBgn0031208:4_737': ['FBgn0031208'], 'three_prime_UTR_FBgn0031208:4_737': ['FBgn0031208']} gtf_parent_check_level_1 = {'exon:chr2L:7529-8116:+': ['FBtr0300689'], 'exon:chr2L:7529-8116:+_1': ['FBtr0300690'], 'exon:chr2L:8193-9484:+': ['FBtr0300689'], 'exon:chr2L:8193-8589:+': ['FBtr0300690'], 'exon:chr2L:8668-9484:+': ['FBtr0300690'], 'exon:chr2L:10000-11000:-': ['transcript_Fk_gene_1'], 'exon:chr2L:11500-12500:-': ['transcript_Fk_gene_2'], 'CDS:chr2L:7680-8116:+': ['FBtr0300689'], 'CDS:chr2L:7680-8116:+_1': ['FBtr0300690'], 'CDS:chr2L:8193-8610:+': ['FBtr0300689'], 'CDS:chr2L:8193-8589:+': ['FBtr0300690'], 'CDS:chr2L:8668-9276:+': ['FBtr0300690'], 'CDS:chr2L:10000-11000:-': ['transcript_Fk_gene_1'], 'FBtr0300689': ['FBgn0031208'], 'FBtr0300690': ['FBgn0031208'], 'transcript_Fk_gene_1': ['Fk_gene_1'], 'transcript_Fk_gene_2': ['Fk_gene_2'], 'start_codon:chr2L:7680-7682:+': ['FBtr0300689'], 'start_codon:chr2L:7680-7682:+_1': ['FBtr0300690'], 'start_codon:chr2L:10000-11002:-': ['transcript_Fk_gene_1'], 'stop_codon:chr2L:8611-8613:+': ['FBtr0300689'], 'stop_codon:chr2L:9277-9279:+': ['FBtr0300690'], 'stop_codon:chr2L:11001-11003:-': ['transcript_Fk_gene_1']} gtf_parent_check_level_2 = {'exon:chr2L:7529-8116:+': ['FBgn0031208'], 'exon:chr2L:8193-9484:+': ['FBgn0031208'], 'exon:chr2L:8193-8589:+': ['FBgn0031208'], 'exon:chr2L:8668-9484:+': ['FBgn0031208'], 'exon:chr2L:10000-11000:-': ['Fk_gene_1'], 'exon:chr2L:11500-12500:-': ['Fk_gene_2'], 'CDS:chr2L:7680-8116:+': ['FBgn0031208'], 'CDS:chr2L:8193-8610:+': ['FBgn0031208'], 'CDS:chr2L:8193-8589:+': ['FBgn0031208'], 'CDS:chr2L:8668-9276:+': ['FBgn0031208'], 'CDS:chr2L:10000-11000:-': ['Fk_gene_1'], 'FBtr0300689': [], 'FBtr0300690': [], 'transcript_Fk_gene_1': [], 'transcript_Fk_gene_2': [], 'start_codon:chr2L:7680-7682:+': ['FBgn0031208'], 'start_codon:chr2L:10000-11002:-': ['Fk_gene_1'], 'stop_codon:chr2L:8611-8613:+': ['FBgn0031208'], 'stop_codon:chr2L:9277-9279:+': ['FBgn0031208'], 'stop_codon:chr2L:11001-11003:-': ['Fk_gene_1']} expected_feature_counts = {'gff3': {'gene': 3, 'mRNA': 4, 'exon': 6, 'CDS': 5, 'five_prime_UTR': 1, 'intron': 3, 'pcr_product': 1, 'protein': 2, 'three_prime_UTR': 2}, 'gtf': {'CDS': 6, 'exon': 7, 'start_codon': 3, 'stop_codon': 3}} expected_features = {'gff3': ['gene', 'mRNA', 'protein', 'five_prime_UTR', 'three_prime_UTR', 'pcr_product', 'CDS', 'exon', 'intron'], 'gtf': ['gene', 'mRNA', 'CDS', 'exon', 'start_codon', 'stop_codon']}
def user_class(row_series): """ Defines the user class for this trip list. This function takes a single argument, the pandas.Series with person, household and trip_list attributes, and returns a user class string. """ # print row_series if row_series["hh_id"] == "simpson": return "not_real" return "real"
def user_class(row_series): """ Defines the user class for this trip list. This function takes a single argument, the pandas.Series with person, household and trip_list attributes, and returns a user class string. """ if row_series['hh_id'] == 'simpson': return 'not_real' return 'real'
# 1. Even Numbers # Write a program that receives a sequence of numbers (integers), separated by a single space. # It should print a list of only the even numbers. Use filter(). def filter_even(iters): return list(filter(lambda x: x % 2 == 0, iters)) nums = map(int, input().split()) print(filter_even(nums))
def filter_even(iters): return list(filter(lambda x: x % 2 == 0, iters)) nums = map(int, input().split()) print(filter_even(nums))
class Foo: def __init__(self, id): self.id = id def __str__(self): return 'Foo instance id: {}'.format(self.id) class Bar: def __init__(self, id): self.id = id def __str__(self): return 'Bar instance id: {}'.format(self.id) class Baz: def __init__(self, id): self.id = id def __str__(self): return 'Baz instance id: {}'.format(self.id) foo_1 = Foo("to go") foo_2 = Foo("to clean") foo_3 = Foo("to avoid") foo_4 = Foo("to destroy") bar_1 = Bar("the bathroom") bar_2 = Bar("the kitchen") bar_3 = Bar("the bedroom") bar_4 = Bar("the basement") bar_5 = Bar("the garage") my_dictionary = {Foo: [foo_1, foo_2, foo_3, foo_4], Bar: [bar_1, bar_2, bar_3, bar_4, bar_5]} if Baz in my_dictionary: textBatch = my_dictionary[Baz] else: textBatch = [] my_dictionary[Baz] = textBatch textBatch.append(5) # Pass by reference # test = my_dictionary.get(Foo) # print(test) # retest = my_dictionary[Foo] # print(retest) for model_type in my_dictionary: for entity in my_dictionary[model_type]: print(entity) for unit in my_dictionary: print(unit) if Baz in my_dictionary: del my_dictionary[Baz] for model_type in my_dictionary: for entity in my_dictionary[model_type]: print(entity) # # if Foo in my_dictionary: # # for entity in my_dictionary[Foo]: # # print(entity) # my_dictionary[Foo].append(Foo("to dirty")) # for entity in my_dictionary[Foo]: # print(entity) # # # # if Baz in my_dictionary: # # print("Should not see this") # # for entity in my_dictionary[Baz]: # # print(entity) # # else: # # my_dictionary[Baz] = [Baz("big test")] # # # # # # print("\nNow testing for Baz") # # if Baz in my_dictionary: # # for entity in my_dictionary[Baz]: # # print(entity) for unit in my_dictionary: print(unit)
class Foo: def __init__(self, id): self.id = id def __str__(self): return 'Foo instance id: {}'.format(self.id) class Bar: def __init__(self, id): self.id = id def __str__(self): return 'Bar instance id: {}'.format(self.id) class Baz: def __init__(self, id): self.id = id def __str__(self): return 'Baz instance id: {}'.format(self.id) foo_1 = foo('to go') foo_2 = foo('to clean') foo_3 = foo('to avoid') foo_4 = foo('to destroy') bar_1 = bar('the bathroom') bar_2 = bar('the kitchen') bar_3 = bar('the bedroom') bar_4 = bar('the basement') bar_5 = bar('the garage') my_dictionary = {Foo: [foo_1, foo_2, foo_3, foo_4], Bar: [bar_1, bar_2, bar_3, bar_4, bar_5]} if Baz in my_dictionary: text_batch = my_dictionary[Baz] else: text_batch = [] my_dictionary[Baz] = textBatch textBatch.append(5) for model_type in my_dictionary: for entity in my_dictionary[model_type]: print(entity) for unit in my_dictionary: print(unit) if Baz in my_dictionary: del my_dictionary[Baz] for model_type in my_dictionary: for entity in my_dictionary[model_type]: print(entity) for unit in my_dictionary: print(unit)
#=========================================================================== # # Convert decoded data to MQTT messages. # #=========================================================================== #=========================================================================== def convert( config, data ): # List of tuples of ( topic, payload ) where payload is a dictionary. msgs = [] if hasattr( data, "battery" ): topic = config.mqttBattery % data.location payload = { "time" : data.time, "battery" : data.battery, } msgs.append( ( topic, payload ) ) if hasattr( data, "signal" ): topic = config.mqttRssi % data.location payload = { "time" : data.time, # Input is 0->1, convert to 0->100 "rssi" : data.signal * 100, } msgs.append( ( topic, payload ) ) if hasattr( data, "humidity" ): topic = config.mqttHumidity % data.location payload = { "time" : data.time, "humidity" : data.humidity, } msgs.append( ( topic, payload ) ) if hasattr( data, "temperature" ): topic = config.mqttTemp % data.location payload = { "time" : data.time, "temperature" : data.temperature, } msgs.append( ( topic, payload ) ) if hasattr( data, "windSpeed" ): topic = config.mqttWindSpeed % data.location payload = { "time" : data.time, "speed" : data.windSpeed, } msgs.append( ( topic, payload ) ) if hasattr( data, "windDir" ): topic = config.mqttWindDir % data.location payload = { "time" : data.time, "direction" : data.windDir, } msgs.append( ( topic, payload ) ) if hasattr( data, "pressure" ): topic = config.mqttBarometer % data.location payload = { "time" : data.time, "pressure" : data.pressure, } msgs.append( ( topic, payload ) ) if hasattr( data, "rainfall" ): topic = config.mqttRain % data.location payload = { "time" : data.time, "rain" : data.rainfall, } msgs.append( ( topic, payload ) ) return msgs #===========================================================================
def convert(config, data): msgs = [] if hasattr(data, 'battery'): topic = config.mqttBattery % data.location payload = {'time': data.time, 'battery': data.battery} msgs.append((topic, payload)) if hasattr(data, 'signal'): topic = config.mqttRssi % data.location payload = {'time': data.time, 'rssi': data.signal * 100} msgs.append((topic, payload)) if hasattr(data, 'humidity'): topic = config.mqttHumidity % data.location payload = {'time': data.time, 'humidity': data.humidity} msgs.append((topic, payload)) if hasattr(data, 'temperature'): topic = config.mqttTemp % data.location payload = {'time': data.time, 'temperature': data.temperature} msgs.append((topic, payload)) if hasattr(data, 'windSpeed'): topic = config.mqttWindSpeed % data.location payload = {'time': data.time, 'speed': data.windSpeed} msgs.append((topic, payload)) if hasattr(data, 'windDir'): topic = config.mqttWindDir % data.location payload = {'time': data.time, 'direction': data.windDir} msgs.append((topic, payload)) if hasattr(data, 'pressure'): topic = config.mqttBarometer % data.location payload = {'time': data.time, 'pressure': data.pressure} msgs.append((topic, payload)) if hasattr(data, 'rainfall'): topic = config.mqttRain % data.location payload = {'time': data.time, 'rain': data.rainfall} msgs.append((topic, payload)) return msgs
def special_sort(alphabet, s): a = {c: i for i, c in enumerate(alphabet)} return ''.join(sorted(list(s), key=lambda x: a[x.lower()])) a = 'wvutsrqponmlkjihgfedcbaxyz' t = 'camelCasE' print(special_sort(a, t))
def special_sort(alphabet, s): a = {c: i for (i, c) in enumerate(alphabet)} return ''.join(sorted(list(s), key=lambda x: a[x.lower()])) a = 'wvutsrqponmlkjihgfedcbaxyz' t = 'camelCasE' print(special_sort(a, t))
# Next Greater Element I: https://leetcode.com/problems/next-greater-element-i/ # The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. # You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. # For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. # Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. # The simple solution is to for each i in nums1 search for it in 2 and then find the first largest number after that this will run in o(N^2) and o(N) space as we have to append it to a result # This is quite a tricky mouthful of a solution basically we need to create a dictionary of the next highest value of every number # however to do this we will need to implement a stack. Luckily we can bulid this dict in o(N) time and using o(N) space so it ever so slightly optimized # as we will not be evaluating the same two numbers twice class Solution: def nextGreaterElement(self, nums1, nums2): nextGreater = {} stack = [] for num in nums2: while len(stack) > 0 and num > stack[-1]: nextGreater[stack.pop()] = num stack.append(num) # while len(stack) > 0: # nextGreater[stack.pop()] = -1 result = [] for num in nums1: result.append(nextGreater.get(num, -1)) return result # This is a super simple stack scanning solution because we can always see the number we are at and then you can check if the last n numbers were less than its value # this solution will run in o(M+N) time and space as we will have to iterate through both nums array and store the result in a dict or in result # Score Card # Did I need hints? N # Did you finish within 30 min? 10 # Was the solution optimal? Oh yea # Were there any bugs? None submitted with 0 issue first try # 5 5 5 5 = 5
class Solution: def next_greater_element(self, nums1, nums2): next_greater = {} stack = [] for num in nums2: while len(stack) > 0 and num > stack[-1]: nextGreater[stack.pop()] = num stack.append(num) result = [] for num in nums1: result.append(nextGreater.get(num, -1)) return result
''' @Date: 2019-12-22 20:38:38 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors : ywyz @LastEditTime : 2019-12-22 20:52:02 ''' strings = input("Enter the first 12 digits of an ISBN-13 as a string: ") temp = 1 total = 0 for i in strings: if temp % 2 == 0: total += 3 * int(i) else: total += int(i) temp += 1 total = 10 - total % 10 if total == 10: total = 0 strings = strings + str(total) print("The ISBN-13 number is ", strings)
""" @Date: 2019-12-22 20:38:38 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors : ywyz @LastEditTime : 2019-12-22 20:52:02 """ strings = input('Enter the first 12 digits of an ISBN-13 as a string: ') temp = 1 total = 0 for i in strings: if temp % 2 == 0: total += 3 * int(i) else: total += int(i) temp += 1 total = 10 - total % 10 if total == 10: total = 0 strings = strings + str(total) print('The ISBN-13 number is ', strings)
# Generator used for all the Skinned Lanterns lantern variants! lanterns = ["pufferfish", "zombie", "creeper", "skeleton", "wither_skeleton", "bee", "jack_o_lantern", "ghost", "inky", "pinky", "blinky", "clyde", "pacman", "paper_white", "paper_yellow", "paper_orange", "paper_blue", "paper_light_blue", "paper_cyan", "paper_lime", "paper_green", "paper_red", "paper_pink", "paper_brown", "paper_black", "paper_gray", "paper_light_gray", "paper_magenta", "paper_purple", "guardian"] shader_path = "assets/skinnedlanterns/materialmaps/" handheld_path = "assets/skinnedlanterns/lights/item/" material = """ {{ "defaultMaterial": "canvas:{type}_glow", "variants": {{ "facing=north,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=north,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=north,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=north,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=east,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=east,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=east,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=east,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=south,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=south,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=south,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=south,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=west,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=west,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=west,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=west,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=up,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=up,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=up,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=up,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=down,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=down,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=down,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=down,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }} }} }} """ normal_light = """ { "intensity": 0.93, "red": 1.0, "green": 1.0, "blue": 0.8, "worksInFluid": false } """ soul_light = """ { "intensity": 0.93, "red": 0.6, "green": 0.8, "blue": 1.0, "worksInFluid": true } """ for lantern in lanterns: normal = open(shader_path + "block/" + lantern + "_lantern_block.json", "w") soul = open(shader_path + "block/" + lantern + "_soul_lantern_block.json", "w") normal_item = open(shader_path + "item/" + lantern + "_lantern_block.json", "w") soul_item = open(shader_path + "item/" + lantern + "_soul_lantern_block.json", "w") normal_handheld = open(handheld_path + lantern + "_lantern_block.json", "w") soul_handheld = open(handheld_path + lantern + "_soul_lantern_block.json", "w") normal.write(material.format(type = "warm")) soul.write(material.format(type = "luminance")) normal_item.write("{}") soul_item.write("{}") normal_handheld.write(normal_light) soul_handheld.write(soul_light) normal.close() soul.close() normal_item.close() soul_item.close() normal_handheld.close() soul_handheld.close() print("Filegen complete!")
lanterns = ['pufferfish', 'zombie', 'creeper', 'skeleton', 'wither_skeleton', 'bee', 'jack_o_lantern', 'ghost', 'inky', 'pinky', 'blinky', 'clyde', 'pacman', 'paper_white', 'paper_yellow', 'paper_orange', 'paper_blue', 'paper_light_blue', 'paper_cyan', 'paper_lime', 'paper_green', 'paper_red', 'paper_pink', 'paper_brown', 'paper_black', 'paper_gray', 'paper_light_gray', 'paper_magenta', 'paper_purple', 'guardian'] shader_path = 'assets/skinnedlanterns/materialmaps/' handheld_path = 'assets/skinnedlanterns/lights/item/' material = '\n{{\n \t"defaultMaterial": "canvas:{type}_glow",\n\n \t"variants": {{\n "facing=north,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=north,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=north,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=north,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=east,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=east,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=east,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=east,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=south,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=south,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=south,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=south,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=west,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=west,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=west,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=west,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=up,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=up,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=up,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=up,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=down,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=down,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }},\n "facing=down,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }},\n "facing=down,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}\n \t}}\n}}\n' normal_light = '\n{\n "intensity": 0.93,\n "red": 1.0,\n "green": 1.0,\n "blue": 0.8,\n "worksInFluid": false\n}\n' soul_light = '\n{\n "intensity": 0.93,\n "red": 0.6,\n "green": 0.8,\n "blue": 1.0,\n "worksInFluid": true\n}\n' for lantern in lanterns: normal = open(shader_path + 'block/' + lantern + '_lantern_block.json', 'w') soul = open(shader_path + 'block/' + lantern + '_soul_lantern_block.json', 'w') normal_item = open(shader_path + 'item/' + lantern + '_lantern_block.json', 'w') soul_item = open(shader_path + 'item/' + lantern + '_soul_lantern_block.json', 'w') normal_handheld = open(handheld_path + lantern + '_lantern_block.json', 'w') soul_handheld = open(handheld_path + lantern + '_soul_lantern_block.json', 'w') normal.write(material.format(type='warm')) soul.write(material.format(type='luminance')) normal_item.write('{}') soul_item.write('{}') normal_handheld.write(normal_light) soul_handheld.write(soul_light) normal.close() soul.close() normal_item.close() soul_item.close() normal_handheld.close() soul_handheld.close() print('Filegen complete!')
def count_up_to(max): count = 1 while count <= max: yield count count += 1 counter = count_up_to(5) for num in counter: print(num)
def count_up_to(max): count = 1 while count <= max: yield count count += 1 counter = count_up_to(5) for num in counter: print(num)
__strict__ = True class SpotifyOauthError(Exception): pass class SpotifyRepositoryError(Exception): def __init__(self, http_status: int, body: str): self.http_status = http_status self.body = body def __str__(self): return 'http status: {0}, code:{1}'.format(str(self.http_status), self.body)
__strict__ = True class Spotifyoautherror(Exception): pass class Spotifyrepositoryerror(Exception): def __init__(self, http_status: int, body: str): self.http_status = http_status self.body = body def __str__(self): return 'http status: {0}, code:{1}'.format(str(self.http_status), self.body)
# program numbers BASIC = 140624 GOTO = 158250875866513204219300194287615 VARIABLES = 6198727823
basic = 140624 goto = 158250875866513204219300194287615 variables = 6198727823
ENV_NAMES = { "PASSWORD": "DECT_MAIL_EXTRACT_PASSWORD", "USERNAME": "DECT_MAIL_EXTRACT_USER", "SERVER": "DECT_MAIL_EXTRACT_SERVER", }
env_names = {'PASSWORD': 'DECT_MAIL_EXTRACT_PASSWORD', 'USERNAME': 'DECT_MAIL_EXTRACT_USER', 'SERVER': 'DECT_MAIL_EXTRACT_SERVER'}
@customop('numpy') def my_softmax(x, y): probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True)) probs /= numpy.sum(probs, axis=1, keepdims=True) N = x.shape[0] loss = -numpy.sum(numpy.log(probs[numpy.arange(N), y])) / N return loss def my_softmax_grad(ans, x, y): def grad(g): N = x.shape[0] probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True)) probs /= numpy.sum(probs, axis=1, keepdims=True) probs[numpy.arange(N), y] -= 1 probs /= N return probs return grad my_softmax.def_grad(my_softmax_grad)
@customop('numpy') def my_softmax(x, y): probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True)) probs /= numpy.sum(probs, axis=1, keepdims=True) n = x.shape[0] loss = -numpy.sum(numpy.log(probs[numpy.arange(N), y])) / N return loss def my_softmax_grad(ans, x, y): def grad(g): n = x.shape[0] probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True)) probs /= numpy.sum(probs, axis=1, keepdims=True) probs[numpy.arange(N), y] -= 1 probs /= N return probs return grad my_softmax.def_grad(my_softmax_grad)
""" This file was made for exercise 9-11""" class Users: def __init__(self, first_name, last_name, email, username): self.first_name = first_name self.last_name = last_name self.email = email self.username = username self.login_attempts = 0 def describe_user(self): print(f'{self.first_name.title()} {self.last_name.title()}') print(f'- Email: {self.email}') print(f'- Username: {self.username}') def greet_user(self): print(f'Welcome {self.first_name.title()}') def increment_login_attempts(self): self.login_attempts += 1 print(self.login_attempts) def reset_login_attempts(self): self.login_attempts = 0 print(self.login_attempts) class Admin(Users): def __init__(self, first_name, last_name, email, username): super().__init__(first_name, last_name, email, username) self.privileges = Privileges() class Privileges: def __init__(self, privileges=[]): self.privileges = privileges def show_privileges(self): print('ADMIN PRIVILEGES:') if self.privileges: for privilege in self.privileges: print(f'- {privilege.title()}') else: print('No privileges') if __name__ == '__main__': admin1 = Admin('james', 'noria', 'jamesnoria@gmail.com', 'jamesnoria') admin1.describe_user() admin1.privileges.privileges = ['can post', 'can delete'] admin1.privileges.show_privileges()
""" This file was made for exercise 9-11""" class Users: def __init__(self, first_name, last_name, email, username): self.first_name = first_name self.last_name = last_name self.email = email self.username = username self.login_attempts = 0 def describe_user(self): print(f'{self.first_name.title()} {self.last_name.title()}') print(f'- Email: {self.email}') print(f'- Username: {self.username}') def greet_user(self): print(f'Welcome {self.first_name.title()}') def increment_login_attempts(self): self.login_attempts += 1 print(self.login_attempts) def reset_login_attempts(self): self.login_attempts = 0 print(self.login_attempts) class Admin(Users): def __init__(self, first_name, last_name, email, username): super().__init__(first_name, last_name, email, username) self.privileges = privileges() class Privileges: def __init__(self, privileges=[]): self.privileges = privileges def show_privileges(self): print('ADMIN PRIVILEGES:') if self.privileges: for privilege in self.privileges: print(f'- {privilege.title()}') else: print('No privileges') if __name__ == '__main__': admin1 = admin('james', 'noria', 'jamesnoria@gmail.com', 'jamesnoria') admin1.describe_user() admin1.privileges.privileges = ['can post', 'can delete'] admin1.privileges.show_privileges()
class MdFile(): def __init__(self, file_path, base_name, title, mdlinks): self.uid = 0 self.file_path = file_path self.base_name = base_name self.title = title if title else base_name self.mdlinks = mdlinks def __str__(self): return f'{self.uid}: {self.file_path}, {self.title}, {self.mdlinks}'
class Mdfile: def __init__(self, file_path, base_name, title, mdlinks): self.uid = 0 self.file_path = file_path self.base_name = base_name self.title = title if title else base_name self.mdlinks = mdlinks def __str__(self): return f'{self.uid}: {self.file_path}, {self.title}, {self.mdlinks}'
#/* *** ODSATag: MinVertex *** */ # Find the unvisited vertex with the smalled distance def minVertex(G, D): v = 0 # Initialize v to any unvisited vertex for i in range(G.nodeCount()): if G.getValue(i) != VISITED: v = i break for i in range(G.nodeCount()): # Now find smallest value if G.getValue(i) != VISITED and D[i] < D[v]: v = i return v #/* *** ODSAendTag: MinVertex *** */ #/* *** ODSATag: GraphDijk1 *** */ # Compute shortest path distances from s, store them in D def Dijkstra(G, s, D): for i in range(G.nodeCount()): # Initialize D[i] = INFINITY D[s] = 0 for i in range(G.nodeCount()): # Process the vertices v = minVertex(G, D) # Find next-closest vertex G.setValue(v, VISITED) if D[v] == INFINITY: return # Unreachable for w in G.neighbors(v): if D[w] > D[v] + G.weight(v, w): D[w] = D[v] + G.weight(v, w) #/* *** ODSAendTag: GraphDijk1 *** */
def min_vertex(G, D): v = 0 for i in range(G.nodeCount()): if G.getValue(i) != VISITED: v = i break for i in range(G.nodeCount()): if G.getValue(i) != VISITED and D[i] < D[v]: v = i return v def dijkstra(G, s, D): for i in range(G.nodeCount()): D[i] = INFINITY D[s] = 0 for i in range(G.nodeCount()): v = min_vertex(G, D) G.setValue(v, VISITED) if D[v] == INFINITY: return for w in G.neighbors(v): if D[w] > D[v] + G.weight(v, w): D[w] = D[v] + G.weight(v, w)
config = { # -------------------------------------------------------------------------- # Database Connections # -------------------------------------------------------------------------- 'database': { 'default': 'auth', 'connections': { # SQLite # 'auth': { # 'driver': 'sqlite', # 'dialect': None, # 'host': None, # 'port': None, # 'database': ':memory', # 'username': None, # 'password': None, # 'prefix': 'auth_', # }, # MySQL 'auth': { 'driver': 'mysql', 'dialect': 'pymysql', 'host': '127.0.0.1', 'port': 3306, 'database': 'uvicore_test', 'username': 'root', 'password': 'techie', 'prefix': 'auth_', }, }, }, }
config = {'database': {'default': 'auth', 'connections': {'auth': {'driver': 'mysql', 'dialect': 'pymysql', 'host': '127.0.0.1', 'port': 3306, 'database': 'uvicore_test', 'username': 'root', 'password': 'techie', 'prefix': 'auth_'}}}}
data = open('output_dataset_ALL.txt').readlines() original = open('dataset_ALL.txt').readlines() #data = open('dataset.txt').readlines() out = open('output_gcode_merged.gcode', 'w') for j in range(len(data)/4): i = j*4 x = data[i].strip() y = data[i+1].strip() z = original[i+2].strip() e = original[i+3].strip() out.write('G1 X' + x[:-2] + ' Y' + y[:-2] + ' Z' + z[:-2] + ' E' + e + '\n') out.close()
data = open('output_dataset_ALL.txt').readlines() original = open('dataset_ALL.txt').readlines() out = open('output_gcode_merged.gcode', 'w') for j in range(len(data) / 4): i = j * 4 x = data[i].strip() y = data[i + 1].strip() z = original[i + 2].strip() e = original[i + 3].strip() out.write('G1 X' + x[:-2] + ' Y' + y[:-2] + ' Z' + z[:-2] + ' E' + e + '\n') out.close()
def adder_model(a, b): """ My golden reference model """ return my_adder(a, b) def my_adder(a, b): """ My golden reference model """ return a + b
def adder_model(a, b): """ My golden reference model """ return my_adder(a, b) def my_adder(a, b): """ My golden reference model """ return a + b
## # Copyright 2018, Ammar Ali Khan # Licensed under MIT. ## # Application configuration APPLICATION_NAME = '' APPLICATION_VERSION = '1.0.1' # HTTP Port for web streaming HTTP_PORT = 8000 # HTTP page template path HTML_TEMPLATE_PATH = './src/common/package/http/template' # Capturing device index (used for web camera) CAPTURING_DEVICE = 0 # To user Pi Camera USE_PI_CAMERA = True # Capture configuration WIDTH = 640 HEIGHT = 480 RESOLUTION = [WIDTH, HEIGHT] FRAME_RATE = 24 # Storage configuration DATABASE_NAME = 'database.db' STORAGE_DIRECTORY = './dataset/' UNKNOWN_PREFIX = 'unknown' FILE_EXTENSION = '.pgm'
application_name = '' application_version = '1.0.1' http_port = 8000 html_template_path = './src/common/package/http/template' capturing_device = 0 use_pi_camera = True width = 640 height = 480 resolution = [WIDTH, HEIGHT] frame_rate = 24 database_name = 'database.db' storage_directory = './dataset/' unknown_prefix = 'unknown' file_extension = '.pgm'
Total_Fuel_Need =0 Data_File = open("Day1_Data.txt") Data_Lines = Data_File.readlines() for i in range(len(Data_Lines)): Data_Lines[i] = int(Data_Lines[i].rstrip('\n')) Total_Fuel_Need += int(Data_Lines[i] / 3) - 2 print(Total_Fuel_Need)
total__fuel__need = 0 data__file = open('Day1_Data.txt') data__lines = Data_File.readlines() for i in range(len(Data_Lines)): Data_Lines[i] = int(Data_Lines[i].rstrip('\n')) total__fuel__need += int(Data_Lines[i] / 3) - 2 print(Total_Fuel_Need)
# This sample tests the special-case handling of Self when comparing # two functions whose signatures differ only in the Self scope. class SomeClass: def __str__(self) -> str: ... __repr__ = __str__
class Someclass: def __str__(self) -> str: ... __repr__ = __str__
lines = open("input").read().strip().splitlines() print("--- Day11 ---") class Seat: directions = [ (dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if (dx, dy) != (0, 0) ] def __init__(self, x, y, dx, dy): self.x = x self.y = y self.dx = dx self.dy = dy def p1(part2=False): G, rows, columns = load_grid(lines) i = 0 while True: i += 1 NG = {} for x in range(rows): for y in range(columns): other = [Seat(x + d[0], y + d[1], *d) for d in Seat.directions] adjacent = 4 if part2: for seat in other: while G.get((seat.x, seat.y)) == ".": seat.x += seat.dx seat.y += seat.dy adjacent = 5 other = [G[s.x, s.y] for s in other if (s.x, s.y) in G] if G[x, y] == "L" and all(s != "#" for s in other): NG[x, y] = "#" elif G[x, y] == "#" and (sum([s == "#" for s in other]) >= adjacent): NG[x, y] = "L" else: NG[x, y] = G[x, y] if G == NG: break G = NG print(sum([cell == "#" for cell in G.values()])) def p2(): p1(part2=True) def load_grid(lines): G = {} first_row = lines[0] for y, line in enumerate(lines): # Check if grid is really a grid. assert len(line) == len(first_row) for x, ch in enumerate(line): G[y, x] = ch rows = len(lines) columns = len(first_row) return G, rows, columns def print_grid(grid, maxx, maxy, zfill_padding=3): header = [" " * zfill_padding, " "] for x in range(maxx): header.append(str(x % 10)) print("".join(header)) for y in range(maxy): row = [str(y).zfill(zfill_padding), " "] for x in range(maxx): row.append(grid[x, y]) print("".join(row)) print("Part1") p1() print("Part2") p2() print("---- EOD ----")
lines = open('input').read().strip().splitlines() print('--- Day11 ---') class Seat: directions = [(dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if (dx, dy) != (0, 0)] def __init__(self, x, y, dx, dy): self.x = x self.y = y self.dx = dx self.dy = dy def p1(part2=False): (g, rows, columns) = load_grid(lines) i = 0 while True: i += 1 ng = {} for x in range(rows): for y in range(columns): other = [seat(x + d[0], y + d[1], *d) for d in Seat.directions] adjacent = 4 if part2: for seat in other: while G.get((seat.x, seat.y)) == '.': seat.x += seat.dx seat.y += seat.dy adjacent = 5 other = [G[s.x, s.y] for s in other if (s.x, s.y) in G] if G[x, y] == 'L' and all((s != '#' for s in other)): NG[x, y] = '#' elif G[x, y] == '#' and sum([s == '#' for s in other]) >= adjacent: NG[x, y] = 'L' else: NG[x, y] = G[x, y] if G == NG: break g = NG print(sum([cell == '#' for cell in G.values()])) def p2(): p1(part2=True) def load_grid(lines): g = {} first_row = lines[0] for (y, line) in enumerate(lines): assert len(line) == len(first_row) for (x, ch) in enumerate(line): G[y, x] = ch rows = len(lines) columns = len(first_row) return (G, rows, columns) def print_grid(grid, maxx, maxy, zfill_padding=3): header = [' ' * zfill_padding, ' '] for x in range(maxx): header.append(str(x % 10)) print(''.join(header)) for y in range(maxy): row = [str(y).zfill(zfill_padding), ' '] for x in range(maxx): row.append(grid[x, y]) print(''.join(row)) print('Part1') p1() print('Part2') p2() print('---- EOD ----')
#list = [1,2,3,4,5] arr = list(range(1,6)) count = 0 #print(arr) #for i in arr: #print(i) list = ["a","b","c","d","e"] for index in range(len(arr)): print(f'Phan tu tai vi tri {index} cua arr la : {list[index]}') count += 1 print(count)
arr = list(range(1, 6)) count = 0 list = ['a', 'b', 'c', 'd', 'e'] for index in range(len(arr)): print(f'Phan tu tai vi tri {index} cua arr la : {list[index]}') count += 1 print(count)
def baseline3(X): return ( X['ABS'] | X['INT'] | X['UINT'] | (X['TDEP'] > X['TDEP'].mean()) | (X['FIELD'] > X['FIELD'].mean()) | ((X['UAPI']+X['TUAPI']) > (X['UAPI']+X['TUAPI']).mean()) | (X['EXPCAT'] > 0) | (X['RBFA'] > 0) | (X['CONDCALL'] > 0) | (X['SYNC'] > X['SYNC'].mean()) | (X['AFPR'] > 0) )
def baseline3(X): return X['ABS'] | X['INT'] | X['UINT'] | (X['TDEP'] > X['TDEP'].mean()) | (X['FIELD'] > X['FIELD'].mean()) | (X['UAPI'] + X['TUAPI'] > (X['UAPI'] + X['TUAPI']).mean()) | (X['EXPCAT'] > 0) | (X['RBFA'] > 0) | (X['CONDCALL'] > 0) | (X['SYNC'] > X['SYNC'].mean()) | (X['AFPR'] > 0)
def search_in_rotated_array(alist, k, leftix=0, rightix=None): if not rightix: rightix = len(alist) midpoint = (leftix + rightix) / 2 aleft, amiddle = alist[leftix], alist[midpoint] if k == amiddle: return midpoint if k == aleft: return leftix if aleft > amiddle: if amiddle < k and k < aleft: return search_in_rotated_array(alist, k, midpoint+1, rightix) else: return search_in_rotated_array(alist, k, leftix+1, midpoint) elif aleft < k and k < amiddle: return search_in_rotated_array(alist, k, leftix+1, midpoint) else: return search_in_rotated_array(alist, k, midpoint+1, rightix) array = [55, 60, 65, 70, 75, 80, 85, 90, 95, 15, 20, 25, 30, 35, 40, 45] print(search_in_rotated_array(array, 40))
def search_in_rotated_array(alist, k, leftix=0, rightix=None): if not rightix: rightix = len(alist) midpoint = (leftix + rightix) / 2 (aleft, amiddle) = (alist[leftix], alist[midpoint]) if k == amiddle: return midpoint if k == aleft: return leftix if aleft > amiddle: if amiddle < k and k < aleft: return search_in_rotated_array(alist, k, midpoint + 1, rightix) else: return search_in_rotated_array(alist, k, leftix + 1, midpoint) elif aleft < k and k < amiddle: return search_in_rotated_array(alist, k, leftix + 1, midpoint) else: return search_in_rotated_array(alist, k, midpoint + 1, rightix) array = [55, 60, 65, 70, 75, 80, 85, 90, 95, 15, 20, 25, 30, 35, 40, 45] print(search_in_rotated_array(array, 40))
""" Program functionalities module """ def create_transaction(day, value, type, description): """ :return: a dictionary that contains the data of a transaction """ return {'day': day, 'value': value, 'type': type, 'description': description} def get_day(transaction): """ :return: the day of the transaction """ return transaction['day'] def get_value(transaction): """ :return: the amount of money of the transaction """ return transaction['value'] def get_type(transaction): """ :return: the type of the transaction """ return transaction['type'] def get_description(transaction): """ :return: the description of the transaction """ return transaction['description'] def set_value(transaction, value): """ modify the amount of money of a existing transaction """ transaction['value'] = value def add_transaction(transactions_list, transaction): transactions_list.append(transaction) def remove_transaction(transactions_list, index): transactions_list.pop(index) def remove_transactions_from_a_day(transactions_list, day): """ removes all the transactions from a speciefied day """ lenght = len(transactions_list) i = 0 while i < lenght: if get_day(transactions_list[i]) == day: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def remove_transactions_from_day1_to_day2(transactions_list, day1, day2): """ removes all the transactions from day1 to day2 """ lenght = len(transactions_list) i = 0 while i < lenght: if day1 <= get_day(transactions_list[i]) <= day2: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def remove_transactions_type(transactions_list, type): """ removes all the transactions of a certain type """ lenght = len(transactions_list) i = 0 while i < lenght: if get_type(transactions_list[i]) == type: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def replace_value_of_transaction(transactions_list, day, type, description, new_value): """ replace the value of a transaction with a new one """ for i in range(0, len(transactions_list)): transaction = transactions_list[i] if get_day(transaction) == day and get_type(transaction) == type and get_description(transaction) == description: set_value(transactions_list[i], new_value) break def transaction_having_type(transactions_list, type): """ returns the list of all the transcations of a certain type """ print_list = [] for i in range(0, len(transactions_list)): if get_type(transactions_list[i]) == type: add_transaction(print_list, transactions_list[i]) return print_list def transactions_having_property_than_value(transactions_list, property, value): """ :param property: = / > / < :returns: all the transactions which respect the property with the respect of the value """ print_list = [] for i in range(0, len(transactions_list)): if property == '=': if get_value(transactions_list[i]) == value: add_transaction(print_list, transactions_list[i]) elif property == '>': if get_value(transactions_list[i]) > value: add_transaction(print_list, transactions_list[i]) elif property == '<': if get_value(transactions_list[i]) < value: add_transaction(print_list, transactions_list[i]) return print_list def transactions_sum_having_type_before_day(transactions_list, type, day): """ transactions_list = the list of transactions type = the type of the transactions 'in'/'out' :return: sum of all type transactions """ s = 0 for i in range(0, len(transactions_list)): if get_day(transactions_list[i]) <= day and get_type(transactions_list[i]) == type: s = s + get_value(transactions_list[i]) return s def account_balance_before_day(transactions_list, day): """ :param transactions_list: the list of transactions :param day: the last day before the balance check :return: account balance before a certain day(including that day) """ sum1 = transactions_sum_having_type_before_day(transactions_list, "in".casefold(), day) sum2 = transactions_sum_having_type_before_day(transactions_list, "out".casefold(), day) account_balance = sum1 - sum2 return account_balance def sum_having_type(transactions_list, type): """ :param transactions_list: a list of transactions :param type: "in"/"out" :return: the sum of all transactions which have type 'type' """ s = 0 for transaction in transactions_list: if get_type(transaction) == type: s = s + get_value(transaction) return s def max_transanction_having_type_from_day(transactions_list, type, day): """ :param transactions_list: a list of transactions :param type: "in"/"out" :param value: the day of the transactions :return: a list of maximum transactions of type 'type' and day 'day' """ maximum = -1 max_list = [] for transaction in transactions_list: if get_type(transaction) == type and get_day(transaction) == day: if get_value(transaction) > maximum: maximum = get_value(transaction) for transaction in transactions_list: if get_type(transaction) == type and get_day(transaction) == day: if get_value(transaction) == maximum: add_transaction(max_list, transaction) return max_list def filter_type(transactions_list, type): """ :param transactions_list: a list of transactions :param type: the type of transactions we want to filter keeps only type trasactions """ if type == "in": remove_transactions_type(transactions_list, "out") else: remove_transactions_type(transactions_list, "in") def filter_type_smaller_than_value(transactions_list, type, value): """ :param transactions_list: a list of transactions :param type: the type of transactions we want to filter :param value: the upper bound of the value of a transaction of type 'type' keeps all 'type' transactions smaller than value(not inclunding it) """ lenght = len(transactions_list) i = 0 while i < lenght: if get_type(transactions_list[i]) != type or get_value(transactions_list[i]) >= value: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def copy_transactions_list(transactions_list): """ :param transactions_list: a list :return: a copy of that list """ new_list = [] for transaction in transactions_list: day = get_day(transaction) type = get_type(transaction) value = get_value(transaction) description = get_description(transaction) new_transaction = create_transaction(day, value, type, description) new_list.append(new_transaction) return new_list
""" Program functionalities module """ def create_transaction(day, value, type, description): """ :return: a dictionary that contains the data of a transaction """ return {'day': day, 'value': value, 'type': type, 'description': description} def get_day(transaction): """ :return: the day of the transaction """ return transaction['day'] def get_value(transaction): """ :return: the amount of money of the transaction """ return transaction['value'] def get_type(transaction): """ :return: the type of the transaction """ return transaction['type'] def get_description(transaction): """ :return: the description of the transaction """ return transaction['description'] def set_value(transaction, value): """ modify the amount of money of a existing transaction """ transaction['value'] = value def add_transaction(transactions_list, transaction): transactions_list.append(transaction) def remove_transaction(transactions_list, index): transactions_list.pop(index) def remove_transactions_from_a_day(transactions_list, day): """ removes all the transactions from a speciefied day """ lenght = len(transactions_list) i = 0 while i < lenght: if get_day(transactions_list[i]) == day: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def remove_transactions_from_day1_to_day2(transactions_list, day1, day2): """ removes all the transactions from day1 to day2 """ lenght = len(transactions_list) i = 0 while i < lenght: if day1 <= get_day(transactions_list[i]) <= day2: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def remove_transactions_type(transactions_list, type): """ removes all the transactions of a certain type """ lenght = len(transactions_list) i = 0 while i < lenght: if get_type(transactions_list[i]) == type: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def replace_value_of_transaction(transactions_list, day, type, description, new_value): """ replace the value of a transaction with a new one """ for i in range(0, len(transactions_list)): transaction = transactions_list[i] if get_day(transaction) == day and get_type(transaction) == type and (get_description(transaction) == description): set_value(transactions_list[i], new_value) break def transaction_having_type(transactions_list, type): """ returns the list of all the transcations of a certain type """ print_list = [] for i in range(0, len(transactions_list)): if get_type(transactions_list[i]) == type: add_transaction(print_list, transactions_list[i]) return print_list def transactions_having_property_than_value(transactions_list, property, value): """ :param property: = / > / < :returns: all the transactions which respect the property with the respect of the value """ print_list = [] for i in range(0, len(transactions_list)): if property == '=': if get_value(transactions_list[i]) == value: add_transaction(print_list, transactions_list[i]) elif property == '>': if get_value(transactions_list[i]) > value: add_transaction(print_list, transactions_list[i]) elif property == '<': if get_value(transactions_list[i]) < value: add_transaction(print_list, transactions_list[i]) return print_list def transactions_sum_having_type_before_day(transactions_list, type, day): """ transactions_list = the list of transactions type = the type of the transactions 'in'/'out' :return: sum of all type transactions """ s = 0 for i in range(0, len(transactions_list)): if get_day(transactions_list[i]) <= day and get_type(transactions_list[i]) == type: s = s + get_value(transactions_list[i]) return s def account_balance_before_day(transactions_list, day): """ :param transactions_list: the list of transactions :param day: the last day before the balance check :return: account balance before a certain day(including that day) """ sum1 = transactions_sum_having_type_before_day(transactions_list, 'in'.casefold(), day) sum2 = transactions_sum_having_type_before_day(transactions_list, 'out'.casefold(), day) account_balance = sum1 - sum2 return account_balance def sum_having_type(transactions_list, type): """ :param transactions_list: a list of transactions :param type: "in"/"out" :return: the sum of all transactions which have type 'type' """ s = 0 for transaction in transactions_list: if get_type(transaction) == type: s = s + get_value(transaction) return s def max_transanction_having_type_from_day(transactions_list, type, day): """ :param transactions_list: a list of transactions :param type: "in"/"out" :param value: the day of the transactions :return: a list of maximum transactions of type 'type' and day 'day' """ maximum = -1 max_list = [] for transaction in transactions_list: if get_type(transaction) == type and get_day(transaction) == day: if get_value(transaction) > maximum: maximum = get_value(transaction) for transaction in transactions_list: if get_type(transaction) == type and get_day(transaction) == day: if get_value(transaction) == maximum: add_transaction(max_list, transaction) return max_list def filter_type(transactions_list, type): """ :param transactions_list: a list of transactions :param type: the type of transactions we want to filter keeps only type trasactions """ if type == 'in': remove_transactions_type(transactions_list, 'out') else: remove_transactions_type(transactions_list, 'in') def filter_type_smaller_than_value(transactions_list, type, value): """ :param transactions_list: a list of transactions :param type: the type of transactions we want to filter :param value: the upper bound of the value of a transaction of type 'type' keeps all 'type' transactions smaller than value(not inclunding it) """ lenght = len(transactions_list) i = 0 while i < lenght: if get_type(transactions_list[i]) != type or get_value(transactions_list[i]) >= value: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def copy_transactions_list(transactions_list): """ :param transactions_list: a list :return: a copy of that list """ new_list = [] for transaction in transactions_list: day = get_day(transaction) type = get_type(transaction) value = get_value(transaction) description = get_description(transaction) new_transaction = create_transaction(day, value, type, description) new_list.append(new_transaction) return new_list
''' https://www.codingame.com/training/easy/brackets-extreme-edition ''' e = input() d = {')': '(', ']': '[', '}': '{'} s = [] for c in e: if c in d.values(): s.append(c) elif c in d.keys(): if len(s) == 0: print("false") exit(0) else: if d[c] == s.pop(): pass else: print("false") exit(0) if len(s) == 0: print("true") else: print("false")
""" https://www.codingame.com/training/easy/brackets-extreme-edition """ e = input() d = {')': '(', ']': '[', '}': '{'} s = [] for c in e: if c in d.values(): s.append(c) elif c in d.keys(): if len(s) == 0: print('false') exit(0) elif d[c] == s.pop(): pass else: print('false') exit(0) if len(s) == 0: print('true') else: print('false')
#!/usr/bin/env python # from .api import SteamAPI class SteamUser(object): def __init__(self, steam_id=None, steam_api=None, **kwargs): self.steam_id = steam_id self.steam_api = steam_api self.__dict__.update(**kwargs) self._friends = None self._games = None self._profile_data = None self._profile_data_items = [ u'steamid', u'primaryclanid', u'realname', u'personaname', u'personastate', u'personastateflags', u'communityvisibilitystate', u'loccountrycode', u'profilestate', u'profileurl', u'timecreated', u'avatar', u'commentpermission', u'avatarfull', u'avatarmedium', u'lastlogoff' ] @property def friends(self, steam_id=None): if self._friends: return self._friends self._friends = self.get_friends_list(steam_id=steam_id) return self._friends def Game(self, app_id): return Game(app_id=app_id, steam_api=self.steam_api, owner=self) @property def games(self): if self._games: return self._games self._games = self.get_games_list() return self._games @property def games_set(self): return set([_.app_id for _ in self.games]) def _profile_property_wrapper(self, profile_data, key): if self._profile_data: return self._profile_data.get(key) self._profile_data = profile_data return self._profile_data.get(key) def __getattr__(self, key): if key in self._profile_data_items: self._profile_data = self.get_profile() return self._profile_data.get(key) return super(SteamUser, self).__getattribute__(key)() def get_profile(self, steam_id=None): if self._profile_data: return self._profile_data if steam_id: self.steam_id = steam_id response_json = self.steam_api.get( 'ISteamUser', 'GetPlayerSummaries', version='v0002', steamids=self.steam_id ) # Make this better return response_json.get('response', {}).get('players', [])[0] def get_friends_list(self, steam_id=None): if steam_id: self.steam_id = steam_id response_json = self.steam_api.get('ISteamUser', 'GetFriendList', steamid=self.steam_id) for friend in response_json.get('friendslist', {}).get('friends', []): yield SteamUser( steam_id=friend.get('steamid'), steam_api=self.steam_api, friend_since=friend.get('friend_since') ) def get_games_list(self, steam_id=None): if steam_id: self.steam_id = steam_id game_list = self.steam_api.get( 'IPlayerService', 'GetOwnedGames', steamid=self.steam_id ) for game in game_list.get('response', {}).get('games', []): yield Game(app_id=game.get('appid'), owner=self) def __repr__(self): return "<SteamUser:{.steam_id}>".format(self)
class Steamuser(object): def __init__(self, steam_id=None, steam_api=None, **kwargs): self.steam_id = steam_id self.steam_api = steam_api self.__dict__.update(**kwargs) self._friends = None self._games = None self._profile_data = None self._profile_data_items = [u'steamid', u'primaryclanid', u'realname', u'personaname', u'personastate', u'personastateflags', u'communityvisibilitystate', u'loccountrycode', u'profilestate', u'profileurl', u'timecreated', u'avatar', u'commentpermission', u'avatarfull', u'avatarmedium', u'lastlogoff'] @property def friends(self, steam_id=None): if self._friends: return self._friends self._friends = self.get_friends_list(steam_id=steam_id) return self._friends def game(self, app_id): return game(app_id=app_id, steam_api=self.steam_api, owner=self) @property def games(self): if self._games: return self._games self._games = self.get_games_list() return self._games @property def games_set(self): return set([_.app_id for _ in self.games]) def _profile_property_wrapper(self, profile_data, key): if self._profile_data: return self._profile_data.get(key) self._profile_data = profile_data return self._profile_data.get(key) def __getattr__(self, key): if key in self._profile_data_items: self._profile_data = self.get_profile() return self._profile_data.get(key) return super(SteamUser, self).__getattribute__(key)() def get_profile(self, steam_id=None): if self._profile_data: return self._profile_data if steam_id: self.steam_id = steam_id response_json = self.steam_api.get('ISteamUser', 'GetPlayerSummaries', version='v0002', steamids=self.steam_id) return response_json.get('response', {}).get('players', [])[0] def get_friends_list(self, steam_id=None): if steam_id: self.steam_id = steam_id response_json = self.steam_api.get('ISteamUser', 'GetFriendList', steamid=self.steam_id) for friend in response_json.get('friendslist', {}).get('friends', []): yield steam_user(steam_id=friend.get('steamid'), steam_api=self.steam_api, friend_since=friend.get('friend_since')) def get_games_list(self, steam_id=None): if steam_id: self.steam_id = steam_id game_list = self.steam_api.get('IPlayerService', 'GetOwnedGames', steamid=self.steam_id) for game in game_list.get('response', {}).get('games', []): yield game(app_id=game.get('appid'), owner=self) def __repr__(self): return '<SteamUser:{.steam_id}>'.format(self)
def parse_map(_map): """ Returns a dictionary where from you can look up which center a given orbiter has """ orbits = {} for orbit in _map.split("\n"): center, orbiter = orbit.split(")") orbits[orbiter] = center return orbits def count_orbits(_map): orbits = parse_map(_map) orbiters = orbits.keys() i = 0 for obj in orbiters: while obj != "COM": obj = orbits[obj] i += 1 return i test_map = """ COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L """.strip("\n \t") assert count_orbits(test_map) == 42 with open("input06.txt", "r") as f: _map = f.read() print(count_orbits(_map))
def parse_map(_map): """ Returns a dictionary where from you can look up which center a given orbiter has """ orbits = {} for orbit in _map.split('\n'): (center, orbiter) = orbit.split(')') orbits[orbiter] = center return orbits def count_orbits(_map): orbits = parse_map(_map) orbiters = orbits.keys() i = 0 for obj in orbiters: while obj != 'COM': obj = orbits[obj] i += 1 return i test_map = '\nCOM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L\n'.strip('\n \t') assert count_orbits(test_map) == 42 with open('input06.txt', 'r') as f: _map = f.read() print(count_orbits(_map))
class Solution: def solve(self, matrix): if matrix[0][0] == 1: return -1 R,C = len(matrix),len(matrix[0]) bfs = deque([[0,0]]) dists = {(0,0): 1} while bfs: r,c = bfs.popleft() if (r,c) == (R-1,C-1): return dists[r,c] for nr,nc in [[r-1,c],[r+1,c],[r,c-1],[r,c+1]]: if 0<=nr<R and 0<=nc<C and (nr,nc) not in dists and matrix[nr][nc] == 0: dists[nr,nc] = dists[r,c] + 1 bfs.append((nr,nc)) return -1
class Solution: def solve(self, matrix): if matrix[0][0] == 1: return -1 (r, c) = (len(matrix), len(matrix[0])) bfs = deque([[0, 0]]) dists = {(0, 0): 1} while bfs: (r, c) = bfs.popleft() if (r, c) == (R - 1, C - 1): return dists[r, c] for (nr, nc) in [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]]: if 0 <= nr < R and 0 <= nc < C and ((nr, nc) not in dists) and (matrix[nr][nc] == 0): dists[nr, nc] = dists[r, c] + 1 bfs.append((nr, nc)) return -1
class Solution: def rob(self, nums: list[int]) -> int: if len(nums) == 0: return 0 max_loot: list[int] = [0 for _ in nums] for index, num in enumerate(nums): if index == 0: max_loot[index] = num elif index == 1: max_loot[index] = max(max_loot[index-1], num) else: max_loot[index] = max( max_loot[index-1], num + max_loot[index-2] ) return max_loot[-1] tests = [ ( ([1, 2, 3, 1],), 4, ), ( ([2, 7, 9, 3, 1],), 12, ), ]
class Solution: def rob(self, nums: list[int]) -> int: if len(nums) == 0: return 0 max_loot: list[int] = [0 for _ in nums] for (index, num) in enumerate(nums): if index == 0: max_loot[index] = num elif index == 1: max_loot[index] = max(max_loot[index - 1], num) else: max_loot[index] = max(max_loot[index - 1], num + max_loot[index - 2]) return max_loot[-1] tests = [(([1, 2, 3, 1],), 4), (([2, 7, 9, 3, 1],), 12)]
async def processEvent(event): # Do event processing here ... return event
async def processEvent(event): return event
#!/usr/bin/env python # coding=utf-8 """ # pyORM : Implementation of managers.py Summary : <summary of module/class being implemented> Use Case : As a <actor> I want <outcome> So that <justification> Testable Statements : Can I <Boolean statement> .... """ __version__ = "0.1" __author__ = 'Tony Flury : anthony.flury@btinternet.com' __created__ = '26 Aug 2017' class Manager: def __init__(self, name='', model=None): self._name = name self._model = model @property def model(self): return self._model @property def name(self): return self._name @name.setter def name(self, new_name): if self.name: raise AttributeError('Cannot change name attribute once set') self._name = new_name # Todo Add all relevant methods to the Manager - including filters etc #Todo write ForiegnKey, One to One and Many to Many Managers
""" # pyORM : Implementation of managers.py Summary : <summary of module/class being implemented> Use Case : As a <actor> I want <outcome> So that <justification> Testable Statements : Can I <Boolean statement> .... """ __version__ = '0.1' __author__ = 'Tony Flury : anthony.flury@btinternet.com' __created__ = '26 Aug 2017' class Manager: def __init__(self, name='', model=None): self._name = name self._model = model @property def model(self): return self._model @property def name(self): return self._name @name.setter def name(self, new_name): if self.name: raise attribute_error('Cannot change name attribute once set') self._name = new_name
print("\nAverage is being calculated\n") APITimingFile = open("APITiming.txt", "r") APITimingVals = APITimingFile.readlines() sum = 0 for i in APITimingVals: sum += float(i[slice(len(i)-2)]) print("\nThe average time of start providing is " + str(round(sum/len(APITimingVals), 4)) + "\n")
print('\nAverage is being calculated\n') api_timing_file = open('APITiming.txt', 'r') api_timing_vals = APITimingFile.readlines() sum = 0 for i in APITimingVals: sum += float(i[slice(len(i) - 2)]) print('\nThe average time of start providing is ' + str(round(sum / len(APITimingVals), 4)) + '\n')
class OrderLog: def __init__(self, size): self.log = list() self.size = size def __repr__(self): return str(self.log) def record(self, order_id): self.log.append(order_id) if len(self.log) > self.size: self.log = self.log[1:] def get_last(self, i): return self.log[-i] log = OrderLog(5) log.record(1) log.record(2) assert log.log == [1, 2] log.record(3) log.record(4) log.record(5) assert log.log == [1, 2, 3, 4, 5] log.record(6) log.record(7) log.record(8) assert log.log == [4, 5, 6, 7, 8] assert log.get_last(4) == 5 assert log.get_last(1) == 8
class Orderlog: def __init__(self, size): self.log = list() self.size = size def __repr__(self): return str(self.log) def record(self, order_id): self.log.append(order_id) if len(self.log) > self.size: self.log = self.log[1:] def get_last(self, i): return self.log[-i] log = order_log(5) log.record(1) log.record(2) assert log.log == [1, 2] log.record(3) log.record(4) log.record(5) assert log.log == [1, 2, 3, 4, 5] log.record(6) log.record(7) log.record(8) assert log.log == [4, 5, 6, 7, 8] assert log.get_last(4) == 5 assert log.get_last(1) == 8
# # PySNMP MIB module OADHCP-SERVER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OADHCP-SERVER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:22:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Integer32, Unsigned32, iso, NotificationType, Gauge32, ModuleIdentity, TimeTicks, ObjectIdentity, Counter32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, enterprises, MibIdentifier, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Integer32", "Unsigned32", "iso", "NotificationType", "Gauge32", "ModuleIdentity", "TimeTicks", "ObjectIdentity", "Counter32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "enterprises", "MibIdentifier", "Bits") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") class HostName(DisplayString): subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(0, 32) class EntryStatus(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("valid", 1), ("invalid", 2), ("insert", 3)) class ObjectStatus(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("enable", 1), ("disable", 2), ("other", 3)) oaccess = MibIdentifier((1, 3, 6, 1, 4, 1, 6926)) oaManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1)) oaDhcp = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11)) oaDhcpServer = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1)) oaDhcpServerGeneral = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1)) oaDhcpServerStatus = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 1), ObjectStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpServerStatus.setStatus('mandatory') oaDhcpNetbiosNodeType = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("B-node", 2), ("P-node", 3), ("M-node", 4), ("H-node", 5)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpNetbiosNodeType.setStatus('mandatory') oaDhcpDomainName = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 3), HostName()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDomainName.setStatus('mandatory') oaDhcpDefaultLeaseTime = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDefaultLeaseTime.setStatus('mandatory') oaDhcpMaxLeaseTime = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpMaxLeaseTime.setStatus('mandatory') oaDhcpDNSTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2), ) if mibBuilder.loadTexts: oaDhcpDNSTable.setStatus('mandatory') oaDhcpDNSEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpDNSNum")) if mibBuilder.loadTexts: oaDhcpDNSEntry.setStatus('mandatory') oaDhcpDNSNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpDNSNum.setStatus('mandatory') oaDhcpDNSIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDNSIp.setStatus('mandatory') oaDhcpDNSStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 3), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDNSStatus.setStatus('mandatory') oaDhcpNetbiosServersTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3), ) if mibBuilder.loadTexts: oaDhcpNetbiosServersTable.setStatus('mandatory') oaDhcpNetbiosServersEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpNetbiosServerNum")) if mibBuilder.loadTexts: oaDhcpNetbiosServersEntry.setStatus('mandatory') oaDhcpNetbiosServerNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpNetbiosServerNum.setStatus('mandatory') oaDhcpNetbiosServerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpNetbiosServerIp.setStatus('mandatory') oaDhcpNetbiosServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 3), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpNetbiosServerStatus.setStatus('mandatory') oaDhcpSubnetConfigTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4), ) if mibBuilder.loadTexts: oaDhcpSubnetConfigTable.setStatus('mandatory') oaDhcpSubnetConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpInterfaceName"), (0, "OADHCP-SERVER-MIB", "oaDhcpSubnetIp"), (0, "OADHCP-SERVER-MIB", "oaDhcpSubnetMask")) if mibBuilder.loadTexts: oaDhcpSubnetConfigEntry.setStatus('mandatory') oaDhcpInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpInterfaceName.setStatus('mandatory') oaDhcpSubnetIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpSubnetIp.setStatus('mandatory') oaDhcpSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpSubnetMask.setStatus('mandatory') oaDhcpOptionSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpOptionSubnetMask.setStatus('mandatory') oaDhcpIsOptionMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 5), ObjectStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpIsOptionMask.setStatus('mandatory') oaDhcpSubnetConfigStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 6), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpSubnetConfigStatus.setStatus('mandatory') oaDhcpIpRangeTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5), ) if mibBuilder.loadTexts: oaDhcpIpRangeTable.setStatus('mandatory') oaDhcpIpRangeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpIpRangeSubnetIp"), (0, "OADHCP-SERVER-MIB", "oaDhcpIpRangeSubnetMask"), (0, "OADHCP-SERVER-MIB", "oaDhcpIpRangeStart")) if mibBuilder.loadTexts: oaDhcpIpRangeEntry.setStatus('mandatory') oaDhcpIpRangeSubnetIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpIpRangeSubnetIp.setStatus('mandatory') oaDhcpIpRangeSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpIpRangeSubnetMask.setStatus('mandatory') oaDhcpIpRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpIpRangeStart.setStatus('mandatory') oaDhcpIpRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpIpRangeEnd.setStatus('mandatory') oaDhcpIpRangeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 5), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpIpRangeStatus.setStatus('mandatory') oaDhcpDefaultGWTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6), ) if mibBuilder.loadTexts: oaDhcpDefaultGWTable.setStatus('mandatory') oaDhcpDefaultGWEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpDefaultGWSubnetIp"), (0, "OADHCP-SERVER-MIB", "oaDhcpDefaultGWSubnetMask"), (0, "OADHCP-SERVER-MIB", "oaDhcpDefaultGWIp")) if mibBuilder.loadTexts: oaDhcpDefaultGWEntry.setStatus('mandatory') oaDhcpDefaultGWSubnetIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpDefaultGWSubnetIp.setStatus('mandatory') oaDhcpDefaultGWSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpDefaultGWSubnetMask.setStatus('mandatory') oaDhcpDefaultGWIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpDefaultGWIp.setStatus('mandatory') oaDhcpDefaultGWStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 4), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDefaultGWStatus.setStatus('mandatory') oaDhcpRelay = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2)) oaDhcpRelayGeneral = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1)) oaDhcpRelayStatus = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1, 1), ObjectStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpRelayStatus.setStatus('mandatory') oaDhcpRelayClearConfig = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("None", 1), ("ResetConfig", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpRelayClearConfig.setStatus('mandatory') oaDhcpRelayServerTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2), ) if mibBuilder.loadTexts: oaDhcpRelayServerTable.setStatus('mandatory') oaDhcpRelayServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpRelayServerIp")) if mibBuilder.loadTexts: oaDhcpRelayServerEntry.setStatus('mandatory') oaDhcpRelayServerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpRelayServerIp.setStatus('mandatory') oaDhcpRelayServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1, 2), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpRelayServerStatus.setStatus('mandatory') oaDhcpRelayInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3), ) if mibBuilder.loadTexts: oaDhcpRelayInterfaceTable.setStatus('mandatory') oaDhcpRelayInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpRelayIfName")) if mibBuilder.loadTexts: oaDhcpRelayInterfaceEntry.setStatus('mandatory') oaDhcpRelayIfName = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpRelayIfName.setStatus('mandatory') oaDhcpRelayIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1, 2), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpRelayIfStatus.setStatus('mandatory') mibBuilder.exportSymbols("OADHCP-SERVER-MIB", oaDhcpDNSNum=oaDhcpDNSNum, oaDhcpDNSIp=oaDhcpDNSIp, oaDhcpNetbiosServerStatus=oaDhcpNetbiosServerStatus, oaDhcpRelayStatus=oaDhcpRelayStatus, oaDhcpIpRangeTable=oaDhcpIpRangeTable, oaDhcpServer=oaDhcpServer, oaDhcpDefaultGWIp=oaDhcpDefaultGWIp, oaDhcpDefaultGWEntry=oaDhcpDefaultGWEntry, oaDhcpDefaultLeaseTime=oaDhcpDefaultLeaseTime, EntryStatus=EntryStatus, oaDhcpNetbiosServersTable=oaDhcpNetbiosServersTable, oaDhcpRelay=oaDhcpRelay, oaDhcpNetbiosServerNum=oaDhcpNetbiosServerNum, oaManagement=oaManagement, oaDhcpNetbiosNodeType=oaDhcpNetbiosNodeType, oaDhcpOptionSubnetMask=oaDhcpOptionSubnetMask, oaDhcpIpRangeStatus=oaDhcpIpRangeStatus, oaDhcpRelayInterfaceEntry=oaDhcpRelayInterfaceEntry, oaDhcpIpRangeSubnetMask=oaDhcpIpRangeSubnetMask, oaccess=oaccess, oaDhcpSubnetConfigEntry=oaDhcpSubnetConfigEntry, oaDhcpRelayServerIp=oaDhcpRelayServerIp, oaDhcpRelayClearConfig=oaDhcpRelayClearConfig, oaDhcpRelayGeneral=oaDhcpRelayGeneral, oaDhcpRelayIfName=oaDhcpRelayIfName, oaDhcpMaxLeaseTime=oaDhcpMaxLeaseTime, oaDhcpServerGeneral=oaDhcpServerGeneral, ObjectStatus=ObjectStatus, oaDhcpDefaultGWStatus=oaDhcpDefaultGWStatus, oaDhcpDefaultGWSubnetIp=oaDhcpDefaultGWSubnetIp, oaDhcpIpRangeEnd=oaDhcpIpRangeEnd, oaDhcpDNSEntry=oaDhcpDNSEntry, oaDhcpSubnetConfigTable=oaDhcpSubnetConfigTable, oaDhcpSubnetConfigStatus=oaDhcpSubnetConfigStatus, oaDhcpDefaultGWTable=oaDhcpDefaultGWTable, oaDhcpDNSStatus=oaDhcpDNSStatus, oaDhcpNetbiosServersEntry=oaDhcpNetbiosServersEntry, oaDhcp=oaDhcp, oaDhcpServerStatus=oaDhcpServerStatus, oaDhcpInterfaceName=oaDhcpInterfaceName, oaDhcpRelayServerTable=oaDhcpRelayServerTable, oaDhcpRelayInterfaceTable=oaDhcpRelayInterfaceTable, oaDhcpSubnetMask=oaDhcpSubnetMask, oaDhcpIpRangeEntry=oaDhcpIpRangeEntry, oaDhcpIsOptionMask=oaDhcpIsOptionMask, oaDhcpDomainName=oaDhcpDomainName, oaDhcpIpRangeSubnetIp=oaDhcpIpRangeSubnetIp, oaDhcpDNSTable=oaDhcpDNSTable, oaDhcpRelayServerStatus=oaDhcpRelayServerStatus, oaDhcpNetbiosServerIp=oaDhcpNetbiosServerIp, oaDhcpDefaultGWSubnetMask=oaDhcpDefaultGWSubnetMask, oaDhcpRelayServerEntry=oaDhcpRelayServerEntry, oaDhcpRelayIfStatus=oaDhcpRelayIfStatus, HostName=HostName, oaDhcpSubnetIp=oaDhcpSubnetIp, oaDhcpIpRangeStart=oaDhcpIpRangeStart)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (ip_address, integer32, unsigned32, iso, notification_type, gauge32, module_identity, time_ticks, object_identity, counter32, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, enterprises, mib_identifier, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Integer32', 'Unsigned32', 'iso', 'NotificationType', 'Gauge32', 'ModuleIdentity', 'TimeTicks', 'ObjectIdentity', 'Counter32', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'enterprises', 'MibIdentifier', 'Bits') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') class Hostname(DisplayString): subtype_spec = DisplayString.subtypeSpec + value_size_constraint(0, 32) class Entrystatus(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3)) named_values = named_values(('valid', 1), ('invalid', 2), ('insert', 3)) class Objectstatus(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3)) named_values = named_values(('enable', 1), ('disable', 2), ('other', 3)) oaccess = mib_identifier((1, 3, 6, 1, 4, 1, 6926)) oa_management = mib_identifier((1, 3, 6, 1, 4, 1, 6926, 1)) oa_dhcp = mib_identifier((1, 3, 6, 1, 4, 1, 6926, 1, 11)) oa_dhcp_server = mib_identifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1)) oa_dhcp_server_general = mib_identifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1)) oa_dhcp_server_status = mib_scalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 1), object_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpServerStatus.setStatus('mandatory') oa_dhcp_netbios_node_type = mib_scalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('other', 1), ('B-node', 2), ('P-node', 3), ('M-node', 4), ('H-node', 5)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpNetbiosNodeType.setStatus('mandatory') oa_dhcp_domain_name = mib_scalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 3), host_name()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpDomainName.setStatus('mandatory') oa_dhcp_default_lease_time = mib_scalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 4), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpDefaultLeaseTime.setStatus('mandatory') oa_dhcp_max_lease_time = mib_scalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 5), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpMaxLeaseTime.setStatus('mandatory') oa_dhcp_dns_table = mib_table((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2)) if mibBuilder.loadTexts: oaDhcpDNSTable.setStatus('mandatory') oa_dhcp_dns_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1)).setIndexNames((0, 'OADHCP-SERVER-MIB', 'oaDhcpDNSNum')) if mibBuilder.loadTexts: oaDhcpDNSEntry.setStatus('mandatory') oa_dhcp_dns_num = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpDNSNum.setStatus('mandatory') oa_dhcp_dns_ip = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 2), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpDNSIp.setStatus('mandatory') oa_dhcp_dns_status = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 3), entry_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpDNSStatus.setStatus('mandatory') oa_dhcp_netbios_servers_table = mib_table((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3)) if mibBuilder.loadTexts: oaDhcpNetbiosServersTable.setStatus('mandatory') oa_dhcp_netbios_servers_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1)).setIndexNames((0, 'OADHCP-SERVER-MIB', 'oaDhcpNetbiosServerNum')) if mibBuilder.loadTexts: oaDhcpNetbiosServersEntry.setStatus('mandatory') oa_dhcp_netbios_server_num = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpNetbiosServerNum.setStatus('mandatory') oa_dhcp_netbios_server_ip = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 2), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpNetbiosServerIp.setStatus('mandatory') oa_dhcp_netbios_server_status = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 3), entry_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpNetbiosServerStatus.setStatus('mandatory') oa_dhcp_subnet_config_table = mib_table((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4)) if mibBuilder.loadTexts: oaDhcpSubnetConfigTable.setStatus('mandatory') oa_dhcp_subnet_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1)).setIndexNames((0, 'OADHCP-SERVER-MIB', 'oaDhcpInterfaceName'), (0, 'OADHCP-SERVER-MIB', 'oaDhcpSubnetIp'), (0, 'OADHCP-SERVER-MIB', 'oaDhcpSubnetMask')) if mibBuilder.loadTexts: oaDhcpSubnetConfigEntry.setStatus('mandatory') oa_dhcp_interface_name = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpInterfaceName.setStatus('mandatory') oa_dhcp_subnet_ip = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 2), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpSubnetIp.setStatus('mandatory') oa_dhcp_subnet_mask = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 3), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpSubnetMask.setStatus('mandatory') oa_dhcp_option_subnet_mask = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 4), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpOptionSubnetMask.setStatus('mandatory') oa_dhcp_is_option_mask = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 5), object_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpIsOptionMask.setStatus('mandatory') oa_dhcp_subnet_config_status = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 6), entry_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpSubnetConfigStatus.setStatus('mandatory') oa_dhcp_ip_range_table = mib_table((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5)) if mibBuilder.loadTexts: oaDhcpIpRangeTable.setStatus('mandatory') oa_dhcp_ip_range_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1)).setIndexNames((0, 'OADHCP-SERVER-MIB', 'oaDhcpIpRangeSubnetIp'), (0, 'OADHCP-SERVER-MIB', 'oaDhcpIpRangeSubnetMask'), (0, 'OADHCP-SERVER-MIB', 'oaDhcpIpRangeStart')) if mibBuilder.loadTexts: oaDhcpIpRangeEntry.setStatus('mandatory') oa_dhcp_ip_range_subnet_ip = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 1), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpIpRangeSubnetIp.setStatus('mandatory') oa_dhcp_ip_range_subnet_mask = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 2), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpIpRangeSubnetMask.setStatus('mandatory') oa_dhcp_ip_range_start = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 3), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpIpRangeStart.setStatus('mandatory') oa_dhcp_ip_range_end = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 4), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpIpRangeEnd.setStatus('mandatory') oa_dhcp_ip_range_status = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 5), entry_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpIpRangeStatus.setStatus('mandatory') oa_dhcp_default_gw_table = mib_table((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6)) if mibBuilder.loadTexts: oaDhcpDefaultGWTable.setStatus('mandatory') oa_dhcp_default_gw_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1)).setIndexNames((0, 'OADHCP-SERVER-MIB', 'oaDhcpDefaultGWSubnetIp'), (0, 'OADHCP-SERVER-MIB', 'oaDhcpDefaultGWSubnetMask'), (0, 'OADHCP-SERVER-MIB', 'oaDhcpDefaultGWIp')) if mibBuilder.loadTexts: oaDhcpDefaultGWEntry.setStatus('mandatory') oa_dhcp_default_gw_subnet_ip = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 1), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpDefaultGWSubnetIp.setStatus('mandatory') oa_dhcp_default_gw_subnet_mask = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 2), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpDefaultGWSubnetMask.setStatus('mandatory') oa_dhcp_default_gw_ip = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 3), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpDefaultGWIp.setStatus('mandatory') oa_dhcp_default_gw_status = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 4), entry_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpDefaultGWStatus.setStatus('mandatory') oa_dhcp_relay = mib_identifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2)) oa_dhcp_relay_general = mib_identifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1)) oa_dhcp_relay_status = mib_scalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1, 1), object_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpRelayStatus.setStatus('mandatory') oa_dhcp_relay_clear_config = mib_scalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('None', 1), ('ResetConfig', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpRelayClearConfig.setStatus('mandatory') oa_dhcp_relay_server_table = mib_table((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2)) if mibBuilder.loadTexts: oaDhcpRelayServerTable.setStatus('mandatory') oa_dhcp_relay_server_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1)).setIndexNames((0, 'OADHCP-SERVER-MIB', 'oaDhcpRelayServerIp')) if mibBuilder.loadTexts: oaDhcpRelayServerEntry.setStatus('mandatory') oa_dhcp_relay_server_ip = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1, 1), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpRelayServerIp.setStatus('mandatory') oa_dhcp_relay_server_status = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1, 2), entry_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpRelayServerStatus.setStatus('mandatory') oa_dhcp_relay_interface_table = mib_table((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3)) if mibBuilder.loadTexts: oaDhcpRelayInterfaceTable.setStatus('mandatory') oa_dhcp_relay_interface_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1)).setIndexNames((0, 'OADHCP-SERVER-MIB', 'oaDhcpRelayIfName')) if mibBuilder.loadTexts: oaDhcpRelayInterfaceEntry.setStatus('mandatory') oa_dhcp_relay_if_name = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: oaDhcpRelayIfName.setStatus('mandatory') oa_dhcp_relay_if_status = mib_table_column((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1, 2), entry_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: oaDhcpRelayIfStatus.setStatus('mandatory') mibBuilder.exportSymbols('OADHCP-SERVER-MIB', oaDhcpDNSNum=oaDhcpDNSNum, oaDhcpDNSIp=oaDhcpDNSIp, oaDhcpNetbiosServerStatus=oaDhcpNetbiosServerStatus, oaDhcpRelayStatus=oaDhcpRelayStatus, oaDhcpIpRangeTable=oaDhcpIpRangeTable, oaDhcpServer=oaDhcpServer, oaDhcpDefaultGWIp=oaDhcpDefaultGWIp, oaDhcpDefaultGWEntry=oaDhcpDefaultGWEntry, oaDhcpDefaultLeaseTime=oaDhcpDefaultLeaseTime, EntryStatus=EntryStatus, oaDhcpNetbiosServersTable=oaDhcpNetbiosServersTable, oaDhcpRelay=oaDhcpRelay, oaDhcpNetbiosServerNum=oaDhcpNetbiosServerNum, oaManagement=oaManagement, oaDhcpNetbiosNodeType=oaDhcpNetbiosNodeType, oaDhcpOptionSubnetMask=oaDhcpOptionSubnetMask, oaDhcpIpRangeStatus=oaDhcpIpRangeStatus, oaDhcpRelayInterfaceEntry=oaDhcpRelayInterfaceEntry, oaDhcpIpRangeSubnetMask=oaDhcpIpRangeSubnetMask, oaccess=oaccess, oaDhcpSubnetConfigEntry=oaDhcpSubnetConfigEntry, oaDhcpRelayServerIp=oaDhcpRelayServerIp, oaDhcpRelayClearConfig=oaDhcpRelayClearConfig, oaDhcpRelayGeneral=oaDhcpRelayGeneral, oaDhcpRelayIfName=oaDhcpRelayIfName, oaDhcpMaxLeaseTime=oaDhcpMaxLeaseTime, oaDhcpServerGeneral=oaDhcpServerGeneral, ObjectStatus=ObjectStatus, oaDhcpDefaultGWStatus=oaDhcpDefaultGWStatus, oaDhcpDefaultGWSubnetIp=oaDhcpDefaultGWSubnetIp, oaDhcpIpRangeEnd=oaDhcpIpRangeEnd, oaDhcpDNSEntry=oaDhcpDNSEntry, oaDhcpSubnetConfigTable=oaDhcpSubnetConfigTable, oaDhcpSubnetConfigStatus=oaDhcpSubnetConfigStatus, oaDhcpDefaultGWTable=oaDhcpDefaultGWTable, oaDhcpDNSStatus=oaDhcpDNSStatus, oaDhcpNetbiosServersEntry=oaDhcpNetbiosServersEntry, oaDhcp=oaDhcp, oaDhcpServerStatus=oaDhcpServerStatus, oaDhcpInterfaceName=oaDhcpInterfaceName, oaDhcpRelayServerTable=oaDhcpRelayServerTable, oaDhcpRelayInterfaceTable=oaDhcpRelayInterfaceTable, oaDhcpSubnetMask=oaDhcpSubnetMask, oaDhcpIpRangeEntry=oaDhcpIpRangeEntry, oaDhcpIsOptionMask=oaDhcpIsOptionMask, oaDhcpDomainName=oaDhcpDomainName, oaDhcpIpRangeSubnetIp=oaDhcpIpRangeSubnetIp, oaDhcpDNSTable=oaDhcpDNSTable, oaDhcpRelayServerStatus=oaDhcpRelayServerStatus, oaDhcpNetbiosServerIp=oaDhcpNetbiosServerIp, oaDhcpDefaultGWSubnetMask=oaDhcpDefaultGWSubnetMask, oaDhcpRelayServerEntry=oaDhcpRelayServerEntry, oaDhcpRelayIfStatus=oaDhcpRelayIfStatus, HostName=HostName, oaDhcpSubnetIp=oaDhcpSubnetIp, oaDhcpIpRangeStart=oaDhcpIpRangeStart)
sample_split=1.0 data_loader_usage = 'Training' training_data = "train_train" evaluate_data = "privatetest"
sample_split = 1.0 data_loader_usage = 'Training' training_data = 'train_train' evaluate_data = 'privatetest'
# This function checks if year is a leap year. def isLeapYear(year): if year%100 == 0: return True if year%400 == 0 else False elif year%4 == 0: return True else: return False # This function returns the number of days in a month def monthDays(year, month): MONTHDAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) if month == 2 and isLeapYear(year): return 29 return MONTHDAYS[month-1] # Returns the next day def nextDay(year, month, day): if day == monthDays(year,month): if month == 12: return year+1, 1, 1 else: return year, month+1, 1 return year, month, day+1 # This is the main function def main(): print("Was", 2017, "a leap year?", isLeapYear(2017)) # False? print("Was", 2016, "a leap year?", isLeapYear(2016)) # True? print("Was", 2000, "a leap year?", isLeapYear(2000)) # True? print("Was", 1900, "a leap year?", isLeapYear(1900)) # False? print("January 2017 had", monthDays(2017, 1), "days") # 31? print("February 2017 had", monthDays(2017, 2), "days") # 28? print("February 2016 had", monthDays(2016, 2), "days") # 29? print("February 2000 had", monthDays(2000, 2), "days") # 29? print("February 1900 had", monthDays(1900, 2), "days") # 28? y, m, d = nextDay(2017, 1, 30) print(y, m, d) # 2017 1 31 ? y, m, d = nextDay(2017, 1, 31) print(y, m, d) # 2017 2 1 ? y, m, d = nextDay(2017, 2, 28) print(y, m, d) # 2017 3 1 ? y, m, d = nextDay(2016, 2, 29) print(y, m, d) # 2016 3 1 ? y, m, d = nextDay(2017, 12, 31) print(y, m, d) # 2018 1 1 ? # call the main function main()
def is_leap_year(year): if year % 100 == 0: return True if year % 400 == 0 else False elif year % 4 == 0: return True else: return False def month_days(year, month): monthdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) if month == 2 and is_leap_year(year): return 29 return MONTHDAYS[month - 1] def next_day(year, month, day): if day == month_days(year, month): if month == 12: return (year + 1, 1, 1) else: return (year, month + 1, 1) return (year, month, day + 1) def main(): print('Was', 2017, 'a leap year?', is_leap_year(2017)) print('Was', 2016, 'a leap year?', is_leap_year(2016)) print('Was', 2000, 'a leap year?', is_leap_year(2000)) print('Was', 1900, 'a leap year?', is_leap_year(1900)) print('January 2017 had', month_days(2017, 1), 'days') print('February 2017 had', month_days(2017, 2), 'days') print('February 2016 had', month_days(2016, 2), 'days') print('February 2000 had', month_days(2000, 2), 'days') print('February 1900 had', month_days(1900, 2), 'days') (y, m, d) = next_day(2017, 1, 30) print(y, m, d) (y, m, d) = next_day(2017, 1, 31) print(y, m, d) (y, m, d) = next_day(2017, 2, 28) print(y, m, d) (y, m, d) = next_day(2016, 2, 29) print(y, m, d) (y, m, d) = next_day(2017, 12, 31) print(y, m, d) main()
#encoding:utf-8 subreddit = 'wtf' t_channel = '@reddit_wtf' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'wtf' t_channel = '@reddit_wtf' def send_post(submission, r2t): return r2t.send_simple(submission)
programming_languages = ["Python", "Scala", "Haskell", "F#", "C#", "JavaScript"] for lang in programming_languages: if (lang == "Haskell"): continue print("Found Haskell !!!", end='\n') # this statement will never be executed print(lang, end=' ')
programming_languages = ['Python', 'Scala', 'Haskell', 'F#', 'C#', 'JavaScript'] for lang in programming_languages: if lang == 'Haskell': continue print('Found Haskell !!!', end='\n') print(lang, end=' ')
inc = 1 num = 1 for x in range (5,0,-1): for y in range(x,0,-1): print(" ",end="") print(str(num)*inc) num += 2 inc += 2
inc = 1 num = 1 for x in range(5, 0, -1): for y in range(x, 0, -1): print(' ', end='') print(str(num) * inc) num += 2 inc += 2
n = int(input()) a = list(map(int, input().split())) k_max = 0 g_max = 0 for k in range(2, max(a) + 1): gcdness = 0 for elem in a: if elem % k == 0: gcdness += 1 if gcdness >= g_max: g_max = gcdness k_max = k print(k_max)
n = int(input()) a = list(map(int, input().split())) k_max = 0 g_max = 0 for k in range(2, max(a) + 1): gcdness = 0 for elem in a: if elem % k == 0: gcdness += 1 if gcdness >= g_max: g_max = gcdness k_max = k print(k_max)
# 326. Power of Three # ttungl@gmail.com # Given an integer, write a function to determine if it is a power of three. # Follow up: # Could you do it without using any loop / recursion? class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ # sol 1: follow-up # runtime: 193ms # Use 3^19 (is 1162261467), bcos 3^20 is bigger than int. return n > 0 and (3**19 % n) == 0 # sol 2: # runtime: 205ms if n <= 0: return False while n % 3==0: n/=3 return n==1
class Solution(object): def is_power_of_three(self, n): """ :type n: int :rtype: bool """ return n > 0 and 3 ** 19 % n == 0 if n <= 0: return False while n % 3 == 0: n /= 3 return n == 1
class Solution: def getSmallestString(self, n: int, k: int) -> str: result = "" for index in range(n): digitsLeft = n - index - 1 for c in range(1, 27): if k - c <= digitsLeft * 26: k -= c result += chr(ord('a') + c -1) break return result
class Solution: def get_smallest_string(self, n: int, k: int) -> str: result = '' for index in range(n): digits_left = n - index - 1 for c in range(1, 27): if k - c <= digitsLeft * 26: k -= c result += chr(ord('a') + c - 1) break return result
a_val = int(input()) b_val = int(input()) def gcd(a, b): if b > a: a, b = b, a if a % b == 0: return b else: return gcd(b, a % b) def reduce_fraction(n, m): divider = gcd(n, m) return int(n / divider), int(m / divider) result = reduce_fraction(a_val, b_val) print(*result)
a_val = int(input()) b_val = int(input()) def gcd(a, b): if b > a: (a, b) = (b, a) if a % b == 0: return b else: return gcd(b, a % b) def reduce_fraction(n, m): divider = gcd(n, m) return (int(n / divider), int(m / divider)) result = reduce_fraction(a_val, b_val) print(*result)
class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 0 elif n < 0: return (1.0 / x) ** abs(n) else: return x ** n s = Solution() print(s.myPow(2.00000, 10))
class Solution: def my_pow(self, x: float, n: int) -> float: if n == 0: return 0 elif n < 0: return (1.0 / x) ** abs(n) else: return x ** n s = solution() print(s.myPow(2.0, 10))
MOD = 998244353 r, c, n = map(int, input().split()) dp = [[0] * (1 << c) for _ in range(r + 1)] dp[0][0] = 1 for row in range(r): for bit_prev in range(1 << c): bit_prev <<= 1 for bit in range(1 << c): bit <<= 1 count = 0 for i in range(c + 1): if ((bit_prev >> i) & 1 + (bit_prev >> i + 1) & 1 + (bit >> i) & 1 + (bit >> i + 1) & 1) & 1: count += 1 bit >>= 1 dp[row + 1][bit] += count print(sum(dp[-1]))
mod = 998244353 (r, c, n) = map(int, input().split()) dp = [[0] * (1 << c) for _ in range(r + 1)] dp[0][0] = 1 for row in range(r): for bit_prev in range(1 << c): bit_prev <<= 1 for bit in range(1 << c): bit <<= 1 count = 0 for i in range(c + 1): if bit_prev >> i & 1 + (bit_prev >> i + 1) & 1 + (bit >> i) & 1 + (bit >> i + 1) & 1 & 1: count += 1 bit >>= 1 dp[row + 1][bit] += count print(sum(dp[-1]))