content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
s = b'abcdefgabc' print(s) print('c:', s.rindex(b'c')) print('c:', s.index(b'c')) #print('z:', s.rindex(b'z'))#ValueError: subsection not found s = bytearray(b'abcdefgabc') print(s) print('c:', s.rindex(bytearray(b'c'))) print('c:', s.index(bytearray(b'c'))) #print('z:', s.rindex(bytearray(b'z')))#ValueError: subsection not found
s = b'abcdefgabc' print(s) print('c:', s.rindex(b'c')) print('c:', s.index(b'c')) s = bytearray(b'abcdefgabc') print(s) print('c:', s.rindex(bytearray(b'c'))) print('c:', s.index(bytearray(b'c')))
def bubblesort(vals): changed = True while changed: changed = False for i in range(len(vals) - 1): if vals[i] > vals[i + 1]: changed = True vals[i], vals[i + 1] = vals[i + 1], vals[i] # Yield gives the "state" yield vals vals = [int(x) for x in input().split()] for state in bubblesort(vals): print(*state)
def bubblesort(vals): changed = True while changed: changed = False for i in range(len(vals) - 1): if vals[i] > vals[i + 1]: changed = True (vals[i], vals[i + 1]) = (vals[i + 1], vals[i]) yield vals vals = [int(x) for x in input().split()] for state in bubblesort(vals): print(*state)
#!/usr/bin/env python # -*- coding: utf-8 -*- # This script contains functions that don't belong to a specific category. # The buffer_size function computes a buffer around the input ee.Element # whilst the get_metrics function returns the accuracy metrics of the input # classifier and test set. # # Author: Davide Lomeo, # Email: davide.lomeo20@imperial.ac.uk # GitHub: https://github.com/acse-2020/acse2020-acse9-finalreport-acse-dl1420-3 # Date: 19 July 2021 # Version: 0.1.0 __all__ = ['buffer_size', 'get_metrics'] def buffer_size(size): """ Function that uses the concept of currying to help the .map() method take more than one argument. The function uses the input 'size' and call a nested function to create a buffer around the centroid of the feature parsed by the .map() method.The geometry of the parsed feature is modified in place. Parameters ---------- size : int Distance of the buffering in meters Returns ------- ee.element.Element Feature with a buffer of 'size' around its centroid """ def create_buffer(feature): """Child function that creates the buffer of 'size' meters""" return feature.buffer(size) return create_buffer def get_metrics(classifier, test_dataset, class_columns_name, metrics=['error_matrix'], decimal=4): """ Function that requires a trained classifier and a test set to return a dictionary that contains the chosen metrics. metrics available are: 'train_accuracy', 'test_accuracy', 'kappa_coefficient', 'producers_accuracy', 'consumers_accuracy', 'error_matrix'. NOTE: use this function carefully, especially if wanting to return more than one of the available metrics. This is because the values are retrieved directly from the Google sevrer using the method .getInfo() and it may take up to 15 minutes to get all the metrics. Parameters ---------- classifier : ee.classifier.Classifier Trained classifier needed to evaluate the test set test_dataset : ee.featurecollection.FeatureCollection Feature Collction that needed to evaluate the classifier class_column_name : string Name of the classification column in the input Collection metrics : list, optional List of metrics to return as a dictionary decimal : int, optional Number of decimals for each figure Returns ------- dictionary A dictionary containing the selected metrics """ try: # Clssification of the test dataset test = test_dataset.classify(classifier) # Accuracy of the training dataset classifier training_accuracy = classifier.confusionMatrix().accuracy() # Error matrix of the test set error_matrix = test.errorMatrix(class_columns_name, 'classification') # Computing consumers and producers accuracies producers_accuracy = error_matrix.producersAccuracy() consumers_accuracy = error_matrix.consumersAccuracy() except AttributeError: print(""" Error: one of the inputs is invalid. Please only input a ee.Classifier, a ee.FeatureCollection and a string respectively""") return None metrics_dict = {} for i in metrics: if i == 'train_accuracy': metrics_dict[i] = round(training_accuracy.getInfo(), decimal) elif i == 'test_accuracy:': metrics_dict[i] = round(error_matrix.accuracy().getInfo(), decimal) elif i == 'kappa_coefficient:': metrics_dict[i] = round(error_matrix.kappa().getInfo(), decimal) elif i == 'producers_accuracy': metrics_dict[i] = producers_accuracy.getInfo() for i, j in enumerate(metrics_dict['producers_accuracy'][0]): metrics_dict['producers_accuracy'][0][i] = round(j, decimal) elif i == 'consumers_accuracy': metrics_dict[i] = consumers_accuracy.getInfo() for i, j in enumerate(metrics_dict['consumers_accuracy'][0]): metrics_dict['consumers_accuracy'][0][i] = round(j, decimal) elif i == 'error_matrix': metrics_dict[i] = error_matrix.getInfo() else: print( "'{}' isn't a valid metric. Please correct the input".format(i) ) return None return metrics_dict
__all__ = ['buffer_size', 'get_metrics'] def buffer_size(size): """ Function that uses the concept of currying to help the .map() method take more than one argument. The function uses the input 'size' and call a nested function to create a buffer around the centroid of the feature parsed by the .map() method.The geometry of the parsed feature is modified in place. Parameters ---------- size : int Distance of the buffering in meters Returns ------- ee.element.Element Feature with a buffer of 'size' around its centroid """ def create_buffer(feature): """Child function that creates the buffer of 'size' meters""" return feature.buffer(size) return create_buffer def get_metrics(classifier, test_dataset, class_columns_name, metrics=['error_matrix'], decimal=4): """ Function that requires a trained classifier and a test set to return a dictionary that contains the chosen metrics. metrics available are: 'train_accuracy', 'test_accuracy', 'kappa_coefficient', 'producers_accuracy', 'consumers_accuracy', 'error_matrix'. NOTE: use this function carefully, especially if wanting to return more than one of the available metrics. This is because the values are retrieved directly from the Google sevrer using the method .getInfo() and it may take up to 15 minutes to get all the metrics. Parameters ---------- classifier : ee.classifier.Classifier Trained classifier needed to evaluate the test set test_dataset : ee.featurecollection.FeatureCollection Feature Collction that needed to evaluate the classifier class_column_name : string Name of the classification column in the input Collection metrics : list, optional List of metrics to return as a dictionary decimal : int, optional Number of decimals for each figure Returns ------- dictionary A dictionary containing the selected metrics """ try: test = test_dataset.classify(classifier) training_accuracy = classifier.confusionMatrix().accuracy() error_matrix = test.errorMatrix(class_columns_name, 'classification') producers_accuracy = error_matrix.producersAccuracy() consumers_accuracy = error_matrix.consumersAccuracy() except AttributeError: print('\n Error: one of the inputs is invalid. Please only input a ee.Classifier,\n a ee.FeatureCollection and a string respectively') return None metrics_dict = {} for i in metrics: if i == 'train_accuracy': metrics_dict[i] = round(training_accuracy.getInfo(), decimal) elif i == 'test_accuracy:': metrics_dict[i] = round(error_matrix.accuracy().getInfo(), decimal) elif i == 'kappa_coefficient:': metrics_dict[i] = round(error_matrix.kappa().getInfo(), decimal) elif i == 'producers_accuracy': metrics_dict[i] = producers_accuracy.getInfo() for (i, j) in enumerate(metrics_dict['producers_accuracy'][0]): metrics_dict['producers_accuracy'][0][i] = round(j, decimal) elif i == 'consumers_accuracy': metrics_dict[i] = consumers_accuracy.getInfo() for (i, j) in enumerate(metrics_dict['consumers_accuracy'][0]): metrics_dict['consumers_accuracy'][0][i] = round(j, decimal) elif i == 'error_matrix': metrics_dict[i] = error_matrix.getInfo() else: print("'{}' isn't a valid metric. Please correct the input".format(i)) return None return metrics_dict
r = '\033[31m' # red b = '\033[34m' # blue g = '\033[32m' # green y = '\033[33m' # yellow f = '\33[m' bb = '\033[44m' # backgournd blue def tela(mensagem, colunatxt=5): espaco = bb + ' ' + f mensagem = bb + y + mensagem for i in range(12): print('') if i == 5: print(espaco * colunatxt + mensagem + espaco*(50 - (len(mensagem)-colunatxt)), end='') else: for ii in range(50): print(espaco, end='') print() tela('aqui tem uma mensagem escrita')
r = '\x1b[31m' b = '\x1b[34m' g = '\x1b[32m' y = '\x1b[33m' f = '\x1b[m' bb = '\x1b[44m' def tela(mensagem, colunatxt=5): espaco = bb + ' ' + f mensagem = bb + y + mensagem for i in range(12): print('') if i == 5: print(espaco * colunatxt + mensagem + espaco * (50 - (len(mensagem) - colunatxt)), end='') else: for ii in range(50): print(espaco, end='') print() tela('aqui tem uma mensagem escrita')
"""This package contains components for working with switches.""" __all__ = ( "momentary_switch", "momentary_switch_component", "switch", "switch_state", "switch_state_change_event", "toggle_switch", "toggle_switch_component" )
"""This package contains components for working with switches.""" __all__ = ('momentary_switch', 'momentary_switch_component', 'switch', 'switch_state', 'switch_state_change_event', 'toggle_switch', 'toggle_switch_component')
tst = int(input()) ids = [ int(w) for w in input().split(',') if w != 'x' ] def wait_time(bus_id): return (bus_id - tst % bus_id, bus_id) min_id = min(map(wait_time, ids)) print(f"{min_id=}")
tst = int(input()) ids = [int(w) for w in input().split(',') if w != 'x'] def wait_time(bus_id): return (bus_id - tst % bus_id, bus_id) min_id = min(map(wait_time, ids)) print(f'min_id={min_id!r}')
# Aiden Baker # 2/12/2021 # DoNow103 print(2*3*5) print("abc") print("abc"+"bde")
print(2 * 3 * 5) print('abc') print('abc' + 'bde')
name = "ServerName" user = "mongo" japd = None host = "hostname" port = 27017 auth = False auth_db = "admin" use_arg = True use_uri = False repset = "ReplicaSet" repset_hosts = ["host1:27017", "host2:27017"]
name = 'ServerName' user = 'mongo' japd = None host = 'hostname' port = 27017 auth = False auth_db = 'admin' use_arg = True use_uri = False repset = 'ReplicaSet' repset_hosts = ['host1:27017', 'host2:27017']
def solution(xs): """Returns integer representing maximum power output of solar panel array Args: xs: List of integers representing power output of each of the solar panels in a given array """ negatives = [] smallest_negative = None positives = [] contains_panel_with_zero_power = False if isinstance(xs, list) and not xs: raise IndexError("xs must be a non-empty list. Empty list received.") for x in xs: if x > 0: positives.append(x) if x < 0: if not smallest_negative or abs(smallest_negative) > abs(x): smallest_negative = x negatives.append(x) if x == 0: contains_panel_with_zero_power = True if not positives and len(negatives) == 1: # Best-case scenario is zero power output for panel array. Looking bad. if contains_panel_with_zero_power: max_power = 0 else: # Panel array is draining power. Ouch. max_power = negatives.pop() return str(max_power) # Ensures panels with negative outputs are in pairs to take # advantage of the panels' wave stabilizer, which makes paired # negative-output panels have a positive output together if positives and len(negatives) % 2 != 0: negatives.remove(smallest_negative) max_power = 1 # initialize for multiplication panel_outputs = positives panel_outputs.extend(negatives) for output in panel_outputs: max_power *= output return str(max_power)
def solution(xs): """Returns integer representing maximum power output of solar panel array Args: xs: List of integers representing power output of each of the solar panels in a given array """ negatives = [] smallest_negative = None positives = [] contains_panel_with_zero_power = False if isinstance(xs, list) and (not xs): raise index_error('xs must be a non-empty list. Empty list received.') for x in xs: if x > 0: positives.append(x) if x < 0: if not smallest_negative or abs(smallest_negative) > abs(x): smallest_negative = x negatives.append(x) if x == 0: contains_panel_with_zero_power = True if not positives and len(negatives) == 1: if contains_panel_with_zero_power: max_power = 0 else: max_power = negatives.pop() return str(max_power) if positives and len(negatives) % 2 != 0: negatives.remove(smallest_negative) max_power = 1 panel_outputs = positives panel_outputs.extend(negatives) for output in panel_outputs: max_power *= output return str(max_power)
class GlobalConfig: def __init__(self): self.logger_name = "ecom" self.log_level = "INFO" self.vocab_filename = "products.vocab" self.labels_filename = "labels.vocab" self.model_filename = "classifier.mdl" gconf = GlobalConfig()
class Globalconfig: def __init__(self): self.logger_name = 'ecom' self.log_level = 'INFO' self.vocab_filename = 'products.vocab' self.labels_filename = 'labels.vocab' self.model_filename = 'classifier.mdl' gconf = global_config()
def fact(n): if n > 0: return (n*fact(n - 1)) else: return 1 print(fact(5))
def fact(n): if n > 0: return n * fact(n - 1) else: return 1 print(fact(5))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 3 14:39:32 2020 @author: zo """ def tokenizer_and_model_config_mismatch(config, tokenizer): """ Check for tokenizer and model config miss match. Args: config: model config. tokenizer: tokenizer. Raises: ValueError: A special token id in config is different from tokenizer. """ id_check_list = ['bos_token_id', 'eos_token_id', 'pad_token_id', 'mask_token_id', 'unk_token_id'] for id_type in id_check_list: if getattr(config, id_type) != getattr(tokenizer, id_type): # We should tell how to resolve it. raise ValueError('A special token id in config is different from tokenizer') def block_size_exceed_max_position_embeddings(config, block_size): # This will cause position ids automatically create from model # to go beyond embedding size of position id embedding. # And return not so useful error. # This sound like a bug in transformers library. # If we got this error the work around for now id to set # `max_position_embeddings` of model config to be higher than or equal to # `max_seq_len + config.pad_token_id + 1` at least to avoid problem. if(block_size > config.max_position_embeddings + config.pad_token_id + 1): recommend_block_size = config.max_position_embeddings + config.pad_token_id + 1 raise ValueError(f'This block size will cause error due to max_position_embeddings. ' f'Use this block_size={recommend_block_size} or ' f'increase max_position_embeddings')
""" Created on Tue Nov 3 14:39:32 2020 @author: zo """ def tokenizer_and_model_config_mismatch(config, tokenizer): """ Check for tokenizer and model config miss match. Args: config: model config. tokenizer: tokenizer. Raises: ValueError: A special token id in config is different from tokenizer. """ id_check_list = ['bos_token_id', 'eos_token_id', 'pad_token_id', 'mask_token_id', 'unk_token_id'] for id_type in id_check_list: if getattr(config, id_type) != getattr(tokenizer, id_type): raise value_error('A special token id in config is different from tokenizer') def block_size_exceed_max_position_embeddings(config, block_size): if block_size > config.max_position_embeddings + config.pad_token_id + 1: recommend_block_size = config.max_position_embeddings + config.pad_token_id + 1 raise value_error(f'This block size will cause error due to max_position_embeddings. Use this block_size={recommend_block_size} or increase max_position_embeddings')
#!/usr/bin/env python3 class Service: def __init__(self, kube_connector, resource): self.__resource = resource self.__kube_connector = kube_connector self.__extract_meta() def __extract_meta(self): self.namespace = self.__resource.metadata.namespace self.name = self.__resource.metadata.name self.selector = self.__resource.spec.selector self.labels = self.__resource.metadata.labels if self.__resource.metadata.labels else {}
class Service: def __init__(self, kube_connector, resource): self.__resource = resource self.__kube_connector = kube_connector self.__extract_meta() def __extract_meta(self): self.namespace = self.__resource.metadata.namespace self.name = self.__resource.metadata.name self.selector = self.__resource.spec.selector self.labels = self.__resource.metadata.labels if self.__resource.metadata.labels else {}
BOT_NAME = 'AmazonHeadSetScraping' SPIDER_MODULES = ['AmazonHeadSetScraping.spiders'] NEWSPIDER_MODULE = 'AmazonHeadSetScraping.spiders' USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0' DOWNLOAD_DELAY = 3 DOWNLOAD_TIMEOUT = 30 RANDOMIZE_DOWNLOAD_DELAY = True REACTOR_THREADPOOL_MAXSIZE = 8 CONCURRENT_REQUESTS = 16 CONCURRENT_REQUESTS_PER_DOMAIN = 16 CONCURRENT_REQUESTS_PER_IP = 16 AUTOTHROTTLE_ENABLED = True AUTOTHROTTLE_START_DELAY = 1 AUTOTHROTTLE_MAX_DELAY = 3 AUTOTHROTTLE_TARGET_CONCURRENCY = 8 AUTOTHROTTLE_DEBUG = True RETRY_ENABLED = True RETRY_TIMES = 3 RETRY_HTTP_CODES = [500, 502, 503, 504, 400, 401, 403, 404, 405, 406, 407, 408, 409, 410, 429] DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, 'scrapy.spidermiddlewares.referer.RefererMiddleware': 80, 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90, 'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 120, 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware': 130, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware': 900, }
bot_name = 'AmazonHeadSetScraping' spider_modules = ['AmazonHeadSetScraping.spiders'] newspider_module = 'AmazonHeadSetScraping.spiders' user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0' download_delay = 3 download_timeout = 30 randomize_download_delay = True reactor_threadpool_maxsize = 8 concurrent_requests = 16 concurrent_requests_per_domain = 16 concurrent_requests_per_ip = 16 autothrottle_enabled = True autothrottle_start_delay = 1 autothrottle_max_delay = 3 autothrottle_target_concurrency = 8 autothrottle_debug = True retry_enabled = True retry_times = 3 retry_http_codes = [500, 502, 503, 504, 400, 401, 403, 404, 405, 406, 407, 408, 409, 410, 429] downloader_middlewares = {'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, 'scrapy.spidermiddlewares.referer.RefererMiddleware': 80, 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90, 'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 120, 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware': 130, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware': 900}
#!/usr/bin/python DIR = "data_tmp/" FILES = {} FILES['20_avg'] = [] FILES['40_avg'] = [] FILES['50_avg'] = [] FILES['60_avg'] = [] FILES['80_avg'] = [] FILES['20_opt'] = [] FILES['40_opt'] = [] FILES['50_opt'] = [] FILES['60_opt'] = [] FILES['80_opt'] = [] FILES['20_avg'].append("04_attk2_avg20_20_test") FILES['20_avg'].append("04_attk2_avg20_40_test") FILES['20_avg'].append("04_attk2_avg20_60_test") FILES['20_avg'].append("04_attk2_avg20_80_test") FILES['40_avg'].append("04_attk2_avg40_20_test") FILES['40_avg'].append("04_attk2_avg40_40_test") FILES['40_avg'].append("04_attk2_avg40_60_test") FILES['40_avg'].append("04_attk2_avg40_80_test") FILES['50_avg'].append("04_attk2_avg50_20_test") FILES['50_avg'].append("04_attk2_avg50_40_test") FILES['50_avg'].append("04_attk2_avg50_60_test") FILES['50_avg'].append("04_attk2_avg50_80_test") FILES['60_avg'].append("04_attk2_avg60_20_test") FILES['60_avg'].append("04_attk2_avg60_40_test") FILES['60_avg'].append("04_attk2_avg60_60_test") FILES['60_avg'].append("04_attk2_avg60_80_test") FILES['80_avg'].append("04_attk2_avg80_20_test") FILES['80_avg'].append("04_attk2_avg80_40_test") FILES['80_avg'].append("04_attk2_avg80_60_test") FILES['80_avg'].append("04_attk2_avg80_80_test") FILES['20_opt'].append("05_attk2_opt20_20_test") FILES['20_opt'].append("05_attk2_opt20_40_test") FILES['20_opt'].append("05_attk2_opt20_60_test") FILES['20_opt'].append("05_attk2_opt20_80_test") FILES['40_opt'].append("05_attk2_opt40_20_test") FILES['40_opt'].append("05_attk2_opt40_40_test") FILES['40_opt'].append("05_attk2_opt40_60_test") FILES['40_opt'].append("05_attk2_opt40_80_test") FILES['50_opt'].append("05_attk2_opt50_20_test") FILES['50_opt'].append("05_attk2_opt50_40_test") FILES['50_opt'].append("05_attk2_opt50_60_test") FILES['50_opt'].append("05_attk2_opt50_80_test") FILES['60_opt'].append("05_attk2_opt60_20_test") FILES['60_opt'].append("05_attk2_opt60_40_test") FILES['60_opt'].append("05_attk2_opt60_60_test") FILES['60_opt'].append("05_attk2_opt60_80_test") FILES['80_opt'].append("05_attk2_opt80_20_test") FILES['80_opt'].append("05_attk2_opt80_40_test") FILES['80_opt'].append("05_attk2_opt80_60_test") FILES['80_opt'].append("05_attk2_opt80_80_test") # AVG nums = [] for id in ['20_avg', '40_avg', '50_avg', '60_avg', '80_avg']: for ff in FILES[id]: with open(DIR + ff, 'r') as f: print("Working on " + ff) lines = f.readlines() nums.append(lines[4].split()[2]) f.close() with open(DIR + "09-workers-data-avg.txt", 'w') as f: f.write('- - "20% Data Alteration" - "40% Data Alteration" - "50% Data Alteration" - "60% Data Alteration" - "80% Data Alteration "\n') f.write("20 20% " + nums[0] + " " + nums[1] + " " + nums[2] + " " + nums[3] + "\n") f.write("40 40% " + nums[4] + " " + nums[5] + " " + nums[6] + " " + nums[7] + "\n") f.write("50 50% " + nums[8] + " " + nums[9] + " " + nums[10] + " " + nums[11] + "\n") f.write("60 60% " + nums[12] + " " + nums[13] + " " + nums[14] + " " + nums[15] + "\n") f.write("80 80% " + nums[16] + " " + nums[17] + " " + nums[17] + " " + nums[19] + "\n") f.close() # OPT nums = [] for id in ['20_opt', '40_opt', '50_opt', '60_opt', '80_opt']: for ff in FILES[id]: with open(DIR + ff, 'r') as f: print("Working on " + ff) lines = f.readlines() nums.append(lines[4].split()[2]) f.close() with open(DIR + "09-workers-data-opt.txt", 'w') as f: f.write('- - "20% Data Alteration" - "40% Data Alteration" - "50% Data Alteration" - "60% Data Alteration" - "80% Data Alteration "\n') f.write("20 20% " + nums[0] + " " + nums[1] + " " + nums[2] + " " + nums[3] + "\n") f.write("40 40% " + nums[4] + " " + nums[5] + " " + nums[6] + " " + nums[7] + "\n") f.write("50 50% " + nums[8] + " " + nums[9] + " " + nums[10] + " " + nums[11] + "\n") f.write("60 60% " + nums[12] + " " + nums[13] + " " + nums[14] + " " + nums[15] + "\n") f.write("80 80% " + nums[16] + " " + nums[17] + " " + nums[17] + " " + nums[19] + "\n") f.close()
dir = 'data_tmp/' files = {} FILES['20_avg'] = [] FILES['40_avg'] = [] FILES['50_avg'] = [] FILES['60_avg'] = [] FILES['80_avg'] = [] FILES['20_opt'] = [] FILES['40_opt'] = [] FILES['50_opt'] = [] FILES['60_opt'] = [] FILES['80_opt'] = [] FILES['20_avg'].append('04_attk2_avg20_20_test') FILES['20_avg'].append('04_attk2_avg20_40_test') FILES['20_avg'].append('04_attk2_avg20_60_test') FILES['20_avg'].append('04_attk2_avg20_80_test') FILES['40_avg'].append('04_attk2_avg40_20_test') FILES['40_avg'].append('04_attk2_avg40_40_test') FILES['40_avg'].append('04_attk2_avg40_60_test') FILES['40_avg'].append('04_attk2_avg40_80_test') FILES['50_avg'].append('04_attk2_avg50_20_test') FILES['50_avg'].append('04_attk2_avg50_40_test') FILES['50_avg'].append('04_attk2_avg50_60_test') FILES['50_avg'].append('04_attk2_avg50_80_test') FILES['60_avg'].append('04_attk2_avg60_20_test') FILES['60_avg'].append('04_attk2_avg60_40_test') FILES['60_avg'].append('04_attk2_avg60_60_test') FILES['60_avg'].append('04_attk2_avg60_80_test') FILES['80_avg'].append('04_attk2_avg80_20_test') FILES['80_avg'].append('04_attk2_avg80_40_test') FILES['80_avg'].append('04_attk2_avg80_60_test') FILES['80_avg'].append('04_attk2_avg80_80_test') FILES['20_opt'].append('05_attk2_opt20_20_test') FILES['20_opt'].append('05_attk2_opt20_40_test') FILES['20_opt'].append('05_attk2_opt20_60_test') FILES['20_opt'].append('05_attk2_opt20_80_test') FILES['40_opt'].append('05_attk2_opt40_20_test') FILES['40_opt'].append('05_attk2_opt40_40_test') FILES['40_opt'].append('05_attk2_opt40_60_test') FILES['40_opt'].append('05_attk2_opt40_80_test') FILES['50_opt'].append('05_attk2_opt50_20_test') FILES['50_opt'].append('05_attk2_opt50_40_test') FILES['50_opt'].append('05_attk2_opt50_60_test') FILES['50_opt'].append('05_attk2_opt50_80_test') FILES['60_opt'].append('05_attk2_opt60_20_test') FILES['60_opt'].append('05_attk2_opt60_40_test') FILES['60_opt'].append('05_attk2_opt60_60_test') FILES['60_opt'].append('05_attk2_opt60_80_test') FILES['80_opt'].append('05_attk2_opt80_20_test') FILES['80_opt'].append('05_attk2_opt80_40_test') FILES['80_opt'].append('05_attk2_opt80_60_test') FILES['80_opt'].append('05_attk2_opt80_80_test') nums = [] for id in ['20_avg', '40_avg', '50_avg', '60_avg', '80_avg']: for ff in FILES[id]: with open(DIR + ff, 'r') as f: print('Working on ' + ff) lines = f.readlines() nums.append(lines[4].split()[2]) f.close() with open(DIR + '09-workers-data-avg.txt', 'w') as f: f.write('- - "20% Data Alteration" - "40% Data Alteration" - "50% Data Alteration" - "60% Data Alteration" - "80% Data Alteration "\n') f.write('20 20% ' + nums[0] + ' ' + nums[1] + ' ' + nums[2] + ' ' + nums[3] + '\n') f.write('40 40% ' + nums[4] + ' ' + nums[5] + ' ' + nums[6] + ' ' + nums[7] + '\n') f.write('50 50% ' + nums[8] + ' ' + nums[9] + ' ' + nums[10] + ' ' + nums[11] + '\n') f.write('60 60% ' + nums[12] + ' ' + nums[13] + ' ' + nums[14] + ' ' + nums[15] + '\n') f.write('80 80% ' + nums[16] + ' ' + nums[17] + ' ' + nums[17] + ' ' + nums[19] + '\n') f.close() nums = [] for id in ['20_opt', '40_opt', '50_opt', '60_opt', '80_opt']: for ff in FILES[id]: with open(DIR + ff, 'r') as f: print('Working on ' + ff) lines = f.readlines() nums.append(lines[4].split()[2]) f.close() with open(DIR + '09-workers-data-opt.txt', 'w') as f: f.write('- - "20% Data Alteration" - "40% Data Alteration" - "50% Data Alteration" - "60% Data Alteration" - "80% Data Alteration "\n') f.write('20 20% ' + nums[0] + ' ' + nums[1] + ' ' + nums[2] + ' ' + nums[3] + '\n') f.write('40 40% ' + nums[4] + ' ' + nums[5] + ' ' + nums[6] + ' ' + nums[7] + '\n') f.write('50 50% ' + nums[8] + ' ' + nums[9] + ' ' + nums[10] + ' ' + nums[11] + '\n') f.write('60 60% ' + nums[12] + ' ' + nums[13] + ' ' + nums[14] + ' ' + nums[15] + '\n') f.write('80 80% ' + nums[16] + ' ' + nums[17] + ' ' + nums[17] + ' ' + nums[19] + '\n') f.close()
class Int32CollectionConverter(TypeConverter): """ Converts an System.Windows.Media.Int32Collection to and from other data types. Int32CollectionConverter() """ def CanConvertFrom(self,*__args): """ CanConvertFrom(self: Int32CollectionConverter,context: ITypeDescriptorContext,sourceType: Type) -> bool Determines if the converter can convert an object of the given type to an instance of System.Windows.Media.Int32Collection. context: Describes the context information of a type. sourceType: The type of the source that is being evaluated for conversion. Returns: true if the converter can convert the provided type to an instance of System.Windows.Media.Int32Collection; otherwise,false. """ pass def CanConvertTo(self,*__args): """ CanConvertTo(self: Int32CollectionConverter,context: ITypeDescriptorContext,destinationType: Type) -> bool Determines if the converter can convert an System.Windows.Media.Int32Collection to a given data type. context: The context information of a type. destinationType: The desired type to evaluate the conversion to. Returns: true if an System.Windows.Media.Int32Collection can convert to destinationType; otherwise false. """ pass def ConvertFrom(self,*__args): """ ConvertFrom(self: Int32CollectionConverter,context: ITypeDescriptorContext,culture: CultureInfo,value: object) -> object Attempts to convert a specified object to an System.Windows.Media.Int32Collection instance. context: Context information used for conversion. culture: Cultural information that is respected during conversion. value: The object being converted. Returns: A new instance of System.Windows.Media.Int32Collection. """ pass def ConvertTo(self,*__args): """ ConvertTo(self: Int32CollectionConverter,context: ITypeDescriptorContext,culture: CultureInfo,value: object,destinationType: Type) -> object Attempts to convert an instance of System.Windows.Media.Int32Collection to a specified type. context: Context information used for conversion. culture: Cultural information that is respected during conversion. value: System.Windows.Media.Int32Collection to convert. destinationType: Type being evaluated for conversion. Returns: A new instance of the destinationType. """ pass
class Int32Collectionconverter(TypeConverter): """ Converts an System.Windows.Media.Int32Collection to and from other data types. Int32CollectionConverter() """ def can_convert_from(self, *__args): """ CanConvertFrom(self: Int32CollectionConverter,context: ITypeDescriptorContext,sourceType: Type) -> bool Determines if the converter can convert an object of the given type to an instance of System.Windows.Media.Int32Collection. context: Describes the context information of a type. sourceType: The type of the source that is being evaluated for conversion. Returns: true if the converter can convert the provided type to an instance of System.Windows.Media.Int32Collection; otherwise,false. """ pass def can_convert_to(self, *__args): """ CanConvertTo(self: Int32CollectionConverter,context: ITypeDescriptorContext,destinationType: Type) -> bool Determines if the converter can convert an System.Windows.Media.Int32Collection to a given data type. context: The context information of a type. destinationType: The desired type to evaluate the conversion to. Returns: true if an System.Windows.Media.Int32Collection can convert to destinationType; otherwise false. """ pass def convert_from(self, *__args): """ ConvertFrom(self: Int32CollectionConverter,context: ITypeDescriptorContext,culture: CultureInfo,value: object) -> object Attempts to convert a specified object to an System.Windows.Media.Int32Collection instance. context: Context information used for conversion. culture: Cultural information that is respected during conversion. value: The object being converted. Returns: A new instance of System.Windows.Media.Int32Collection. """ pass def convert_to(self, *__args): """ ConvertTo(self: Int32CollectionConverter,context: ITypeDescriptorContext,culture: CultureInfo,value: object,destinationType: Type) -> object Attempts to convert an instance of System.Windows.Media.Int32Collection to a specified type. context: Context information used for conversion. culture: Cultural information that is respected during conversion. value: System.Windows.Media.Int32Collection to convert. destinationType: Type being evaluated for conversion. Returns: A new instance of the destinationType. """ pass
def list_of_lists(l, n): q = len(l) // n r = len(l) % n if r == 0: return [l[i * n:(i + 1) * n] for i in range(q)] else: return [l[i * n:(i + 1) * n] if i <= q else l[i * n:i * n + r] for i in range(q + 1)]
def list_of_lists(l, n): q = len(l) // n r = len(l) % n if r == 0: return [l[i * n:(i + 1) * n] for i in range(q)] else: return [l[i * n:(i + 1) * n] if i <= q else l[i * n:i * n + r] for i in range(q + 1)]
"""Type stubs for gi.repository.GLib.""" class Error(Exception): """Horrific GLib Error God Object.""" @property def message(self) -> str: ... class MainLoop: def run(self) -> None: ... def quit(self) -> None: ...
"""Type stubs for gi.repository.GLib.""" class Error(Exception): """Horrific GLib Error God Object.""" @property def message(self) -> str: ... class Mainloop: def run(self) -> None: ... def quit(self) -> None: ...
class PrefixList: """ The PrefixList holds the data received from routing registries and the validation results of this data. """ def __init__(self, name): self.name = name self.members = {} def __iter__(self): for asn in self.members: yield self.members[asn] def add_member(self, member): if member.asn in self.members: return memb = { "asn": member.asn, "permit": None, "inet": [], "inet6": [] } for prefix in member.inet: p = { "prefix": prefix, "permit": None } memb["inet"].append(p) for prefix in member.inet6: p = { "prefix": prefix, "permit": None } memb["inet6"].append(p) self.members[member.asn] = memb @classmethod def from_asset(cls, asset): obj = PrefixList(asset.name) for member in asset: obj.add_member(member) return obj def debug(self): for asn in self.members: member = self.members[asn] print("AS{}: {}".format(asn, member["permit"])) for i in member["inet"]: print("--{}: {}".format(i["prefix"], i["permit"])) for i in member["inet6"]: print("--{}: {}".format(i["prefix"], i["permit"]))
class Prefixlist: """ The PrefixList holds the data received from routing registries and the validation results of this data. """ def __init__(self, name): self.name = name self.members = {} def __iter__(self): for asn in self.members: yield self.members[asn] def add_member(self, member): if member.asn in self.members: return memb = {'asn': member.asn, 'permit': None, 'inet': [], 'inet6': []} for prefix in member.inet: p = {'prefix': prefix, 'permit': None} memb['inet'].append(p) for prefix in member.inet6: p = {'prefix': prefix, 'permit': None} memb['inet6'].append(p) self.members[member.asn] = memb @classmethod def from_asset(cls, asset): obj = prefix_list(asset.name) for member in asset: obj.add_member(member) return obj def debug(self): for asn in self.members: member = self.members[asn] print('AS{}: {}'.format(asn, member['permit'])) for i in member['inet']: print('--{}: {}'.format(i['prefix'], i['permit'])) for i in member['inet6']: print('--{}: {}'.format(i['prefix'], i['permit']))
def find_common_number(*args): result = args[0] for arr in args: result = insect_array(result, arr) return result def union_array(arr1, arr2): return list(set.union(arr1, arr2)) def insect_array(arr1, arr2): return list(set(arr1) & set(arr2)) arr1 = [1,5,10,20,40,80] arr2 = [6,27,20,80,100] arr3 = [3,4,15,20,30,70,80,120] print(find_common_number(arr1, arr2, arr3))
def find_common_number(*args): result = args[0] for arr in args: result = insect_array(result, arr) return result def union_array(arr1, arr2): return list(set.union(arr1, arr2)) def insect_array(arr1, arr2): return list(set(arr1) & set(arr2)) arr1 = [1, 5, 10, 20, 40, 80] arr2 = [6, 27, 20, 80, 100] arr3 = [3, 4, 15, 20, 30, 70, 80, 120] print(find_common_number(arr1, arr2, arr3))
# Question 2 # Convert all units of time into seconds. day = float(input("Enter number of days: ")) hour = float(input("Enter number of hours: ")) minute = float(input("Enter number of minutes: ")) second = float(input("Enter number of seconds: ")) day = day * 3600 * 24 hour *= 3600 minute *= 60 second = day + hour + minute + second print("Time: " + str(round((second),2)) +" seconds. ")
day = float(input('Enter number of days: ')) hour = float(input('Enter number of hours: ')) minute = float(input('Enter number of minutes: ')) second = float(input('Enter number of seconds: ')) day = day * 3600 * 24 hour *= 3600 minute *= 60 second = day + hour + minute + second print('Time: ' + str(round(second, 2)) + ' seconds. ')
text = """ ar-EG* Female "Microsoft Server Speech Text to Speech Voice (ar-EG, Hoda)" ar-SA Male "Microsoft Server Speech Text to Speech Voice (ar-SA, Naayf)" ca-ES Female "Microsoft Server Speech Text to Speech Voice (ca-ES, HerenaRUS)" cs-CZ Male "Microsoft Server Speech Text to Speech Voice (cs-CZ, Vit)" da-DK Female "Microsoft Server Speech Text to Speech Voice (da-DK, HelleRUS)" de-AT Male "Microsoft Server Speech Text to Speech Voice (de-AT, Michael)" de-CH Male "Microsoft Server Speech Text to Speech Voice (de-CH, Karsten)" de-DE Female "Microsoft Server Speech Text to Speech Voice (de-DE, Hedda) " de-DE Female "Microsoft Server Speech Text to Speech Voice (de-DE, HeddaRUS)" de-DE Male "Microsoft Server Speech Text to Speech Voice (de-DE, Stefan, Apollo) " el-GR Male "Microsoft Server Speech Text to Speech Voice (el-GR, Stefanos)" en-AU Female "Microsoft Server Speech Text to Speech Voice (en-AU, Catherine) " en-AU Female "Microsoft Server Speech Text to Speech Voice (en-AU, HayleyRUS)" en-CA Female "Microsoft Server Speech Text to Speech Voice (en-CA, Linda)" en-CA Female "Microsoft Server Speech Text to Speech Voice (en-CA, HeatherRUS)" en-GB Female "Microsoft Server Speech Text to Speech Voice (en-GB, Susan, Apollo)" en-GB Female "Microsoft Server Speech Text to Speech Voice (en-GB, HazelRUS)" en-GB Male "Microsoft Server Speech Text to Speech Voice (en-GB, George, Apollo)" en-IE Male "Microsoft Server Speech Text to Speech Voice (en-IE, Shaun)" en-IN Female "Microsoft Server Speech Text to Speech Voice (en-IN, Heera, Apollo)" en-IN Female "Microsoft Server Speech Text to Speech Voice (en-IN, PriyaRUS)" en-IN Male "Microsoft Server Speech Text to Speech Voice (en-IN, Ravi, Apollo)" en-US Female "Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)" en-US Female "Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)" en-US Male "Microsoft Server Speech Text to Speech Voice (en-US, BenjaminRUS)" es-ES Female "Microsoft Server Speech Text to Speech Voice (es-ES, Laura, Apollo)" es-ES Female "Microsoft Server Speech Text to Speech Voice (es-ES, HelenaRUS)" es-ES Male "Microsoft Server Speech Text to Speech Voice (es-ES, Pablo, Apollo)" es-MX Female "Microsoft Server Speech Text to Speech Voice (es-MX, HildaRUS)" es-MX Male "Microsoft Server Speech Text to Speech Voice (es-MX, Raul, Apollo)" fi-FI Female "Microsoft Server Speech Text to Speech Voice (fi-FI, HeidiRUS)" fr-CA Female "Microsoft Server Speech Text to Speech Voice (fr-CA, Caroline)" fr-CA Female "Microsoft Server Speech Text to Speech Voice (fr-CA, HarmonieRUS)" fr-CH Male "Microsoft Server Speech Text to Speech Voice (fr-CH, Guillaume)" fr-FR Female "Microsoft Server Speech Text to Speech Voice (fr-FR, Julie, Apollo)" fr-FR Female "Microsoft Server Speech Text to Speech Voice (fr-FR, HortenseRUS)" fr-FR Male "Microsoft Server Speech Text to Speech Voice (fr-FR, Paul, Apollo)" he-IL Male "Microsoft Server Speech Text to Speech Voice (he-IL, Asaf)" hi-IN Female "Microsoft Server Speech Text to Speech Voice (hi-IN, Kalpana, Apollo)" hi-IN Female "Microsoft Server Speech Text to Speech Voice (hi-IN, Kalpana)" hi-IN Male "Microsoft Server Speech Text to Speech Voice (hi-IN, Hemant)" hu-HU Male "Microsoft Server Speech Text to Speech Voice (hu-HU, Szabolcs)" id-ID Male "Microsoft Server Speech Text to Speech Voice (id-ID, Andika)" it-IT Male "Microsoft Server Speech Text to Speech Voice (it-IT, Cosimo, Apollo)" ja-JP Female "Microsoft Server Speech Text to Speech Voice (ja-JP, Ayumi, Apollo)" ja-JP Male "Microsoft Server Speech Text to Speech Voice (ja-JP, Ichiro, Apollo)" ja-JP Female "Microsoft Server Speech Text to Speech Voice (ja-JP, HarukaRUS)" ja-JP Female "Microsoft Server Speech Text to Speech Voice (ja-JP, LuciaRUS)" ja-JP Male "Microsoft Server Speech Text to Speech Voice (ja-JP, EkaterinaRUS)" ko-KR Female "Microsoft Server Speech Text to Speech Voice (ko-KR, HeamiRUS)" nb-NO Female "Microsoft Server Speech Text to Speech Voice (nb-NO, HuldaRUS)" nl-NL Female "Microsoft Server Speech Text to Speech Voice (nl-NL, HannaRUS)" pl-PL Female "Microsoft Server Speech Text to Speech Voice (pl-PL, PaulinaRUS)" pt-BR Female "Microsoft Server Speech Text to Speech Voice (pt-BR, HeloisaRUS)" pt-BR Male "Microsoft Server Speech Text to Speech Voice (pt-BR, Daniel, Apollo)" pt-PT Female "Microsoft Server Speech Text to Speech Voice (pt-PT, HeliaRUS)" ro-RO Male "Microsoft Server Speech Text to Speech Voice (ro-RO, Andrei)" ru-RU Female "Microsoft Server Speech Text to Speech Voice (ru-RU, Irina, Apollo)" ru-RU Male "Microsoft Server Speech Text to Speech Voice (ru-RU, Pavel, Apollo)" sk-SK Male "Microsoft Server Speech Text to Speech Voice (sk-SK, Filip)" sv-SE Female "Microsoft Server Speech Text to Speech Voice (sv-SE, HedvigRUS)" th-TH Male "Microsoft Server Speech Text to Speech Voice (th-TH, Pattara)" tr-TR Female "Microsoft Server Speech Text to Speech Voice (tr-TR, SedaRUS)" zh-CN Female "Microsoft Server Speech Text to Speech Voice (zh-CN, HuihuiRUS)" zh-CN Female "Microsoft Server Speech Text to Speech Voice (zh-CN, Yaoyao, Apollo)" zh-CN Male "Microsoft Server Speech Text to Speech Voice (zh-CN, Kangkang, Apollo)" zh-HK Female "Microsoft Server Speech Text to Speech Voice (zh-HK, Tracy, Apollo)" zh-HK Female "Microsoft Server Speech Text to Speech Voice (zh-HK, TracyRUS)" zh-HK Male "Microsoft Server Speech Text to Speech Voice (zh-HK, Danny, Apollo)" zh-TW Female "Microsoft Server Speech Text to Speech Voice (zh-TW, Yating, Apollo)" zh-TW Female "Microsoft Server Speech Text to Speech Voice (zh-TW, HanHanRUS)" zh-TW Male "Microsoft Server Speech Text to Speech Voice (zh-TW, Zhiwei, Apollo)" """ def clean(vals): for i in range(3): vals[i] = vals[i].strip().replace('*', '').replace('"', '') return vals def get_lang_dict(): lang_dict = {} for i in text.splitlines()[1:-1]: vals = clean(i.split('\t')) if lang_dict.get(vals[0], None) == None: lang_dict[vals[0]] = {} lang_dict[vals[0]][vals[1]] = vals[2] return lang_dict
text = '\nar-EG* \tFemale \t"Microsoft Server Speech Text to Speech Voice (ar-EG, Hoda)"\nar-SA \tMale \t"Microsoft Server Speech Text to Speech Voice (ar-SA, Naayf)"\nca-ES \tFemale \t"Microsoft Server Speech Text to Speech Voice (ca-ES, HerenaRUS)"\ncs-CZ \tMale \t"Microsoft Server Speech Text to Speech Voice (cs-CZ, Vit)"\nda-DK \tFemale \t"Microsoft Server Speech Text to Speech Voice (da-DK, HelleRUS)"\nde-AT \tMale \t"Microsoft Server Speech Text to Speech Voice (de-AT, Michael)"\nde-CH \tMale \t"Microsoft Server Speech Text to Speech Voice (de-CH, Karsten)"\nde-DE \tFemale \t"Microsoft Server Speech Text to Speech Voice (de-DE, Hedda) "\nde-DE \tFemale \t"Microsoft Server Speech Text to Speech Voice (de-DE, HeddaRUS)"\nde-DE \tMale \t"Microsoft Server Speech Text to Speech Voice (de-DE, Stefan, Apollo) "\nel-GR \tMale \t"Microsoft Server Speech Text to Speech Voice (el-GR, Stefanos)"\nen-AU \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-AU, Catherine) "\nen-AU \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-AU, HayleyRUS)"\nen-CA \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-CA, Linda)"\nen-CA \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-CA, HeatherRUS)"\nen-GB \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-GB, Susan, Apollo)"\nen-GB \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-GB, HazelRUS)"\nen-GB \tMale \t"Microsoft Server Speech Text to Speech Voice (en-GB, George, Apollo)"\nen-IE \tMale \t"Microsoft Server Speech Text to Speech Voice (en-IE, Shaun)"\nen-IN \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-IN, Heera, Apollo)"\nen-IN \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-IN, PriyaRUS)"\nen-IN \tMale \t"Microsoft Server Speech Text to Speech Voice (en-IN, Ravi, Apollo)"\nen-US \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)"\nen-US \tFemale \t"Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)"\nen-US \tMale \t"Microsoft Server Speech Text to Speech Voice (en-US, BenjaminRUS)"\nes-ES \tFemale \t"Microsoft Server Speech Text to Speech Voice (es-ES, Laura, Apollo)"\nes-ES \tFemale \t"Microsoft Server Speech Text to Speech Voice (es-ES, HelenaRUS)"\nes-ES \tMale \t"Microsoft Server Speech Text to Speech Voice (es-ES, Pablo, Apollo)"\nes-MX \tFemale \t"Microsoft Server Speech Text to Speech Voice (es-MX, HildaRUS)"\nes-MX \tMale \t"Microsoft Server Speech Text to Speech Voice (es-MX, Raul, Apollo)"\nfi-FI \tFemale \t"Microsoft Server Speech Text to Speech Voice (fi-FI, HeidiRUS)"\nfr-CA \tFemale \t"Microsoft Server Speech Text to Speech Voice (fr-CA, Caroline)"\nfr-CA \tFemale \t"Microsoft Server Speech Text to Speech Voice (fr-CA, HarmonieRUS)"\nfr-CH \tMale \t"Microsoft Server Speech Text to Speech Voice (fr-CH, Guillaume)"\nfr-FR \tFemale \t"Microsoft Server Speech Text to Speech Voice (fr-FR, Julie, Apollo)"\nfr-FR \tFemale \t"Microsoft Server Speech Text to Speech Voice (fr-FR, HortenseRUS)"\nfr-FR \tMale \t"Microsoft Server Speech Text to Speech Voice (fr-FR, Paul, Apollo)"\nhe-IL \tMale \t"Microsoft Server Speech Text to Speech Voice (he-IL, Asaf)"\nhi-IN \tFemale \t"Microsoft Server Speech Text to Speech Voice (hi-IN, Kalpana, Apollo)"\nhi-IN \tFemale \t"Microsoft Server Speech Text to Speech Voice (hi-IN, Kalpana)"\nhi-IN \tMale \t"Microsoft Server Speech Text to Speech Voice (hi-IN, Hemant)"\nhu-HU \tMale \t"Microsoft Server Speech Text to Speech Voice (hu-HU, Szabolcs)"\nid-ID \tMale \t"Microsoft Server Speech Text to Speech Voice (id-ID, Andika)"\nit-IT \tMale \t"Microsoft Server Speech Text to Speech Voice (it-IT, Cosimo, Apollo)"\nja-JP \tFemale \t"Microsoft Server Speech Text to Speech Voice (ja-JP, Ayumi, Apollo)"\nja-JP \tMale \t"Microsoft Server Speech Text to Speech Voice (ja-JP, Ichiro, Apollo)"\nja-JP \tFemale \t"Microsoft Server Speech Text to Speech Voice (ja-JP, HarukaRUS)"\nja-JP \tFemale \t"Microsoft Server Speech Text to Speech Voice (ja-JP, LuciaRUS)"\nja-JP \tMale \t"Microsoft Server Speech Text to Speech Voice (ja-JP, EkaterinaRUS)"\nko-KR \tFemale \t"Microsoft Server Speech Text to Speech Voice (ko-KR, HeamiRUS)"\nnb-NO \tFemale \t"Microsoft Server Speech Text to Speech Voice (nb-NO, HuldaRUS)"\nnl-NL \tFemale \t"Microsoft Server Speech Text to Speech Voice (nl-NL, HannaRUS)"\npl-PL \tFemale \t"Microsoft Server Speech Text to Speech Voice (pl-PL, PaulinaRUS)"\npt-BR \tFemale \t"Microsoft Server Speech Text to Speech Voice (pt-BR, HeloisaRUS)"\npt-BR \tMale \t"Microsoft Server Speech Text to Speech Voice (pt-BR, Daniel, Apollo)"\npt-PT \tFemale \t"Microsoft Server Speech Text to Speech Voice (pt-PT, HeliaRUS)"\nro-RO \tMale \t"Microsoft Server Speech Text to Speech Voice (ro-RO, Andrei)"\nru-RU \tFemale \t"Microsoft Server Speech Text to Speech Voice (ru-RU, Irina, Apollo)"\nru-RU \tMale \t"Microsoft Server Speech Text to Speech Voice (ru-RU, Pavel, Apollo)"\nsk-SK \tMale \t"Microsoft Server Speech Text to Speech Voice (sk-SK, Filip)"\nsv-SE \tFemale \t"Microsoft Server Speech Text to Speech Voice (sv-SE, HedvigRUS)"\nth-TH \tMale \t"Microsoft Server Speech Text to Speech Voice (th-TH, Pattara)"\ntr-TR \tFemale \t"Microsoft Server Speech Text to Speech Voice (tr-TR, SedaRUS)"\nzh-CN \tFemale \t"Microsoft Server Speech Text to Speech Voice (zh-CN, HuihuiRUS)"\nzh-CN \tFemale \t"Microsoft Server Speech Text to Speech Voice (zh-CN, Yaoyao, Apollo)"\nzh-CN \tMale \t"Microsoft Server Speech Text to Speech Voice (zh-CN, Kangkang, Apollo)"\nzh-HK \tFemale \t"Microsoft Server Speech Text to Speech Voice (zh-HK, Tracy, Apollo)"\nzh-HK \tFemale \t"Microsoft Server Speech Text to Speech Voice (zh-HK, TracyRUS)"\nzh-HK \tMale \t"Microsoft Server Speech Text to Speech Voice (zh-HK, Danny, Apollo)"\nzh-TW \tFemale \t"Microsoft Server Speech Text to Speech Voice (zh-TW, Yating, Apollo)"\nzh-TW \tFemale \t"Microsoft Server Speech Text to Speech Voice (zh-TW, HanHanRUS)"\nzh-TW \tMale \t"Microsoft Server Speech Text to Speech Voice (zh-TW, Zhiwei, Apollo)"\n' def clean(vals): for i in range(3): vals[i] = vals[i].strip().replace('*', '').replace('"', '') return vals def get_lang_dict(): lang_dict = {} for i in text.splitlines()[1:-1]: vals = clean(i.split('\t')) if lang_dict.get(vals[0], None) == None: lang_dict[vals[0]] = {} lang_dict[vals[0]][vals[1]] = vals[2] return lang_dict
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: """ 0 1 2. 3 [[1,2],[3],[3],[]] ^ paths = [[0, 1, 3], [0,2,3]] path = """ end = len(graph)-1 @lru_cache(maxsize=None) def dfs_bottomup(node): if node == end: return [[node]] paths = [] for next_node in graph[node]: for path in dfs_bottomup(next_node): paths.append( [node] + path) return paths return dfs_bottomup(0) def allPathsSourceTarget1(self, graph: List[List[int]]) -> List[List[int]]: """ TC - O(V*E) SC - O(V*E) """ start = 0 end = len(graph) - 1 paths = [] self.dfs_topdown(graph, start, end, paths, [0]) return paths def dfs(self, graph, node, end, paths, path): if node == end: paths.append(path[:]) return if not (0 <= node <= end): return for next_node in graph[node]: path.append(next_node) self.dfs(graph, next_node, end, paths, path) path.pop()
class Solution: def all_paths_source_target(self, graph: List[List[int]]) -> List[List[int]]: """ 0 1 2. 3 [[1,2],[3],[3],[]] ^ paths = [[0, 1, 3], [0,2,3]] path = """ end = len(graph) - 1 @lru_cache(maxsize=None) def dfs_bottomup(node): if node == end: return [[node]] paths = [] for next_node in graph[node]: for path in dfs_bottomup(next_node): paths.append([node] + path) return paths return dfs_bottomup(0) def all_paths_source_target1(self, graph: List[List[int]]) -> List[List[int]]: """ TC - O(V*E) SC - O(V*E) """ start = 0 end = len(graph) - 1 paths = [] self.dfs_topdown(graph, start, end, paths, [0]) return paths def dfs(self, graph, node, end, paths, path): if node == end: paths.append(path[:]) return if not 0 <= node <= end: return for next_node in graph[node]: path.append(next_node) self.dfs(graph, next_node, end, paths, path) path.pop()
class QueueMember: def __init__(self, number): self.number = number self.next = self self.prev = self def set_next(self, next): self.next = next def get_next(self): return self.next def set_prev(self, prev): self.prev = prev def get_prev(self): return self.prev def insert_after(self, new_next): new_next.set_next(self.next) new_next.set_prev(self) self.next.set_prev(new_next) self.set_next(new_next) def remove(self): if not self.last(): self.next.set_prev(self.prev) self.prev.set_next(self.next) def last(self): return self.next == self def main(): while True: input_string = input() if input_string == '0 0 0': return N, k, m = [int(x) for x in input_string.split()] dole_queue = None for i in range(N): if dole_queue is None: dole_queue = QueueMember(i + 1) else: dole_queue.insert_after(QueueMember(i + 1)) dole_queue = dole_queue.get_next() officer_1 = dole_queue officer_2 = dole_queue.get_next() output_string = '' while True: for _ in range(k): officer_1 = officer_1.get_next() for _ in range(m): officer_2 = officer_2.get_prev() if officer_1 == officer_2: output_string += (' ' + str(officer_1.number))[-3:] if officer_1.last(): print(output_string) break officer_1 = officer_1.get_prev() officer_2 = officer_2.get_next() officer_2.get_prev().remove() else: output_string += (' ' + str(officer_1.number))[-3:] officer_1 = officer_1.get_prev() officer_1.get_next().remove() output_string += (' ' + str(officer_2.number))[-3:] if officer_2.last(): print(output_string) break if officer_1 == officer_2: officer_1 = officer_1.get_prev() officer_2 = officer_2.get_next() officer_2.get_prev().remove() output_string += ',' main()
class Queuemember: def __init__(self, number): self.number = number self.next = self self.prev = self def set_next(self, next): self.next = next def get_next(self): return self.next def set_prev(self, prev): self.prev = prev def get_prev(self): return self.prev def insert_after(self, new_next): new_next.set_next(self.next) new_next.set_prev(self) self.next.set_prev(new_next) self.set_next(new_next) def remove(self): if not self.last(): self.next.set_prev(self.prev) self.prev.set_next(self.next) def last(self): return self.next == self def main(): while True: input_string = input() if input_string == '0 0 0': return (n, k, m) = [int(x) for x in input_string.split()] dole_queue = None for i in range(N): if dole_queue is None: dole_queue = queue_member(i + 1) else: dole_queue.insert_after(queue_member(i + 1)) dole_queue = dole_queue.get_next() officer_1 = dole_queue officer_2 = dole_queue.get_next() output_string = '' while True: for _ in range(k): officer_1 = officer_1.get_next() for _ in range(m): officer_2 = officer_2.get_prev() if officer_1 == officer_2: output_string += (' ' + str(officer_1.number))[-3:] if officer_1.last(): print(output_string) break officer_1 = officer_1.get_prev() officer_2 = officer_2.get_next() officer_2.get_prev().remove() else: output_string += (' ' + str(officer_1.number))[-3:] officer_1 = officer_1.get_prev() officer_1.get_next().remove() output_string += (' ' + str(officer_2.number))[-3:] if officer_2.last(): print(output_string) break if officer_1 == officer_2: officer_1 = officer_1.get_prev() officer_2 = officer_2.get_next() officer_2.get_prev().remove() output_string += ',' main()
class AgedPeer: def __init__(self, address, age=0): self.address = address self.age = age def __eq__(self, other): if isinstance(other, AgedPeer): return self.address == other.address return False @staticmethod def from_json(json_object): return AgedPeer(json_object['address'], json_object['age'])
class Agedpeer: def __init__(self, address, age=0): self.address = address self.age = age def __eq__(self, other): if isinstance(other, AgedPeer): return self.address == other.address return False @staticmethod def from_json(json_object): return aged_peer(json_object['address'], json_object['age'])
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) EVENT_SOURCE = 'DatadogTest' EVENT_ID = 9000 EVENT_CATEGORY = 42 INSTANCE = { 'legacy_mode': False, 'timeout': 2, 'path': 'Application', 'filters': {'source': [EVENT_SOURCE]}, }
event_source = 'DatadogTest' event_id = 9000 event_category = 42 instance = {'legacy_mode': False, 'timeout': 2, 'path': 'Application', 'filters': {'source': [EVENT_SOURCE]}}
""" Entradas Sueldo_bruto-->float-->sa Salidas Categoria-->int-->c Sueldo_neto-->float-->sn """ sa=float(input("Digite el salario bruto: ")) sn=0.0#float if(sa>=5_000_000): sn=(sa*0.10)+sa c=1 elif(sa<5_000_000 and sa>=4_300_000): sn=(sa*0.15)+sa c=2 elif(sa<4_300_000 and sa>=3_600_000): sn=(sa*0.20)+sa c=3 elif(sa<3_600_000 and sa>=2_000_000): sn=(sa*0.40)+sa c=4 elif(sa<2_000_000 and sa>=900_000): sn=(sa*0.60)+sa c=5 print("La categoria es: "+str(c)) print("El sueldo neto es de: $","{:.0f}".format(sn))
""" Entradas Sueldo_bruto-->float-->sa Salidas Categoria-->int-->c Sueldo_neto-->float-->sn """ sa = float(input('Digite el salario bruto: ')) sn = 0.0 if sa >= 5000000: sn = sa * 0.1 + sa c = 1 elif sa < 5000000 and sa >= 4300000: sn = sa * 0.15 + sa c = 2 elif sa < 4300000 and sa >= 3600000: sn = sa * 0.2 + sa c = 3 elif sa < 3600000 and sa >= 2000000: sn = sa * 0.4 + sa c = 4 elif sa < 2000000 and sa >= 900000: sn = sa * 0.6 + sa c = 5 print('La categoria es: ' + str(c)) print('El sueldo neto es de: $', '{:.0f}'.format(sn))
# 3/15 num_of_pages = int(input()) # < 10000 visited = set() shortest_path = 0 instructions = [list(map(int, input().split()))[1:] for _ in range(num_of_pages)] def choose_paths(page, history): if page not in visited: visited.add(page) if not len(instructions[page - 1]): # if this page doesn't need to lead ot any more (it is an ending) global shortest_path if shortest_path == 0 or len(history) + 1 < shortest_path: shortest_path = len(history) + 1 return history.append(page) for p in filter(lambda x: x not in history, instructions[page - 1]): choose_paths(p, history) history.pop() return choose_paths(1, []) print("Y" if len(visited) == len(instructions) else "N") print(shortest_path)
num_of_pages = int(input()) visited = set() shortest_path = 0 instructions = [list(map(int, input().split()))[1:] for _ in range(num_of_pages)] def choose_paths(page, history): if page not in visited: visited.add(page) if not len(instructions[page - 1]): global shortest_path if shortest_path == 0 or len(history) + 1 < shortest_path: shortest_path = len(history) + 1 return history.append(page) for p in filter(lambda x: x not in history, instructions[page - 1]): choose_paths(p, history) history.pop() return choose_paths(1, []) print('Y' if len(visited) == len(instructions) else 'N') print(shortest_path)
conn_info = {'host': 'vertica.server.ip.address', 'port': 5433, 'user': 'readonlyuser', 'password': 'XXXXXX', 'database': '', # 10 minutes timeout on queries 'read_timeout': 600, # default throw error on invalid UTF-8 results 'unicode_error': 'strict', # SSL is disabled by default 'ssl': False, 'connection_timeout': 5 # connection timeout is not enabled by default }
conn_info = {'host': 'vertica.server.ip.address', 'port': 5433, 'user': 'readonlyuser', 'password': 'XXXXXX', 'database': '', 'read_timeout': 600, 'unicode_error': 'strict', 'ssl': False, 'connection_timeout': 5}
# Created by MechAviv # Quest ID :: 25562 # Fostering the Dark sm.setSpeakerID(0) sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendNext("Dark magic is so much easier than light...") sm.setSpeakerID(0) sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay("But I do not fully understand it. With every minor touch, I feel the lust for destruction well up within me. It would be foolish to use this power without more understanding.") sm.setSpeakerID(0) sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay("It's time I left this forest and found some answers.") sm.setSpeakerID(0) sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay("The world has changed in the last few centuries. Thankfully, I have a map I can check by pressing #b#e[W] (basic key setting) or [N] (secondary key settings)#n#k.") sm.startQuest(25562) sm.completeQuest(25562) sm.giveExp(900) sm.startQuest(25559)
sm.setSpeakerID(0) sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendNext('Dark magic is so much easier than light...') sm.setSpeakerID(0) sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay('But I do not fully understand it. With every minor touch, I feel the lust for destruction well up within me. It would be foolish to use this power without more understanding.') sm.setSpeakerID(0) sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay("It's time I left this forest and found some answers.") sm.setSpeakerID(0) sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay('The world has changed in the last few centuries. Thankfully, I have a map I can check by pressing #b#e[W] (basic key setting) or [N] (secondary key settings)#n#k.') sm.startQuest(25562) sm.completeQuest(25562) sm.giveExp(900) sm.startQuest(25559)
# (n, k) represent nCk # (N+M-1, N-1)-(N+M-1, N) = (N-M)/(N+M) * (N+M, N) def solution(): T = int(input()) for i in range(T): N, M = map(float, input().split(' ')) print('Case #%d: %f' % (i+1, (N-M)/(N+M))) solution()
def solution(): t = int(input()) for i in range(T): (n, m) = map(float, input().split(' ')) print('Case #%d: %f' % (i + 1, (N - M) / (N + M))) solution()
class HttpException(Exception): """ A base exception designed to support all API error handling. All exceptions should inherit from this or a subclass of it (depending on the usage), this will allow all apps and libraries to maintain a common exception chain """ def __init__(self, message, debug_message=None, code=None, status=500): super().__init__(message) self.status = status self.code = code self.message = message self.debug_message = debug_message def marshal(self): return { "code": self.code, "message": self.message, "debug_message": self.debug_message, } @classmethod def reraise(cls, message, debug_message=None, code=None, status=500): raise cls( message=message, code=code, debug_message=debug_message, status=status, ) class HttpCodeException(HttpException): status = None code = None message = None def __init__(self, debug_message=None): super().__init__(self.message, debug_message, self.code, self.status) class ServerException(HttpCodeException): status = 500 class BadRequestException(HttpCodeException): status = 400 class UnauthorisedException(HttpCodeException): status = 401 class NotFoundException(HttpCodeException): status = 404
class Httpexception(Exception): """ A base exception designed to support all API error handling. All exceptions should inherit from this or a subclass of it (depending on the usage), this will allow all apps and libraries to maintain a common exception chain """ def __init__(self, message, debug_message=None, code=None, status=500): super().__init__(message) self.status = status self.code = code self.message = message self.debug_message = debug_message def marshal(self): return {'code': self.code, 'message': self.message, 'debug_message': self.debug_message} @classmethod def reraise(cls, message, debug_message=None, code=None, status=500): raise cls(message=message, code=code, debug_message=debug_message, status=status) class Httpcodeexception(HttpException): status = None code = None message = None def __init__(self, debug_message=None): super().__init__(self.message, debug_message, self.code, self.status) class Serverexception(HttpCodeException): status = 500 class Badrequestexception(HttpCodeException): status = 400 class Unauthorisedexception(HttpCodeException): status = 401 class Notfoundexception(HttpCodeException): status = 404
# Find len of ll. k = k%l. Then mode l-k-1 steps and break the ll. Add the remaining part of the LL in the front. # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: l, ptr = 0, head while ptr: l += 1 ptr = ptr.next if l==0 or k%l==0: return head k = k % l ptr = head for _ in range(l-k-1): ptr = ptr.next new_head = ptr.next ptr.next = None ptr = new_head while ptr.next: ptr = ptr.next ptr.next = head return new_head
class Solution: def rotate_right(self, head: ListNode, k: int) -> ListNode: (l, ptr) = (0, head) while ptr: l += 1 ptr = ptr.next if l == 0 or k % l == 0: return head k = k % l ptr = head for _ in range(l - k - 1): ptr = ptr.next new_head = ptr.next ptr.next = None ptr = new_head while ptr.next: ptr = ptr.next ptr.next = head return new_head
MY_MAC = "" MY_IP = "" IFACE = "" GATEWAY_MAC = "" _SRC_DST = {} PROTO = "" CMD = "" STOP_SNIFF = False
my_mac = '' my_ip = '' iface = '' gateway_mac = '' _src_dst = {} proto = '' cmd = '' stop_sniff = False
"""Top-level package for Image to LaTeX.""" __author__ = """Oscar Arbelaez""" __email__ = 'odarbelaeze@gmail.com' __version__ = '0.2.1'
"""Top-level package for Image to LaTeX.""" __author__ = 'Oscar Arbelaez' __email__ = 'odarbelaeze@gmail.com' __version__ = '0.2.1'
# Convert the temperature from Fahrenheit to Celsius in the # function below. You can use this formula: # C = (F - 32) * 5/9 # Round the returned result to 3 decimal places. # You don't have to handle input, just implement the function # below. # Also, make sure your function returns the value. Please do NOT # print anything. # put your python code here def fahrenheit_to_celsius(fahrenheit): return round((fahrenheit - 32) * 5 / 9, 3)
def fahrenheit_to_celsius(fahrenheit): return round((fahrenheit - 32) * 5 / 9, 3)
""" Sponge Knowledge Base Action metadata Record type - sub-arguments """ def createBookRecordType(name): return RecordType(name, [ IntegerType("id").withNullable().withLabel("Identifier").withFeature("visible", False), StringType("author").withLabel("Author"), StringType("title").withLabel("Title"), ]) class Library(Action): def onConfigure(self): self.withArgs([ ListType("books").withLabel("Books").withProvided(ProvidedMeta().withValue()).withFeatures({ "createAction":SubAction("RecordCreateBook"), "updateAction":SubAction("RecordUpdateBook").withArg("book", "@this"), }).withElement( createBookRecordType("book").withAnnotated() ) ]).withNoResult() def onCall(self, search, order, books): return None def onProvideArgs(self, context): if "books" in context.provide: context.provided["books"] = ProvidedValue().withValue([ {"id":1, "author":"James Joyce", "title":"Ulysses"}, {"id":2, "author":"Arthur Conan Doyle", "title":"Adventures of Sherlock Holmes"} ]) class RecordCreateBook(Action): def onConfigure(self): self.withArgs([ createBookRecordType("book").withLabel("Book").withFields([ StringType("author").withProvided(ProvidedMeta().withValueSet(ValueSetMeta().withNotLimited())), ]) ]).withNoResult() def onCall(self, book): pass def onProvideArgs(self, context): if "book.author" in context.provide: context.provided["book.author"] = ProvidedValue().withValueSet(["James Joyce", "Arthur Conan Doyle"]) class RecordUpdateBook(Action): def onConfigure(self): self.withArg( createBookRecordType("book").withAnnotated().withProvided(ProvidedMeta().withValue().withDependency("book.id")).withFields([ StringType("author").withProvided(ProvidedMeta().withValueSet(ValueSetMeta().withNotLimited())), ]) ).withNoResult() def onProvideArgs(self, context): if "book" in context.provide: context.provided["book"] = ProvidedValue().withValue(AnnotatedValue({"id":context.current["book.id"], "author":"James Joyce", "title":"Ulysses"})) if "book.author" in context.provide: context.provided["book.author"] = ProvidedValue().withValueSet(["James Joyce", "Arthur Conan Doyle"]) def onCall(self, book): pass
""" Sponge Knowledge Base Action metadata Record type - sub-arguments """ def create_book_record_type(name): return record_type(name, [integer_type('id').withNullable().withLabel('Identifier').withFeature('visible', False), string_type('author').withLabel('Author'), string_type('title').withLabel('Title')]) class Library(Action): def on_configure(self): self.withArgs([list_type('books').withLabel('Books').withProvided(provided_meta().withValue()).withFeatures({'createAction': sub_action('RecordCreateBook'), 'updateAction': sub_action('RecordUpdateBook').withArg('book', '@this')}).withElement(create_book_record_type('book').withAnnotated())]).withNoResult() def on_call(self, search, order, books): return None def on_provide_args(self, context): if 'books' in context.provide: context.provided['books'] = provided_value().withValue([{'id': 1, 'author': 'James Joyce', 'title': 'Ulysses'}, {'id': 2, 'author': 'Arthur Conan Doyle', 'title': 'Adventures of Sherlock Holmes'}]) class Recordcreatebook(Action): def on_configure(self): self.withArgs([create_book_record_type('book').withLabel('Book').withFields([string_type('author').withProvided(provided_meta().withValueSet(value_set_meta().withNotLimited()))])]).withNoResult() def on_call(self, book): pass def on_provide_args(self, context): if 'book.author' in context.provide: context.provided['book.author'] = provided_value().withValueSet(['James Joyce', 'Arthur Conan Doyle']) class Recordupdatebook(Action): def on_configure(self): self.withArg(create_book_record_type('book').withAnnotated().withProvided(provided_meta().withValue().withDependency('book.id')).withFields([string_type('author').withProvided(provided_meta().withValueSet(value_set_meta().withNotLimited()))])).withNoResult() def on_provide_args(self, context): if 'book' in context.provide: context.provided['book'] = provided_value().withValue(annotated_value({'id': context.current['book.id'], 'author': 'James Joyce', 'title': 'Ulysses'})) if 'book.author' in context.provide: context.provided['book.author'] = provided_value().withValueSet(['James Joyce', 'Arthur Conan Doyle']) def on_call(self, book): pass
def zero(f=lambda a: a): return f(0) def one(f=lambda a: a): return f(1) def two(f=lambda a: a): return f(2) def three(f=lambda a: a): return f(3) def four(f=lambda a: a): return f(4) def five(f=lambda a: a): return f(5) def six(f=lambda a: a): return f(6) def seven(f=lambda a: a): return f(7) def eight(f=lambda a: a): return f(8) def nine(f=lambda a: a): return f(9) def plus(f): return lambda a: a + f def minus(f): return lambda a: a - f def times(f): return lambda a: a * f def divided_by(f): return lambda a: a // f def test(): assert seven(times(five())) == 35 assert four(plus(nine())) == 13 assert eight(minus(three())) == 5 assert six(divided_by(two())) == 3 pass if __name__ == "__main__": test() pass
def zero(f=lambda a: a): return f(0) def one(f=lambda a: a): return f(1) def two(f=lambda a: a): return f(2) def three(f=lambda a: a): return f(3) def four(f=lambda a: a): return f(4) def five(f=lambda a: a): return f(5) def six(f=lambda a: a): return f(6) def seven(f=lambda a: a): return f(7) def eight(f=lambda a: a): return f(8) def nine(f=lambda a: a): return f(9) def plus(f): return lambda a: a + f def minus(f): return lambda a: a - f def times(f): return lambda a: a * f def divided_by(f): return lambda a: a // f def test(): assert seven(times(five())) == 35 assert four(plus(nine())) == 13 assert eight(minus(three())) == 5 assert six(divided_by(two())) == 3 pass if __name__ == '__main__': test() pass
""" Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". """ class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ list_a = [int(i) for i in a[::-1]] list_b = [int(i) for i in b[::-1]] la = len(list_a) lb = len(list_b) # Pad zeroes if la < lb: list_a += [0 for i in range(lb - la)] la = len(list_a) else: list_b += [0 for i in range(la - lb)] lb = len(list_b) carry = 0 res = [] for i in range(la): t = (list_a[i] + list_b[i] + carry) % 2 carry = (list_a[i] + list_b[i] + carry) / 2 res.append(t) if carry == 1: res.append(1) return ''.join([str(d) for d in res[::-1]])
""" Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". """ class Solution(object): def add_binary(self, a, b): """ :type a: str :type b: str :rtype: str """ list_a = [int(i) for i in a[::-1]] list_b = [int(i) for i in b[::-1]] la = len(list_a) lb = len(list_b) if la < lb: list_a += [0 for i in range(lb - la)] la = len(list_a) else: list_b += [0 for i in range(la - lb)] lb = len(list_b) carry = 0 res = [] for i in range(la): t = (list_a[i] + list_b[i] + carry) % 2 carry = (list_a[i] + list_b[i] + carry) / 2 res.append(t) if carry == 1: res.append(1) return ''.join([str(d) for d in res[::-1]])
# coding=utf-8 """Hive: microservice powering social networks on the dPay blockchain. Hive is a "consensus interpretation" layer for the dPay blockchain, maintaining the state of social features such as post feeds, follows, and communities. Written in Python, it synchronizes an SQL database with chain state, providing developers with a more flexible/extensible alternative to the raw dpayd API. """
"""Hive: microservice powering social networks on the dPay blockchain. Hive is a "consensus interpretation" layer for the dPay blockchain, maintaining the state of social features such as post feeds, follows, and communities. Written in Python, it synchronizes an SQL database with chain state, providing developers with a more flexible/extensible alternative to the raw dpayd API. """
def ChangeText(s): print('ChangeText() received:', s) decoded = s.decode("utf-16-le") print('Decoded:', decoded) returned = None if decoded == 'hello': returned = 'world' if returned is None: return None else: b = returned.encode("utf-16-le") + b'\0\0' return b if __name__ == '__main__': print(ChangeText(b'h\0e\0l\0l\0o\0')) input()
def change_text(s): print('ChangeText() received:', s) decoded = s.decode('utf-16-le') print('Decoded:', decoded) returned = None if decoded == 'hello': returned = 'world' if returned is None: return None else: b = returned.encode('utf-16-le') + b'\x00\x00' return b if __name__ == '__main__': print(change_text(b'h\x00e\x00l\x00l\x00o\x00')) input()
print("""interface GigabitEthernet0/3.100\nvlan 100\nnameif wireless_user-v100\nsecurity-level 75\nip addr 10.1.100.1 255.255.255.0 interface GigabitEthernet0/3.101\nvlan 101\nnameif wireless_user-v101\nsecurity-level 75\nip addr 10.1.101.1 255.255.255.0 interface GigabitEthernet0/3.102\nvlan 102\nnameif wireless_user-v102\nsecurity-level 75\nip addr 10.1.102.1 255.255.255.0 interface GigabitEthernet0/3.103\nvlan 103\nnameif wireless_user-v103\nsecurity-level 75\nip addr 10.1.103.1 255.255.255.0 interface GigabitEthernet0/3.104\nvlan 104\nnameif wireless_user-v104\nsecurity-level 75\nip addr 10.1.104.1 255.255.255.0 interface GigabitEthernet0/3.105\nvlan 105\nnameif wireless_user-v105\nsecurity-level 75\nip addr 10.1.105.1 255.255.255.0 interface GigabitEthernet0/3.106\nvlan 106\nnameif wireless_user-v106\nsecurity-level 75\nip addr 10.1.106.1 255.255.255.0 interface GigabitEthernet0/3.107\nvlan 107\nnameif wireless_user-v107\nsecurity-level 75\nip addr 10.1.107.1 255.255.255.0 interface GigabitEthernet0/3.108\nvlan 108\nnameif wireless_user-v108\nsecurity-level 75\nip addr 10.1.108.1 255.255.255.0 interface GigabitEthernet0/3.109\nvlan 109\nnameif wireless_user-v109\nsecurity-level 75\nip addr 10.1.109.1 255.255.255.0 interface GigabitEthernet0/3.110\nvlan 110\nnameif wireless_user-v110\nsecurity-level 75\nip addr 10.1.110.1 255.255.255.0 interface GigabitEthernet0/3.111\nvlan 111\nnameif wireless_user-v111\nsecurity-level 75\nip addr 10.1.111.1 255.255.255.0 interface GigabitEthernet0/3.112\nvlan 112\nnameif wireless_user-v112\nsecurity-level 75\nip addr 10.1.112.1 255.255.255.0 interface GigabitEthernet0/3.113\nvlan 113\nnameif wireless_user-v113\nsecurity-level 75\nip addr 10.1.113.1 255.255.255.0 interface GigabitEthernet0/3.114\nvlan 114\nnameif wireless_user-v114\nsecurity-level 75\nip addr 10.1.114.1 255.255.255.0 interface GigabitEthernet0/3.115\nvlan 115\nnameif wireless_user-v115\nsecurity-level 75\nip addr 10.1.115.1 255.255.255.0 interface GigabitEthernet0/3.116\nvlan 116\nnameif wireless_user-v116\nsecurity-level 75\nip addr 10.1.116.1 255.255.255.0 interface GigabitEthernet0/3.117\nvlan 117\nnameif wireless_user-v117\nsecurity-level 75\nip addr 10.1.117.1 255.255.255.0 interface GigabitEthernet0/3.118\nvlan 118\nnameif wireless_user-v118\nsecurity-level 75\nip addr 10.1.118.1 255.255.255.0 interface GigabitEthernet0/3.119\nvlan 119\nnameif wireless_user-v119\nsecurity-level 75\nip addr 10.1.119.1 255.255.255.0 interface GigabitEthernet0/3.120\nvlan 120\nnameif wireless_user-v120\nsecurity-level 75\nip addr 10.1.120.1 255.255.255.0 interface GigabitEthernet0/3.121\nvlan 121\nnameif wireless_user-v121\nsecurity-level 75\nip addr 10.1.121.1 255.255.255.0 interface GigabitEthernet0/3.122\nvlan 122\nnameif wireless_user-v122\nsecurity-level 75\nip addr 10.1.122.1 255.255.255.0 interface GigabitEthernet0/3.123\nvlan 123\nnameif wireless_user-v123\nsecurity-level 75\nip addr 10.1.123.1 255.255.255.0 interface GigabitEthernet0/3.124\nvlan 124\nnameif wireless_user-v124\nsecurity-level 75\nip addr 10.1.124.1 255.255.255.0 interface GigabitEthernet0/3.125\nvlan 125\nnameif wireless_user-v125\nsecurity-level 75\nip addr 10.1.125.1 255.255.255.0 interface GigabitEthernet0/3.126\nvlan 126\nnameif wireless_user-v126\nsecurity-level 75\nip addr 10.1.126.1 255.255.255.0 interface GigabitEthernet0/3.127\nvlan 127\nnameif wireless_user-v127\nsecurity-level 75\nip addr 10.1.127.1 255.255.255.0 interface GigabitEthernet0/3.128\nvlan 128\nnameif wireless_user-v128\nsecurity-level 75\nip addr 10.1.128.1 255.255.255.0 interface GigabitEthernet0/3.129\nvlan 129\nnameif wireless_user-v129\nsecurity-level 75\nip addr 10.1.129.1 255.255.255.0 interface GigabitEthernet0/3.130\nvlan 130\nnameif wireless_user-v130\nsecurity-level 75\nip addr 10.1.130.1 255.255.255.0 interface GigabitEthernet0/3.131\nvlan 131\nnameif wireless_user-v131\nsecurity-level 75\nip addr 10.1.131.1 255.255.255.0 interface GigabitEthernet0/3.132\nvlan 132\nnameif wireless_user-v132\nsecurity-level 75\nip addr 10.1.132.1 255.255.255.0 interface GigabitEthernet0/3.133\nvlan 133\nnameif wireless_user-v133\nsecurity-level 75\nip addr 10.1.133.1 255.255.255.0 interface GigabitEthernet0/3.134\nvlan 134\nnameif wireless_user-v134\nsecurity-level 75\nip addr 10.1.134.1 255.255.255.0 interface GigabitEthernet0/3.135\nvlan 135\nnameif wireless_user-v135\nsecurity-level 75\nip addr 10.1.135.1 255.255.255.0 interface GigabitEthernet0/3.136\nvlan 136\nnameif wireless_user-v136\nsecurity-level 75\nip addr 10.1.136.1 255.255.255.0 interface GigabitEthernet0/3.137\nvlan 137\nnameif wireless_user-v137\nsecurity-level 75\nip addr 10.1.137.1 255.255.255.0 interface GigabitEthernet0/3.138\nvlan 138\nnameif wireless_user-v138\nsecurity-level 75\nip addr 10.1.138.1 255.255.255.0 interface GigabitEthernet0/3.139\nvlan 139\nnameif wireless_user-v139\nsecurity-level 75\nip addr 10.1.139.1 255.255.255.0 interface GigabitEthernet0/3.140\nvlan 140\nnameif wireless_user-v140\nsecurity-level 75\nip addr 10.1.140.1 255.255.255.0 interface GigabitEthernet0/3.141\nvlan 141\nnameif wireless_user-v141\nsecurity-level 75\nip addr 10.1.141.1 255.255.255.0 interface GigabitEthernet0/3.142\nvlan 142\nnameif wireless_user-v142\nsecurity-level 75\nip addr 10.1.142.1 255.255.255.0 interface GigabitEthernet0/3.143\nvlan 143\nnameif wireless_user-v143\nsecurity-level 75\nip addr 10.1.143.1 255.255.255.0 interface GigabitEthernet0/3.144\nvlan 144\nnameif wireless_user-v144\nsecurity-level 75\nip addr 10.1.144.1 255.255.255.0 interface GigabitEthernet0/3.145\nvlan 145\nnameif wireless_user-v145\nsecurity-level 75\nip addr 10.1.145.1 255.255.255.0 interface GigabitEthernet0/3.146\nvlan 146\nnameif wireless_user-v146\nsecurity-level 75\nip addr 10.1.146.1 255.255.255.0 interface GigabitEthernet0/3.147\nvlan 147\nnameif wireless_user-v147\nsecurity-level 75\nip addr 10.1.147.1 255.255.255.0 interface GigabitEthernet0/3.148\nvlan 148\nnameif wireless_user-v148\nsecurity-level 75\nip addr 10.1.148.1 255.255.255.0 interface GigabitEthernet0/3.149\nvlan 149\nnameif wireless_user-v149\nsecurity-level 75\nip addr 10.1.149.1 255.255.255.0 interface GigabitEthernet0/3.150\nvlan 150\nnameif server-v150\nsecurity-level 75\nip addr 10.1.150.1 255.255.255.0 interface GigabitEthernet0/3.151\nvlan 151\nnameif server-v151\nsecurity-level 75\nip addr 10.1.151.1 255.255.255.0 interface GigabitEthernet0/3.152\nvlan 152\nnameif server-v152\nsecurity-level 75\nip addr 10.1.152.1 255.255.255.0 interface GigabitEthernet0/3.153\nvlan 153\nnameif server-v153\nsecurity-level 75\nip addr 10.1.153.1 255.255.255.0 interface GigabitEthernet0/3.154\nvlan 154\nnameif server-v154\nsecurity-level 75\nip addr 10.1.154.1 255.255.255.0 interface GigabitEthernet0/3.155\nvlan 155\nnameif server-v155\nsecurity-level 75\nip addr 10.1.155.1 255.255.255.0 interface GigabitEthernet0/3.156\nvlan 156\nnameif server-v156\nsecurity-level 75\nip addr 10.1.156.1 255.255.255.0 interface GigabitEthernet0/3.157\nvlan 157\nnameif server-v157\nsecurity-level 75\nip addr 10.1.157.1 255.255.255.0 interface GigabitEthernet0/3.158\nvlan 158\nnameif server-v158\nsecurity-level 75\nip addr 10.1.158.1 255.255.255.0 interface GigabitEthernet0/3.159\nvlan 159\nnameif server-v159\nsecurity-level 75\nip addr 10.1.159.1 255.255.255.0 interface GigabitEthernet0/3.160\nvlan 160\nnameif server-v160\nsecurity-level 75\nip addr 10.1.160.1 255.255.255.0 interface GigabitEthernet0/3.161\nvlan 161\nnameif server-v161\nsecurity-level 75\nip addr 10.1.161.1 255.255.255.0 interface GigabitEthernet0/3.162\nvlan 162\nnameif server-v162\nsecurity-level 75\nip addr 10.1.162.1 255.255.255.0 interface GigabitEthernet0/3.163\nvlan 163\nnameif server-v163\nsecurity-level 75\nip addr 10.1.163.1 255.255.255.0 interface GigabitEthernet0/3.164\nvlan 164\nnameif server-v164\nsecurity-level 75\nip addr 10.1.164.1 255.255.255.0 interface GigabitEthernet0/3.165\nvlan 165\nnameif server-v165\nsecurity-level 75\nip addr 10.1.165.1 255.255.255.0 interface GigabitEthernet0/3.166\nvlan 166\nnameif server-v166\nsecurity-level 75\nip addr 10.1.166.1 255.255.255.0 interface GigabitEthernet0/3.167\nvlan 167\nnameif server-v167\nsecurity-level 75\nip addr 10.1.167.1 255.255.255.0 interface GigabitEthernet0/3.168\nvlan 168\nnameif server-v168\nsecurity-level 75\nip addr 10.1.168.1 255.255.255.0 interface GigabitEthernet0/3.169\nvlan 169\nnameif server-v169\nsecurity-level 75\nip addr 10.1.169.1 255.255.255.0 interface GigabitEthernet0/3.170\nvlan 170\nnameif server-v170\nsecurity-level 75\nip addr 10.1.170.1 255.255.255.0 interface GigabitEthernet0/3.171\nvlan 171\nnameif server-v171\nsecurity-level 75\nip addr 10.1.171.1 255.255.255.0 interface GigabitEthernet0/3.172\nvlan 172\nnameif server-v172\nsecurity-level 75\nip addr 10.1.172.1 255.255.255.0 interface GigabitEthernet0/3.173\nvlan 173\nnameif server-v173\nsecurity-level 75\nip addr 10.1.173.1 255.255.255.0 interface GigabitEthernet0/3.174\nvlan 174\nnameif server-v174\nsecurity-level 75\nip addr 10.1.174.1 255.255.255.0 interface GigabitEthernet0/3.175\nvlan 175\nnameif server-v175\nsecurity-level 75\nip addr 10.1.175.1 255.255.255.0 interface GigabitEthernet0/3.176\nvlan 176\nnameif server-v176\nsecurity-level 75\nip addr 10.1.176.1 255.255.255.0 interface GigabitEthernet0/3.177\nvlan 177\nnameif server-v177\nsecurity-level 75\nip addr 10.1.177.1 255.255.255.0 interface GigabitEthernet0/3.178\nvlan 178\nnameif server-v178\nsecurity-level 75\nip addr 10.1.178.1 255.255.255.0 interface GigabitEthernet0/3.179\nvlan 179\nnameif server-v179\nsecurity-level 75\nip addr 10.1.179.1 255.255.255.0 interface GigabitEthernet0/3.180\nvlan 180\nnameif server-v180\nsecurity-level 75\nip addr 10.1.180.1 255.255.255.0 interface GigabitEthernet0/3.181\nvlan 181\nnameif server-v181\nsecurity-level 75\nip addr 10.1.181.1 255.255.255.0 interface GigabitEthernet0/3.182\nvlan 182\nnameif server-v182\nsecurity-level 75\nip addr 10.1.182.1 255.255.255.0 interface GigabitEthernet0/3.183\nvlan 183\nnameif server-v183\nsecurity-level 75\nip addr 10.1.183.1 255.255.255.0 interface GigabitEthernet0/3.184\nvlan 184\nnameif server-v184\nsecurity-level 75\nip addr 10.1.184.1 255.255.255.0 interface GigabitEthernet0/3.185\nvlan 185\nnameif server-v185\nsecurity-level 75\nip addr 10.1.185.1 255.255.255.0 interface GigabitEthernet0/3.186\nvlan 186\nnameif server-v186\nsecurity-level 75\nip addr 10.1.186.1 255.255.255.0 interface GigabitEthernet0/3.187\nvlan 187\nnameif server-v187\nsecurity-level 75\nip addr 10.1.187.1 255.255.255.0 interface GigabitEthernet0/3.188\nvlan 188\nnameif server-v188\nsecurity-level 75\nip addr 10.1.188.1 255.255.255.0 interface GigabitEthernet0/3.189\nvlan 189\nnameif server-v189\nsecurity-level 75\nip addr 10.1.189.1 255.255.255.0 interface GigabitEthernet0/3.190\nvlan 190\nnameif server-v190\nsecurity-level 75\nip addr 10.1.190.1 255.255.255.0 interface GigabitEthernet0/3.191\nvlan 191\nnameif server-v191\nsecurity-level 75\nip addr 10.1.191.1 255.255.255.0 interface GigabitEthernet0/3.192\nvlan 192\nnameif server-v192\nsecurity-level 75\nip addr 10.1.192.1 255.255.255.0 interface GigabitEthernet0/3.193\nvlan 193\nnameif server-v193\nsecurity-level 75\nip addr 10.1.193.1 255.255.255.0 interface GigabitEthernet0/3.194\nvlan 194\nnameif server-v194\nsecurity-level 75\nip addr 10.1.194.1 255.255.255.0 interface GigabitEthernet0/3.195\nvlan 195\nnameif server-v195\nsecurity-level 75\nip addr 10.1.195.1 255.255.255.0 interface GigabitEthernet0/3.196\nvlan 196\nnameif server-v196\nsecurity-level 75\nip addr 10.1.196.1 255.255.255.0 interface GigabitEthernet0/3.197\nvlan 197\nnameif server-v197\nsecurity-level 75\nip addr 10.1.197.1 255.255.255.0 interface GigabitEthernet0/3.198\nvlan 198\nnameif server-v198\nsecurity-level 75\nip addr 10.1.198.1 255.255.255.0 interface GigabitEthernet0/3.199\nvlan 199\nnameif server-v199\nsecurity-level 75\nip addr 10.1.199.1 255.255.255.0 interface GigabitEthernet0/3.200\nvlan 200\nnameif wired_user-v200\nsecurity-level 75\nip addr 10.1.200.1 255.255.255.0 interface GigabitEthernet0/3.201\nvlan 201\nnameif wired_user-v201\nsecurity-level 75\nip addr 10.1.201.1 255.255.255.0 interface GigabitEthernet0/3.202\nvlan 202\nnameif wired_user-v202\nsecurity-level 75\nip addr 10.1.202.1 255.255.255.0 interface GigabitEthernet0/3.203\nvlan 203\nnameif wired_user-v203\nsecurity-level 75\nip addr 10.1.203.1 255.255.255.0 interface GigabitEthernet0/3.204\nvlan 204\nnameif wired_user-v204\nsecurity-level 75\nip addr 10.1.204.1 255.255.255.0 interface GigabitEthernet0/3.205\nvlan 205\nnameif wired_user-v205\nsecurity-level 75\nip addr 10.1.205.1 255.255.255.0 interface GigabitEthernet0/3.206\nvlan 206\nnameif wired_user-v206\nsecurity-level 75\nip addr 10.1.206.1 255.255.255.0 interface GigabitEthernet0/3.207\nvlan 207\nnameif wired_user-v207\nsecurity-level 75\nip addr 10.1.207.1 255.255.255.0 interface GigabitEthernet0/3.208\nvlan 208\nnameif wired_user-v208\nsecurity-level 75\nip addr 10.1.208.1 255.255.255.0 interface GigabitEthernet0/3.209\nvlan 209\nnameif wired_user-v209\nsecurity-level 75\nip addr 10.1.209.1 255.255.255.0 interface GigabitEthernet0/3.210\nvlan 210\nnameif wired_user-v210\nsecurity-level 75\nip addr 10.1.210.1 255.255.255.0 interface GigabitEthernet0/3.211\nvlan 211\nnameif wired_user-v211\nsecurity-level 75\nip addr 10.1.211.1 255.255.255.0 interface GigabitEthernet0/3.212\nvlan 212\nnameif wired_user-v212\nsecurity-level 75\nip addr 10.1.212.1 255.255.255.0 interface GigabitEthernet0/3.213\nvlan 213\nnameif wired_user-v213\nsecurity-level 75\nip addr 10.1.213.1 255.255.255.0 interface GigabitEthernet0/3.214\nvlan 214\nnameif wired_user-v214\nsecurity-level 75\nip addr 10.1.214.1 255.255.255.0 interface GigabitEthernet0/3.215\nvlan 215\nnameif wired_user-v215\nsecurity-level 75\nip addr 10.1.215.1 255.255.255.0 interface GigabitEthernet0/3.216\nvlan 216\nnameif wired_user-v216\nsecurity-level 75\nip addr 10.1.216.1 255.255.255.0 interface GigabitEthernet0/3.217\nvlan 217\nnameif wired_user-v217\nsecurity-level 75\nip addr 10.1.217.1 255.255.255.0 interface GigabitEthernet0/3.218\nvlan 218\nnameif wired_user-v218\nsecurity-level 75\nip addr 10.1.218.1 255.255.255.0 interface GigabitEthernet0/3.219\nvlan 219\nnameif wired_user-v219\nsecurity-level 75\nip addr 10.1.219.1 255.255.255.0 interface GigabitEthernet0/3.220\nvlan 220\nnameif wired_user-v220\nsecurity-level 75\nip addr 10.1.220.1 255.255.255.0 interface GigabitEthernet0/3.221\nvlan 221\nnameif wired_user-v221\nsecurity-level 75\nip addr 10.1.221.1 255.255.255.0 interface GigabitEthernet0/3.222\nvlan 222\nnameif wired_user-v222\nsecurity-level 75\nip addr 10.1.222.1 255.255.255.0 interface GigabitEthernet0/3.223\nvlan 223\nnameif wired_user-v223\nsecurity-level 75\nip addr 10.1.223.1 255.255.255.0 interface GigabitEthernet0/3.224\nvlan 224\nnameif wired_user-v224\nsecurity-level 75\nip addr 10.1.224.1 255.255.255.0 interface GigabitEthernet0/3.225\nvlan 225\nnameif wired_user-v225\nsecurity-level 75\nip addr 10.1.225.1 255.255.255.0 interface GigabitEthernet0/3.226\nvlan 226\nnameif wired_user-v226\nsecurity-level 75\nip addr 10.1.226.1 255.255.255.0 interface GigabitEthernet0/3.227\nvlan 227\nnameif wired_user-v227\nsecurity-level 75\nip addr 10.1.227.1 255.255.255.0 interface GigabitEthernet0/3.228\nvlan 228\nnameif wired_user-v228\nsecurity-level 75\nip addr 10.1.228.1 255.255.255.0 interface GigabitEthernet0/3.229\nvlan 229\nnameif wired_user-v229\nsecurity-level 75\nip addr 10.1.229.1 255.255.255.0 interface GigabitEthernet0/3.230\nvlan 230\nnameif wired_user-v230\nsecurity-level 75\nip addr 10.1.230.1 255.255.255.0 interface GigabitEthernet0/3.231\nvlan 231\nnameif wired_user-v231\nsecurity-level 75\nip addr 10.1.231.1 255.255.255.0 interface GigabitEthernet0/3.232\nvlan 232\nnameif wired_user-v232\nsecurity-level 75\nip addr 10.1.232.1 255.255.255.0 interface GigabitEthernet0/3.233\nvlan 233\nnameif wired_user-v233\nsecurity-level 75\nip addr 10.1.233.1 255.255.255.0 interface GigabitEthernet0/3.234\nvlan 234\nnameif wired_user-v234\nsecurity-level 75\nip addr 10.1.234.1 255.255.255.0 interface GigabitEthernet0/3.235\nvlan 235\nnameif wired_user-v235\nsecurity-level 75\nip addr 10.1.235.1 255.255.255.0 interface GigabitEthernet0/3.236\nvlan 236\nnameif wired_user-v236\nsecurity-level 75\nip addr 10.1.236.1 255.255.255.0 interface GigabitEthernet0/3.237\nvlan 237\nnameif wired_user-v237\nsecurity-level 75\nip addr 10.1.237.1 255.255.255.0 interface GigabitEthernet0/3.238\nvlan 238\nnameif wired_user-v238\nsecurity-level 75\nip addr 10.1.238.1 255.255.255.0 interface GigabitEthernet0/3.239\nvlan 239\nnameif wired_user-v239\nsecurity-level 75\nip addr 10.1.239.1 255.255.255.0 interface GigabitEthernet0/3.240\nvlan 240\nnameif wired_user-v240\nsecurity-level 75\nip addr 10.1.240.1 255.255.255.0 interface GigabitEthernet0/3.241\nvlan 241\nnameif wired_user-v241\nsecurity-level 75\nip addr 10.1.241.1 255.255.255.0 interface GigabitEthernet0/3.242\nvlan 242\nnameif wired_user-v242\nsecurity-level 75\nip addr 10.1.242.1 255.255.255.0 interface GigabitEthernet0/3.243\nvlan 243\nnameif wired_user-v243\nsecurity-level 75\nip addr 10.1.243.1 255.255.255.0 interface GigabitEthernet0/3.244\nvlan 244\nnameif wired_user-v244\nsecurity-level 75\nip addr 10.1.244.1 255.255.255.0 interface GigabitEthernet0/3.245\nvlan 245\nnameif wired_user-v245\nsecurity-level 75\nip addr 10.1.245.1 255.255.255.0 interface GigabitEthernet0/3.246\nvlan 246\nnameif wired_user-v246\nsecurity-level 75\nip addr 10.1.246.1 255.255.255.0 interface GigabitEthernet0/3.247\nvlan 247\nnameif wired_user-v247\nsecurity-level 75\nip addr 10.1.247.1 255.255.255.0 interface GigabitEthernet0/3.248\nvlan 248\nnameif wired_user-v248\nsecurity-level 75\nip addr 10.1.248.1 255.255.255.0 interface GigabitEthernet0/3.249\nvlan 249\nnameif wired_user-v249\nsecurity-level 75\nip addr 10.1.249.1 255.255.255.0""")
print('interface GigabitEthernet0/3.100\nvlan 100\nnameif wireless_user-v100\nsecurity-level 75\nip addr 10.1.100.1 255.255.255.0\ninterface GigabitEthernet0/3.101\nvlan 101\nnameif wireless_user-v101\nsecurity-level 75\nip addr 10.1.101.1 255.255.255.0\ninterface GigabitEthernet0/3.102\nvlan 102\nnameif wireless_user-v102\nsecurity-level 75\nip addr 10.1.102.1 255.255.255.0\ninterface GigabitEthernet0/3.103\nvlan 103\nnameif wireless_user-v103\nsecurity-level 75\nip addr 10.1.103.1 255.255.255.0\ninterface GigabitEthernet0/3.104\nvlan 104\nnameif wireless_user-v104\nsecurity-level 75\nip addr 10.1.104.1 255.255.255.0\ninterface GigabitEthernet0/3.105\nvlan 105\nnameif wireless_user-v105\nsecurity-level 75\nip addr 10.1.105.1 255.255.255.0\ninterface GigabitEthernet0/3.106\nvlan 106\nnameif wireless_user-v106\nsecurity-level 75\nip addr 10.1.106.1 255.255.255.0\ninterface GigabitEthernet0/3.107\nvlan 107\nnameif wireless_user-v107\nsecurity-level 75\nip addr 10.1.107.1 255.255.255.0\ninterface GigabitEthernet0/3.108\nvlan 108\nnameif wireless_user-v108\nsecurity-level 75\nip addr 10.1.108.1 255.255.255.0\ninterface GigabitEthernet0/3.109\nvlan 109\nnameif wireless_user-v109\nsecurity-level 75\nip addr 10.1.109.1 255.255.255.0\ninterface GigabitEthernet0/3.110\nvlan 110\nnameif wireless_user-v110\nsecurity-level 75\nip addr 10.1.110.1 255.255.255.0\ninterface GigabitEthernet0/3.111\nvlan 111\nnameif wireless_user-v111\nsecurity-level 75\nip addr 10.1.111.1 255.255.255.0\ninterface GigabitEthernet0/3.112\nvlan 112\nnameif wireless_user-v112\nsecurity-level 75\nip addr 10.1.112.1 255.255.255.0\ninterface GigabitEthernet0/3.113\nvlan 113\nnameif wireless_user-v113\nsecurity-level 75\nip addr 10.1.113.1 255.255.255.0\ninterface GigabitEthernet0/3.114\nvlan 114\nnameif wireless_user-v114\nsecurity-level 75\nip addr 10.1.114.1 255.255.255.0\ninterface GigabitEthernet0/3.115\nvlan 115\nnameif wireless_user-v115\nsecurity-level 75\nip addr 10.1.115.1 255.255.255.0\ninterface GigabitEthernet0/3.116\nvlan 116\nnameif wireless_user-v116\nsecurity-level 75\nip addr 10.1.116.1 255.255.255.0\ninterface GigabitEthernet0/3.117\nvlan 117\nnameif wireless_user-v117\nsecurity-level 75\nip addr 10.1.117.1 255.255.255.0\ninterface GigabitEthernet0/3.118\nvlan 118\nnameif wireless_user-v118\nsecurity-level 75\nip addr 10.1.118.1 255.255.255.0\ninterface GigabitEthernet0/3.119\nvlan 119\nnameif wireless_user-v119\nsecurity-level 75\nip addr 10.1.119.1 255.255.255.0\ninterface GigabitEthernet0/3.120\nvlan 120\nnameif wireless_user-v120\nsecurity-level 75\nip addr 10.1.120.1 255.255.255.0\ninterface GigabitEthernet0/3.121\nvlan 121\nnameif wireless_user-v121\nsecurity-level 75\nip addr 10.1.121.1 255.255.255.0\ninterface GigabitEthernet0/3.122\nvlan 122\nnameif wireless_user-v122\nsecurity-level 75\nip addr 10.1.122.1 255.255.255.0\ninterface GigabitEthernet0/3.123\nvlan 123\nnameif wireless_user-v123\nsecurity-level 75\nip addr 10.1.123.1 255.255.255.0\ninterface GigabitEthernet0/3.124\nvlan 124\nnameif wireless_user-v124\nsecurity-level 75\nip addr 10.1.124.1 255.255.255.0\ninterface GigabitEthernet0/3.125\nvlan 125\nnameif wireless_user-v125\nsecurity-level 75\nip addr 10.1.125.1 255.255.255.0\ninterface GigabitEthernet0/3.126\nvlan 126\nnameif wireless_user-v126\nsecurity-level 75\nip addr 10.1.126.1 255.255.255.0\ninterface GigabitEthernet0/3.127\nvlan 127\nnameif wireless_user-v127\nsecurity-level 75\nip addr 10.1.127.1 255.255.255.0\ninterface GigabitEthernet0/3.128\nvlan 128\nnameif wireless_user-v128\nsecurity-level 75\nip addr 10.1.128.1 255.255.255.0\ninterface GigabitEthernet0/3.129\nvlan 129\nnameif wireless_user-v129\nsecurity-level 75\nip addr 10.1.129.1 255.255.255.0\ninterface GigabitEthernet0/3.130\nvlan 130\nnameif wireless_user-v130\nsecurity-level 75\nip addr 10.1.130.1 255.255.255.0\ninterface GigabitEthernet0/3.131\nvlan 131\nnameif wireless_user-v131\nsecurity-level 75\nip addr 10.1.131.1 255.255.255.0\ninterface GigabitEthernet0/3.132\nvlan 132\nnameif wireless_user-v132\nsecurity-level 75\nip addr 10.1.132.1 255.255.255.0\ninterface GigabitEthernet0/3.133\nvlan 133\nnameif wireless_user-v133\nsecurity-level 75\nip addr 10.1.133.1 255.255.255.0\ninterface GigabitEthernet0/3.134\nvlan 134\nnameif wireless_user-v134\nsecurity-level 75\nip addr 10.1.134.1 255.255.255.0\ninterface GigabitEthernet0/3.135\nvlan 135\nnameif wireless_user-v135\nsecurity-level 75\nip addr 10.1.135.1 255.255.255.0\ninterface GigabitEthernet0/3.136\nvlan 136\nnameif wireless_user-v136\nsecurity-level 75\nip addr 10.1.136.1 255.255.255.0\ninterface GigabitEthernet0/3.137\nvlan 137\nnameif wireless_user-v137\nsecurity-level 75\nip addr 10.1.137.1 255.255.255.0\ninterface GigabitEthernet0/3.138\nvlan 138\nnameif wireless_user-v138\nsecurity-level 75\nip addr 10.1.138.1 255.255.255.0\ninterface GigabitEthernet0/3.139\nvlan 139\nnameif wireless_user-v139\nsecurity-level 75\nip addr 10.1.139.1 255.255.255.0\ninterface GigabitEthernet0/3.140\nvlan 140\nnameif wireless_user-v140\nsecurity-level 75\nip addr 10.1.140.1 255.255.255.0\ninterface GigabitEthernet0/3.141\nvlan 141\nnameif wireless_user-v141\nsecurity-level 75\nip addr 10.1.141.1 255.255.255.0\ninterface GigabitEthernet0/3.142\nvlan 142\nnameif wireless_user-v142\nsecurity-level 75\nip addr 10.1.142.1 255.255.255.0\ninterface GigabitEthernet0/3.143\nvlan 143\nnameif wireless_user-v143\nsecurity-level 75\nip addr 10.1.143.1 255.255.255.0\ninterface GigabitEthernet0/3.144\nvlan 144\nnameif wireless_user-v144\nsecurity-level 75\nip addr 10.1.144.1 255.255.255.0\ninterface GigabitEthernet0/3.145\nvlan 145\nnameif wireless_user-v145\nsecurity-level 75\nip addr 10.1.145.1 255.255.255.0\ninterface GigabitEthernet0/3.146\nvlan 146\nnameif wireless_user-v146\nsecurity-level 75\nip addr 10.1.146.1 255.255.255.0\ninterface GigabitEthernet0/3.147\nvlan 147\nnameif wireless_user-v147\nsecurity-level 75\nip addr 10.1.147.1 255.255.255.0\ninterface GigabitEthernet0/3.148\nvlan 148\nnameif wireless_user-v148\nsecurity-level 75\nip addr 10.1.148.1 255.255.255.0\ninterface GigabitEthernet0/3.149\nvlan 149\nnameif wireless_user-v149\nsecurity-level 75\nip addr 10.1.149.1 255.255.255.0\ninterface GigabitEthernet0/3.150\nvlan 150\nnameif server-v150\nsecurity-level 75\nip addr 10.1.150.1 255.255.255.0\ninterface GigabitEthernet0/3.151\nvlan 151\nnameif server-v151\nsecurity-level 75\nip addr 10.1.151.1 255.255.255.0\ninterface GigabitEthernet0/3.152\nvlan 152\nnameif server-v152\nsecurity-level 75\nip addr 10.1.152.1 255.255.255.0\ninterface GigabitEthernet0/3.153\nvlan 153\nnameif server-v153\nsecurity-level 75\nip addr 10.1.153.1 255.255.255.0\ninterface GigabitEthernet0/3.154\nvlan 154\nnameif server-v154\nsecurity-level 75\nip addr 10.1.154.1 255.255.255.0\ninterface GigabitEthernet0/3.155\nvlan 155\nnameif server-v155\nsecurity-level 75\nip addr 10.1.155.1 255.255.255.0\ninterface GigabitEthernet0/3.156\nvlan 156\nnameif server-v156\nsecurity-level 75\nip addr 10.1.156.1 255.255.255.0\ninterface GigabitEthernet0/3.157\nvlan 157\nnameif server-v157\nsecurity-level 75\nip addr 10.1.157.1 255.255.255.0\ninterface GigabitEthernet0/3.158\nvlan 158\nnameif server-v158\nsecurity-level 75\nip addr 10.1.158.1 255.255.255.0\ninterface GigabitEthernet0/3.159\nvlan 159\nnameif server-v159\nsecurity-level 75\nip addr 10.1.159.1 255.255.255.0\ninterface GigabitEthernet0/3.160\nvlan 160\nnameif server-v160\nsecurity-level 75\nip addr 10.1.160.1 255.255.255.0\ninterface GigabitEthernet0/3.161\nvlan 161\nnameif server-v161\nsecurity-level 75\nip addr 10.1.161.1 255.255.255.0\ninterface GigabitEthernet0/3.162\nvlan 162\nnameif server-v162\nsecurity-level 75\nip addr 10.1.162.1 255.255.255.0\ninterface GigabitEthernet0/3.163\nvlan 163\nnameif server-v163\nsecurity-level 75\nip addr 10.1.163.1 255.255.255.0\ninterface GigabitEthernet0/3.164\nvlan 164\nnameif server-v164\nsecurity-level 75\nip addr 10.1.164.1 255.255.255.0\ninterface GigabitEthernet0/3.165\nvlan 165\nnameif server-v165\nsecurity-level 75\nip addr 10.1.165.1 255.255.255.0\ninterface GigabitEthernet0/3.166\nvlan 166\nnameif server-v166\nsecurity-level 75\nip addr 10.1.166.1 255.255.255.0\ninterface GigabitEthernet0/3.167\nvlan 167\nnameif server-v167\nsecurity-level 75\nip addr 10.1.167.1 255.255.255.0\ninterface GigabitEthernet0/3.168\nvlan 168\nnameif server-v168\nsecurity-level 75\nip addr 10.1.168.1 255.255.255.0\ninterface GigabitEthernet0/3.169\nvlan 169\nnameif server-v169\nsecurity-level 75\nip addr 10.1.169.1 255.255.255.0\ninterface GigabitEthernet0/3.170\nvlan 170\nnameif server-v170\nsecurity-level 75\nip addr 10.1.170.1 255.255.255.0\ninterface GigabitEthernet0/3.171\nvlan 171\nnameif server-v171\nsecurity-level 75\nip addr 10.1.171.1 255.255.255.0\ninterface GigabitEthernet0/3.172\nvlan 172\nnameif server-v172\nsecurity-level 75\nip addr 10.1.172.1 255.255.255.0\ninterface GigabitEthernet0/3.173\nvlan 173\nnameif server-v173\nsecurity-level 75\nip addr 10.1.173.1 255.255.255.0\ninterface GigabitEthernet0/3.174\nvlan 174\nnameif server-v174\nsecurity-level 75\nip addr 10.1.174.1 255.255.255.0\ninterface GigabitEthernet0/3.175\nvlan 175\nnameif server-v175\nsecurity-level 75\nip addr 10.1.175.1 255.255.255.0\ninterface GigabitEthernet0/3.176\nvlan 176\nnameif server-v176\nsecurity-level 75\nip addr 10.1.176.1 255.255.255.0\ninterface GigabitEthernet0/3.177\nvlan 177\nnameif server-v177\nsecurity-level 75\nip addr 10.1.177.1 255.255.255.0\ninterface GigabitEthernet0/3.178\nvlan 178\nnameif server-v178\nsecurity-level 75\nip addr 10.1.178.1 255.255.255.0\ninterface GigabitEthernet0/3.179\nvlan 179\nnameif server-v179\nsecurity-level 75\nip addr 10.1.179.1 255.255.255.0\ninterface GigabitEthernet0/3.180\nvlan 180\nnameif server-v180\nsecurity-level 75\nip addr 10.1.180.1 255.255.255.0\ninterface GigabitEthernet0/3.181\nvlan 181\nnameif server-v181\nsecurity-level 75\nip addr 10.1.181.1 255.255.255.0\ninterface GigabitEthernet0/3.182\nvlan 182\nnameif server-v182\nsecurity-level 75\nip addr 10.1.182.1 255.255.255.0\ninterface GigabitEthernet0/3.183\nvlan 183\nnameif server-v183\nsecurity-level 75\nip addr 10.1.183.1 255.255.255.0\ninterface GigabitEthernet0/3.184\nvlan 184\nnameif server-v184\nsecurity-level 75\nip addr 10.1.184.1 255.255.255.0\ninterface GigabitEthernet0/3.185\nvlan 185\nnameif server-v185\nsecurity-level 75\nip addr 10.1.185.1 255.255.255.0\ninterface GigabitEthernet0/3.186\nvlan 186\nnameif server-v186\nsecurity-level 75\nip addr 10.1.186.1 255.255.255.0\ninterface GigabitEthernet0/3.187\nvlan 187\nnameif server-v187\nsecurity-level 75\nip addr 10.1.187.1 255.255.255.0\ninterface GigabitEthernet0/3.188\nvlan 188\nnameif server-v188\nsecurity-level 75\nip addr 10.1.188.1 255.255.255.0\ninterface GigabitEthernet0/3.189\nvlan 189\nnameif server-v189\nsecurity-level 75\nip addr 10.1.189.1 255.255.255.0\ninterface GigabitEthernet0/3.190\nvlan 190\nnameif server-v190\nsecurity-level 75\nip addr 10.1.190.1 255.255.255.0\ninterface GigabitEthernet0/3.191\nvlan 191\nnameif server-v191\nsecurity-level 75\nip addr 10.1.191.1 255.255.255.0\ninterface GigabitEthernet0/3.192\nvlan 192\nnameif server-v192\nsecurity-level 75\nip addr 10.1.192.1 255.255.255.0\ninterface GigabitEthernet0/3.193\nvlan 193\nnameif server-v193\nsecurity-level 75\nip addr 10.1.193.1 255.255.255.0\ninterface GigabitEthernet0/3.194\nvlan 194\nnameif server-v194\nsecurity-level 75\nip addr 10.1.194.1 255.255.255.0\ninterface GigabitEthernet0/3.195\nvlan 195\nnameif server-v195\nsecurity-level 75\nip addr 10.1.195.1 255.255.255.0\ninterface GigabitEthernet0/3.196\nvlan 196\nnameif server-v196\nsecurity-level 75\nip addr 10.1.196.1 255.255.255.0\ninterface GigabitEthernet0/3.197\nvlan 197\nnameif server-v197\nsecurity-level 75\nip addr 10.1.197.1 255.255.255.0\ninterface GigabitEthernet0/3.198\nvlan 198\nnameif server-v198\nsecurity-level 75\nip addr 10.1.198.1 255.255.255.0\ninterface GigabitEthernet0/3.199\nvlan 199\nnameif server-v199\nsecurity-level 75\nip addr 10.1.199.1 255.255.255.0\ninterface GigabitEthernet0/3.200\nvlan 200\nnameif wired_user-v200\nsecurity-level 75\nip addr 10.1.200.1 255.255.255.0\ninterface GigabitEthernet0/3.201\nvlan 201\nnameif wired_user-v201\nsecurity-level 75\nip addr 10.1.201.1 255.255.255.0\ninterface GigabitEthernet0/3.202\nvlan 202\nnameif wired_user-v202\nsecurity-level 75\nip addr 10.1.202.1 255.255.255.0\ninterface GigabitEthernet0/3.203\nvlan 203\nnameif wired_user-v203\nsecurity-level 75\nip addr 10.1.203.1 255.255.255.0\ninterface GigabitEthernet0/3.204\nvlan 204\nnameif wired_user-v204\nsecurity-level 75\nip addr 10.1.204.1 255.255.255.0\ninterface GigabitEthernet0/3.205\nvlan 205\nnameif wired_user-v205\nsecurity-level 75\nip addr 10.1.205.1 255.255.255.0\ninterface GigabitEthernet0/3.206\nvlan 206\nnameif wired_user-v206\nsecurity-level 75\nip addr 10.1.206.1 255.255.255.0\ninterface GigabitEthernet0/3.207\nvlan 207\nnameif wired_user-v207\nsecurity-level 75\nip addr 10.1.207.1 255.255.255.0\ninterface GigabitEthernet0/3.208\nvlan 208\nnameif wired_user-v208\nsecurity-level 75\nip addr 10.1.208.1 255.255.255.0\ninterface GigabitEthernet0/3.209\nvlan 209\nnameif wired_user-v209\nsecurity-level 75\nip addr 10.1.209.1 255.255.255.0\ninterface GigabitEthernet0/3.210\nvlan 210\nnameif wired_user-v210\nsecurity-level 75\nip addr 10.1.210.1 255.255.255.0\ninterface GigabitEthernet0/3.211\nvlan 211\nnameif wired_user-v211\nsecurity-level 75\nip addr 10.1.211.1 255.255.255.0\ninterface GigabitEthernet0/3.212\nvlan 212\nnameif wired_user-v212\nsecurity-level 75\nip addr 10.1.212.1 255.255.255.0\ninterface GigabitEthernet0/3.213\nvlan 213\nnameif wired_user-v213\nsecurity-level 75\nip addr 10.1.213.1 255.255.255.0\ninterface GigabitEthernet0/3.214\nvlan 214\nnameif wired_user-v214\nsecurity-level 75\nip addr 10.1.214.1 255.255.255.0\ninterface GigabitEthernet0/3.215\nvlan 215\nnameif wired_user-v215\nsecurity-level 75\nip addr 10.1.215.1 255.255.255.0\ninterface GigabitEthernet0/3.216\nvlan 216\nnameif wired_user-v216\nsecurity-level 75\nip addr 10.1.216.1 255.255.255.0\ninterface GigabitEthernet0/3.217\nvlan 217\nnameif wired_user-v217\nsecurity-level 75\nip addr 10.1.217.1 255.255.255.0\ninterface GigabitEthernet0/3.218\nvlan 218\nnameif wired_user-v218\nsecurity-level 75\nip addr 10.1.218.1 255.255.255.0\ninterface GigabitEthernet0/3.219\nvlan 219\nnameif wired_user-v219\nsecurity-level 75\nip addr 10.1.219.1 255.255.255.0\ninterface GigabitEthernet0/3.220\nvlan 220\nnameif wired_user-v220\nsecurity-level 75\nip addr 10.1.220.1 255.255.255.0\ninterface GigabitEthernet0/3.221\nvlan 221\nnameif wired_user-v221\nsecurity-level 75\nip addr 10.1.221.1 255.255.255.0\ninterface GigabitEthernet0/3.222\nvlan 222\nnameif wired_user-v222\nsecurity-level 75\nip addr 10.1.222.1 255.255.255.0\ninterface GigabitEthernet0/3.223\nvlan 223\nnameif wired_user-v223\nsecurity-level 75\nip addr 10.1.223.1 255.255.255.0\ninterface GigabitEthernet0/3.224\nvlan 224\nnameif wired_user-v224\nsecurity-level 75\nip addr 10.1.224.1 255.255.255.0\ninterface GigabitEthernet0/3.225\nvlan 225\nnameif wired_user-v225\nsecurity-level 75\nip addr 10.1.225.1 255.255.255.0\ninterface GigabitEthernet0/3.226\nvlan 226\nnameif wired_user-v226\nsecurity-level 75\nip addr 10.1.226.1 255.255.255.0\ninterface GigabitEthernet0/3.227\nvlan 227\nnameif wired_user-v227\nsecurity-level 75\nip addr 10.1.227.1 255.255.255.0\ninterface GigabitEthernet0/3.228\nvlan 228\nnameif wired_user-v228\nsecurity-level 75\nip addr 10.1.228.1 255.255.255.0\ninterface GigabitEthernet0/3.229\nvlan 229\nnameif wired_user-v229\nsecurity-level 75\nip addr 10.1.229.1 255.255.255.0\ninterface GigabitEthernet0/3.230\nvlan 230\nnameif wired_user-v230\nsecurity-level 75\nip addr 10.1.230.1 255.255.255.0\ninterface GigabitEthernet0/3.231\nvlan 231\nnameif wired_user-v231\nsecurity-level 75\nip addr 10.1.231.1 255.255.255.0\ninterface GigabitEthernet0/3.232\nvlan 232\nnameif wired_user-v232\nsecurity-level 75\nip addr 10.1.232.1 255.255.255.0\ninterface GigabitEthernet0/3.233\nvlan 233\nnameif wired_user-v233\nsecurity-level 75\nip addr 10.1.233.1 255.255.255.0\ninterface GigabitEthernet0/3.234\nvlan 234\nnameif wired_user-v234\nsecurity-level 75\nip addr 10.1.234.1 255.255.255.0\ninterface GigabitEthernet0/3.235\nvlan 235\nnameif wired_user-v235\nsecurity-level 75\nip addr 10.1.235.1 255.255.255.0\ninterface GigabitEthernet0/3.236\nvlan 236\nnameif wired_user-v236\nsecurity-level 75\nip addr 10.1.236.1 255.255.255.0\ninterface GigabitEthernet0/3.237\nvlan 237\nnameif wired_user-v237\nsecurity-level 75\nip addr 10.1.237.1 255.255.255.0\ninterface GigabitEthernet0/3.238\nvlan 238\nnameif wired_user-v238\nsecurity-level 75\nip addr 10.1.238.1 255.255.255.0\ninterface GigabitEthernet0/3.239\nvlan 239\nnameif wired_user-v239\nsecurity-level 75\nip addr 10.1.239.1 255.255.255.0\ninterface GigabitEthernet0/3.240\nvlan 240\nnameif wired_user-v240\nsecurity-level 75\nip addr 10.1.240.1 255.255.255.0\ninterface GigabitEthernet0/3.241\nvlan 241\nnameif wired_user-v241\nsecurity-level 75\nip addr 10.1.241.1 255.255.255.0\ninterface GigabitEthernet0/3.242\nvlan 242\nnameif wired_user-v242\nsecurity-level 75\nip addr 10.1.242.1 255.255.255.0\ninterface GigabitEthernet0/3.243\nvlan 243\nnameif wired_user-v243\nsecurity-level 75\nip addr 10.1.243.1 255.255.255.0\ninterface GigabitEthernet0/3.244\nvlan 244\nnameif wired_user-v244\nsecurity-level 75\nip addr 10.1.244.1 255.255.255.0\ninterface GigabitEthernet0/3.245\nvlan 245\nnameif wired_user-v245\nsecurity-level 75\nip addr 10.1.245.1 255.255.255.0\ninterface GigabitEthernet0/3.246\nvlan 246\nnameif wired_user-v246\nsecurity-level 75\nip addr 10.1.246.1 255.255.255.0\ninterface GigabitEthernet0/3.247\nvlan 247\nnameif wired_user-v247\nsecurity-level 75\nip addr 10.1.247.1 255.255.255.0\ninterface GigabitEthernet0/3.248\nvlan 248\nnameif wired_user-v248\nsecurity-level 75\nip addr 10.1.248.1 255.255.255.0\ninterface GigabitEthernet0/3.249\nvlan 249\nnameif wired_user-v249\nsecurity-level 75\nip addr 10.1.249.1 255.255.255.0')
#! /usr/bin/env python3 # coding:utf-8 def main(): #answer = [(a, b, c) for a in range(21) for b in range(34) for c in range(101-a-b) # if a*5 + b*3 +c/3 == 100 and a+b+c == 100] #print(answer) for a in range(21): for b in range(34): c = 100-a-b if a*5 + b*3 +c/3 == 100: print(a, b, c) if __name__ == '__main__': main()
def main(): for a in range(21): for b in range(34): c = 100 - a - b if a * 5 + b * 3 + c / 3 == 100: print(a, b, c) if __name__ == '__main__': main()
name = "qt" version = "4.8.7" description = \ """ Qt """ build_requires = [ "python-2.7" ] def commands(): # export CMAKE_MODULE_PATH=$CMAKE_MODULE_PATH:!ROOT!/cmake # export QTDIR=!ROOT! # export QT_INCLUDE_DIR=!ROOT!/include # export QT_LIB_DIR=!ROOT!/lib # export LD_LIBRARY_PATH=!ROOT!/lib:$LD_LIBRARY_PATH # export QTLIB=!ROOT!/lib # export QT_QMAKE_EXECUTABLE=!ROOT!/bin/qmake # export PATH=!ROOT!/bin:$PATH # export CMAKE_MODULE_PATH=$CMAKE_MODULE_PATH:!ROOT!/cmake env.LD_LIBRARY_PATH.prepend("{root}/lib") env.QT_ROOT = '{root}' if building: env.CMAKE_MODULE_PATH.append("{root}/cmake") uuid = "repository.qt"
name = 'qt' version = '4.8.7' description = '\n Qt\n ' build_requires = ['python-2.7'] def commands(): env.LD_LIBRARY_PATH.prepend('{root}/lib') env.QT_ROOT = '{root}' if building: env.CMAKE_MODULE_PATH.append('{root}/cmake') uuid = 'repository.qt'
def getCommonLetters(word1, word2): return ''.join(sorted(set(word1).intersection(set(word2)))) print(getCommonLetters('apple', 'strw')) print(getCommonLetters('sing', 'song'))
def get_common_letters(word1, word2): return ''.join(sorted(set(word1).intersection(set(word2)))) print(get_common_letters('apple', 'strw')) print(get_common_letters('sing', 'song'))
class ParseFailure(Exception): def __init__(self, message, offset=None, column=None, row=None, text=None): self.message = message self.offset = offset self.column = column self.row = row self.text = text super(ParseFailure, self).__init__( self.message, self.offset, self.column, self.row, self.text) class JSONSquaredError(Exception): pass
class Parsefailure(Exception): def __init__(self, message, offset=None, column=None, row=None, text=None): self.message = message self.offset = offset self.column = column self.row = row self.text = text super(ParseFailure, self).__init__(self.message, self.offset, self.column, self.row, self.text) class Jsonsquarederror(Exception): pass
# # @lc app=leetcode id=71 lang=python3 # # [71] Simplify Path # # @lc code=start class Solution: def simplifyPath(self, path: str) -> str: stack = [] for token in path.split('/'): if token in ('', '.'): pass elif token == '..': if stack: stack.pop() else: stack.append(token) return '/' + '/'.join(stack) # @lc code=end # Accepted # 254/254 cases passed(24 ms) # Your runtime beats 99.96 % of python3 submissions # Your memory usage beats 100 % of python3 submissions(12.8 MB)
class Solution: def simplify_path(self, path: str) -> str: stack = [] for token in path.split('/'): if token in ('', '.'): pass elif token == '..': if stack: stack.pop() else: stack.append(token) return '/' + '/'.join(stack)
"""A walrus pattern looks like d := datetime(year=2020, month=m). It matches only if its sub-pattern also matches. It binds whatever the sub-pattern match does, and also binds the named variable to the entire object. """ # TODO # match group_shapes(): # case [], [point := Point(x, y), *other]: # print(f"Got {point} in the second group") # process_coordinates(x, y) # ...
"""A walrus pattern looks like d := datetime(year=2020, month=m). It matches only if its sub-pattern also matches. It binds whatever the sub-pattern match does, and also binds the named variable to the entire object. """
test_cases = int(input()) while test_cases > 0: burles = int(input()) optimal = 0 while True: # The main logic here is to divide the burles into small parts of burles, as, that would be optimal. If Mishka sell 10 burles, he'd get one back; if less, nothing, if higher than 10 and lower than 20 then still one. partition = int(burles / 10) * 10 optimal += partition # Now assigning the part he'd get back and the left one to the initial variable. burles_left = burles - partition burles = int(burles / 10) + burles_left # Well, if the burles are less than 10, he have no option rather than selling them all. if burles < 10: optimal += burles break print(optimal) test_cases -= 1
test_cases = int(input()) while test_cases > 0: burles = int(input()) optimal = 0 while True: partition = int(burles / 10) * 10 optimal += partition burles_left = burles - partition burles = int(burles / 10) + burles_left if burles < 10: optimal += burles break print(optimal) test_cases -= 1
def MathOp(): classic_division=3/2 floor_division=3//2 modulus=3%2 power=3**2 return [classic_division, floor_division, modulus, power] [classic_division, floor_division, modulus, power]=MathOp() print(classic_division) print(floor_division) print(modulus) print(power)
def math_op(): classic_division = 3 / 2 floor_division = 3 // 2 modulus = 3 % 2 power = 3 ** 2 return [classic_division, floor_division, modulus, power] [classic_division, floor_division, modulus, power] = math_op() print(classic_division) print(floor_division) print(modulus) print(power)
""" Python implementation of a linked list """ # TODO docstrings class Node(object): def __init__(self, data=None): self.data = data self.next_node = None class LinkedList(object): def __init__(self): self.head = None self.size = 0 def __getitem__(self, index): if index < 0 or index > self.size: raise Exception(f"[ERROR] cannot acces index {index} in LinkedList with size {self.size}") curr = self.head for _i in range(0, index): curr = curr.next_node return curr def insertFirst(self, new_data): node = Node(data=new_data) if self.head is None: self.head = node else: node.next_node = self.head self.head = node self.size += 1 def insertAt(self, new_data, index): if index > self.size: raise Exception(f"[ERROR] cannot insert Node at index {index} in LinkedList with size {self.size}") elif index == 0: self.insertFirst(new_data) else: node = Node(data=new_data) curr = self.head ctr = 1 while curr.next_node is not None and ctr < index: curr = curr.next_node ctr += 1 node.next_node = curr.next_node curr.next_node = node self.size += 1 def insertLast(self, new_data): node = Node(data=new_data) if self.head is None: self.head = node else: curr = self.head while curr.next_node is not None: curr = curr.next_node curr.next_node = node self.size += 1 def remove(self, data_key): if self.size == 0: raise Exception("[ERROR] cannot remove() from LinkedList with size 0") curr = self.head while curr.next_node.data != data_key: curr = curr.next_node if curr.next_node.data == data_key: curr.next_node = curr.next_node.next_node self.size -= 1 else: raise Exception(f"[ERROR] could not find {data_key} in LinkedList to remove()") def union(self, linkedlist): if self.size == 0: self.head = linkedlist.head else: curr = self.head while curr.next_node is not None: curr = curr.next_node curr.next_node = linkedlist.head def show(self): curr = self.head print(f"[LL s={self.size}]:", end=" ") while curr is not None: print(f"{curr.data}", end=" ") curr = curr.next_node print("")
""" Python implementation of a linked list """ class Node(object): def __init__(self, data=None): self.data = data self.next_node = None class Linkedlist(object): def __init__(self): self.head = None self.size = 0 def __getitem__(self, index): if index < 0 or index > self.size: raise exception(f'[ERROR] cannot acces index {index} in LinkedList with size {self.size}') curr = self.head for _i in range(0, index): curr = curr.next_node return curr def insert_first(self, new_data): node = node(data=new_data) if self.head is None: self.head = node else: node.next_node = self.head self.head = node self.size += 1 def insert_at(self, new_data, index): if index > self.size: raise exception(f'[ERROR] cannot insert Node at index {index} in LinkedList with size {self.size}') elif index == 0: self.insertFirst(new_data) else: node = node(data=new_data) curr = self.head ctr = 1 while curr.next_node is not None and ctr < index: curr = curr.next_node ctr += 1 node.next_node = curr.next_node curr.next_node = node self.size += 1 def insert_last(self, new_data): node = node(data=new_data) if self.head is None: self.head = node else: curr = self.head while curr.next_node is not None: curr = curr.next_node curr.next_node = node self.size += 1 def remove(self, data_key): if self.size == 0: raise exception('[ERROR] cannot remove() from LinkedList with size 0') curr = self.head while curr.next_node.data != data_key: curr = curr.next_node if curr.next_node.data == data_key: curr.next_node = curr.next_node.next_node self.size -= 1 else: raise exception(f'[ERROR] could not find {data_key} in LinkedList to remove()') def union(self, linkedlist): if self.size == 0: self.head = linkedlist.head else: curr = self.head while curr.next_node is not None: curr = curr.next_node curr.next_node = linkedlist.head def show(self): curr = self.head print(f'[LL s={self.size}]:', end=' ') while curr is not None: print(f'{curr.data}', end=' ') curr = curr.next_node print('')
# # PySNMP MIB module Juniper-Multicast-Router-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-Multicast-Router-CONF # Produced by pysmi-0.3.4 at Wed May 1 14:03:31 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, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint") juniAgents, = mibBuilder.importSymbols("Juniper-Agents", "juniAgents") AgentCapabilities, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "NotificationGroup", "ModuleCompliance") ModuleIdentity, Counter64, Gauge32, MibIdentifier, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Counter32, IpAddress, Integer32, ObjectIdentity, Bits, NotificationType, iso = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Counter64", "Gauge32", "MibIdentifier", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Counter32", "IpAddress", "Integer32", "ObjectIdentity", "Bits", "NotificationType", "iso") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") juniMRouterAgent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55)) juniMRouterAgent.setRevisions(('2006-09-18 08:09', '2006-09-02 11:02', '2006-06-15 10:13', '2002-10-28 20:04', '2002-04-01 20:17',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: juniMRouterAgent.setRevisionsDescriptions(('Extended the ipMRouteInterfaceEntry Table, introduced traps and platform dependent rsMRoutePortTable.', 'Scalar attribute rsMcastRpfDisable is supported for the Juniper-MROUTER-MIB.', 'Extended the ipMRouteEntry Table', 'Replaced Unisphere names with Juniper names. Added support for the Juniper-MROUTER-MIB.', 'The initial release of this management information module.',)) if mibBuilder.loadTexts: juniMRouterAgent.setLastUpdated('200609180809Z') if mibBuilder.loadTexts: juniMRouterAgent.setOrganization('Juniper Networks, Inc.') if mibBuilder.loadTexts: juniMRouterAgent.setContactInfo(' Juniper Networks, Inc. Postal: 10 Technology Park Drive Westford, MA 01886-3146 USA Tel: +1 978 589 5800 E-mail: mib@Juniper.net') if mibBuilder.loadTexts: juniMRouterAgent.setDescription('The agent capabilities definitions for the multicast router component of the SNMP agent in the Juniper E-series family of products.') juniMRouterAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniMRouterAgentV1 = juniMRouterAgentV1.setProductRelease('Version 1 of the multicast router component of the JUNOSe SNMP agent.\n This version of the multicast router component was supported in JUNOSe\n 4.1 and subsequent 4.x system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniMRouterAgentV1 = juniMRouterAgentV1.setStatus('obsolete') if mibBuilder.loadTexts: juniMRouterAgentV1.setDescription('The MIBs supported by the SNMP agent for the multicast router application in JUNOSe. These capabilities became obsolete when support was added for the Juniper-MROUTER-MIB.') juniMRouterAgentV2 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 2)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniMRouterAgentV2 = juniMRouterAgentV2.setProductRelease('Version 2 of the multicast router component of the JUNOSe SNMP agent.\n These capabilities became obsolete when support was added to Juniper-MROUTER-MIB\n This version of the multicast router component is supported in the\n Juniper JUNOSe 5.0 and subsequent system releases upto 8.0.0.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniMRouterAgentV2 = juniMRouterAgentV2.setStatus('obsolete') if mibBuilder.loadTexts: juniMRouterAgentV2.setDescription('The MIB supported by the SNMP agent for the multicast router application in JUNOSe. These capabilities became obsolete when juniMRouteConfGroup support was added to Juniper-MROUTER-MIB.') juniMRouterAgentV3 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 3)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniMRouterAgentV3 = juniMRouterAgentV3.setProductRelease('Version 3 of the multicast router component of the JUNOSe SNMP agent.\n This version of the multicast router component is supported in the\n Juniper JUNOSe 8.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniMRouterAgentV3 = juniMRouterAgentV3.setStatus('obsolete') if mibBuilder.loadTexts: juniMRouterAgentV3.setDescription('The MIB supported by the SNMP agent for the multicast router application in JUNOSe.These capabilities became obsolete when juniMcastGlobalConfGroup support was added to Juniper-MROUTER-MIB.') uniMRouterAgentV4 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 4)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): uniMRouterAgentV4 = uniMRouterAgentV4.setProductRelease('Version 4 of the multicast router component of the JUNOSe SNMP agent.\n This version of the multicast router component is supported in the\n Juniper JUNOSe 8.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): uniMRouterAgentV4 = uniMRouterAgentV4.setStatus('obsolete') if mibBuilder.loadTexts: uniMRouterAgentV4.setDescription('The MIB supported by the SNMP agent for the multicast router application in JUNOSe. These capabilities became obsolete when rsMRoutePortConfGroup support was added to Juniper-MROUTER-MIB.') uniMRouterAgentV5 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 5)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): uniMRouterAgentV5 = uniMRouterAgentV5.setProductRelease('Version 5 of the multicast router component of the JUNOSe SNMP agent.\n This version of the multicast router component is supported in the\n Juniper JUNOSe 8.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): uniMRouterAgentV5 = uniMRouterAgentV5.setStatus('current') if mibBuilder.loadTexts: uniMRouterAgentV5.setDescription('The MIB supported by the SNMP agent for the multicast router application in JUNOSe.') mibBuilder.exportSymbols("Juniper-Multicast-Router-CONF", juniMRouterAgentV1=juniMRouterAgentV1, PYSNMP_MODULE_ID=juniMRouterAgent, juniMRouterAgent=juniMRouterAgent, juniMRouterAgentV3=juniMRouterAgentV3, uniMRouterAgentV4=uniMRouterAgentV4, juniMRouterAgentV2=juniMRouterAgentV2, uniMRouterAgentV5=uniMRouterAgentV5)
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, constraints_union, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint') (juni_agents,) = mibBuilder.importSymbols('Juniper-Agents', 'juniAgents') (agent_capabilities, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'AgentCapabilities', 'NotificationGroup', 'ModuleCompliance') (module_identity, counter64, gauge32, mib_identifier, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, counter32, ip_address, integer32, object_identity, bits, notification_type, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'Counter64', 'Gauge32', 'MibIdentifier', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'Counter32', 'IpAddress', 'Integer32', 'ObjectIdentity', 'Bits', 'NotificationType', 'iso') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') juni_m_router_agent = module_identity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55)) juniMRouterAgent.setRevisions(('2006-09-18 08:09', '2006-09-02 11:02', '2006-06-15 10:13', '2002-10-28 20:04', '2002-04-01 20:17')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: juniMRouterAgent.setRevisionsDescriptions(('Extended the ipMRouteInterfaceEntry Table, introduced traps and platform dependent rsMRoutePortTable.', 'Scalar attribute rsMcastRpfDisable is supported for the Juniper-MROUTER-MIB.', 'Extended the ipMRouteEntry Table', 'Replaced Unisphere names with Juniper names. Added support for the Juniper-MROUTER-MIB.', 'The initial release of this management information module.')) if mibBuilder.loadTexts: juniMRouterAgent.setLastUpdated('200609180809Z') if mibBuilder.loadTexts: juniMRouterAgent.setOrganization('Juniper Networks, Inc.') if mibBuilder.loadTexts: juniMRouterAgent.setContactInfo(' Juniper Networks, Inc. Postal: 10 Technology Park Drive Westford, MA 01886-3146 USA Tel: +1 978 589 5800 E-mail: mib@Juniper.net') if mibBuilder.loadTexts: juniMRouterAgent.setDescription('The agent capabilities definitions for the multicast router component of the SNMP agent in the Juniper E-series family of products.') juni_m_router_agent_v1 = agent_capabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juni_m_router_agent_v1 = juniMRouterAgentV1.setProductRelease('Version 1 of the multicast router component of the JUNOSe SNMP agent.\n This version of the multicast router component was supported in JUNOSe\n 4.1 and subsequent 4.x system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juni_m_router_agent_v1 = juniMRouterAgentV1.setStatus('obsolete') if mibBuilder.loadTexts: juniMRouterAgentV1.setDescription('The MIBs supported by the SNMP agent for the multicast router application in JUNOSe. These capabilities became obsolete when support was added for the Juniper-MROUTER-MIB.') juni_m_router_agent_v2 = agent_capabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 2)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juni_m_router_agent_v2 = juniMRouterAgentV2.setProductRelease('Version 2 of the multicast router component of the JUNOSe SNMP agent.\n These capabilities became obsolete when support was added to Juniper-MROUTER-MIB\n This version of the multicast router component is supported in the\n Juniper JUNOSe 5.0 and subsequent system releases upto 8.0.0.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juni_m_router_agent_v2 = juniMRouterAgentV2.setStatus('obsolete') if mibBuilder.loadTexts: juniMRouterAgentV2.setDescription('The MIB supported by the SNMP agent for the multicast router application in JUNOSe. These capabilities became obsolete when juniMRouteConfGroup support was added to Juniper-MROUTER-MIB.') juni_m_router_agent_v3 = agent_capabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 3)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juni_m_router_agent_v3 = juniMRouterAgentV3.setProductRelease('Version 3 of the multicast router component of the JUNOSe SNMP agent.\n This version of the multicast router component is supported in the\n Juniper JUNOSe 8.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juni_m_router_agent_v3 = juniMRouterAgentV3.setStatus('obsolete') if mibBuilder.loadTexts: juniMRouterAgentV3.setDescription('The MIB supported by the SNMP agent for the multicast router application in JUNOSe.These capabilities became obsolete when juniMcastGlobalConfGroup support was added to Juniper-MROUTER-MIB.') uni_m_router_agent_v4 = agent_capabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 4)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): uni_m_router_agent_v4 = uniMRouterAgentV4.setProductRelease('Version 4 of the multicast router component of the JUNOSe SNMP agent.\n This version of the multicast router component is supported in the\n Juniper JUNOSe 8.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): uni_m_router_agent_v4 = uniMRouterAgentV4.setStatus('obsolete') if mibBuilder.loadTexts: uniMRouterAgentV4.setDescription('The MIB supported by the SNMP agent for the multicast router application in JUNOSe. These capabilities became obsolete when rsMRoutePortConfGroup support was added to Juniper-MROUTER-MIB.') uni_m_router_agent_v5 = agent_capabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 55, 5)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): uni_m_router_agent_v5 = uniMRouterAgentV5.setProductRelease('Version 5 of the multicast router component of the JUNOSe SNMP agent.\n This version of the multicast router component is supported in the\n Juniper JUNOSe 8.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): uni_m_router_agent_v5 = uniMRouterAgentV5.setStatus('current') if mibBuilder.loadTexts: uniMRouterAgentV5.setDescription('The MIB supported by the SNMP agent for the multicast router application in JUNOSe.') mibBuilder.exportSymbols('Juniper-Multicast-Router-CONF', juniMRouterAgentV1=juniMRouterAgentV1, PYSNMP_MODULE_ID=juniMRouterAgent, juniMRouterAgent=juniMRouterAgent, juniMRouterAgentV3=juniMRouterAgentV3, uniMRouterAgentV4=uniMRouterAgentV4, juniMRouterAgentV2=juniMRouterAgentV2, uniMRouterAgentV5=uniMRouterAgentV5)
#!/usr/bin/env python3 """Reading in and writing out files""" def main(): # old method for opening files # requires closing the file object when done myfile = open("vendor.txt", 'r') # new method for opening files # closes file when indentation ends with open('vendor-ips.txt', 'w') as myoutfile: for line in myfile.readlines(): splitline = line.split(' ') print(splitline[-1].strip()) #myoutfile.write(splitline[-1] + '\n') # ['', 'cisco', 'v18', 'ios', 'http://example.com/cisco', '192.168.1.55\n'] # 0 1 2 3 4 5 # -6 -5 -4 -3 -2 -1 # close the open file object myfile.close() main()
"""Reading in and writing out files""" def main(): myfile = open('vendor.txt', 'r') with open('vendor-ips.txt', 'w') as myoutfile: for line in myfile.readlines(): splitline = line.split(' ') print(splitline[-1].strip()) myfile.close() main()
# Global Moderation ACCOUNT_BAN = "ACB" ACCOUNT_UNBAN = "UBN" ACCOUNT_TIMEOUT = "TMO" SERVER_KICK = "KIK" PROMOTE_GLOBAL_OP = "AOP" DEMOTE_GLOBAL_OP = "DOP" LIST_ALTS = "AWC" BROADCAST = "BRO" REWARD = "RWD" RELOAD_SERVER_CONFIG = "RLD" # Channels LIST_OFFICAL_CHANNELS = "CHA" LIST_PRIVATE_CHANNELS = "ORS" INITIAL_CHANNEL_DATA = "ICH" TIMEOUT = "CTU" KICK = "CKU" BAN = "CBU" UNBAN = "CUB" BANLIST = "CBL" CREATE_PRIVATE_CHANNEL = "CCR" CREATE_OFFICAL_CHANNEL = "CRC" SET_CHANNEL_DESCRIPTION = "CDS" SET_CHANNEL_OWNER = "CSO" PROMOTE_OP = "COA" DEMOTE_OP = "COR" INVITE = "CIU" LIST_OPS = "COL" SET_CHANNEL_MODE = "RMO" SET_PRIVATE_CHANNEL_STATE = "RST" ROLEPLAY_AD = "LRP" CHANNEL_MESSAGE = "MSG" # Characters JOIN_CHANNEL = "JCH" GONE_OFFLINE = "FLN" PROFILE_DATA = "PRD" PROFILE = "PRO" KINKS_DATA = "KID" KINKS = "KIN" LEAVE_CHANNEL = "LCH" LIST_CHARACTERS = "LIS" USER_CONNECTED = "NLN" FRIENDS_LIST = "FRL" PRIVATE_MESSAGE = "PRI" IGNORE = "IGN" TYPING = "TPN" STATUS = "STA" # General LIST_GLOBAL_OPS = "ADL" NUMBER_OF_CONNECTED_USERS = "CON" ERROR = "ERR" SEARCH = "FKS" SERVER_HELLO = "HLO" IDENTIFY = "IDN" PING = "PIN" ROLL = "RLL" REPORT = "SFC" SITE_EVENT = "RTB" SYSTEM_MESSAGE = "SYS" UPTIME = "UPT" VARIABLES = "VAR"
account_ban = 'ACB' account_unban = 'UBN' account_timeout = 'TMO' server_kick = 'KIK' promote_global_op = 'AOP' demote_global_op = 'DOP' list_alts = 'AWC' broadcast = 'BRO' reward = 'RWD' reload_server_config = 'RLD' list_offical_channels = 'CHA' list_private_channels = 'ORS' initial_channel_data = 'ICH' timeout = 'CTU' kick = 'CKU' ban = 'CBU' unban = 'CUB' banlist = 'CBL' create_private_channel = 'CCR' create_offical_channel = 'CRC' set_channel_description = 'CDS' set_channel_owner = 'CSO' promote_op = 'COA' demote_op = 'COR' invite = 'CIU' list_ops = 'COL' set_channel_mode = 'RMO' set_private_channel_state = 'RST' roleplay_ad = 'LRP' channel_message = 'MSG' join_channel = 'JCH' gone_offline = 'FLN' profile_data = 'PRD' profile = 'PRO' kinks_data = 'KID' kinks = 'KIN' leave_channel = 'LCH' list_characters = 'LIS' user_connected = 'NLN' friends_list = 'FRL' private_message = 'PRI' ignore = 'IGN' typing = 'TPN' status = 'STA' list_global_ops = 'ADL' number_of_connected_users = 'CON' error = 'ERR' search = 'FKS' server_hello = 'HLO' identify = 'IDN' ping = 'PIN' roll = 'RLL' report = 'SFC' site_event = 'RTB' system_message = 'SYS' uptime = 'UPT' variables = 'VAR'
# Suppose you have a multiplication table that is N by N. That is, a 2D array # where the value at the i-th row and j-th column is (i + 1) * (j + 1) # (if 0-indexed) or i * j (if 1-indexed). # Given integers N and X, write a function that returns the number of times X # appears as a value in an N by N multiplication table. def count_appearance(n, x): count = 0 for i in range(1, n + 1): for j in range(1, n + 1): multip = i * j if multip > x: break if multip == x: count += 1 break return count if __name__ == '__main__': print(count_appearance(6, 12))
def count_appearance(n, x): count = 0 for i in range(1, n + 1): for j in range(1, n + 1): multip = i * j if multip > x: break if multip == x: count += 1 break return count if __name__ == '__main__': print(count_appearance(6, 12))
class Solution(object): def minTotalDistance(self, grid): """ :type grid: List[List[int]] :rtype: int """ # basically try to solve for median for 1D array twice vertical_list = [] horizontal_list = [] for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]: vertical_list += i, horizontal_list += j, horizontal_list.sort() result = 0 start,end = 0,len(horizontal_list)-1 while end -start >= 1: result += vertical_list[end] - vertical_list[start] result += horizontal_list[end] - horizontal_list[start] end -= 1 start += 1 return result
class Solution(object): def min_total_distance(self, grid): """ :type grid: List[List[int]] :rtype: int """ vertical_list = [] horizontal_list = [] for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]: vertical_list += (i,) horizontal_list += (j,) horizontal_list.sort() result = 0 (start, end) = (0, len(horizontal_list) - 1) while end - start >= 1: result += vertical_list[end] - vertical_list[start] result += horizontal_list[end] - horizontal_list[start] end -= 1 start += 1 return result
""" Easy 1640. [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/) You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. Example 1: Input: arr = [85], pieces = [[85]] Output: true Example 2: Input: arr = [15,88], pieces = [[88],[15]] Output: true Explanation: Concatenate [15] then [88] Example 3: Input: arr = [49,18,16], pieces = [[16,18,49]] Output: false Explanation: Even though the numbers match, we cannot reorder pieces[0]. Example 4: Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]] Output: true Explanation: Concatenate [91] then [4,64] then [78] Example 5: Input: arr = [1,3,5,7], pieces = [[2,4,6,8]] Output: false Constraints: 1 <= pieces.length <= arr.length <= 100 sum(pieces[i].length) == arr.length 1 <= pieces[i].length <= arr.length 1 <= arr[i], pieces[i][j] <= 100 The integers in arr are distinct. The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct). """ # Solutions class Solution: """ len(arr) = m len(pieces) = n Time Complexity: O( max(m, n) ) Space Complexity: O( n ) """ def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: d = {x[0]: x for x in pieces} ind = 0 while ind < len(arr): value = d.get(arr[ind]) if not value or arr[ind : ind + len(value)] != value: return False ind += len(value) return True # Runtime : 28 ms, faster than 99.69% of Python3 online submissions # Memory Usage : 14.5 MB, less than 16.74% of Python3 online submissions
""" Easy 1640. [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/) You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. Example 1: Input: arr = [85], pieces = [[85]] Output: true Example 2: Input: arr = [15,88], pieces = [[88],[15]] Output: true Explanation: Concatenate [15] then [88] Example 3: Input: arr = [49,18,16], pieces = [[16,18,49]] Output: false Explanation: Even though the numbers match, we cannot reorder pieces[0]. Example 4: Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]] Output: true Explanation: Concatenate [91] then [4,64] then [78] Example 5: Input: arr = [1,3,5,7], pieces = [[2,4,6,8]] Output: false Constraints: 1 <= pieces.length <= arr.length <= 100 sum(pieces[i].length) == arr.length 1 <= pieces[i].length <= arr.length 1 <= arr[i], pieces[i][j] <= 100 The integers in arr are distinct. The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct). """ class Solution: """ len(arr) = m len(pieces) = n Time Complexity: O( max(m, n) ) Space Complexity: O( n ) """ def can_form_array(self, arr: List[int], pieces: List[List[int]]) -> bool: d = {x[0]: x for x in pieces} ind = 0 while ind < len(arr): value = d.get(arr[ind]) if not value or arr[ind:ind + len(value)] != value: return False ind += len(value) return True
def maxSubArray(X): # Store sum, start, end result = (X[0], 0, 0) for i in range(0, len(X)): for j in range(i, len(X)): subSum = 0 for k in range(i, j + 1): subSum += X[k] if result[0] < subSum: result = (subSum, i, j) return result
def max_sub_array(X): result = (X[0], 0, 0) for i in range(0, len(X)): for j in range(i, len(X)): sub_sum = 0 for k in range(i, j + 1): sub_sum += X[k] if result[0] < subSum: result = (subSum, i, j) return result
# -*- coding: utf-8 -*- a = [] b = a c = [] print("id(a) = ", id(a)) print("id(b) = ", id(b)) print("id(c) = ", id(c)) a.append(1) b.append(2) c.append(3) print("id(a) = ", id(a)) print("id(b) = ", id(b)) print("id(c) = ", id(c))
a = [] b = a c = [] print('id(a) = ', id(a)) print('id(b) = ', id(b)) print('id(c) = ', id(c)) a.append(1) b.append(2) c.append(3) print('id(a) = ', id(a)) print('id(b) = ', id(b)) print('id(c) = ', id(c))
__all__ = ('ConnectionClosed',) class ConnectionClosed(Exception): """Exception indicating that the connection to Discord fully closed. This is raised when the connection cannot naturally reconnect and the program should exit - which happens if Discord unexpectedly closes the socket during the crucial bootstrapping process. Additionally, it may also be raised if Discord responded with a special error code in the 4000-range - which signals that the connection absolutely cannot reconnect such as sending an improper token or intents. """ pass
__all__ = ('ConnectionClosed',) class Connectionclosed(Exception): """Exception indicating that the connection to Discord fully closed. This is raised when the connection cannot naturally reconnect and the program should exit - which happens if Discord unexpectedly closes the socket during the crucial bootstrapping process. Additionally, it may also be raised if Discord responded with a special error code in the 4000-range - which signals that the connection absolutely cannot reconnect such as sending an improper token or intents. """ pass
""" .. module:: check_in_known_missions :synopsis: Given a string, checks if it's in a list of known mission values. .. moduleauthor:: Scott W. Fleming <fleming@stsci.edu> """ #-------------------- def check_in_known_missions(istring, known_missions, exclude_missions): """ Checks if mission string is in list of known values. :param istring: The string to check. :type istring: str :param known_missions: The list of known values for the "mission" part of file names. :type known_missions: set :param exclude_missions: Optional list of values for the "mission" part of the file names that will be temporarily accepted (for this run only). :type exclude_missions: list :returns: bool - True if in set of known values, false otherwise. """ # The input string can contain one or more mission values. If multiple, # they are separated by a hyphen ("-"). # Split into pieces. mission_splits = istring.split('-') # If provided, add the list of mission values to exclude temporarily to the # list to check against. if exclude_missions: all_known_missions = known_missions.union(exclude_missions) else: all_known_missions = known_missions # Check if this is a subset of the known missions. return set(mission_splits).issubset(all_known_missions) #--------------------
""" .. module:: check_in_known_missions :synopsis: Given a string, checks if it's in a list of known mission values. .. moduleauthor:: Scott W. Fleming <fleming@stsci.edu> """ def check_in_known_missions(istring, known_missions, exclude_missions): """ Checks if mission string is in list of known values. :param istring: The string to check. :type istring: str :param known_missions: The list of known values for the "mission" part of file names. :type known_missions: set :param exclude_missions: Optional list of values for the "mission" part of the file names that will be temporarily accepted (for this run only). :type exclude_missions: list :returns: bool - True if in set of known values, false otherwise. """ mission_splits = istring.split('-') if exclude_missions: all_known_missions = known_missions.union(exclude_missions) else: all_known_missions = known_missions return set(mission_splits).issubset(all_known_missions)
# read_stocks.py # Read the current data of the stock market and show them if need be def is_open(api): #Check if market is closed clock = api.get_clock() print('The market is {}'.format('open.' if clock.is_open else 'closed.')) ### Please check again here def read_market_data(api,input_stocks,intervals,ma_interval): barset = api.get_barset(input_stocks,'day', limit = intervals+ma_interval) #acquire additional data for moving average (add extra ma_interval) stock_bars = barset[input_stocks] week_open = stock_bars[intervals+ma_interval-5].o week_close = stock_bars[-1].c percent_change = (week_close-week_open)/week_open*100 # Print if how stocks have evolved over last couple of days print(input_stocks,' moved {}% over the last 5 days'.format(percent_change)) # convert time in datetime return stock_bars
def is_open(api): clock = api.get_clock() print('The market is {}'.format('open.' if clock.is_open else 'closed.')) def read_market_data(api, input_stocks, intervals, ma_interval): barset = api.get_barset(input_stocks, 'day', limit=intervals + ma_interval) stock_bars = barset[input_stocks] week_open = stock_bars[intervals + ma_interval - 5].o week_close = stock_bars[-1].c percent_change = (week_close - week_open) / week_open * 100 print(input_stocks, ' moved {}% over the last 5 days'.format(percent_change)) return stock_bars
with open('input.txt') as file: sum = 0 group = None for line in file: if line.strip(): if group is None: group = set(line.strip()) else: group = group.intersection(line.strip()) else: print("group:", ''.join(sorted(group))) sum += len(group) group = None print("group:", ''.join(sorted(group))) sum += len(group) print(sum)
with open('input.txt') as file: sum = 0 group = None for line in file: if line.strip(): if group is None: group = set(line.strip()) else: group = group.intersection(line.strip()) else: print('group:', ''.join(sorted(group))) sum += len(group) group = None print('group:', ''.join(sorted(group))) sum += len(group) print(sum)
# # PySNMP MIB module CISCO-COMMON-MGMT-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-MGMT-CAPABILITY # Produced by pysmi-0.3.4 at Wed May 1 11:53:37 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) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability") NotificationGroup, ModuleCompliance, AgentCapabilities = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "AgentCapabilities") Integer32, Counter64, IpAddress, MibIdentifier, ObjectIdentity, Bits, iso, ModuleIdentity, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Gauge32, NotificationType, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Counter64", "IpAddress", "MibIdentifier", "ObjectIdentity", "Bits", "iso", "ModuleIdentity", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Gauge32", "NotificationType", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ciscoCommonMgmtCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 448)) ciscoCommonMgmtCapability.setRevisions(('2005-08-27 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setRevisionsDescriptions(('Initial version of this MIB module.',)) if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setLastUpdated('200508270000Z') if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-san@cisco.com') if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setDescription('Agent capabilities for CISCO-COMMON-MGMT-MIB') ciscoCommonMgmtCapMDS30R1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 448, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoCommonMgmtCapMDS30R1 = ciscoCommonMgmtCapMDS30R1.setProductRelease('Cisco MDS 3.0(1)') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoCommonMgmtCapMDS30R1 = ciscoCommonMgmtCapMDS30R1.setStatus('current') if mibBuilder.loadTexts: ciscoCommonMgmtCapMDS30R1.setDescription('Cisco Common Management MIB capabilities') mibBuilder.exportSymbols("CISCO-COMMON-MGMT-CAPABILITY", PYSNMP_MODULE_ID=ciscoCommonMgmtCapability, ciscoCommonMgmtCapMDS30R1=ciscoCommonMgmtCapMDS30R1, ciscoCommonMgmtCapability=ciscoCommonMgmtCapability)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint') (cisco_agent_capability,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoAgentCapability') (notification_group, module_compliance, agent_capabilities) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'AgentCapabilities') (integer32, counter64, ip_address, mib_identifier, object_identity, bits, iso, module_identity, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, gauge32, notification_type, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'Counter64', 'IpAddress', 'MibIdentifier', 'ObjectIdentity', 'Bits', 'iso', 'ModuleIdentity', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'Gauge32', 'NotificationType', 'Unsigned32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') cisco_common_mgmt_capability = module_identity((1, 3, 6, 1, 4, 1, 9, 7, 448)) ciscoCommonMgmtCapability.setRevisions(('2005-08-27 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setRevisionsDescriptions(('Initial version of this MIB module.',)) if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setLastUpdated('200508270000Z') if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-san@cisco.com') if mibBuilder.loadTexts: ciscoCommonMgmtCapability.setDescription('Agent capabilities for CISCO-COMMON-MGMT-MIB') cisco_common_mgmt_cap_mds30_r1 = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 448, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_common_mgmt_cap_mds30_r1 = ciscoCommonMgmtCapMDS30R1.setProductRelease('Cisco MDS 3.0(1)') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_common_mgmt_cap_mds30_r1 = ciscoCommonMgmtCapMDS30R1.setStatus('current') if mibBuilder.loadTexts: ciscoCommonMgmtCapMDS30R1.setDescription('Cisco Common Management MIB capabilities') mibBuilder.exportSymbols('CISCO-COMMON-MGMT-CAPABILITY', PYSNMP_MODULE_ID=ciscoCommonMgmtCapability, ciscoCommonMgmtCapMDS30R1=ciscoCommonMgmtCapMDS30R1, ciscoCommonMgmtCapability=ciscoCommonMgmtCapability)
class Edge: pass class Loop(Edge): pass class ParallelEdge(Edge): pass
class Edge: pass class Loop(Edge): pass class Paralleledge(Edge): pass
# Division with int # Prompt user for x x = int(input("x: ")) # Prompt user for y y = int(input("y: ")) # Perform division print(x / y)
x = int(input('x: ')) y = int(input('y: ')) print(x / y)
# Python - 2.7.6 Test.describe('combine names') Test.it('example tests') Test.assert_equals(combine_names('James', 'Stevens'), 'James Stevens') Test.assert_equals(combine_names('Davy', 'Back'), 'Davy Back') Test.assert_equals(combine_names('Arthur', 'Dent'), 'Arthur Dent')
Test.describe('combine names') Test.it('example tests') Test.assert_equals(combine_names('James', 'Stevens'), 'James Stevens') Test.assert_equals(combine_names('Davy', 'Back'), 'Davy Back') Test.assert_equals(combine_names('Arthur', 'Dent'), 'Arthur Dent')
""" Leetcode problem: https://leetcode.com/problems/super-egg-drop/ """ def solve_dp(K: int, N: int): def solve(k, moves): dp = [None] * (k + 1) for i in range(k + 1): dp[i] = [0] * (moves + 1) for i in range(1, k + 1): for j in range(1, moves + 1): dp[i][j] = 1 + dp[i - 1][j - 1] + dp[i][j - 1] # triangular numbers in DP return dp[k][moves] # if k == 1: # return moves # if moves == 1 or moves == 0: # return moves # return 1 + solve(k - 1, moves - 1) + solve(k, moves - 1) left, right = 1, N + 1 while left < right: # logN * K * (N/2 + N/4 + ..) ~= K * N * logN mid = (left + right) // 2 if solve(K, mid) >= N: # try finding less moves right = mid else: left = mid + 1 return left
""" Leetcode problem: https://leetcode.com/problems/super-egg-drop/ """ def solve_dp(K: int, N: int): def solve(k, moves): dp = [None] * (k + 1) for i in range(k + 1): dp[i] = [0] * (moves + 1) for i in range(1, k + 1): for j in range(1, moves + 1): dp[i][j] = 1 + dp[i - 1][j - 1] + dp[i][j - 1] return dp[k][moves] (left, right) = (1, N + 1) while left < right: mid = (left + right) // 2 if solve(K, mid) >= N: right = mid else: left = mid + 1 return left
a,b = [int(i) for i in input().split()] def gcd(a,b): if b==0: print(a) quit() c = a%b gcd(b,c) if a>b: gcd(a,b) else: gcd(b,a)
(a, b) = [int(i) for i in input().split()] def gcd(a, b): if b == 0: print(a) quit() c = a % b gcd(b, c) if a > b: gcd(a, b) else: gcd(b, a)
DEFAULT_LOGGING_CONFIG = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(levelname)s][%(name)s]: %(reset)s%(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'console' }, 'syslog': { 'class': 'logging.handlers.SysLogHandler', 'level': 'INFO' } }, 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False } }, 'root': { 'level': 'INFO', 'handlers': ['console'] } }
default_logging_config = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'console': {'()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(levelname)s][%(name)s]: %(reset)s%(message)s'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'console'}, 'syslog': {'class': 'logging.handlers.SysLogHandler', 'level': 'INFO'}}, 'loggers': {'': {'handlers': ['console'], 'level': 'INFO', 'propagate': False}}, 'root': {'level': 'INFO', 'handlers': ['console']}}
class Solution: def numberToWords(self, num: int) -> str: """ :type num: int :rtype: str """ if not num: return 'Zero' onedigit = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'} twodigits_10to19 = {10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'} tens = {2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety'} def one(num): # if not num: return '' return onedigit[num] def two(num): # if not num: return '' if num < 10: return one(num) elif num < 20: return twodigits_10to19[num] else: _ty, rest = divmod(num, 10) return tens[_ty] + ' ' + one(rest) if rest else tens[_ty] def three(num): # if not num: return '' hundred, rest = divmod(num, 100) if hundred and rest: return one(hundred) + ' Hundred ' + two(rest) elif hundred and not rest: return one(hundred) + ' Hundred' elif not hundred and rest: return two(rest) billions, rest = divmod(num, 1000000000) millions, rest = divmod(rest, 1000000) thousands, rest = divmod(rest, 1000) result = '' if billions: result += three(billions) + ' Billion' if millions: if result: result += ' ' result += three(millions) + ' Million' if thousands: if result: result += ' ' result += three(thousands) + ' Thousand' if rest: if result: result += ' ' result += three(rest) return result
class Solution: def number_to_words(self, num: int) -> str: """ :type num: int :rtype: str """ if not num: return 'Zero' onedigit = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'} twodigits_10to19 = {10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'} tens = {2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety'} def one(num): return onedigit[num] def two(num): if num < 10: return one(num) elif num < 20: return twodigits_10to19[num] else: (_ty, rest) = divmod(num, 10) return tens[_ty] + ' ' + one(rest) if rest else tens[_ty] def three(num): (hundred, rest) = divmod(num, 100) if hundred and rest: return one(hundred) + ' Hundred ' + two(rest) elif hundred and (not rest): return one(hundred) + ' Hundred' elif not hundred and rest: return two(rest) (billions, rest) = divmod(num, 1000000000) (millions, rest) = divmod(rest, 1000000) (thousands, rest) = divmod(rest, 1000) result = '' if billions: result += three(billions) + ' Billion' if millions: if result: result += ' ' result += three(millions) + ' Million' if thousands: if result: result += ' ' result += three(thousands) + ' Thousand' if rest: if result: result += ' ' result += three(rest) return result
# Write an algorithm to determine if a number n is "happy". # A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. # Return True if n is a happy number, and False if not. # Example: # Input: 19 # Output: true # Explanation: # 12 + 92 = 82 # 82 + 22 = 68 # 62 + 82 = 100 # 12 + 02 + 02 = 1 class Solution: def isHappy(self, n: int, s=set()) -> bool: if n == 1: return True if n in s: return False total = 0 s.add(n) for i in str(n): total += int(i)**2 return self.isHappy(total) s = 19 s = 11 s = 10 print(Solution().isHappy(s))
class Solution: def is_happy(self, n: int, s=set()) -> bool: if n == 1: return True if n in s: return False total = 0 s.add(n) for i in str(n): total += int(i) ** 2 return self.isHappy(total) s = 19 s = 11 s = 10 print(solution().isHappy(s))
def Mean_of_All_Digits(num): arr = [] n = num while n > 0: r = n % 10 n = n // 10 arr.append(r) return sum(arr)//len(arr) print(Mean_of_All_Digits(42)) print(Mean_of_All_Digits(12345)) print(Mean_of_All_Digits(666))
def mean_of__all__digits(num): arr = [] n = num while n > 0: r = n % 10 n = n // 10 arr.append(r) return sum(arr) // len(arr) print(mean_of__all__digits(42)) print(mean_of__all__digits(12345)) print(mean_of__all__digits(666))
#make a way to quickly make a new dictionary with the right properties def tool_dict(line): return {"name":line[0],"2015":line[1],"2016":line[2],"2017":line[3],"2018":line[4],"2019":line[5],"total":sum(line[1:])} #open file file=open("tools_dh_proceedings.csv") print("Opened tools_dh_proceedings.csv") #throw away title line file.readline() #get the rest of the lines lines=file.readlines() file.close() print("File has been read.") dh_tools=[] for line in lines: line=line.split(',') for i in range(1,len(line)): line[i]=int(line[i]) dh_tools.append(tool_dict(line)) print("List of tools successfully created.") #enter a loop where you can choose between printing the info of a tool or all stats for a year x="" while x!="EXIT": x=input("Type... \nNAME to display info of a tool by name, \nTOTALS to see a list of **all** tool totals, \nYEAR to input a year to see its top 10 tools, or \nEXIT to exit this loop.\n") if "TOTALS" in x: for tool in dh_tools: print(tool["name"]+": "+str(tool["total"])) print("Printed all tool names.") elif "YEAR" in x: z=input("What year?\n") if z in ["2015","2016","2017","2018","2019"]: print("Top tools for "+z+":") dh_tools.sort(key=lambda tool: tool[z],reverse=True) for tool in dh_tools[0:10]: print(tool["name"]+": "+str(tool[z])) else: print("Sorry, we don't have data for that year.") elif "NAME" in x: z=input("What name?\n") found=False for tool in dh_tools: if z==tool["name"]: print(z) for key, value in tool.items(): print(key+": "+str(value)) found=True if( not found): print("Sorry, couldn't find data for that tool.") elif "EXIT" not in x: print("Please match the commands exactly.") print("Quit loop successfully.")
def tool_dict(line): return {'name': line[0], '2015': line[1], '2016': line[2], '2017': line[3], '2018': line[4], '2019': line[5], 'total': sum(line[1:])} file = open('tools_dh_proceedings.csv') print('Opened tools_dh_proceedings.csv') file.readline() lines = file.readlines() file.close() print('File has been read.') dh_tools = [] for line in lines: line = line.split(',') for i in range(1, len(line)): line[i] = int(line[i]) dh_tools.append(tool_dict(line)) print('List of tools successfully created.') x = '' while x != 'EXIT': x = input('Type... \nNAME to display info of a tool by name, \nTOTALS to see a list of **all** tool totals, \nYEAR to input a year to see its top 10 tools, or \nEXIT to exit this loop.\n') if 'TOTALS' in x: for tool in dh_tools: print(tool['name'] + ': ' + str(tool['total'])) print('Printed all tool names.') elif 'YEAR' in x: z = input('What year?\n') if z in ['2015', '2016', '2017', '2018', '2019']: print('Top tools for ' + z + ':') dh_tools.sort(key=lambda tool: tool[z], reverse=True) for tool in dh_tools[0:10]: print(tool['name'] + ': ' + str(tool[z])) else: print("Sorry, we don't have data for that year.") elif 'NAME' in x: z = input('What name?\n') found = False for tool in dh_tools: if z == tool['name']: print(z) for (key, value) in tool.items(): print(key + ': ' + str(value)) found = True if not found: print("Sorry, couldn't find data for that tool.") elif 'EXIT' not in x: print('Please match the commands exactly.') print('Quit loop successfully.')
numbers = [3, 5, 7, 9, 4, 8, 15, 16, 23, 42] is_there_any_odd_number = False is_odd = lambda num: num % 2 == 1 def fun(num): print(f"fun({num})") return num % 2 == 1 for num in numbers: if is_odd(num): is_there_any_odd_number = True break print(is_there_any_odd_number) # print(any(map(is_odd, numbers))) print(all(map(fun, numbers)))
numbers = [3, 5, 7, 9, 4, 8, 15, 16, 23, 42] is_there_any_odd_number = False is_odd = lambda num: num % 2 == 1 def fun(num): print(f'fun({num})') return num % 2 == 1 for num in numbers: if is_odd(num): is_there_any_odd_number = True break print(is_there_any_odd_number) print(all(map(fun, numbers)))
def bfs(graph, source, target): visited = {k: False for k in graph} distance = {k: 1000000 for k in graph} queue = [] visited[source] = True distance[source] = 0 queue.append(source) while queue: node = queue.pop(0) for n in graph[node]: if not visited[n]: visited[n] = True distance[n] = distance[node] + 1 queue.append(n) if n == target: return distance[n] def main(): graph = {} with open("input.txt") as input_file: for line in input_file: a, b = line[:-1].split(")") if a in graph: graph[a].append(b) else: graph[a] = [b] if b in graph: graph[b].append(a) else: graph[b] = [a] print(bfs(graph, "YOU", "SAN") - 2) if __name__ == "__main__": main()
def bfs(graph, source, target): visited = {k: False for k in graph} distance = {k: 1000000 for k in graph} queue = [] visited[source] = True distance[source] = 0 queue.append(source) while queue: node = queue.pop(0) for n in graph[node]: if not visited[n]: visited[n] = True distance[n] = distance[node] + 1 queue.append(n) if n == target: return distance[n] def main(): graph = {} with open('input.txt') as input_file: for line in input_file: (a, b) = line[:-1].split(')') if a in graph: graph[a].append(b) else: graph[a] = [b] if b in graph: graph[b].append(a) else: graph[b] = [a] print(bfs(graph, 'YOU', 'SAN') - 2) if __name__ == '__main__': main()
_base_ = [ # '../_base_/models/deeplabv3plus_r18-d8.py', '../_base_/models/deeplabv3plus_r50-d8.py', '../_base_/datasets/boulderset.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py' ] norm_cfg = dict(type='BN', requires_grad=True) num_classes = 3 model = dict( pretrained='torchvision://resnet18', backbone=dict( type='ResNet', depth=18, norm_cfg=norm_cfg), decode_head=dict( c1_in_channels=64, c1_channels=12, in_channels=512, channels=128, num_classes=num_classes, norm_cfg=norm_cfg ), auxiliary_head=dict( in_channels=256, channels=64, num_classes=num_classes, norm_cfg=norm_cfg )) runner = dict( type='IterBasedRunner', # Type of runner to use (i.e. IterBasedRunner or EpochBasedRunner) max_iters=50000) # Total number of iterations. For EpochBasedRunner use `max_epochs` checkpoint_config = dict( # Config to set the checkpoint hook, Refer to https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/hooks/checkpoint.py for implementation. by_epoch=False, # Whethe count by epoch or not. interval=4000) # The save interval. evaluation = dict( # The config to build the evaluation hook. Please refer to mmseg/core/evaulation/eval_hook.py for details. interval=4000, # The interval of evaluation. metric='mIoU') log_config = dict( # config to register logger hook interval=50, # Interval to print the log hooks=[ # dict(type='TensorboardLoggerHook') # The Tensorboard logger is also supported dict(type='TextLoggerHook', by_epoch=False) ])
_base_ = ['../_base_/models/deeplabv3plus_r50-d8.py', '../_base_/datasets/boulderset.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py'] norm_cfg = dict(type='BN', requires_grad=True) num_classes = 3 model = dict(pretrained='torchvision://resnet18', backbone=dict(type='ResNet', depth=18, norm_cfg=norm_cfg), decode_head=dict(c1_in_channels=64, c1_channels=12, in_channels=512, channels=128, num_classes=num_classes, norm_cfg=norm_cfg), auxiliary_head=dict(in_channels=256, channels=64, num_classes=num_classes, norm_cfg=norm_cfg)) runner = dict(type='IterBasedRunner', max_iters=50000) checkpoint_config = dict(by_epoch=False, interval=4000) evaluation = dict(interval=4000, metric='mIoU') log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook', by_epoch=False)])
print(''' ,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba, a8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P' "Y8 8b ,adPPPPP88 8PP""""""" `"Y8ba, ,adPPPPP88 88 "8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88 `"Ybbd8"' `"8bbdP"Y8 `"Ybbd8"' `"YbbdP"' `"8bbdP"Y8 88 88 88 "" 88 ,adPPYba, 88 8b,dPPYba, 88,dPPYba, ,adPPYba, 8b,dPPYba, a8" "" 88 88P' "8a 88P' "8a a8P_____88 88P' "Y8 8b 88 88 d8 88 88 8PP""""""" 88 "8a, ,aa 88 88b, ,a8" 88 88 "8b, ,aa 88 `"Ybbd8"' 88 88`YbbdP"' 88 88 `"Ybbd8"' 88 88 ----------------------------------------------------------------- ''') alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] #Double for (26+shift_amount) should_continue=True while should_continue: direction = input("Type 'encode' to encrypt, type 'decode' to decrypt [encode|decode]:") if (direction != "encode") and (direction != "decode"): print("Invalid choose") exit() text = input("Type your message:").lower() try: shift = int(input("Type the shift number:")) except: print("Give an integer!") exit() def cipher(start_text,shift_amount,cipher_direction): end_text="" if cipher_direction == "decode": shift_amount *= -1 for letter in start_text: if letter in alphabet: position=(alphabet.index(letter)) new_position= position+shift_amount end_text += alphabet[new_position] else: end_text += letter print(f"\nYour {cipher_direction}d text: {end_text}\n") shift = shift % 26 cipher(start_text=text,shift_amount=shift,cipher_direction=direction) shall_continue=input("Do you want to shall_continue? [yes|no]:") if shall_continue == "no": should_continue=False print("Veni, vidi, utor cipher...") print("Good Bye!")
print('\n ,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba, \na8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P\' "Y8 \n8b ,adPPPPP88 8PP""""""" `"Y8ba, ,adPPPPP88 88 \n"8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88 \n `"Ybbd8"\' `"8bbdP"Y8 `"Ybbd8"\' `"YbbdP"\' `"8bbdP"Y8 88 \n\n 88 88 \n "" 88 \n ,adPPYba, 88 8b,dPPYba, 88,dPPYba, ,adPPYba, 8b,dPPYba, \na8" "" 88 88P\' "8a 88P\' "8a a8P_____88 88P\' "Y8 \n8b 88 88 d8 88 88 8PP""""""" 88 \n"8a, ,aa 88 88b, ,a8" 88 88 "8b, ,aa 88 \n `"Ybbd8"\' 88 88`YbbdP"\' 88 88 `"Ybbd8"\' 88 \n 88 \n-----------------------------------------------------------------\n') alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] should_continue = True while should_continue: direction = input("Type 'encode' to encrypt, type 'decode' to decrypt [encode|decode]:") if direction != 'encode' and direction != 'decode': print('Invalid choose') exit() text = input('Type your message:').lower() try: shift = int(input('Type the shift number:')) except: print('Give an integer!') exit() def cipher(start_text, shift_amount, cipher_direction): end_text = '' if cipher_direction == 'decode': shift_amount *= -1 for letter in start_text: if letter in alphabet: position = alphabet.index(letter) new_position = position + shift_amount end_text += alphabet[new_position] else: end_text += letter print(f'\nYour {cipher_direction}d text: {end_text}\n') shift = shift % 26 cipher(start_text=text, shift_amount=shift, cipher_direction=direction) shall_continue = input('Do you want to shall_continue? [yes|no]:') if shall_continue == 'no': should_continue = False print('Veni, vidi, utor cipher...') print('Good Bye!')
PARAMETERS = { # Input params "training_data_patterns": [ "data/tfrecord_v2/20180101.gz" ], "evaluation_data_patterns":[ "data/tfrecord_v2/20180101.gz" ], # Training data loader properties "buffer_size": 10000, "num_parsing_threads": 16, "num_parallel_readers": 4, "prefetch_buffer_size": 1, "compression_type": "GZIP", # Model params "initializer_gain": 1.0, # Used in trainable variable initialization. "hidden_size": 32, # Model dimension in the hidden layers, input embedding dimension "num_hidden_layers": 3, # Number of layers in the encoder stacks. "num_heads": 4, "filter_size": 256, "feature_hidden_size": [32,32], "riichi_loss_weight": 0.5, "after_riichi_instance_multiplier": 1.0, # Dropout values (only used when training) "layer_postprocess_dropout": 0.1, "attention_dropout": 0.1, "relu_dropout": 0.1, # Training params "learning_rate": 0.01, "learning_rate_decay_rate": 1.0, "learning_rate_warmup_steps": 16000, # Optimizer params "optimizer_adam_beta1": 0.9, "optimizer_adam_beta2": 0.997, "optimizer_adam_epsilon": 1e-09, # batch size "batch_size": 32, # Training and evaluation parameters "num_gpus": 0, "model_dir": "/tmp/model", "num_train_steps": 1000, "num_eval_steps": 1000, # Params for transformer TPU "allow_ffn_pad": True, }
parameters = {'training_data_patterns': ['data/tfrecord_v2/20180101.gz'], 'evaluation_data_patterns': ['data/tfrecord_v2/20180101.gz'], 'buffer_size': 10000, 'num_parsing_threads': 16, 'num_parallel_readers': 4, 'prefetch_buffer_size': 1, 'compression_type': 'GZIP', 'initializer_gain': 1.0, 'hidden_size': 32, 'num_hidden_layers': 3, 'num_heads': 4, 'filter_size': 256, 'feature_hidden_size': [32, 32], 'riichi_loss_weight': 0.5, 'after_riichi_instance_multiplier': 1.0, 'layer_postprocess_dropout': 0.1, 'attention_dropout': 0.1, 'relu_dropout': 0.1, 'learning_rate': 0.01, 'learning_rate_decay_rate': 1.0, 'learning_rate_warmup_steps': 16000, 'optimizer_adam_beta1': 0.9, 'optimizer_adam_beta2': 0.997, 'optimizer_adam_epsilon': 1e-09, 'batch_size': 32, 'num_gpus': 0, 'model_dir': '/tmp/model', 'num_train_steps': 1000, 'num_eval_steps': 1000, 'allow_ffn_pad': True}
# encoding: utf-8 """Dict of COMMANDS.""" # clArg: [function, help, args:{ # shortCommand, LongCommand, choices # store_true, help # }] COMMANDS = { # --------------------- # SERVICE_DEVICE_CONFIG # --------------------- 'login': ['login', 'Attempts to login to router'], 'reboot': ['reboot', 'Reboot Router', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'check_fw': ['check_new_firmware', 'Check for new firmware', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'check_app_fw': ['check_app_new_firmware', 'Check app for new firmware', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'get_device_config_info': [ 'get_device_config_info', 'Get Device Config Info', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # **SET** 'enable_block_device': [ 'set_block_device_enable', 'Enable Access Control', { 'enable': [ '-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'block_device_status': [ 'get_block_device_enable_status', 'Get Access Control Status', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # **SET** 'block_device_cli': [ 'set_block_device_by_mac', 'Allow/Block Device by MAC', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], 'mac': [ '-m', '--mac', False, False, 'MAC Address to Allow/Block'], 'action': [ '-a', '--action', ['allow', 'block'], False, 'Action to take, Allow or Block'], } ], # **SET** 'enable_traffic_meter': [ 'enable_traffic_meter', 'Enable/Disable Traffic Meter', { 'enable': [ '-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'traffic_meter': [ 'get_traffic_meter_statistics', 'Get Traffic Meter Statistics', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'traffic_meter_enabled': [ 'get_traffic_meter_enabled', 'Get Traffic Meter Status', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'traffic_meter_options': [ 'get_traffic_meter_options', 'Get Traffic Meter Options', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # --------------------- # SERVICE_LAN_CONFIG_SECURITY # --------------------- # GET 'get_lan_config_info': [ 'get_lan_config_sec_info', 'Get LAN Config Sec Info', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # --------------------- # SERVICE_WAN_IP_CONNECTION # --------------------- # GET 'get_wan_ip_info': ['get_wan_ip_con_info', 'Get WAN IP Info', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # --------------------- # SERVICE_PARENTAL_CONTROL # --------------------- # **SET** 'enable_parental_control': [ 'enable_parental_control', 'Enable/Disable Parental Control', { 'enable': [ '-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'parental_control_status': [ 'get_parental_control_enable_status', 'Get Parental Control Status', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'mac_address': [ 'get_all_mac_addresses', 'Get all MAC Addresses', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'dns_masq': [ 'get_dns_masq_device_id', 'Get DNS Masq Device ID', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # --------------------- # SERVICE_DEVICE_INFO # --------------------- # GET 'info': [ 'get_info', 'Get Info', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'support_feature': [ 'get_support_feature_list_XML', 'Get Supported Features', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'attached_devices': [ 'get_attached_devices', 'Get Attached Devices', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], 'verbose': [ '-v', '--verbose', False, 'store_true', 'This switch will enable, without will disable'], } ], # GET 'attached_devices2': [ 'get_attached_devices_2', 'Get Attached Devices 2', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # --------------------- # SERVICE_ADVANCED_QOS # --------------------- # **SET** 'speed_test_start': [ 'set_speed_test_start', 'Start Speed Test', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'speed_test_result': [ 'get_speed_test_result', 'Get Speed Test Results', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'qos_enabled': [ 'get_qos_enable_status', 'Get QOS Status', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # **SET** 'emable_qos': [ 'set_qos_enable_status', 'Enable/Disable QOS', { 'enable': [ '-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'bw_control': [ 'get_bandwidth_control_options', 'Get Bandwidth Control Options', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # --------------------- # SERVICE_WLAN_CONFIGURATION # --------------------- # **SET** 'guest_access_enable': [ 'set_guest_access_enabled', 'Enable/Disable Guest 2.4G Wifi', { 'enable': [ '-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # **SET** 'guest_access_enable2': [ 'set_guest_access_enabled_2', 'Enable/Disable Guest 2.4G Wifi', { 'enable': [ '-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'guest_access': [ 'get_guest_access_enabled', 'Get 2G Guest Wifi Status', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # **SET** 'guest_access_enable_5g': [ 'set_5g_guest_access_enabled', 'Enable/Disable Guest 5G Wifi', { 'enable': [ '-e', '--enable', False, 'store_true', False], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # **SET** 'guest_access_enable_5g_2': [ 'set_5g_guest_access_enabled_2', 'Enable/Disable Guest 5G Wifi', { 'enable': [ '-e', '--enable', False, 'store_true', False], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # **SET** 'guest_access_enable_5g_3': [ 'set_5g_guest_access_enabled_3', 'Enable/Disable Guest 5G Wifi', { 'enable': [ '-e', '--enable', False, 'store_true', False], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'guest_access_5g': [ 'get_5g_guest_access_enabled', 'Get 5G Guest Wifi Status', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'wpa_key': [ 'get_wpa_security_keys', 'Get 2G WPA Key', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'wpa_key_5g': [ 'get_5g_wpa_security_keys', 'Get 5G WPA Key', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'get_2g_info': [ 'get_2g_info', 'Get 2G Info', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'get_5g_info': [ 'get_5g_info', 'Get 5G Info', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'get_channel': [ 'get_available_channel', 'Get Channel', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'guest_access_net': [ 'get_guest_access_network_info', 'Get 2G Guest Wifi Info', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'guest_access_net_5g': [ 'get_5g_guest_access_network_info', 'Get 5G Guest Wifi Info', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # GET 'get_smart_conn': ['get_smart_connect_enabled', 'Get Smart Conn Status', { 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], # **SET** 'set_smart_conn': [ 'set_smart_connect_enabled', 'Enable/Disable Smart Connect', { 'enable': [ '-e', '--enable', False, 'store_true', False], 'test': [ '-t', '--test', False, 'store_true', 'Output SOAP Response'], } ], }
"""Dict of COMMANDS.""" commands = {'login': ['login', 'Attempts to login to router'], 'reboot': ['reboot', 'Reboot Router', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'check_fw': ['check_new_firmware', 'Check for new firmware', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'check_app_fw': ['check_app_new_firmware', 'Check app for new firmware', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'get_device_config_info': ['get_device_config_info', 'Get Device Config Info', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'enable_block_device': ['set_block_device_enable', 'Enable Access Control', {'enable': ['-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'block_device_status': ['get_block_device_enable_status', 'Get Access Control Status', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'block_device_cli': ['set_block_device_by_mac', 'Allow/Block Device by MAC', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response'], 'mac': ['-m', '--mac', False, False, 'MAC Address to Allow/Block'], 'action': ['-a', '--action', ['allow', 'block'], False, 'Action to take, Allow or Block']}], 'enable_traffic_meter': ['enable_traffic_meter', 'Enable/Disable Traffic Meter', {'enable': ['-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'traffic_meter': ['get_traffic_meter_statistics', 'Get Traffic Meter Statistics', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'traffic_meter_enabled': ['get_traffic_meter_enabled', 'Get Traffic Meter Status', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'traffic_meter_options': ['get_traffic_meter_options', 'Get Traffic Meter Options', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'get_lan_config_info': ['get_lan_config_sec_info', 'Get LAN Config Sec Info', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'get_wan_ip_info': ['get_wan_ip_con_info', 'Get WAN IP Info', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'enable_parental_control': ['enable_parental_control', 'Enable/Disable Parental Control', {'enable': ['-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'parental_control_status': ['get_parental_control_enable_status', 'Get Parental Control Status', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'mac_address': ['get_all_mac_addresses', 'Get all MAC Addresses', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'dns_masq': ['get_dns_masq_device_id', 'Get DNS Masq Device ID', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'info': ['get_info', 'Get Info', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'support_feature': ['get_support_feature_list_XML', 'Get Supported Features', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'attached_devices': ['get_attached_devices', 'Get Attached Devices', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response'], 'verbose': ['-v', '--verbose', False, 'store_true', 'This switch will enable, without will disable']}], 'attached_devices2': ['get_attached_devices_2', 'Get Attached Devices 2', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'speed_test_start': ['set_speed_test_start', 'Start Speed Test', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'speed_test_result': ['get_speed_test_result', 'Get Speed Test Results', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'qos_enabled': ['get_qos_enable_status', 'Get QOS Status', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'emable_qos': ['set_qos_enable_status', 'Enable/Disable QOS', {'enable': ['-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'bw_control': ['get_bandwidth_control_options', 'Get Bandwidth Control Options', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access_enable': ['set_guest_access_enabled', 'Enable/Disable Guest 2.4G Wifi', {'enable': ['-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access_enable2': ['set_guest_access_enabled_2', 'Enable/Disable Guest 2.4G Wifi', {'enable': ['-e', '--enable', False, 'store_true', 'This switch will enable, without will disable'], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access': ['get_guest_access_enabled', 'Get 2G Guest Wifi Status', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access_enable_5g': ['set_5g_guest_access_enabled', 'Enable/Disable Guest 5G Wifi', {'enable': ['-e', '--enable', False, 'store_true', False], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access_enable_5g_2': ['set_5g_guest_access_enabled_2', 'Enable/Disable Guest 5G Wifi', {'enable': ['-e', '--enable', False, 'store_true', False], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access_enable_5g_3': ['set_5g_guest_access_enabled_3', 'Enable/Disable Guest 5G Wifi', {'enable': ['-e', '--enable', False, 'store_true', False], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access_5g': ['get_5g_guest_access_enabled', 'Get 5G Guest Wifi Status', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'wpa_key': ['get_wpa_security_keys', 'Get 2G WPA Key', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'wpa_key_5g': ['get_5g_wpa_security_keys', 'Get 5G WPA Key', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'get_2g_info': ['get_2g_info', 'Get 2G Info', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'get_5g_info': ['get_5g_info', 'Get 5G Info', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'get_channel': ['get_available_channel', 'Get Channel', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access_net': ['get_guest_access_network_info', 'Get 2G Guest Wifi Info', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'guest_access_net_5g': ['get_5g_guest_access_network_info', 'Get 5G Guest Wifi Info', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'get_smart_conn': ['get_smart_connect_enabled', 'Get Smart Conn Status', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'set_smart_conn': ['set_smart_connect_enabled', 'Enable/Disable Smart Connect', {'enable': ['-e', '--enable', False, 'store_true', False], 'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}]}
class Solution: def FindGreatestSumOfSubArray(self, array): if not array: return 0 cur_sum, max_sum = array[0], array[0] for i in range(1, len(array)): cur_sum = array[i] if cur_sum <= 0 else cur_sum + array[i] max_sum = cur_sum if cur_sum > max_sum else max_sum return max_sum
class Solution: def find_greatest_sum_of_sub_array(self, array): if not array: return 0 (cur_sum, max_sum) = (array[0], array[0]) for i in range(1, len(array)): cur_sum = array[i] if cur_sum <= 0 else cur_sum + array[i] max_sum = cur_sum if cur_sum > max_sum else max_sum return max_sum
def main(): # get sales = get_sales() advanced_pay = get_advanced_pay() rate = determined_comm_rate(sales) # calc pay = sales * rate - advanced_pay # print print("The pay is $", format(pay, ",.2f"), sep='') return def get_sales(): return float(input("Sales: $")) def determined_comm_rate(sales): if sales < 10_000 : return 0.10 elif sales >= 10_000 and sales <= 14_999: return 0.12 elif sales >= 15_000 and sales <= 17_999: return 0.14 elif sales >= 18_000 and sales <= 21_999: return 0.16 else: # 22k+ return 0.18 def get_advanced_pay(): print("Input $0 if you do not have advanced pay") return float(input("Advanced Pay: $")) main()
def main(): sales = get_sales() advanced_pay = get_advanced_pay() rate = determined_comm_rate(sales) pay = sales * rate - advanced_pay print('The pay is $', format(pay, ',.2f'), sep='') return def get_sales(): return float(input('Sales: $')) def determined_comm_rate(sales): if sales < 10000: return 0.1 elif sales >= 10000 and sales <= 14999: return 0.12 elif sales >= 15000 and sales <= 17999: return 0.14 elif sales >= 18000 and sales <= 21999: return 0.16 else: return 0.18 def get_advanced_pay(): print('Input $0 if you do not have advanced pay') return float(input('Advanced Pay: $')) main()
Dataset_Path = dict( CULane = "/home/lion/Dataset/CULane/data/CULane", Tusimple = "/home/lion/Dataset/tusimple" )
dataset__path = dict(CULane='/home/lion/Dataset/CULane/data/CULane', Tusimple='/home/lion/Dataset/tusimple')
for _ in range(int(input())): n, k = map(int, input().split()) p = [0] + list(map(int, input().split())) visited = [False] * (n + 1) cycles = [] for i in range(1, n + 1): cycle = [] while not visited[i]: visited[i] = True cycle += i, i = p[i] if cycle: cycles += cycle, ans = [] tmp = [] flag = True for i in cycles: for j in range(1, len(i) - 1, 2): ans += [i[0], i[j], i[j + 1]], if len(i) % 2 == 0: tmp += [i[0], i[-1]], if len(tmp) % 2: flag = False else: for i in range(0, len(tmp), 2): ans.extend([[tmp[i][0], tmp[i][1], tmp[i + 1][0]], [tmp[i + 1][0], tmp[i][0], tmp[i + 1][1]]]) if flag and len(ans) <= k: print(len(ans)) for i in ans: print(*i) else: print(-1)
for _ in range(int(input())): (n, k) = map(int, input().split()) p = [0] + list(map(int, input().split())) visited = [False] * (n + 1) cycles = [] for i in range(1, n + 1): cycle = [] while not visited[i]: visited[i] = True cycle += (i,) i = p[i] if cycle: cycles += (cycle,) ans = [] tmp = [] flag = True for i in cycles: for j in range(1, len(i) - 1, 2): ans += ([i[0], i[j], i[j + 1]],) if len(i) % 2 == 0: tmp += ([i[0], i[-1]],) if len(tmp) % 2: flag = False else: for i in range(0, len(tmp), 2): ans.extend([[tmp[i][0], tmp[i][1], tmp[i + 1][0]], [tmp[i + 1][0], tmp[i][0], tmp[i + 1][1]]]) if flag and len(ans) <= k: print(len(ans)) for i in ans: print(*i) else: print(-1)
def f(x = True): 'whether x is a correct word or not' if x: print('x is a correct word') print('OK') f() f(False) def g(x, y = True): "x and y both correct words or not" if y: print(x, 'and y both correct') print(x,'is OK') g(68) g(68, False)
def f(x=True): """whether x is a correct word or not""" if x: print('x is a correct word') print('OK') f() f(False) def g(x, y=True): """x and y both correct words or not""" if y: print(x, 'and y both correct') print(x, 'is OK') g(68) g(68, False)
user = "user_name_here" password = "password_here" host = "host_here" app_name = "discogs app name here" user_token = "discogs app token here"
user = 'user_name_here' password = 'password_here' host = 'host_here' app_name = 'discogs app name here' user_token = 'discogs app token here'
#!/usr/bin/env python3 dictionary = { #defines dictionary data structure "class" : "Astr 119", "prof" : "Brant", "awesomeness" : 10 } print(type(dictionary)); #prints the data type of dictionary course = dictionary["class"]; #obtains a value from a key in dictionary print(course); #prints the value dictionary["awesomeness"] += 1; #modifies a value from a key in dictionary print(dictionary); #prints dictionary for x in dictionary.keys(): #for each element in dictionary print(x, dictionary[x]); #prints current element
dictionary = {'class': 'Astr 119', 'prof': 'Brant', 'awesomeness': 10} print(type(dictionary)) course = dictionary['class'] print(course) dictionary['awesomeness'] += 1 print(dictionary) for x in dictionary.keys(): print(x, dictionary[x])
f = open("crime.csv", "r") print("beep") print(f.readline()) print(f.readline()) f.close()
f = open('crime.csv', 'r') print('beep') print(f.readline()) print(f.readline()) f.close()
#program to calculate the maximum profit from selling and buying values of stock.. def buy_and_sell(stock_price): max_profit_val, current_max_val = 0, 0 for price in reversed(stock_price): current_max_val = max(current_max_val, price) potential_profit = current_max_val - price max_profit_val = max(potential_profit, max_profit_val) return max_profit_val print(buy_and_sell([8, 10, 7, 5, 7, 15])) print(buy_and_sell([1, 2, 8, 1])) #7 print(buy_and_sell([]))
def buy_and_sell(stock_price): (max_profit_val, current_max_val) = (0, 0) for price in reversed(stock_price): current_max_val = max(current_max_val, price) potential_profit = current_max_val - price max_profit_val = max(potential_profit, max_profit_val) return max_profit_val print(buy_and_sell([8, 10, 7, 5, 7, 15])) print(buy_and_sell([1, 2, 8, 1])) print(buy_and_sell([]))
class Solution: def findMin(self, nums: List[int]) -> int: val = sys.maxsize for i in nums: if i < val: val = i return val
class Solution: def find_min(self, nums: List[int]) -> int: val = sys.maxsize for i in nums: if i < val: val = i return val
# @Author : Wang Xiaoqiang # @GitHub : https://github.com/rzjing # @Time : 2020-01-06 15:59 # @File : gun.py # gunicorn configuration file bind = '0.0.0.0:5000' loglevel = 'info' access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)s' reload = True if __name__ == '__main__': pass
bind = '0.0.0.0:5000' loglevel = 'info' access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)s' reload = True if __name__ == '__main__': pass
liste = [5, 12, 7, 54, 4, 19, 23] classeur = { 'positif':[], 'negatif': [] }
liste = [5, 12, 7, 54, 4, 19, 23] classeur = {'positif': [], 'negatif': []}
# -*- coding: utf-8 -*- """AccountHistory Definitions.""" definitions = { "InlineCountValue": { "AllPages": "The results will contain a total count of items in the " "queried dataset.", "None": "The results will not contain an inline count.", }, "AccountPerformanceStandardPeriod": { "AllTime": "All time account performance.", "Month": "The month standard account performance.", "Quarter": "The quarter standard account performance.", "Year": "The year standard account performance.", }, "AssetType": { "Name": "Description", "Bond": "Bond.", "Cash": "Cash. Not tradeable!", "CfdIndexOption": "Cfd Index Option.", "CfdOnFutures": "Cfd on Futures.", "CfdOnIndex": "Cfd on Stock Index.", "CfdOnStock": "Cfd on Stock.", "ContractFutures": "Contract Futures.", "FuturesOption": "Futures Option.", "FuturesStrategy": "Futures Strategy.", "FxBinaryOption": "Forex Binary Option.", "FxForwards": "Forex Forward.", "FxKnockInOption": "Forex Knock In Option.", "FxKnockOutOption": "Forex Knock Out Option.", "FxNoTouchOption": "Forex No Touch Option.", "FxOneTouchOption": "Forex One Touch Option.", "FxSpot": "Forex Spot.", "FxVanillaOption": "Forex Vanilla Option.", "ManagedFund": "Obsolete: Managed Fund.", "MutualFund": "Mutual Fund.", "Stock": "Stock.", "StockIndex": "Stock Index.", "StockIndexOption": "Stock Index Option.", "StockOption": "Stock Option.", }, "AccountPerformanceFieldGroup": { "AccountSummary": "", "All": "", "Allocation": "", "AvailableBenchmarks": "", "BalancePerformance": "", "BalancePerformance_AccountValueTimeSeries": "", "BenchMark": "", "BenchmarkPerformance": "", "TimeWeightedPerformance": "", "TimeWeightedPerformance_AccumulatedTimeWeightedTimeSeries": "", "TotalCashBalancePerCurrency": "", "TotalPositionsValuePerCurrency": "", "TotalPositionsValuePerProductPerSecurity": "", "TradeActivity": "", } }
"""AccountHistory Definitions.""" definitions = {'InlineCountValue': {'AllPages': 'The results will contain a total count of items in the queried dataset.', 'None': 'The results will not contain an inline count.'}, 'AccountPerformanceStandardPeriod': {'AllTime': 'All time account performance.', 'Month': 'The month standard account performance.', 'Quarter': 'The quarter standard account performance.', 'Year': 'The year standard account performance.'}, 'AssetType': {'Name': 'Description', 'Bond': 'Bond.', 'Cash': 'Cash. Not tradeable!', 'CfdIndexOption': 'Cfd Index Option.', 'CfdOnFutures': 'Cfd on Futures.', 'CfdOnIndex': 'Cfd on Stock Index.', 'CfdOnStock': 'Cfd on Stock.', 'ContractFutures': 'Contract Futures.', 'FuturesOption': 'Futures Option.', 'FuturesStrategy': 'Futures Strategy.', 'FxBinaryOption': 'Forex Binary Option.', 'FxForwards': 'Forex Forward.', 'FxKnockInOption': 'Forex Knock In Option.', 'FxKnockOutOption': 'Forex Knock Out Option.', 'FxNoTouchOption': 'Forex No Touch Option.', 'FxOneTouchOption': 'Forex One Touch Option.', 'FxSpot': 'Forex Spot.', 'FxVanillaOption': 'Forex Vanilla Option.', 'ManagedFund': 'Obsolete: Managed Fund.', 'MutualFund': 'Mutual Fund.', 'Stock': 'Stock.', 'StockIndex': 'Stock Index.', 'StockIndexOption': 'Stock Index Option.', 'StockOption': 'Stock Option.'}, 'AccountPerformanceFieldGroup': {'AccountSummary': '', 'All': '', 'Allocation': '', 'AvailableBenchmarks': '', 'BalancePerformance': '', 'BalancePerformance_AccountValueTimeSeries': '', 'BenchMark': '', 'BenchmarkPerformance': '', 'TimeWeightedPerformance': '', 'TimeWeightedPerformance_AccumulatedTimeWeightedTimeSeries': '', 'TotalCashBalancePerCurrency': '', 'TotalPositionsValuePerCurrency': '', 'TotalPositionsValuePerProductPerSecurity': '', 'TradeActivity': ''}}
class AirtrackBaseError(Exception): """AirtrackBase error""" class AirtrackError(AirtrackBaseError): """Airtrack error""" class AirtrackSubjectError(AirtrackError): """AirtrackCamera error""" class AirtrackStateMachineError(AirtrackError): """AirtrackStateMachine error""" class AirtrackCameraError(AirtrackError): """AirtrackCamera error""" class AirtrackActuatorError(AirtrackError): """AirtrackActuator error""" class PixyCamError(Exception): """PixyCam error""" def err(error, logger, message): logger.debug(message) raise error(message) def on_error_raise(error, logger, catch_error=Exception, message=None): def decorator(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except catch_error as e: err(error, logger, message or str(e)) return wrapper return decorator
class Airtrackbaseerror(Exception): """AirtrackBase error""" class Airtrackerror(AirtrackBaseError): """Airtrack error""" class Airtracksubjecterror(AirtrackError): """AirtrackCamera error""" class Airtrackstatemachineerror(AirtrackError): """AirtrackStateMachine error""" class Airtrackcameraerror(AirtrackError): """AirtrackCamera error""" class Airtrackactuatorerror(AirtrackError): """AirtrackActuator error""" class Pixycamerror(Exception): """PixyCam error""" def err(error, logger, message): logger.debug(message) raise error(message) def on_error_raise(error, logger, catch_error=Exception, message=None): def decorator(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except catch_error as e: err(error, logger, message or str(e)) return wrapper return decorator
def inputs(): a = int(input()) return a def body(a): if a <= 2: print("NO") elif a % 2 == 0: print("YES") else: print("NO") def main(): a = inputs() body(a) if __name__ == "__main__": main()
def inputs(): a = int(input()) return a def body(a): if a <= 2: print('NO') elif a % 2 == 0: print('YES') else: print('NO') def main(): a = inputs() body(a) if __name__ == '__main__': main()
class ShippingCubes: def minimalCost(self, N): m = 600 for i in xrange(1, 200): for j in xrange(1, i + 1): for k in xrange(1, j + 1): if i * j * k == N: m = min(m, i + j + k) return m
class Shippingcubes: def minimal_cost(self, N): m = 600 for i in xrange(1, 200): for j in xrange(1, i + 1): for k in xrange(1, j + 1): if i * j * k == N: m = min(m, i + j + k) return m
def tem_match(origin_test, origin_template): test = [] for i in origin_test: tem_test = [] for index, j in enumerate(i[1]): j.insert(0, i[0][index]) tem_test.append(j) test.append([i[0], tem_test]) tem_template = {} for i in origin_template: tem_template[i[0]] = i[1] template = {} for k, v in tem_template.items(): template[k] = [[i, j] for i, j in zip(k, v)] set_list = [] for i, _ in enumerate(test): set_list.append(set(test[i][0])) # print(set_list) result_list = [] for k, v in template.items(): key_set = set(k) # print(k) num_list, k_str = [], [] k_str.append(k) # print(k) for set_test in set_list: num_list.append(len(key_set.intersection(set_test))) find = max(num_list) if find: find_index = [i for i, v in enumerate(num_list) if v == find] else: find_index = [] match_rate = 0 match_index = -1 # match_word = [] for i in find_index: # print('TEST:', test[i][0]) # print('TEMPLATE KEY:', k) if test[i][0][0] == k[0] and find/len(k) > match_rate: match_index = i match_rate = find/len(k) # print('find:', find, 'match rate:', match_rate) if match_index != -1 and match_rate > 0.7 and len(k) > 1: # print(test[match_index][1]) uniq_check = [] for i in test[match_index][1]: # print('i:', i,'v:', v) if i[0] in k and i[0]: uniq_check.append(i[0]) if len(uniq_check)==len(set(uniq_check)): k_list = [] for j in v: # print(j) if i[0] == j[0]: tem_cor = j[1:] break else: tem_cor = [] if len(tem_cor) > 0 : k_list.append(i[0]) k_list.append(i[1:]) k_list.append(tem_cor[0]) k_str.append(k_list) # break if len(k_str) > 1: result_list.append(k_str) return result_list
def tem_match(origin_test, origin_template): test = [] for i in origin_test: tem_test = [] for (index, j) in enumerate(i[1]): j.insert(0, i[0][index]) tem_test.append(j) test.append([i[0], tem_test]) tem_template = {} for i in origin_template: tem_template[i[0]] = i[1] template = {} for (k, v) in tem_template.items(): template[k] = [[i, j] for (i, j) in zip(k, v)] set_list = [] for (i, _) in enumerate(test): set_list.append(set(test[i][0])) result_list = [] for (k, v) in template.items(): key_set = set(k) (num_list, k_str) = ([], []) k_str.append(k) for set_test in set_list: num_list.append(len(key_set.intersection(set_test))) find = max(num_list) if find: find_index = [i for (i, v) in enumerate(num_list) if v == find] else: find_index = [] match_rate = 0 match_index = -1 for i in find_index: if test[i][0][0] == k[0] and find / len(k) > match_rate: match_index = i match_rate = find / len(k) if match_index != -1 and match_rate > 0.7 and (len(k) > 1): uniq_check = [] for i in test[match_index][1]: if i[0] in k and i[0]: uniq_check.append(i[0]) if len(uniq_check) == len(set(uniq_check)): k_list = [] for j in v: if i[0] == j[0]: tem_cor = j[1:] break else: tem_cor = [] if len(tem_cor) > 0: k_list.append(i[0]) k_list.append(i[1:]) k_list.append(tem_cor[0]) k_str.append(k_list) if len(k_str) > 1: result_list.append(k_str) return result_list
n = int(input()) for i in range(0,10000,1): if i % n == 2: print(i)
n = int(input()) for i in range(0, 10000, 1): if i % n == 2: print(i)
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ aeneas.cdtw is a Python C extension for computing the DTW. .. function:: cdtw.compute_best_path(mfcc1, mfcc2, delta) Compute the DTW (approximated) best path for the two audio waves, represented by their MFCCs. This function implements the Sakoe-Chiba heuristic, that is, it explores only a band of width ``2 * delta`` around the main diagonal of the cost matrix. The computation is done in-memory, and it might fail if there is not enough memory to allocate the cost matrix or the list to be returned. The returned list contains tuples ``(i, j)``, representing the best path from ``(0, 0)`` to ``(n-1, m-1)``, where ``n`` is the length of ``mfcc1``, and ``m`` is the length of ``mfcc2``. The returned list has length between ``min(n, m)`` and ``n + m`` (it can be less than ``n + m`` if diagonal steps are selected in the best path). :param mfcc1: the MFCCs of the first wave ``(n, mfcc_size)`` :type mfcc1: :class:`numpy.ndarray` :param mfcc2: the MFCCs of the second wave ``(m, mfcc_size)`` :type mfcc2: :class:`numpy.ndarray` :param int delta: the margin parameter :rtype: list of tuples .. function:: cdtw.compute_cost_matrix_step(mfcc1, mfcc2, delta) Compute the DTW (approximated) cost matrix for the two audio waves, represented by their MFCCs. This function implements the Sakoe-Chiba heuristic, that is, it explores only a band of width ``2 * delta`` around the main diagonal of the cost matrix. The computation is done in-memory, and it might fail if there is not enough memory to allocate the cost matrix. The returned tuple ``(cost_matrix, centers)`` contains the cost matrix (NumPy 2D array of shape (n, delta)) and the row centers (NumPy 1D array of size n). :param mfcc1: the MFCCs of the first wave ``(n, mfcc_size)`` :type mfcc1: :class:`numpy.ndarray` :param mfcc2: the MFCCs of the second wave ``(m, mfcc_size)`` :type mfcc2: :class:`numpy.ndarray` :param int delta: the margin parameter :rtype: tuple .. function:: cdtw.compute_accumulated_cost_matrix_step(cost_matrix, centers) Compute the DTW (approximated) accumulated cost matrix from the cost matrix and the row centers. This function implements the Sakoe-Chiba heuristic, that is, it explores only a band of width ``2 * delta`` around the main diagonal of the cost matrix. The computation is done in-memory, and the accumulated cost matrix is computed in place, that is, the original cost matrix is destroyed and its allocated memory used to store the accumulated cost matrix. Hence, this call should not fail for memory reasons. The returned NumPy 2D array of shape ``(n, delta)`` contains the accumulated cost matrix. :param cost_matrix: the cost matrix ``(n, delta)`` :type cost_matrix: :class:`numpy.ndarray` :param centers: the row centers ``(n,)`` :type centers: :class:`numpy.ndarray` :rtype: :class:`numpy.ndarray` .. function:: cdtw.compute_best_path_step(accumulated_cost_matrix, centers) Compute the DTW (approximated) best path from the accumulated cost matrix and the row centers. This function implements the Sakoe-Chiba heuristic, that is, it explores only a band of width ``2 * delta`` around the main diagonal of the cost matrix. The computation is done in-memory, and it might fail if there is not enough memory to allocate the list to be returned. The returned list contains tuples ``(i, j)``, representing the best path from ``(0, 0)`` to ``(n-1, m-1)``, where ``n`` is the length of ``mfcc1``, and ``m`` is the length of ``mfcc2``. The returned list has length between ``min(n, m)`` and ``n + m`` (it can be less than ``n + m`` if diagonal steps are selected in the best path). :param cost_matrix: the accumulated cost matrix ``(n, delta)`` :type cost_matrix: :class:`numpy.ndarray` :param centers: the row centers ``(n, )`` :type centers: :class:`numpy.ndarray` :rtype: list of tuples """
""" aeneas.cdtw is a Python C extension for computing the DTW. .. function:: cdtw.compute_best_path(mfcc1, mfcc2, delta) Compute the DTW (approximated) best path for the two audio waves, represented by their MFCCs. This function implements the Sakoe-Chiba heuristic, that is, it explores only a band of width ``2 * delta`` around the main diagonal of the cost matrix. The computation is done in-memory, and it might fail if there is not enough memory to allocate the cost matrix or the list to be returned. The returned list contains tuples ``(i, j)``, representing the best path from ``(0, 0)`` to ``(n-1, m-1)``, where ``n`` is the length of ``mfcc1``, and ``m`` is the length of ``mfcc2``. The returned list has length between ``min(n, m)`` and ``n + m`` (it can be less than ``n + m`` if diagonal steps are selected in the best path). :param mfcc1: the MFCCs of the first wave ``(n, mfcc_size)`` :type mfcc1: :class:`numpy.ndarray` :param mfcc2: the MFCCs of the second wave ``(m, mfcc_size)`` :type mfcc2: :class:`numpy.ndarray` :param int delta: the margin parameter :rtype: list of tuples .. function:: cdtw.compute_cost_matrix_step(mfcc1, mfcc2, delta) Compute the DTW (approximated) cost matrix for the two audio waves, represented by their MFCCs. This function implements the Sakoe-Chiba heuristic, that is, it explores only a band of width ``2 * delta`` around the main diagonal of the cost matrix. The computation is done in-memory, and it might fail if there is not enough memory to allocate the cost matrix. The returned tuple ``(cost_matrix, centers)`` contains the cost matrix (NumPy 2D array of shape (n, delta)) and the row centers (NumPy 1D array of size n). :param mfcc1: the MFCCs of the first wave ``(n, mfcc_size)`` :type mfcc1: :class:`numpy.ndarray` :param mfcc2: the MFCCs of the second wave ``(m, mfcc_size)`` :type mfcc2: :class:`numpy.ndarray` :param int delta: the margin parameter :rtype: tuple .. function:: cdtw.compute_accumulated_cost_matrix_step(cost_matrix, centers) Compute the DTW (approximated) accumulated cost matrix from the cost matrix and the row centers. This function implements the Sakoe-Chiba heuristic, that is, it explores only a band of width ``2 * delta`` around the main diagonal of the cost matrix. The computation is done in-memory, and the accumulated cost matrix is computed in place, that is, the original cost matrix is destroyed and its allocated memory used to store the accumulated cost matrix. Hence, this call should not fail for memory reasons. The returned NumPy 2D array of shape ``(n, delta)`` contains the accumulated cost matrix. :param cost_matrix: the cost matrix ``(n, delta)`` :type cost_matrix: :class:`numpy.ndarray` :param centers: the row centers ``(n,)`` :type centers: :class:`numpy.ndarray` :rtype: :class:`numpy.ndarray` .. function:: cdtw.compute_best_path_step(accumulated_cost_matrix, centers) Compute the DTW (approximated) best path from the accumulated cost matrix and the row centers. This function implements the Sakoe-Chiba heuristic, that is, it explores only a band of width ``2 * delta`` around the main diagonal of the cost matrix. The computation is done in-memory, and it might fail if there is not enough memory to allocate the list to be returned. The returned list contains tuples ``(i, j)``, representing the best path from ``(0, 0)`` to ``(n-1, m-1)``, where ``n`` is the length of ``mfcc1``, and ``m`` is the length of ``mfcc2``. The returned list has length between ``min(n, m)`` and ``n + m`` (it can be less than ``n + m`` if diagonal steps are selected in the best path). :param cost_matrix: the accumulated cost matrix ``(n, delta)`` :type cost_matrix: :class:`numpy.ndarray` :param centers: the row centers ``(n, )`` :type centers: :class:`numpy.ndarray` :rtype: list of tuples """
""" slackd.common ~~~~~~~~~~~~~ Provides application level utility functions and classes :copyright: (c) 2016 Pinn :license: All rights reserved """
""" slackd.common ~~~~~~~~~~~~~ Provides application level utility functions and classes :copyright: (c) 2016 Pinn :license: All rights reserved """