content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" import pytest import torch import pytorch_lightning as pl from torchphysics.solver import PINNModule from torchphysics.setting import Setting from torchphysics.models.fcn import SimpleFCN from torchphysics.utils.plot import Plotter from torchphysics.problem.condition import DirichletCondition from torchphysics.problem.variables import Variable from torchphysics.problem.parameters import Parameter # Helper functions def _create_model(): model = SimpleFCN(variable_dims={'x': 2}, solution_dims={'u': 1}, depth=1, width=5) return model def _create_dummy_trainer(log=False): trainer = pl.Trainer(gpus=None, num_sanity_val_steps=0, benchmark=False, check_val_every_n_epoch=20, max_epochs=0, logger=log, checkpoint_callback=False) return trainer def _create_whole_dummy_setting(): model = _create_model() setup = Setting() trainer = _create_dummy_trainer() solver = PINNModule(model=model, optimizer=torch.optim.Adam, lr = 3) trainer.datamodule = setup solver.trainer = trainer return solver, setup, trainer def _add_dummy_variable(setup, name, train=True): x = Variable(name='x', domain=None) cond = DirichletCondition(dirichlet_fun=None, name=name, norm=torch.nn.MSELoss()) if train: x.add_train_condition(cond) else: x.add_val_condition(cond) setup.add_variable(x) # Start test of PINNModule def test_create_pinn_module(): solver = PINNModule(model=None, optimizer=torch.optim.Adam, lr = 3) assert solver.model is None assert solver.optimizer == torch.optim.Adam assert solver.lr == 3 assert solver.log_plotter is None assert solver.optim_params == {} assert solver.scheduler is None def test_forward_pinn_module(): solver = PINNModule(model=_create_model(), optimizer=torch.optim.Adam, lr = 3) input_dic = {'x': torch.ones((4, 2))} out = solver(input_dic) assert isinstance(out, dict) assert torch.is_tensor(out['u']) assert out['u'].shape == (4, 1) def test_input_dim_pinn_module(): solver = PINNModule(model=_create_model(), optimizer=torch.optim.Adam, lr = 3) assert solver.input_dim == 2 def test_output_dim_pinn_module(): solver = PINNModule(model=_create_model(), optimizer=torch.optim.Adam, lr = 3) assert solver.output_dim == 1 def test_to_device_pinn_module_without_trainer(): solver = PINNModule(model=_create_model(), optimizer=torch.optim.Adam, lr = 3) out = solver.to('cpu') assert out.device.type == 'cpu' def test_to_device_pinn_module_with_trainer(): solver, _, _ = _create_whole_dummy_setting() out = solver.to('cpu') assert out.device.type == 'cpu' def test_serialize_pinn_module_without_trainer(): model = _create_model() solver = PINNModule(model=model, optimizer=torch.optim.Adam, lr = 3) out = solver.serialize() assert out['name'] == 'PINNModule' assert out['model'] == model.serialize() assert out['problem'] is None assert out['optimizer']['name'] == 'Adam' assert out['optimizer']['lr'] == 3 assert out['optim_params'] == {} def test_serialize_pinn_module_with_trainer(): solver, setup, _ = _create_whole_dummy_setting() out = solver.serialize() assert out['name'] == 'PINNModule' assert out['model'] == solver.model.serialize() assert out['problem'] == setup.serialize() assert out['optimizer']['name'] == 'Adam' assert out['optimizer']['lr'] == 3 assert out['optim_params'] == {} def test_on_train_start_without_logger(): solver = PINNModule(model=None, optimizer=torch.optim.Adam, lr = 3) solver.on_train_start() def test_configure_optimizer_of_pinn_module(): solver, _, _ = _create_whole_dummy_setting() opti = solver.configure_optimizers() assert isinstance(opti, torch.optim.Optimizer) for p in opti.param_groups: assert p['lr'] == 3 def test_configure_optimizer_of_pinn_module_with_scheduler(): solver, _, _ = _create_whole_dummy_setting() solver.scheduler = {'class': torch.optim.lr_scheduler.ExponentialLR, 'args': {'gamma': 3}} opti, scheduler = solver.configure_optimizers() assert isinstance(opti[0], torch.optim.Optimizer) for p in opti[0].param_groups: assert p['lr'] == 3 assert isinstance(scheduler[0]['scheduler'], torch.optim.lr_scheduler._LRScheduler)# Test dont work in GitHub.... def test_training_step_of_pinn_module(): solver, setup, _ = _create_whole_dummy_setting() _add_dummy_variable(setup, 'test') data = {'x': torch.tensor([[2.0, 1.0], [3.0, 0.0]], requires_grad=True), 'target': torch.tensor([[2.0], [3.0]])} batch = {'x_test': data} out = solver.training_step(batch, 0) assert isinstance(out, torch.Tensor) def test_training_step_of_pinn_module_with_parameters(): solver, setup, _ = _create_whole_dummy_setting() _add_dummy_variable(setup, 'test') setup.add_parameter(Parameter([1, 0], name='D')) setup.add_parameter(Parameter(0, name='k')) data = {'x': torch.tensor([[2.0, 1.0], [3.0, 0.0]], requires_grad=True), 'target': torch.tensor([[2.0], [3.0]])} batch = {'x_test': data} out = solver.training_step(batch, 0) assert isinstance(out, torch.Tensor) def test_training_step_of_pinn_module_with_missing_data(): solver, setup, _ = _create_whole_dummy_setting() _add_dummy_variable(setup, 'test') _add_dummy_variable(setup, 'test_2') data = {'x': torch.tensor([[2.0, 1.0], [3.0, 0.0]], requires_grad=True), 'target': torch.tensor([[2.0], [3.0]])} batch = {'x_test': data} with pytest.raises(KeyError): _ = solver.training_step(batch, 0) def test_validation_step_of_pinn_module(): solver, setup, _ = _create_whole_dummy_setting() _add_dummy_variable(setup, 'test', False) data = {'x': torch.tensor([[2.0, 1.0], [3.0, 0.0]], requires_grad=True), 'target': torch.tensor([[2.0], [3.0]])} batch = {'x_test': data} solver.validation_step(batch, 0) """
""" import pytest import torch import pytorch_lightning as pl from torchphysics.solver import PINNModule from torchphysics.setting import Setting from torchphysics.models.fcn import SimpleFCN from torchphysics.utils.plot import Plotter from torchphysics.problem.condition import DirichletCondition from torchphysics.problem.variables import Variable from torchphysics.problem.parameters import Parameter # Helper functions def _create_model(): model = SimpleFCN(variable_dims={'x': 2}, solution_dims={'u': 1}, depth=1, width=5) return model def _create_dummy_trainer(log=False): trainer = pl.Trainer(gpus=None, num_sanity_val_steps=0, benchmark=False, check_val_every_n_epoch=20, max_epochs=0, logger=log, checkpoint_callback=False) return trainer def _create_whole_dummy_setting(): model = _create_model() setup = Setting() trainer = _create_dummy_trainer() solver = PINNModule(model=model, optimizer=torch.optim.Adam, lr = 3) trainer.datamodule = setup solver.trainer = trainer return solver, setup, trainer def _add_dummy_variable(setup, name, train=True): x = Variable(name='x', domain=None) cond = DirichletCondition(dirichlet_fun=None, name=name, norm=torch.nn.MSELoss()) if train: x.add_train_condition(cond) else: x.add_val_condition(cond) setup.add_variable(x) # Start test of PINNModule def test_create_pinn_module(): solver = PINNModule(model=None, optimizer=torch.optim.Adam, lr = 3) assert solver.model is None assert solver.optimizer == torch.optim.Adam assert solver.lr == 3 assert solver.log_plotter is None assert solver.optim_params == {} assert solver.scheduler is None def test_forward_pinn_module(): solver = PINNModule(model=_create_model(), optimizer=torch.optim.Adam, lr = 3) input_dic = {'x': torch.ones((4, 2))} out = solver(input_dic) assert isinstance(out, dict) assert torch.is_tensor(out['u']) assert out['u'].shape == (4, 1) def test_input_dim_pinn_module(): solver = PINNModule(model=_create_model(), optimizer=torch.optim.Adam, lr = 3) assert solver.input_dim == 2 def test_output_dim_pinn_module(): solver = PINNModule(model=_create_model(), optimizer=torch.optim.Adam, lr = 3) assert solver.output_dim == 1 def test_to_device_pinn_module_without_trainer(): solver = PINNModule(model=_create_model(), optimizer=torch.optim.Adam, lr = 3) out = solver.to('cpu') assert out.device.type == 'cpu' def test_to_device_pinn_module_with_trainer(): solver, _, _ = _create_whole_dummy_setting() out = solver.to('cpu') assert out.device.type == 'cpu' def test_serialize_pinn_module_without_trainer(): model = _create_model() solver = PINNModule(model=model, optimizer=torch.optim.Adam, lr = 3) out = solver.serialize() assert out['name'] == 'PINNModule' assert out['model'] == model.serialize() assert out['problem'] is None assert out['optimizer']['name'] == 'Adam' assert out['optimizer']['lr'] == 3 assert out['optim_params'] == {} def test_serialize_pinn_module_with_trainer(): solver, setup, _ = _create_whole_dummy_setting() out = solver.serialize() assert out['name'] == 'PINNModule' assert out['model'] == solver.model.serialize() assert out['problem'] == setup.serialize() assert out['optimizer']['name'] == 'Adam' assert out['optimizer']['lr'] == 3 assert out['optim_params'] == {} def test_on_train_start_without_logger(): solver = PINNModule(model=None, optimizer=torch.optim.Adam, lr = 3) solver.on_train_start() def test_configure_optimizer_of_pinn_module(): solver, _, _ = _create_whole_dummy_setting() opti = solver.configure_optimizers() assert isinstance(opti, torch.optim.Optimizer) for p in opti.param_groups: assert p['lr'] == 3 def test_configure_optimizer_of_pinn_module_with_scheduler(): solver, _, _ = _create_whole_dummy_setting() solver.scheduler = {'class': torch.optim.lr_scheduler.ExponentialLR, 'args': {'gamma': 3}} opti, scheduler = solver.configure_optimizers() assert isinstance(opti[0], torch.optim.Optimizer) for p in opti[0].param_groups: assert p['lr'] == 3 assert isinstance(scheduler[0]['scheduler'], torch.optim.lr_scheduler._LRScheduler)# Test dont work in GitHub.... def test_training_step_of_pinn_module(): solver, setup, _ = _create_whole_dummy_setting() _add_dummy_variable(setup, 'test') data = {'x': torch.tensor([[2.0, 1.0], [3.0, 0.0]], requires_grad=True), 'target': torch.tensor([[2.0], [3.0]])} batch = {'x_test': data} out = solver.training_step(batch, 0) assert isinstance(out, torch.Tensor) def test_training_step_of_pinn_module_with_parameters(): solver, setup, _ = _create_whole_dummy_setting() _add_dummy_variable(setup, 'test') setup.add_parameter(Parameter([1, 0], name='D')) setup.add_parameter(Parameter(0, name='k')) data = {'x': torch.tensor([[2.0, 1.0], [3.0, 0.0]], requires_grad=True), 'target': torch.tensor([[2.0], [3.0]])} batch = {'x_test': data} out = solver.training_step(batch, 0) assert isinstance(out, torch.Tensor) def test_training_step_of_pinn_module_with_missing_data(): solver, setup, _ = _create_whole_dummy_setting() _add_dummy_variable(setup, 'test') _add_dummy_variable(setup, 'test_2') data = {'x': torch.tensor([[2.0, 1.0], [3.0, 0.0]], requires_grad=True), 'target': torch.tensor([[2.0], [3.0]])} batch = {'x_test': data} with pytest.raises(KeyError): _ = solver.training_step(batch, 0) def test_validation_step_of_pinn_module(): solver, setup, _ = _create_whole_dummy_setting() _add_dummy_variable(setup, 'test', False) data = {'x': torch.tensor([[2.0, 1.0], [3.0, 0.0]], requires_grad=True), 'target': torch.tensor([[2.0], [3.0]])} batch = {'x_test': data} solver.validation_step(batch, 0) """
class Solution: def evalRPN(self, tokens: List[str]) -> int: t = -1 for i in range(len(tokens)): if tokens[i] == '+': tokens[t - 1] += tokens[t] t -= 1 elif tokens[i] == '-': tokens[t - 1] -= tokens[t] t -= 1 elif tokens[i] == '*': tokens[t - 1] *= tokens[t] t -= 1 elif tokens[i] == '/': tokens[t - 1] /= tokens[t] if tokens[t - 1] < 0: tokens[t - 1] = math.ceil(tokens[t - 1]) else: tokens[t - 1] = math.floor(tokens[t - 1]) t -= 1 else: t += 1 tokens[t] = int(tokens[i]) return tokens[0]
class Solution: def eval_rpn(self, tokens: List[str]) -> int: t = -1 for i in range(len(tokens)): if tokens[i] == '+': tokens[t - 1] += tokens[t] t -= 1 elif tokens[i] == '-': tokens[t - 1] -= tokens[t] t -= 1 elif tokens[i] == '*': tokens[t - 1] *= tokens[t] t -= 1 elif tokens[i] == '/': tokens[t - 1] /= tokens[t] if tokens[t - 1] < 0: tokens[t - 1] = math.ceil(tokens[t - 1]) else: tokens[t - 1] = math.floor(tokens[t - 1]) t -= 1 else: t += 1 tokens[t] = int(tokens[i]) return tokens[0]
def rotate(A, B, C): return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0]) def jarvismarch(A): points_count = len(A) processing_indexes = range(points_count) # start point for i in range(1, points_count): if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]: processing_indexes[i], processing_indexes[0] = processing_indexes[0], processing_indexes[i] result_indexes = [processing_indexes[0]] processing_indexes = [processing_indexes[i] for i in range(1, len(processing_indexes))] processing_indexes.append(result_indexes[0]) while True: right = 0 for i in range(1, len(processing_indexes)): if rotate(A[result_indexes[-1]], A[processing_indexes[right]], A[processing_indexes[i]]) < 0: right = i if processing_indexes[right] == result_indexes[0]: break else: result_indexes.append(processing_indexes[right]) del processing_indexes[right] return result_indexes if __name__ == '__main__': points = ((0, 0), (0, 2), (2, 0), (2, 2), (1, 1)) print(jarvismarch(points))
def rotate(A, B, C): return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0]) def jarvismarch(A): points_count = len(A) processing_indexes = range(points_count) for i in range(1, points_count): if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]: (processing_indexes[i], processing_indexes[0]) = (processing_indexes[0], processing_indexes[i]) result_indexes = [processing_indexes[0]] processing_indexes = [processing_indexes[i] for i in range(1, len(processing_indexes))] processing_indexes.append(result_indexes[0]) while True: right = 0 for i in range(1, len(processing_indexes)): if rotate(A[result_indexes[-1]], A[processing_indexes[right]], A[processing_indexes[i]]) < 0: right = i if processing_indexes[right] == result_indexes[0]: break else: result_indexes.append(processing_indexes[right]) del processing_indexes[right] return result_indexes if __name__ == '__main__': points = ((0, 0), (0, 2), (2, 0), (2, 2), (1, 1)) print(jarvismarch(points))
class NodoAST: def __init__(self, contenido): self._contenido = contenido self._hijos = [] def getContenido(self): return self._contenido def getHijos(self): return self._hijos def setHijo(self, hijo): self._hijos.append(hijo)
class Nodoast: def __init__(self, contenido): self._contenido = contenido self._hijos = [] def get_contenido(self): return self._contenido def get_hijos(self): return self._hijos def set_hijo(self, hijo): self._hijos.append(hijo)
#This program displays a date in the form #(Month day, Year like March 12, 2014 #ALGORITHM in pseudocode #1. get a date string in the form mm/dd/yyyy from the user #2. use the split method to remove the seperator('/') # and assign the results to a variable. #3. determine the month the user entered # if month is 01: # month is Januray # if month is 02: # month is February # if month is 03: # month is March # if month is 04: # month is April # this keep going till # if month is 12: # month is December #3. using indexes, print the date in the variable #CODE def main(): date_string = input('Enter a date in the form "mm/dd/yyyy": ') date_list = get_date_list(date_string) def get_date_list(date_string): date_list = date_string.split('/') #Determining the month mm = date_list[0] if mm == '01': mm = 'January' elif mm == '02': mm = 'February' elif mm == '03': mm = 'March' elif mm == '04': mm = 'April' elif mm == '05': mm = 'May' elif mm == '06': mm = 'June' elif mm == '07': mm = 'July' elif mm == '08': mm = 'August' elif mm == '09': mm = 'September' elif mm == '10': mm = 'October' elif mm == '11': mm = 'November' elif mm == '12': mm = 'December' #displayin results print('A reform of the date you entered is: ',\ mm,date_list[1]+',',date_list[2]) main()
def main(): date_string = input('Enter a date in the form "mm/dd/yyyy": ') date_list = get_date_list(date_string) def get_date_list(date_string): date_list = date_string.split('/') mm = date_list[0] if mm == '01': mm = 'January' elif mm == '02': mm = 'February' elif mm == '03': mm = 'March' elif mm == '04': mm = 'April' elif mm == '05': mm = 'May' elif mm == '06': mm = 'June' elif mm == '07': mm = 'July' elif mm == '08': mm = 'August' elif mm == '09': mm = 'September' elif mm == '10': mm = 'October' elif mm == '11': mm = 'November' elif mm == '12': mm = 'December' print('A reform of the date you entered is: ', mm, date_list[1] + ',', date_list[2]) main()
# coding=utf-8 """ Package used to unify the different constant values used in entire project """ class Consts(object): """ Class used to unify the different constant values used in entire project """ # BPMN 2.0 element attribute names id = "id" name = "name" # Flow nodes cannot use "name" parameter in dictionary, due to the errors with PyDot node_name = "node_name" gateway_direction = "gatewayDirection" default = "default" instantiate = "instantiate" event_gateway_type = "eventGatewayType" source_ref = "sourceRef" target_ref = "targetRef" triggered_by_event = "triggeredByEvent" parallel_multiple = "parallelMultiple" cancel_activity = "cancelActivity" attached_to_ref = "attachedToRef" is_interrupting = "isInterrupting" is_closed = "isClosed" is_executable = "isExecutable" is_expanded = "isExpanded" is_horizontal = "isHorizontal" is_collection = "isCollection" process_type = "processType" sequence_flow = "sequenceFlow" condition_expression = "conditionExpression" message_flow = "messageFlow" message_flows = "messageFlows" implementation = "implementation" compensation = "isForCompensation" quantity = "startQuantity" # CSV literals csv_order = "Order" csv_activity = "Activity" csv_condition = "Condition" csv_who = "Who" csv_subprocess = "Subprocess" csv_terminated = "Terminated" # BPMN 2.0 diagram interchange element attribute names bpmn_element = "bpmnElement" height = "height" width = "width" x = "x" y = "y" # BPMN 2.0 element names definitions = "definitions" collaboration = "collaboration" participant = "participant" participants = "participants" process = "process" process_ref = "processRef" lane = "lane" lanes = "lanes" lane_set = "laneSet" child_lane_set = "childLaneSet" flow_node_ref = "flowNodeRef" flow_node_refs = "flowNodeRefs" task = "task" user_task = "userTask" send_task = "sendTask" call_activity = "callActivity" service_task = "serviceTask" manual_task = "manualTask" subprocess = "subProcess" data_object = "dataObject" complex_gateway = "complexGateway" event_based_gateway = "eventBasedGateway" inclusive_gateway = "inclusiveGateway" exclusive_gateway = "exclusiveGateway" parallel_gateway = "parallelGateway" start_event = "startEvent" intermediate_catch_event = "intermediateCatchEvent" end_event = "endEvent" intermediate_throw_event = "intermediateThrowEvent" boundary_event = "boundaryEvent" # BPMN 2.0 diagram interchange element names bpmn_shape = "BPMNShape" bpmn_edge = "BPMNEdge" # BPMN 2.0 child element names incoming_flow = "incoming" incoming_flow_list = "incoming_flow_list" outgoing_flow = "outgoing" outgoing_flow_list = "outgoing_flow_list" waypoint = "waypoint" waypoints = "waypoints" documentation = "documentation" # Additional parameter names type = "type" event_definitions = "event_definitions" node_ids = "node_ids" definition_type = "definition_type" grid_column_width = 2
""" Package used to unify the different constant values used in entire project """ class Consts(object): """ Class used to unify the different constant values used in entire project """ id = 'id' name = 'name' node_name = 'node_name' gateway_direction = 'gatewayDirection' default = 'default' instantiate = 'instantiate' event_gateway_type = 'eventGatewayType' source_ref = 'sourceRef' target_ref = 'targetRef' triggered_by_event = 'triggeredByEvent' parallel_multiple = 'parallelMultiple' cancel_activity = 'cancelActivity' attached_to_ref = 'attachedToRef' is_interrupting = 'isInterrupting' is_closed = 'isClosed' is_executable = 'isExecutable' is_expanded = 'isExpanded' is_horizontal = 'isHorizontal' is_collection = 'isCollection' process_type = 'processType' sequence_flow = 'sequenceFlow' condition_expression = 'conditionExpression' message_flow = 'messageFlow' message_flows = 'messageFlows' implementation = 'implementation' compensation = 'isForCompensation' quantity = 'startQuantity' csv_order = 'Order' csv_activity = 'Activity' csv_condition = 'Condition' csv_who = 'Who' csv_subprocess = 'Subprocess' csv_terminated = 'Terminated' bpmn_element = 'bpmnElement' height = 'height' width = 'width' x = 'x' y = 'y' definitions = 'definitions' collaboration = 'collaboration' participant = 'participant' participants = 'participants' process = 'process' process_ref = 'processRef' lane = 'lane' lanes = 'lanes' lane_set = 'laneSet' child_lane_set = 'childLaneSet' flow_node_ref = 'flowNodeRef' flow_node_refs = 'flowNodeRefs' task = 'task' user_task = 'userTask' send_task = 'sendTask' call_activity = 'callActivity' service_task = 'serviceTask' manual_task = 'manualTask' subprocess = 'subProcess' data_object = 'dataObject' complex_gateway = 'complexGateway' event_based_gateway = 'eventBasedGateway' inclusive_gateway = 'inclusiveGateway' exclusive_gateway = 'exclusiveGateway' parallel_gateway = 'parallelGateway' start_event = 'startEvent' intermediate_catch_event = 'intermediateCatchEvent' end_event = 'endEvent' intermediate_throw_event = 'intermediateThrowEvent' boundary_event = 'boundaryEvent' bpmn_shape = 'BPMNShape' bpmn_edge = 'BPMNEdge' incoming_flow = 'incoming' incoming_flow_list = 'incoming_flow_list' outgoing_flow = 'outgoing' outgoing_flow_list = 'outgoing_flow_list' waypoint = 'waypoint' waypoints = 'waypoints' documentation = 'documentation' type = 'type' event_definitions = 'event_definitions' node_ids = 'node_ids' definition_type = 'definition_type' grid_column_width = 2
""" All exceptions that can be raised during handling of a weatherapi request. """ # Functions that make a request to weatherapi.com have the possibility # of raising one of these errors depending on the response. # We use these custom error classes to make the error code more readable # and easier to handle. __all__ = [ 'WeatherApiError', 'NoApiKey', 'InvalidApiKey', 'QuotaExceeded', 'ApiKeyDisabled', 'QueryNotProvided', 'InvalidRequestUrl', 'InvalidLocation', 'InternalError' ] class WeatherApiError(Exception): """ Raised when an unknown weatherapi error is encountered. :var internal_code: :class:`int` The error code returned by weatherapi. :var message: :class:`str` A more detailed description of the error. """ def __init__(self, message, internal_code): self.internal_code = internal_code self.message = message super().__init__(message) class NoApiKey(WeatherApiError): """Raised when no weatherapi key has been provided in a request.""" class InvalidApiKey(WeatherApiError): """Raised when an invalid weatherapi key has been used for a request.""" class QuotaExceeded(WeatherApiError): """Raised when monthly requests limit has been reached.""" class ApiKeyDisabled(WeatherApiError): """Raised when weatherapi key used for a request has been disabled.""" class QueryNotProvided(WeatherApiError): """Raised when a query parameter has not been provided for a request.""" class InvalidRequestUrl(WeatherApiError): """Raised when weatherapi request url is invalid.""" class InvalidLocation(WeatherApiError): """Raised when location request is not found.""" class InternalError(WeatherApiError): """Raised when an internal weatherapi error is encountered."""
""" All exceptions that can be raised during handling of a weatherapi request. """ __all__ = ['WeatherApiError', 'NoApiKey', 'InvalidApiKey', 'QuotaExceeded', 'ApiKeyDisabled', 'QueryNotProvided', 'InvalidRequestUrl', 'InvalidLocation', 'InternalError'] class Weatherapierror(Exception): """ Raised when an unknown weatherapi error is encountered. :var internal_code: :class:`int` The error code returned by weatherapi. :var message: :class:`str` A more detailed description of the error. """ def __init__(self, message, internal_code): self.internal_code = internal_code self.message = message super().__init__(message) class Noapikey(WeatherApiError): """Raised when no weatherapi key has been provided in a request.""" class Invalidapikey(WeatherApiError): """Raised when an invalid weatherapi key has been used for a request.""" class Quotaexceeded(WeatherApiError): """Raised when monthly requests limit has been reached.""" class Apikeydisabled(WeatherApiError): """Raised when weatherapi key used for a request has been disabled.""" class Querynotprovided(WeatherApiError): """Raised when a query parameter has not been provided for a request.""" class Invalidrequesturl(WeatherApiError): """Raised when weatherapi request url is invalid.""" class Invalidlocation(WeatherApiError): """Raised when location request is not found.""" class Internalerror(WeatherApiError): """Raised when an internal weatherapi error is encountered."""
n1 = float(input('Valor do produto (R$): ')) n2 = float(input('Desconto em porcentagem (%): ')) d = n2/100 d1 = n1*d nv = n1-d1 print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2,nv))
n1 = float(input('Valor do produto (R$): ')) n2 = float(input('Desconto em porcentagem (%): ')) d = n2 / 100 d1 = n1 * d nv = n1 - d1 print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2, nv))
mem_key_cache = 'cache' mem_key_metadata = 'meta' mem_key_sponsor = 'sponsor' mem_key_total_open_source_spaces = 'oss' mem_key_creeps_by_role = 'roles_alive' mem_key_work_parts_by_role = 'roles_work' mem_key_carry_parts_by_role = 'roles_carry' mem_key_creeps_by_role_and_replacement_time = 'rt_map' mem_key_prepping_defenses = 'prepping_defenses' mem_key_storage_use_enabled = 'full_storage_use' mem_key_focusing_home = 'focusing_home' mem_key_upgrading_paused = 'upgrading_paused' mem_key_building_paused = 'building_paused' mem_key_spawn_requests = '_requests' mem_key_planned_role_to_spawn = 'next_role' mem_key_observer_plans = 'observer_plan' mem_key_flag_for_testing_spawning_in_simulation = 'completely_sim_testing' mem_key_pause_all_room_operations = 'pause' mem_key_empty_all_resources_into_room = 'empty_to' mem_key_sell_all_but_empty_resources_to = 'sabet' mem_key_room_reserved_up_until_tick = 'rea' mem_key_currently_under_siege = 'attack' mem_key_remotes_safe_when_under_siege = 'remotes_safe' mem_key_remotes_explicitly_marked_under_attack = 'remotes_attack' mem_key_stored_hostiles = 'danger' mem_key_defense_mind_storage = 'defense' mem_key_linking_mind_storage = 'links' mem_key_mineral_mind_storage = 'market' mem_key_building_priority_walls = 'prio_walls' mem_key_building_priority_spawn = 'prio_spawn' mem_key_there_might_be_energy_lying_around = 'tons' mem_key_now_supporting = 's' mem_key_alive_squads = 'st' mem_key_urgency = 'urgency' mem_key_message = 'm' mem_key_dismantler_squad_opts = 'dm_opts' mem_key_squad_memory = 'sqmem' cache_key_spending_now = 'ss' cache_key_squads = 'sqds'
mem_key_cache = 'cache' mem_key_metadata = 'meta' mem_key_sponsor = 'sponsor' mem_key_total_open_source_spaces = 'oss' mem_key_creeps_by_role = 'roles_alive' mem_key_work_parts_by_role = 'roles_work' mem_key_carry_parts_by_role = 'roles_carry' mem_key_creeps_by_role_and_replacement_time = 'rt_map' mem_key_prepping_defenses = 'prepping_defenses' mem_key_storage_use_enabled = 'full_storage_use' mem_key_focusing_home = 'focusing_home' mem_key_upgrading_paused = 'upgrading_paused' mem_key_building_paused = 'building_paused' mem_key_spawn_requests = '_requests' mem_key_planned_role_to_spawn = 'next_role' mem_key_observer_plans = 'observer_plan' mem_key_flag_for_testing_spawning_in_simulation = 'completely_sim_testing' mem_key_pause_all_room_operations = 'pause' mem_key_empty_all_resources_into_room = 'empty_to' mem_key_sell_all_but_empty_resources_to = 'sabet' mem_key_room_reserved_up_until_tick = 'rea' mem_key_currently_under_siege = 'attack' mem_key_remotes_safe_when_under_siege = 'remotes_safe' mem_key_remotes_explicitly_marked_under_attack = 'remotes_attack' mem_key_stored_hostiles = 'danger' mem_key_defense_mind_storage = 'defense' mem_key_linking_mind_storage = 'links' mem_key_mineral_mind_storage = 'market' mem_key_building_priority_walls = 'prio_walls' mem_key_building_priority_spawn = 'prio_spawn' mem_key_there_might_be_energy_lying_around = 'tons' mem_key_now_supporting = 's' mem_key_alive_squads = 'st' mem_key_urgency = 'urgency' mem_key_message = 'm' mem_key_dismantler_squad_opts = 'dm_opts' mem_key_squad_memory = 'sqmem' cache_key_spending_now = 'ss' cache_key_squads = 'sqds'
# -*- coding: utf-8 -*- # Scrapy settings for watches project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'watches' SPIDER_MODULES = ['watches.spiders'] NEWSPIDER_MODULE = 'watches.spiders' REDIRECT_ENABLED = False # Retry many times since proxies often fail RETRY_TIMES = 10 # Retry on most error codes since proxies fail for different reasons RETRY_HTTP_CODES = [500, 503, 504, 400, 403, 404, 408] # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'watches (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 0.2 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) COOKIES_ENABLED = False
bot_name = 'watches' spider_modules = ['watches.spiders'] newspider_module = 'watches.spiders' redirect_enabled = False retry_times = 10 retry_http_codes = [500, 503, 504, 400, 403, 404, 408] robotstxt_obey = False download_delay = 0.2 cookies_enabled = False
#!/usr/bin/env python ####################################### # Installation module for eyewitness ####################################### # AUTHOR OF MODULE NAME AUTHOR="Kirk Hayes (l0gan)" # DESCRIPTION OF THE MODULE DESCRIPTION="This module will install/update EyeWitness." # INSTALL TYPE GIT, SVN, FILE DOWNLOAD # OPTIONS = GIT, SVN, FILE INSTALL_TYPE="GIT" # LOCATION OF THE FILE OR GIT/SVN REPOSITORY REPOSITORY_LOCATION="https://github.com/FortyNorthSecurity/EyeWitness" # WHERE DO YOU WANT TO INSTALL IT INSTALL_LOCATION="eyewitness" # DEPENDS FOR DEBIAN INSTALLS DEBIAN="git,python-setuptools,libffi-dev,libssl-dev" # COMMANDS TO RUN AFTER AFTER_COMMANDS="cd {INSTALL_LOCATION}Python/setup,./setup.sh" LAUNCHER="eyewitness"
author = 'Kirk Hayes (l0gan)' description = 'This module will install/update EyeWitness.' install_type = 'GIT' repository_location = 'https://github.com/FortyNorthSecurity/EyeWitness' install_location = 'eyewitness' debian = 'git,python-setuptools,libffi-dev,libssl-dev' after_commands = 'cd {INSTALL_LOCATION}Python/setup,./setup.sh' launcher = 'eyewitness'
users = {'email1': 'password1'} links = [ # fake array of posts { 'author': 'users', 'date' : "04-08-2017", 'description': 'cool information site', 'link': 'https://www.wikipedia.org', 'tags': None }, { 'author': 'user', 'date' : "06-08-2017", 'description': 'worst site I\'ve ever used', 'link': 'www.facebook.org', 'tags': None }, { 'author': 'user', 'date' : "01-08-2017", 'description': 'other cool site', 'link': 'www.python.org', 'tags': None } ]
users = {'email1': 'password1'} links = [{'author': 'users', 'date': '04-08-2017', 'description': 'cool information site', 'link': 'https://www.wikipedia.org', 'tags': None}, {'author': 'user', 'date': '06-08-2017', 'description': "worst site I've ever used", 'link': 'www.facebook.org', 'tags': None}, {'author': 'user', 'date': '01-08-2017', 'description': 'other cool site', 'link': 'www.python.org', 'tags': None}]
# OAuth app keys DROPBOX_BUSINESS_FILEACCESS_KEY = None DROPBOX_BUSINESS_FILEACCESS_SECRET = None DROPBOX_BUSINESS_MANAGEMENT_KEY = None DROPBOX_BUSINESS_MANAGEMENT_SECRET = None DROPBOX_BUSINESS_AUTH_CSRF_TOKEN = 'dropboxbusiness-auth-csrf-token' TEAM_FOLDER_NAME_FORMAT = '{title}_GRDM_{guid}' # available: {title} {guid} GROUP_NAME_FORMAT = 'GRDM_{guid}' # available: {title} {guid} ADMIN_GROUP_NAME = 'GRDM-ADMIN' USE_PROPERTY_TIMESTAMP = True PROPERTY_GROUP_NAME = 'GRDM' PROPERTY_KEY_TIMESTAMP_STATUS = 'timestamp-status' PROPERTY_KEYS = (PROPERTY_KEY_TIMESTAMP_STATUS,) PROPERTY_MAX_DATA_SIZE = 1000 PROPERTY_SPLIT_DATA_CONF = { 'timestamp': { 'max_size': 5000, } } # Max file size permitted by frontend in megabytes MAX_UPLOAD_SIZE = 5 * 1024 EPPN_TO_EMAIL_MAP = { # e.g. # 'john@idp.example.com': 'john.smith@mail.example.com', } EMAIL_TO_EPPN_MAP = dict( [(EPPN_TO_EMAIL_MAP[k], k) for k in EPPN_TO_EMAIL_MAP] ) DEBUG_FILEACCESS_TOKEN = None DEBUG_MANAGEMENT_TOKEN = None DEBUG_ADMIN_DBMID = None
dropbox_business_fileaccess_key = None dropbox_business_fileaccess_secret = None dropbox_business_management_key = None dropbox_business_management_secret = None dropbox_business_auth_csrf_token = 'dropboxbusiness-auth-csrf-token' team_folder_name_format = '{title}_GRDM_{guid}' group_name_format = 'GRDM_{guid}' admin_group_name = 'GRDM-ADMIN' use_property_timestamp = True property_group_name = 'GRDM' property_key_timestamp_status = 'timestamp-status' property_keys = (PROPERTY_KEY_TIMESTAMP_STATUS,) property_max_data_size = 1000 property_split_data_conf = {'timestamp': {'max_size': 5000}} max_upload_size = 5 * 1024 eppn_to_email_map = {} email_to_eppn_map = dict([(EPPN_TO_EMAIL_MAP[k], k) for k in EPPN_TO_EMAIL_MAP]) debug_fileaccess_token = None debug_management_token = None debug_admin_dbmid = None
colors = { 'default': (0, 'WHITE', 'BLACK', 'NORMAL'), 'title': (1, 'YELLOW', 'BLUE', 'BOLD'), 'status': (2, 'YELLOW', 'BLUE', 'BOLD'), 'error': (3, 'RED', 'BLACK', 'BOLD'), 'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD'), }
colors = {'default': (0, 'WHITE', 'BLACK', 'NORMAL'), 'title': (1, 'YELLOW', 'BLUE', 'BOLD'), 'status': (2, 'YELLOW', 'BLUE', 'BOLD'), 'error': (3, 'RED', 'BLACK', 'BOLD'), 'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD')}
#-----------------problem parameters----------------------- depot = [] capacity = 120 time_dist_factor = 10 # time per job converted to distance num_salesmen = 5 # --------------------------------------------------------- population = 50 nodes = [] node_num = 0 gnd_truth_tsp = [] gnd_truth_dist_list = [] # i-th element is distance between i-th and i+1 th element of gnd_truth_tsp gnd_truth_dist_from_depot = [] # i-th element is distance of i-th element of gnd_truth_tsp from depot def print_error(msg): print("ERROR: "+msg) exit()
depot = [] capacity = 120 time_dist_factor = 10 num_salesmen = 5 population = 50 nodes = [] node_num = 0 gnd_truth_tsp = [] gnd_truth_dist_list = [] gnd_truth_dist_from_depot = [] def print_error(msg): print('ERROR: ' + msg) exit()
class MeuObjeto: def __init__(self, id, nome, sobrenome): self.id = id self.nome = nome self.sobrenome = sobrenome
class Meuobjeto: def __init__(self, id, nome, sobrenome): self.id = id self.nome = nome self.sobrenome = sobrenome
def retry_until(condition): def retry(request): try: return request() except Exception as exception: if condition(exception): return retry(request) else: raise exception return retry def retry(max_retries): retries = [0] def retry_count(): retries[0] += 1 return retries[0] return retry_until(lambda _: retry_count() != max_retries)
def retry_until(condition): def retry(request): try: return request() except Exception as exception: if condition(exception): return retry(request) else: raise exception return retry def retry(max_retries): retries = [0] def retry_count(): retries[0] += 1 return retries[0] return retry_until(lambda _: retry_count() != max_retries)
def list__data_pt(): length = input("\nEnter the Number of Data Point(s) :\t") try: if not length.isnumeric() or int(length) <= 0: raise Exception except Exception: print() print(length) print("ERROR !!!") print("Enter a Natural Number Greater than 0 !!!") exit(1) print("\nEnter your Numerical Data Point(s) :") a = [] for _ in range(int(length)): i = input() try: if not i.isnumeric() and not isinstance(float(i), float): raise Exception except Exception: print() print(i) print("ERROR !!!") print("Enter 0 or any Positive or Negative Integer/Decimal !!!") exit(1) i = float(i) a.append(i) print("\nList of Your Data Point(s) :") return a def nearest__data_pt(): """ My Python Script : Nearest Data Point Tracker Tool $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ """ data = list__data_pt() print(data) x = input(f"\nEnter a Numerical Value :\t") try: if not x.isnumeric() and not isinstance(float(x), float): raise Exception except Exception: print() print(x) print("ERROR !!!") print("Enter 0 or any Positive or Negative Integer/Decimal !!!") exit(1) x = float(x) c = [] for _ in data: b = x - _ b = abs(b) c.append(b) d = min(c[0:len(c)]) print("\n") data_single = [] data_multiple = [] i = 0 for c[i] in c: if c.count(c[i]) > 1 and d == c[i]: data_multiple.append(data[i]) elif c.count(c[i]) == 1 and d == c[i]: data_single.append(data[i]) i += 1 print() if data_single != []: return f"From your List, Nearest Data Point to your Numerical Value --- '{x}' :\t'''{data_single}'''" elif data_multiple != []: return f"From your List, Nearest Data Point to your Numerical Value --- '{x}' :\t'''{data_multiple}'''" # print(nearest__data_pt())
def list__data_pt(): length = input('\nEnter the Number of Data Point(s) :\t') try: if not length.isnumeric() or int(length) <= 0: raise Exception except Exception: print() print(length) print('ERROR !!!') print('Enter a Natural Number Greater than 0 !!!') exit(1) print('\nEnter your Numerical Data Point(s) :') a = [] for _ in range(int(length)): i = input() try: if not i.isnumeric() and (not isinstance(float(i), float)): raise Exception except Exception: print() print(i) print('ERROR !!!') print('Enter 0 or any Positive or Negative Integer/Decimal !!!') exit(1) i = float(i) a.append(i) print('\nList of Your Data Point(s) :') return a def nearest__data_pt(): """ My Python Script : Nearest Data Point Tracker Tool $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ """ data = list__data_pt() print(data) x = input(f'\nEnter a Numerical Value :\t') try: if not x.isnumeric() and (not isinstance(float(x), float)): raise Exception except Exception: print() print(x) print('ERROR !!!') print('Enter 0 or any Positive or Negative Integer/Decimal !!!') exit(1) x = float(x) c = [] for _ in data: b = x - _ b = abs(b) c.append(b) d = min(c[0:len(c)]) print('\n') data_single = [] data_multiple = [] i = 0 for c[i] in c: if c.count(c[i]) > 1 and d == c[i]: data_multiple.append(data[i]) elif c.count(c[i]) == 1 and d == c[i]: data_single.append(data[i]) i += 1 print() if data_single != []: return f"From your List, Nearest Data Point to your Numerical Value --- '{x}' :\t'''{data_single}'''" elif data_multiple != []: return f"From your List, Nearest Data Point to your Numerical Value --- '{x}' :\t'''{data_multiple}'''"
fig, ax = plt.subplots() ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue') ax.set_xlabel('Zr [ppm]') ax.set_ylabel('Likelihood of occurrence')
(fig, ax) = plt.subplots() ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue') ax.set_xlabel('Zr [ppm]') ax.set_ylabel('Likelihood of occurrence')
# Found in https://leetcode.com/problems/two-sum/ # # Time Complexity: O(n) # Space Complexity: O(n) class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ haveSeenIt = {} for idx, val in enumerate(nums): if (target - val) in haveSeenIt: return [haveSeenIt[target - val], idx] haveSeenIt[val] = idx return []
class Solution(object): def two_sum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ have_seen_it = {} for (idx, val) in enumerate(nums): if target - val in haveSeenIt: return [haveSeenIt[target - val], idx] haveSeenIt[val] = idx return []
heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster = [can for can in heights if can > 161] print(can_ride_coaster)
heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster = [can for can in heights if can > 161] print(can_ride_coaster)
"""Common node-related functions """ def set_text_on_node(graph, current_node, errorstring, highlight_color, resize): """Sets an error string on the current_node in graph. Also changes the color to red to highlight it. The parameter current_node should come from the graph that was parsed from file, but errors are written on the corresponding node on a validation/error graph, which was cloned from the original graph during initialization of the GraphParser. """ for node in graph.getElementsByTagName('node'): if node.attributes["id"].value == current_node.attributes["id"].value: node.getElementsByTagName( 'y:NodeLabel')[0].firstChild.replaceWholeText(errorstring) if highlight_color == 'Red': node.getElementsByTagName( 'y:Fill')[0].attributes["color"].value = "#FF9090" node.getElementsByTagName( 'y:Fill')[0].attributes["color2"].value = "#CC0000" elif highlight_color == 'Green': node.getElementsByTagName( 'y:Fill')[0].attributes["color"].value = "#90FF90" node.getElementsByTagName( 'y:Fill')[0].attributes["color2"].value = "#008800" if resize == True: old_width = node.getElementsByTagName( 'y:Geometry')[0].attributes["width"].value new_width = len(errorstring * 5) + 80 node.getElementsByTagName( 'y:Geometry')[0].attributes["width"].value = str(new_width) old_x = node.getElementsByTagName( 'y:Geometry')[0].attributes["x"].value node.getElementsByTagName('y:Geometry')[0].attributes["x"].value = str( float(old_x) - (new_width - float(old_width)) / 2) def get_node_datatext(node): """Returns a string with data node text if it exists on the node, otherwise returns an empty string""" datatext = "" if node.attributes["id"].value: for data_node in node.getElementsByTagName('data'): if data_node.attributes["key"].value == "d5": if data_node.firstChild: datatext = data_node.firstChild.wholeText return datatext def parse_parameter(parameter, node): """Creates a C-code function node parameter Searches for a parameter that matches the given type in parameter. The first occurence found will be used. If the function node creation function has multiple parameters of the given type, deep_parse_parameter must be called. If no parameter of correct type is found the function returns an empty string. """ parameter_value = "" data_nodes = node.getElementsByTagName('data') for data_node in data_nodes: if data_node and data_node.attributes["key"].value == "d5": if data_node.firstChild: datatext = data_node.firstChild.wholeText parameter = "[" + parameter #Parameters should start with a [ character if parameter in datatext: datatext_after_parameter = datatext.split(parameter, 1)[1] parameter_value = (datatext_after_parameter.split("]", 1)[0]).strip() return parameter_value
"""Common node-related functions """ def set_text_on_node(graph, current_node, errorstring, highlight_color, resize): """Sets an error string on the current_node in graph. Also changes the color to red to highlight it. The parameter current_node should come from the graph that was parsed from file, but errors are written on the corresponding node on a validation/error graph, which was cloned from the original graph during initialization of the GraphParser. """ for node in graph.getElementsByTagName('node'): if node.attributes['id'].value == current_node.attributes['id'].value: node.getElementsByTagName('y:NodeLabel')[0].firstChild.replaceWholeText(errorstring) if highlight_color == 'Red': node.getElementsByTagName('y:Fill')[0].attributes['color'].value = '#FF9090' node.getElementsByTagName('y:Fill')[0].attributes['color2'].value = '#CC0000' elif highlight_color == 'Green': node.getElementsByTagName('y:Fill')[0].attributes['color'].value = '#90FF90' node.getElementsByTagName('y:Fill')[0].attributes['color2'].value = '#008800' if resize == True: old_width = node.getElementsByTagName('y:Geometry')[0].attributes['width'].value new_width = len(errorstring * 5) + 80 node.getElementsByTagName('y:Geometry')[0].attributes['width'].value = str(new_width) old_x = node.getElementsByTagName('y:Geometry')[0].attributes['x'].value node.getElementsByTagName('y:Geometry')[0].attributes['x'].value = str(float(old_x) - (new_width - float(old_width)) / 2) def get_node_datatext(node): """Returns a string with data node text if it exists on the node, otherwise returns an empty string""" datatext = '' if node.attributes['id'].value: for data_node in node.getElementsByTagName('data'): if data_node.attributes['key'].value == 'd5': if data_node.firstChild: datatext = data_node.firstChild.wholeText return datatext def parse_parameter(parameter, node): """Creates a C-code function node parameter Searches for a parameter that matches the given type in parameter. The first occurence found will be used. If the function node creation function has multiple parameters of the given type, deep_parse_parameter must be called. If no parameter of correct type is found the function returns an empty string. """ parameter_value = '' data_nodes = node.getElementsByTagName('data') for data_node in data_nodes: if data_node and data_node.attributes['key'].value == 'd5': if data_node.firstChild: datatext = data_node.firstChild.wholeText parameter = '[' + parameter if parameter in datatext: datatext_after_parameter = datatext.split(parameter, 1)[1] parameter_value = datatext_after_parameter.split(']', 1)[0].strip() return parameter_value
i = 1 while (i<=10): print(i, end=" ") i += 1 print()
i = 1 while i <= 10: print(i, end=' ') i += 1 print()
def my_function(*args, **kwargs): for arg in args: print('arg:', arg) for key in kwargs.keys(): print('key:', key, 'has value: ', kwargs[key]) my_function('John', 'Denise', daughter='Phoebe', son='Adam') print('-' * 50) my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='James', daughter='Joselyn') def named(**kwargs): for key in kwargs.keys(): print('arg:', key, 'has value:', kwargs[key]) named(a=1, b=2, c=3) def printer(*args): for arg in args: print('arg:', arg, end=", ") print() a = (1, 2, 3, 4) b = [1, 2, 3, 4] printer(0, 1, 2, 3, 4, 5) printer(0, a, 5) printer(0, b, 5) printer(0, *a) printer(0, *b) printer(0, *[1, 2, 3, 4])
def my_function(*args, **kwargs): for arg in args: print('arg:', arg) for key in kwargs.keys(): print('key:', key, 'has value: ', kwargs[key]) my_function('John', 'Denise', daughter='Phoebe', son='Adam') print('-' * 50) my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='James', daughter='Joselyn') def named(**kwargs): for key in kwargs.keys(): print('arg:', key, 'has value:', kwargs[key]) named(a=1, b=2, c=3) def printer(*args): for arg in args: print('arg:', arg, end=', ') print() a = (1, 2, 3, 4) b = [1, 2, 3, 4] printer(0, 1, 2, 3, 4, 5) printer(0, a, 5) printer(0, b, 5) printer(0, *a) printer(0, *b) printer(0, *[1, 2, 3, 4])
class A: def __init__(self): print("A") super().__init__() class B1(A): def __init__(self): print("B1") super().__init__() class B2(A): def __init__(self): print("B2") super().__init__() class C(B1, A): def __init__(self): print("C") super().__init__() C()
class A: def __init__(self): print('A') super().__init__() class B1(A): def __init__(self): print('B1') super().__init__() class B2(A): def __init__(self): print('B2') super().__init__() class C(B1, A): def __init__(self): print('C') super().__init__() c()
props.bf_Shank_Dia = 10.0 #props.bf_Pitch = 1.5 # Coarse props.bf_Pitch = 1.25 # Fine props.bf_Crest_Percent = 10 props.bf_Root_Percent = 10 props.bf_Major_Dia = 10.0 props.bf_Minor_Dia = props.bf_Major_Dia - (1.082532 * props.bf_Pitch) props.bf_Hex_Head_Flat_Distance = 17.0 props.bf_Hex_Head_Height = 6.4 props.bf_Cap_Head_Dia = 16.0 props.bf_Cap_Head_Height = 10.0 props.bf_CounterSink_Head_Dia = 20.0 props.bf_Allen_Bit_Flat_Distance = 8.0 props.bf_Allen_Bit_Depth = 5.0 props.bf_Pan_Head_Dia = 20.0 props.bf_Dome_Head_Dia = 20.0 props.bf_Philips_Bit_Dia = props.bf_Pan_Head_Dia * (1.82 / 5.6) #props.bf_Phillips_Bit_Depth = Get_Phillips_Bit_Height(props.bf_Philips_Bit_Dia) props.bf_Hex_Nut_Height = 8.0 props.bf_Hex_Nut_Flat_Distance = 17.0 props.bf_Thread_Length = 20 props.bf_Shank_Length = 0.0
props.bf_Shank_Dia = 10.0 props.bf_Pitch = 1.25 props.bf_Crest_Percent = 10 props.bf_Root_Percent = 10 props.bf_Major_Dia = 10.0 props.bf_Minor_Dia = props.bf_Major_Dia - 1.082532 * props.bf_Pitch props.bf_Hex_Head_Flat_Distance = 17.0 props.bf_Hex_Head_Height = 6.4 props.bf_Cap_Head_Dia = 16.0 props.bf_Cap_Head_Height = 10.0 props.bf_CounterSink_Head_Dia = 20.0 props.bf_Allen_Bit_Flat_Distance = 8.0 props.bf_Allen_Bit_Depth = 5.0 props.bf_Pan_Head_Dia = 20.0 props.bf_Dome_Head_Dia = 20.0 props.bf_Philips_Bit_Dia = props.bf_Pan_Head_Dia * (1.82 / 5.6) props.bf_Hex_Nut_Height = 8.0 props.bf_Hex_Nut_Flat_Distance = 17.0 props.bf_Thread_Length = 20 props.bf_Shank_Length = 0.0
def dividedtimes(x): if not isinstance(x, int): raise TypeError('x must be integer.') elif x <= 2: raise ValueError('x must be greater than 2.') counter = 0 while x >= 2: x = x / 2 counter += 1 return counter
def dividedtimes(x): if not isinstance(x, int): raise type_error('x must be integer.') elif x <= 2: raise value_error('x must be greater than 2.') counter = 0 while x >= 2: x = x / 2 counter += 1 return counter
def bubbleSort(list): for i in range(0,len(list)-1): for j in range(0,len(list)-i-1): if list[j] > list[j+1]: print("\n%d > %d"%(list[j],list[j+1])) (list[j], list[j+1]) = (list[j+1], list[j]) print("\nNext Pass\n") print("\nThe elements are now sorted in ascending order:\n") for i in list: print("\t%d\t"%(i),end="") n = int(input("\nEnter the number of elements : \n")) list = [] print("\nEnter the elements one be one:\n") for i in range(n): list.append(int(input())) bubbleSort(list)
def bubble_sort(list): for i in range(0, len(list) - 1): for j in range(0, len(list) - i - 1): if list[j] > list[j + 1]: print('\n%d > %d' % (list[j], list[j + 1])) (list[j], list[j + 1]) = (list[j + 1], list[j]) print('\nNext Pass\n') print('\nThe elements are now sorted in ascending order:\n') for i in list: print('\t%d\t' % i, end='') n = int(input('\nEnter the number of elements : \n')) list = [] print('\nEnter the elements one be one:\n') for i in range(n): list.append(int(input())) bubble_sort(list)
# pylint: disable=missing-docstring,redefined-builtin,unsubscriptable-object # pylint: disable=invalid-name,too-few-public-methods,attribute-defined-outside-init class Repository: def _transfer(self, bytes=-1): self._bytesTransfered = 0 bufff = True while bufff and (bytes < 0 or self._bytesTransfered < bytes): bufff = bufff[: bytes - self._bytesTransfered] self._bytesTransfered += len(bufff)
class Repository: def _transfer(self, bytes=-1): self._bytesTransfered = 0 bufff = True while bufff and (bytes < 0 or self._bytesTransfered < bytes): bufff = bufff[:bytes - self._bytesTransfered] self._bytesTransfered += len(bufff)
# Copyright 2016 Check Point Software Technologies LTD # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # URI Strings URI = 'https://te-api.checkpoint.com/tecloud/api/v1/file/' TOKEN_URI = 'https://cloudinfra-gw.portal.checkpoint.com/auth/external' PORT = "18194" REMOTE_DIR = "tecloud/api/v1/file" QUERY = 'query' UPLOAD = 'upload' DOWNLOAD = 'download' QUERY_SELECTOR = '%s%s' % (URI, QUERY) UPLOAD_SELECTOR = '%s%s' % (URI, UPLOAD) DOWNLOAD_SELECTOR = '%s%s' % (URI, DOWNLOAD) def get_selector(ip_address,selector): url = "" if ip_address: url = 'https://%s:%s/%s/%s' % (ip_address, PORT, REMOTE_DIR, selector) elif selector == QUERY: url = QUERY_SELECTOR elif selector == UPLOAD: url = UPLOAD_SELECTOR elif selector == DOWNLOAD: url = DOWNLOAD_SELECTOR return url # Request Strings MD5 = 'md5' SHA1 = 'sha1' SHA256 = 'sha256' TE = 'te' TEX = 'extraction' PDF = 'pdf' XML = 'xml' SUMMARY = 'summary' # Response Strings STATUS = 'status' LABEL = 'label' RESPONSE = 'response' FOUND = 'FOUND' PARTIALLY_FOUND = 'PARTIALLY_FOUND' NOT_FOUND = 'NOT_FOUND' UPLOAD_SUCCESS = 'UPLOAD_SUCCESS' PENDING = 'PENDING' NO_QUOTA = 'NO_QUOTA' FORBIDDEN = 'FORBIDDEN' BENIGN = 'benign' MALICIOUS = 'malicious' ERROR = 'error' MESSAGE = 'message' # TE Strings TE_VERDICT = 'combined_verdict' TE_SEVERITY = 'severity' TE_CONFIDENCE = 'confidence' TE_VERDICT_MALICIOUS = 'verdict is Malicious' TE_VERDICT_BENIGN = 'verdict is Benign'
uri = 'https://te-api.checkpoint.com/tecloud/api/v1/file/' token_uri = 'https://cloudinfra-gw.portal.checkpoint.com/auth/external' port = '18194' remote_dir = 'tecloud/api/v1/file' query = 'query' upload = 'upload' download = 'download' query_selector = '%s%s' % (URI, QUERY) upload_selector = '%s%s' % (URI, UPLOAD) download_selector = '%s%s' % (URI, DOWNLOAD) def get_selector(ip_address, selector): url = '' if ip_address: url = 'https://%s:%s/%s/%s' % (ip_address, PORT, REMOTE_DIR, selector) elif selector == QUERY: url = QUERY_SELECTOR elif selector == UPLOAD: url = UPLOAD_SELECTOR elif selector == DOWNLOAD: url = DOWNLOAD_SELECTOR return url md5 = 'md5' sha1 = 'sha1' sha256 = 'sha256' te = 'te' tex = 'extraction' pdf = 'pdf' xml = 'xml' summary = 'summary' status = 'status' label = 'label' response = 'response' found = 'FOUND' partially_found = 'PARTIALLY_FOUND' not_found = 'NOT_FOUND' upload_success = 'UPLOAD_SUCCESS' pending = 'PENDING' no_quota = 'NO_QUOTA' forbidden = 'FORBIDDEN' benign = 'benign' malicious = 'malicious' error = 'error' message = 'message' te_verdict = 'combined_verdict' te_severity = 'severity' te_confidence = 'confidence' te_verdict_malicious = 'verdict is Malicious' te_verdict_benign = 'verdict is Benign'
g=[] for a in range (1000): if a%3==0 or a%5==0: g.append(a) print(sum(g))
g = [] for a in range(1000): if a % 3 == 0 or a % 5 == 0: g.append(a) print(sum(g))
#Strinping Names: Person_name = " Chandler Bing " print("Person Name with tab space :\t"+Person_name) print("Person Name in new line :\n"+Person_name) print("Person Name with space removed from left side :"+Person_name.lstrip()) print("Person Name with space removed from right side :"+Person_name.rstrip()) print("Person Name with space removed from both sides:"+Person_name.strip())
person_name = ' Chandler Bing ' print('Person Name with tab space :\t' + Person_name) print('Person Name in new line :\n' + Person_name) print('Person Name with space removed from left side :' + Person_name.lstrip()) print('Person Name with space removed from right side :' + Person_name.rstrip()) print('Person Name with space removed from both sides:' + Person_name.strip())
def divisibleSumPairs(n, k, ar): count = 0 for i in range(len(ar)-1): for j in range(i+1, len(ar)): if (ar[i]+ar[j])%k == 0: count += 1 return count
def divisible_sum_pairs(n, k, ar): count = 0 for i in range(len(ar) - 1): for j in range(i + 1, len(ar)): if (ar[i] + ar[j]) % k == 0: count += 1 return count
# Python3 Binary Tree to Doubly Linked List # 10 # / \ # 12 15 ---> head ---> 25<->12<->30<->10<->36<->15 # / \ / # 25 30 36 # def tree2DLL(root, head): if not root: return prev = None tree2DLL(root.left) if not prev: head = prev else: root.left = prev prev.right = root prev = root
def tree2_dll(root, head): if not root: return prev = None tree2_dll(root.left) if not prev: head = prev else: root.left = prev prev.right = root prev = root
class Synapse: def __init__(self, label, input, weight, next_neurons): self.label = label self.input = input self.weight = weight self.next_neurons = next_neurons
class Synapse: def __init__(self, label, input, weight, next_neurons): self.label = label self.input = input self.weight = weight self.next_neurons = next_neurons
''' Created on 2020-09-10 @author: wf ''' class Labels(object): ''' NLTK labels ''' default=['GPE','PERSON','ORGANIZATION'] geo=['GPE']
""" Created on 2020-09-10 @author: wf """ class Labels(object): """ NLTK labels """ default = ['GPE', 'PERSON', 'ORGANIZATION'] geo = ['GPE']
''' Substring Concatenation Asked in: Facebook https://www.interviewbit.com/problems/substring-concatenation/ You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. Example : S: "barfoothefoobarman" L: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). ''' # @param A : string # @param B : tuple of strings # @return a list of integers def findSubstring(A, B): ans = [] n = len(B) l = len(B[0]) hash_key = ''.join(sorted(B)) l_hash = len(hash_key) for i in range(len(A)-l_hash+1): C = [A[i+j*l:i+j*l+l]for j in range(n)] C = ''.join(sorted(C)) if C==hash_key: ans.append(i) return ans if __name__=='__main__': data = [ [ ["barfoothefoobarman", ["foo", "bar"]], [0,9] ] ] for d in data: print('input', d[0], 'output', findSubstring(*d[0]))
""" Substring Concatenation Asked in: Facebook https://www.interviewbit.com/problems/substring-concatenation/ You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. Example : S: "barfoothefoobarman" L: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). """ def find_substring(A, B): ans = [] n = len(B) l = len(B[0]) hash_key = ''.join(sorted(B)) l_hash = len(hash_key) for i in range(len(A) - l_hash + 1): c = [A[i + j * l:i + j * l + l] for j in range(n)] c = ''.join(sorted(C)) if C == hash_key: ans.append(i) return ans if __name__ == '__main__': data = [[['barfoothefoobarman', ['foo', 'bar']], [0, 9]]] for d in data: print('input', d[0], 'output', find_substring(*d[0]))
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dic = {} for i in range(len(nums)): if nums[i] in dic: return [dic[nums[i]], i] dic[target - nums[i]] = i solution = Solution() n1 = [2,7,11,15] t1 = 9 print(solution.twoSum(n1, t1)) n2 = [3,2,4] t2 = 6 print(solution.twoSum(n2, t2)) n3 = [3,3] t3 = 6 print(solution.twoSum(n3, t3))
class Solution(object): def two_sum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dic = {} for i in range(len(nums)): if nums[i] in dic: return [dic[nums[i]], i] dic[target - nums[i]] = i solution = solution() n1 = [2, 7, 11, 15] t1 = 9 print(solution.twoSum(n1, t1)) n2 = [3, 2, 4] t2 = 6 print(solution.twoSum(n2, t2)) n3 = [3, 3] t3 = 6 print(solution.twoSum(n3, t3))
def trunk_1(arr_1, size_1): result_1 = [] while arr: pop_data = [arr_1.pop(0) for _ in range(size_1)] result_1.append(pop_data) return result_1 def trunk_2(arr_2, size_2): arrs = [] while len(arr_2) > size_2: pice = arr_2[:size_2] arrs.append(pice) arr_2 = arr_2[size:] arrs.append(arr_2) return arrs def trunk_3(arr, size): result = [] count = 0 while count < len(arr): result.append(arr[count:count+size]) count += size return result if __name__ == "__main__": ''' arr = [1, 2, 3, 4, 5, 6] size = 2 result = [[1, 2], [3, 4], [5, 6]] ''' arr = [1, 2, 3, 4, 5, 6] size = 2 result = trunk_1(arr, size) print(result)
def trunk_1(arr_1, size_1): result_1 = [] while arr: pop_data = [arr_1.pop(0) for _ in range(size_1)] result_1.append(pop_data) return result_1 def trunk_2(arr_2, size_2): arrs = [] while len(arr_2) > size_2: pice = arr_2[:size_2] arrs.append(pice) arr_2 = arr_2[size:] arrs.append(arr_2) return arrs def trunk_3(arr, size): result = [] count = 0 while count < len(arr): result.append(arr[count:count + size]) count += size return result if __name__ == '__main__': '\n arr = [1, 2, 3, 4, 5, 6]\n size = 2\n result = [[1, 2], [3, 4], [5, 6]]\n ' arr = [1, 2, 3, 4, 5, 6] size = 2 result = trunk_1(arr, size) print(result)
#!/usr/bin/env python if __name__ == "__main__": print("Hello world from copied executable")
if __name__ == '__main__': print('Hello world from copied executable')
data = open("day3.txt", "r").read().splitlines() openSquare = data[0][0] tree = data[0][6] def howManyTrees(right, down): position = right iterator = down trees = 0 openSquares = 0 for rowIterator in range(0, int((len(data))/down) - 1): row = data[iterator] res_row = row * 100 obstacle = res_row[position] position += right if obstacle == openSquare: openSquares += 1 elif obstacle == tree: trees += 1 iterator += down print("Trees encountered for right ", right, " down ", down, " is ", trees) return trees first = howManyTrees(1,1) second = howManyTrees(3,1) third = howManyTrees(5,1) fourth = howManyTrees(7,1) fifth = howManyTrees(1,2) finalResult = first * second * third * fourth * fifth print("Multiplied trees", finalResult)
data = open('day3.txt', 'r').read().splitlines() open_square = data[0][0] tree = data[0][6] def how_many_trees(right, down): position = right iterator = down trees = 0 open_squares = 0 for row_iterator in range(0, int(len(data) / down) - 1): row = data[iterator] res_row = row * 100 obstacle = res_row[position] position += right if obstacle == openSquare: open_squares += 1 elif obstacle == tree: trees += 1 iterator += down print('Trees encountered for right ', right, ' down ', down, ' is ', trees) return trees first = how_many_trees(1, 1) second = how_many_trees(3, 1) third = how_many_trees(5, 1) fourth = how_many_trees(7, 1) fifth = how_many_trees(1, 2) final_result = first * second * third * fourth * fifth print('Multiplied trees', finalResult)
n = int(input()) d = [[0,0,0] for i in range(n + 1)] for i in range(1, n + 1): (r, g, b) = [int(i) for i in input().split()] d[i][0] = r + min(d[i - 1][1], d[i - 1][2]) d[i][1] = g + min(d[i - 1][0], d[i - 1][2]) d[i][2] = b + min(d[i - 1][0], d[i - 1][1]) print(min(d[n]))
n = int(input()) d = [[0, 0, 0] for i in range(n + 1)] for i in range(1, n + 1): (r, g, b) = [int(i) for i in input().split()] d[i][0] = r + min(d[i - 1][1], d[i - 1][2]) d[i][1] = g + min(d[i - 1][0], d[i - 1][2]) d[i][2] = b + min(d[i - 1][0], d[i - 1][1]) print(min(d[n]))
x = [1,2,3] def weird(num, default_ls=None): default_ls = default_ls or [] default_ls.append(num) print(default_ls) return default_ls weird(1) weird(2) weird(3) ls = list() ls = weird(99, ls) # [99] print(ls) weird(1000001, ls) # [99, 100001] [10000001] """ MacBook-Pro:random_python_stuff demouser$ python data_types.py [1] [1, 2] [1, 2, 3] """
x = [1, 2, 3] def weird(num, default_ls=None): default_ls = default_ls or [] default_ls.append(num) print(default_ls) return default_ls weird(1) weird(2) weird(3) ls = list() ls = weird(99, ls) print(ls) weird(1000001, ls) '\n\nMacBook-Pro:random_python_stuff demouser$ python data_types.py\n[1]\n[1, 2]\n[1, 2, 3]\n'
# Test passwords are randomly hashed def test_passwords_hashed_randomly(test_app, test_database, add_user): user_one = add_user( "test_user_one", "test_user_one@mail.com", "test_password" ) user_two = add_user( "test_user_two", "test_user_two@mail.com", "test_password" ) assert user_one.password != user_two.password assert user_one.password != "test_password" assert user_two.password != "test_password"
def test_passwords_hashed_randomly(test_app, test_database, add_user): user_one = add_user('test_user_one', 'test_user_one@mail.com', 'test_password') user_two = add_user('test_user_two', 'test_user_two@mail.com', 'test_password') assert user_one.password != user_two.password assert user_one.password != 'test_password' assert user_two.password != 'test_password'
def karatsuba(x: int, y: int) -> int: """Multiply two numbers using the Karatsuba algorithm Args: x (int): the first integer to be multiplied y (int): the second integer to be multiplied Returns: int: the result of the multiplication """ # Break the recursion written below if the numbers have less than 2 digits. if x < 10 or y < 10: return x * y # Get the maximum length of (x, y) and get it divided by half n = max(len(str(x)), len(str(y))) half = n // 2 # a,b,c,d are a result of x and y digits separated in half (i.e x = 1234 results in a = 12, x = 34) a = x // 10 ** half b = x % 10 ** half c = y // 10 ** half d = y % 10 ** half # Karatsuba formula is 10^n * ac + 10^(n/2) * (ad+bc) + bd # ac, bd and ad_plus_b are calculated recursively. ac = karatsuba(a, c) bd = karatsuba(b, d) ad_plus_bc = karatsuba(a+b, c+d) - ac - bd # Using half * 2 resolves the algorithm's issue with odd number of inputs return (10 ** (half * 2)) * ac + (10 ** half) * ad_plus_bc + bd
def karatsuba(x: int, y: int) -> int: """Multiply two numbers using the Karatsuba algorithm Args: x (int): the first integer to be multiplied y (int): the second integer to be multiplied Returns: int: the result of the multiplication """ if x < 10 or y < 10: return x * y n = max(len(str(x)), len(str(y))) half = n // 2 a = x // 10 ** half b = x % 10 ** half c = y // 10 ** half d = y % 10 ** half ac = karatsuba(a, c) bd = karatsuba(b, d) ad_plus_bc = karatsuba(a + b, c + d) - ac - bd return 10 ** (half * 2) * ac + 10 ** half * ad_plus_bc + bd
# Defination for mathematical operation def math(token_ip_stream,toko): if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and token_ip_stream[2][1] == "=" and token_ip_stream[3][1] == toko[0][0] and token_ip_stream[5][1] == toko[1][0] and token_ip_stream[6][0] == "STATEMENT_END" : if token_ip_stream[4][1] == "+": toko[2][1] = int(toko[0][1]) + int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "-": toko[2][1] = int(toko[0][1]) - int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "*": toko[2][1] = int(toko[0][1]) * int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "%": toko[2][1] = int(toko[0][1]) % int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "@": toko[2][1] = int(toko[0][1]) // int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "/": toko[2][1] = int(toko[0][1]) / int(toko[1][1]) toko[-1][0] = " " else : print("Syntax ERROR : you miss the operator or you have wrong syntax [Ex. ~ num1 = a + b .] or Statement MISSING : You miss the Statement end notation '.'") return (toko) # Defination for assignment operation def assignmentOpp(token_ip_stream): toko = [] token_chk = 1 for i in range(0 ,len(toko)): tokens_id=toko[i][0] tokens_val=toko[i][1] for token in range(0,len(token_ip_stream)): if token_ip_stream[token][1]== '=': toko.append([token_ip_stream[token-1][1],token_ip_stream[token +1][1]]) return (toko)
def math(token_ip_stream, toko): if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and (token_ip_stream[2][1] == '=') and (token_ip_stream[3][1] == toko[0][0]) and (token_ip_stream[5][1] == toko[1][0]) and (token_ip_stream[6][0] == 'STATEMENT_END'): if token_ip_stream[4][1] == '+': toko[2][1] = int(toko[0][1]) + int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '-': toko[2][1] = int(toko[0][1]) - int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '*': toko[2][1] = int(toko[0][1]) * int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '%': toko[2][1] = int(toko[0][1]) % int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '@': toko[2][1] = int(toko[0][1]) // int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '/': toko[2][1] = int(toko[0][1]) / int(toko[1][1]) toko[-1][0] = ' ' else: print("Syntax ERROR : you miss the operator or you have wrong syntax [Ex. ~ num1 = a + b .] or Statement MISSING : You miss the Statement end notation '.'") return toko def assignment_opp(token_ip_stream): toko = [] token_chk = 1 for i in range(0, len(toko)): tokens_id = toko[i][0] tokens_val = toko[i][1] for token in range(0, len(token_ip_stream)): if token_ip_stream[token][1] == '=': toko.append([token_ip_stream[token - 1][1], token_ip_stream[token + 1][1]]) return toko
# Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2. # First way is brute force def is_triplet(array): # Base case, if array is under 3 elements, not possible if len(array) < 3: return False # Iterate through first element options for i in range(len(array) - 2): for j in range(i + 1, len(array) - 1): for k in range(j, len(array)): A = array[i] * array[i] B = array[j] * array[j] C = array[k] * array[k] # generate all combinations if (A + B == C) or (A + C == B) or (B + C == A): print(array[i], array[j], array[k]) return True return False print(is_triplet([3, 1, 4, 6, 5])) # above is N^3 # Next idea - take square of every number # sort the array of squared numbers # set the last element to A # find B and C def is_triplet(array): if len(array) < 3: return False # Take square of all elements array = [A*A for A in array] # Sort the squared value array.sort() # Set the last element to be A (the largest) # A^2 = B^2 + C^2 for i in range(len(array) - 1, 1, -1): # Fix A, this is a squared A = array[i] # Start from index 0 up to A j = 0 k = len(array) - 1 # last index # Keep going until we cross while j < k: B = array[j] C = array[k] # Check for a triple if (A == C + B): print(A, B, C) return True # Check if we need the numbers to be bigger elif (A > C + B): j = j+ 1 else: k = k -1 return False # Driver program to test above function */ array = [3, 1, 4, 6, 5] print(is_triplet(array))
def is_triplet(array): if len(array) < 3: return False for i in range(len(array) - 2): for j in range(i + 1, len(array) - 1): for k in range(j, len(array)): a = array[i] * array[i] b = array[j] * array[j] c = array[k] * array[k] if A + B == C or A + C == B or B + C == A: print(array[i], array[j], array[k]) return True return False print(is_triplet([3, 1, 4, 6, 5])) def is_triplet(array): if len(array) < 3: return False array = [A * A for a in array] array.sort() for i in range(len(array) - 1, 1, -1): a = array[i] j = 0 k = len(array) - 1 while j < k: b = array[j] c = array[k] if A == C + B: print(A, B, C) return True elif A > C + B: j = j + 1 else: k = k - 1 return False array = [3, 1, 4, 6, 5] print(is_triplet(array))
climacell_yr_map = { "6201": "48", # heavy freezing rain "6001": "12", # freezing rain "6200": "47", # light freezing rain "6000": "47", # freeing drizzle "7101": "48", # heavy ice pellets "7000": "12", # ice pellets "7102": "47", # light ice pellets "5101": "50", # heavy snow "5000": "13", # snow "5100": "49", # light snow "5001": "49", # flurries "8000": "11", # thunderstorm "4201": "10", # heavy rain "4001": "09", # rain "4200": "46", # light rain "4000": "46", # drizzle "2100": "15", # light fog "2000": "15", # fog "1001": "04", # cloudy "1102": "03", # mostly cloudy "1101": "02", # partly cloudy "1100": "01", # mostly clear "1000": "01", # clear "0": "unknown_weather", # UNKNOWN "3000": "01", # light wind "3001": "01", # wind "3002": "01", # strong wind }
climacell_yr_map = {'6201': '48', '6001': '12', '6200': '47', '6000': '47', '7101': '48', '7000': '12', '7102': '47', '5101': '50', '5000': '13', '5100': '49', '5001': '49', '8000': '11', '4201': '10', '4001': '09', '4200': '46', '4000': '46', '2100': '15', '2000': '15', '1001': '04', '1102': '03', '1101': '02', '1100': '01', '1000': '01', '0': 'unknown_weather', '3000': '01', '3001': '01', '3002': '01'}
# -*- coding: utf-8 -*- """ Created on Mon Jan 22 14:49:25 2018 @author: User """ class Airlines(): def __init__(self, code, date, fare): self.code = code self.date = date self.fare = int(fare) def getDates(self): print( self.date) def getFares(self): return int(self.fare) def Description(self): desc_str = [self.code + ', ' + self.date + ', ' + str(self.fare)] print (desc_str) a = Airlines("airone", "11-12",100) b = Airlines("airtwo", "12-20", 99) a.Description() a.getDates() a.getFares() b.Description() b.getDates() b.getFares() def compFare(a, b): first = Airlines.getFares(a) second = Airlines.getFares(b) if int(first) < int(second): print('a is cheaper') else: print('b is cheaper') compFare(a,b)
""" Created on Mon Jan 22 14:49:25 2018 @author: User """ class Airlines: def __init__(self, code, date, fare): self.code = code self.date = date self.fare = int(fare) def get_dates(self): print(self.date) def get_fares(self): return int(self.fare) def description(self): desc_str = [self.code + ', ' + self.date + ', ' + str(self.fare)] print(desc_str) a = airlines('airone', '11-12', 100) b = airlines('airtwo', '12-20', 99) a.Description() a.getDates() a.getFares() b.Description() b.getDates() b.getFares() def comp_fare(a, b): first = Airlines.getFares(a) second = Airlines.getFares(b) if int(first) < int(second): print('a is cheaper') else: print('b is cheaper') comp_fare(a, b)
# read answer, context, question # generate vocabulary file for elmo batcher pre = ['dev', 'train'] fs = ['answer', 'context', 'question'] result = set() for p in pre: for f in fs: print ('Processing ' + p + '.' +f) with open('../../data/' + p + '.' + f) as ff: content = ff.readlines() for line in content: for token in line.split(): result.add(token) ff = open('../../data/elmo_voca.txt', 'w') max_length = 0 for item in result: if len(item) > max_length: max_length = len(item) ff.write(item + '\n') ff.write('</S>\n') ff.write('<S>\n') ff.write('<UNK>\n') ff.close() print ('max length of the token in the data:' + str(max_length))
pre = ['dev', 'train'] fs = ['answer', 'context', 'question'] result = set() for p in pre: for f in fs: print('Processing ' + p + '.' + f) with open('../../data/' + p + '.' + f) as ff: content = ff.readlines() for line in content: for token in line.split(): result.add(token) ff = open('../../data/elmo_voca.txt', 'w') max_length = 0 for item in result: if len(item) > max_length: max_length = len(item) ff.write(item + '\n') ff.write('</S>\n') ff.write('<S>\n') ff.write('<UNK>\n') ff.close() print('max length of the token in the data:' + str(max_length))
''' Insert 5 numbers in the right position without using .sort() Then show the list orderned ''' my_list = [] for c in range(0, 5): num = int(input('Type a number: ')) if c == 0 or num > my_list[-1]: my_list.append(num) print('Add this number at the end.') else: pos = 0 while pos < len(my_list): if num <= my_list[pos]: my_list.insert(pos, num) print(f'The number was added in the {pos} position') break pos +=1 print(my_list)
""" Insert 5 numbers in the right position without using .sort() Then show the list orderned """ my_list = [] for c in range(0, 5): num = int(input('Type a number: ')) if c == 0 or num > my_list[-1]: my_list.append(num) print('Add this number at the end.') else: pos = 0 while pos < len(my_list): if num <= my_list[pos]: my_list.insert(pos, num) print(f'The number was added in the {pos} position') break pos += 1 print(my_list)
# Wi-Fi Diagnostic Tree print(' Please reboot your computer and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Reboot your computer and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Make sure the cables between the router and modem are ' 'plugged in firmly.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Move the router to a new location and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Get a New router.')
print(' Please reboot your computer and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Reboot your computer and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Make sure the cables between the router and modem are plugged in firmly.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Move the router to a new location and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Get a New router.')
class Dictionary: def __init__(self): self.words = set() def check(self, word): return word.lower() in self.words def load(self, dictionary): file = open(dictionary, 'r') for line in file: self.words.add(line.rstrip('\n')) file.close() return True def size(self): return len(self.words) def unload(self): return True
class Dictionary: def __init__(self): self.words = set() def check(self, word): return word.lower() in self.words def load(self, dictionary): file = open(dictionary, 'r') for line in file: self.words.add(line.rstrip('\n')) file.close() return True def size(self): return len(self.words) def unload(self): return True
class Map: def __init__(self, x, y): self.wall = False self.small_dot = False self.big_dot = False self.eaten = False self.x = x self.y = y #--- drawing on map ---# def draw_dot(self): if self.small_dot: if not self.eaten: fill(255, 255, 0) noStroke() ellipse(self.x, self.y, 3, 3) elif self.big_dot: if not self.eaten: fill(255, 255, 0) noStroke() ellipse(self.x, self.y, 6, 6)
class Map: def __init__(self, x, y): self.wall = False self.small_dot = False self.big_dot = False self.eaten = False self.x = x self.y = y def draw_dot(self): if self.small_dot: if not self.eaten: fill(255, 255, 0) no_stroke() ellipse(self.x, self.y, 3, 3) elif self.big_dot: if not self.eaten: fill(255, 255, 0) no_stroke() ellipse(self.x, self.y, 6, 6)
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. ### CONTROLS (non-tunable) ### # general TYPE_OF_RUN = train # train, test, test_episodes, render LOAD_MODEL_FROM = None SAVE_MODELS_TO = models/debugging_wmg_dynamic_state_Collins2018_train10_test15.pth # worker.py ENV = Collins2018_Env ENV_RANDOM_SEED = 2 # Use an integer for deterministic training. AGENT_RANDOM_SEED = 1 REPORTING_INTERVAL = 5_000 TOTAL_STEPS = 10_000_000 ANNEAL_LR = False NUM_EPISODES_TO_TEST = 5 # A3cAgent AGENT_NET = WMG_State_Network # WMG V2 = False LAYER_TYPE = GTrXL-I # Collins2018_Env MIN_NUM_OBJECTS = 3 MAX_NUM_OBJECTS = 10 NUM_ACTIONS = 3 NUM_REPEATS = 13 MAX_OBSERVATIONS = 15 ONE_HOT_PATTERNS = False ALLOW_DELIBERATION = False USE_SUCCESS_RATE = False HELDOUT_TESTING = True HELDOUT_NUM_OBJECTS = 15 ### HYPERPARAMETERS (tunable) ### # A3cAgent A3C_T_MAX = 16 LEARNING_RATE = 0.00016 DISCOUNT_FACTOR = 0.5 GRADIENT_CLIP = 16.0 ENTROPY_TERM_STRENGTH = 0.01 ADAM_EPS = 1e-06 REWARD_SCALE = 2.0 WEIGHT_DECAY = 0. # WMG WMG_MAX_OBS = 0 WMG_MAX_MEMOS = 15 WMG_INIT_MEMOS = 3 WMG_MEMO_SIZE = 20 WMG_NUM_LAYERS = 1 WMG_NUM_ATTENTION_HEADS = 2 WMG_ATTENTION_HEAD_SIZE = 24 WMG_HIDDEN_SIZE = 24 AC_HIDDEN_LAYER_SIZE = 64
type_of_run = train load_model_from = None save_models_to = models / debugging_wmg_dynamic_state_Collins2018_train10_test15.pth env = Collins2018_Env env_random_seed = 2 agent_random_seed = 1 reporting_interval = 5000 total_steps = 10000000 anneal_lr = False num_episodes_to_test = 5 agent_net = WMG_State_Network v2 = False layer_type = GTrXL - I min_num_objects = 3 max_num_objects = 10 num_actions = 3 num_repeats = 13 max_observations = 15 one_hot_patterns = False allow_deliberation = False use_success_rate = False heldout_testing = True heldout_num_objects = 15 a3_c_t_max = 16 learning_rate = 0.00016 discount_factor = 0.5 gradient_clip = 16.0 entropy_term_strength = 0.01 adam_eps = 1e-06 reward_scale = 2.0 weight_decay = 0.0 wmg_max_obs = 0 wmg_max_memos = 15 wmg_init_memos = 3 wmg_memo_size = 20 wmg_num_layers = 1 wmg_num_attention_heads = 2 wmg_attention_head_size = 24 wmg_hidden_size = 24 ac_hidden_layer_size = 64
""" # Startup script Python script to set certain states at HA start and notify. This unifies various automations and HA scripts in a simpler one. """ SWITCH_EXPERT_MODE = 'input_boolean.show_expert_mode' # 'expert mode' for filtering groups and visibility control for ESP modules last_state = hass.states.get(SWITCH_EXPERT_MODE) expert_mode_on = data.get('expert_mode_state', last_state.state) hass.states.set(SWITCH_EXPERT_MODE, expert_mode_on, attributes=last_state.attributes) # Anyone at home? family_home = hass.states.get('group.family').state == 'home' # Turn on default outlets if family_home: hass.services.call( 'switch', 'turn_on', {"entity_id": "switch.camara,switch.caldera,switch.esp_plancha"}) # Sync HA dev trackers with manual HomeKit input_booleans dev_tracking = {'group.eugenio': 'input_boolean.eu_presence', 'group.mary': 'input_boolean.carmen_presence'} for group in dev_tracking: input_b = dev_tracking.get(group) b_in_home = hass.states.get(group).state == 'home' input_b_st = hass.states.get(input_b) input_b_in_home = input_b_st.state == 'on' if input_b_in_home != b_in_home: logger.warning('SYNC error %s: dev_tracker=%s, HomeKit=%s', group.lstrip('group.'), b_in_home, input_b_in_home) hass.states.set(input_b, "on" if b_in_home else "off", attributes=input_b_st.attributes) # Notify HA init with iOS hass.services.call( 'notify', 'ios_iphone', {"title": "Home-assistant started", "message": "Hass is now ready for you", "data": {"push": {"badge": 5, "sound": "US-EN-Morgan-Freeman-Welcome-Home.wav", "category": "CONFIRM"}}})
""" # Startup script Python script to set certain states at HA start and notify. This unifies various automations and HA scripts in a simpler one. """ switch_expert_mode = 'input_boolean.show_expert_mode' last_state = hass.states.get(SWITCH_EXPERT_MODE) expert_mode_on = data.get('expert_mode_state', last_state.state) hass.states.set(SWITCH_EXPERT_MODE, expert_mode_on, attributes=last_state.attributes) family_home = hass.states.get('group.family').state == 'home' if family_home: hass.services.call('switch', 'turn_on', {'entity_id': 'switch.camara,switch.caldera,switch.esp_plancha'}) dev_tracking = {'group.eugenio': 'input_boolean.eu_presence', 'group.mary': 'input_boolean.carmen_presence'} for group in dev_tracking: input_b = dev_tracking.get(group) b_in_home = hass.states.get(group).state == 'home' input_b_st = hass.states.get(input_b) input_b_in_home = input_b_st.state == 'on' if input_b_in_home != b_in_home: logger.warning('SYNC error %s: dev_tracker=%s, HomeKit=%s', group.lstrip('group.'), b_in_home, input_b_in_home) hass.states.set(input_b, 'on' if b_in_home else 'off', attributes=input_b_st.attributes) hass.services.call('notify', 'ios_iphone', {'title': 'Home-assistant started', 'message': 'Hass is now ready for you', 'data': {'push': {'badge': 5, 'sound': 'US-EN-Morgan-Freeman-Welcome-Home.wav', 'category': 'CONFIRM'}}})
class B: pass class A: pass
class B: pass class A: pass
# ############################### # Truthiness of an element: # ############################### def print_truthiness(msg, exp): print(("TRUE" if exp else "FALSE") + " <-- " + msg) print_truthiness("Testing True", True) print_truthiness("Testing False", False) # for sequences seq = [] print_truthiness("Empty list", seq) seq.append("The cat") print_truthiness("1 item list", seq) # for objects and numbers print_truthiness("Zero", 0) print_truthiness("Eleven", 11) print_truthiness("-Eleven", -11) # for None print_truthiness("For none", None) # custom types class AClass: def __init__(self): self.data = [] def add(self, item): self.data.append(item) def __bool__(self): """ Magic method that evaluates the implicit truthiness of an instance of this class. :return: the implicit truth value """ return True if self.data else False a = AClass() print_truthiness("Empty AClass", a) a.add("Thing") print_truthiness("nonempty AClass", a)
def print_truthiness(msg, exp): print(('TRUE' if exp else 'FALSE') + ' <-- ' + msg) print_truthiness('Testing True', True) print_truthiness('Testing False', False) seq = [] print_truthiness('Empty list', seq) seq.append('The cat') print_truthiness('1 item list', seq) print_truthiness('Zero', 0) print_truthiness('Eleven', 11) print_truthiness('-Eleven', -11) print_truthiness('For none', None) class Aclass: def __init__(self): self.data = [] def add(self, item): self.data.append(item) def __bool__(self): """ Magic method that evaluates the implicit truthiness of an instance of this class. :return: the implicit truth value """ return True if self.data else False a = a_class() print_truthiness('Empty AClass', a) a.add('Thing') print_truthiness('nonempty AClass', a)
class Solution: def maxScore(self, cards, k): pre = [0] for card in cards: pre.append(pre[-1] + card) ans = 0 n = len(pre) for i in range(k + 1): ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans) return ans
class Solution: def max_score(self, cards, k): pre = [0] for card in cards: pre.append(pre[-1] + card) ans = 0 n = len(pre) for i in range(k + 1): ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans) return ans
def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday): #assert len(books) == len(L) score = 0. d = 0 for l in L: d += L_signuptimes[l] number_of_books = (D - d) * L_shipperday[l] score += sum(books[l][:number_of_books]) return score
def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday): score = 0.0 d = 0 for l in L: d += L_signuptimes[l] number_of_books = (D - d) * L_shipperday[l] score += sum(books[l][:number_of_books]) return score
MESSAGE_PRIORITY = ( (-2, 'Stumm'), (-1, 'Ruhig'), (0, 'Normal'), (1, 'Wichtig'), (2, 'Emergency'), )
message_priority = ((-2, 'Stumm'), (-1, 'Ruhig'), (0, 'Normal'), (1, 'Wichtig'), (2, 'Emergency'))
class AsyncClass: async def do_coroutine(self): """A documented coroutine function""" attr_coro_result = await _other_coro_func() # NOQA async def _other_coro_func(): return "run"
class Asyncclass: async def do_coroutine(self): """A documented coroutine function""" attr_coro_result = await _other_coro_func() async def _other_coro_func(): return 'run'
class ProcessError(Exception): """Exception raised when a process exits with a non-zero exit code.""" def __init__(self, message): self.message = message
class Processerror(Exception): """Exception raised when a process exits with a non-zero exit code.""" def __init__(self, message): self.message = message
# Copyright 2016 Savoir-faire Linux # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Web No Bubble", "version": "14.0.1.0.0", "author": "Savoir-faire Linux, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/web", "license": "AGPL-3", "category": "Web", "summary": "Remove the bubbles from the web interface", "depends": ["web"], "data": ["views/web_no_bubble.xml"], "installable": True, "application": False, }
{'name': 'Web No Bubble', 'version': '14.0.1.0.0', 'author': 'Savoir-faire Linux, Odoo Community Association (OCA)', 'website': 'https://github.com/OCA/web', 'license': 'AGPL-3', 'category': 'Web', 'summary': 'Remove the bubbles from the web interface', 'depends': ['web'], 'data': ['views/web_no_bubble.xml'], 'installable': True, 'application': False}
# https://adventofcode.com/2019/day/5 # # --- Day 2: 1202 Program Alarm --- # # --- Day 5: Sunny with a Chance of Asteroids --- # def loadintCode(fname='input'): with open(fname, 'r') as f: l = list(f.read().split(',')) p = [int(x) for x in l] return p def printIndexValue(L, pos=0): longest = len(str(max(L))) print("[",end='') for idx, val in enumerate(L): print("{:{width}d},".format(val, width=longest+1),end='') print("]") indices = list(range(len(L))) indices[pos] = "^"*(longest+1) print("(",end='') for idx in indices: print("{:^{width}s},".format(str(idx), width=longest+1),end='') print(")") def ADD(vals): if len(vals) != 2: raise TypeError a,b = vals return a+b def MUL(vals): if len(vals) != 2: raise TypeError a,b = vals return a*b def INP(vals, sim=None): if sim is not None: print("simulate input value: {}".format(sim)) return sim else: print("Enter input: ") sim = int(input()) return sim def OUT(vals): if len(vals) != 1: raise TypeError print("Output is: {}".format(vals[0])) def JPT(vals): if vals[0] != 0: return True else: return False def JPF(vals): if vals[0] == 0: return True else: return False def LES(vals): if vals[0] < vals[1]: return 1 else: return 0 def EQL(vals): if vals[0] == vals[1]: return 1 else: return 0 def END(): #print("END") return "END" instrSet = { # code: (FUNCTION, #ofParams, Outputs, jumps) 1: (ADD, 3, True, False), 2: (MUL, 3, True, False), 3: (INP, 1, True, False), 4: (OUT, 1, False, False), 5: (JPT, 2, False, True), 6: (JPF, 2, False, True), 7: (LES, 3, True, False), 8: (EQL, 3, True, False), 99: (END, 0, False, True) } def decode(val): if val in instrSet.keys(): # valid op code return instrSet[val] else: return None def runCode(intInput, debug=False): ignore = 0 idx = 0 #for idx, val in enumerate(intInput): while(idx <= len(intInput)): val = intInput[idx] if ignore > 0: ignore -= 1 idx += 1 continue if debug: printIndexValue(intInput, idx) cmd = val%100 op, numVar, writes, jumps = decode(cmd) if op == END: op() return intInput modes = val//100 mod= [] while (modes > 0): tmp = modes%10 if tmp not in [0, 1]: raise TypeError mod.append(tmp) modes = modes//10 # now run op(vars) vars = [] for i in range(numVar): try: m = mod[i] except IndexError: m = 0 if m == 0: vars.append(intInput[intInput[idx+1+i]]) elif m == 1: vars.append(intInput[idx+1+i]) else: raise RuntimeError if writes: # an opcode that writes to last parameter intInput[intInput[idx+numVar]] = op(vars[:-1]) elif jumps: print("JUMP") if op(vars[:-1]): idx = vars[-1] continue else: op(vars) ignore = numVar idx += 1 def runIntcode(intInput, debug=False): ignore = 0 for idx, val in enumerate(intInput): if ignore > 0: ignore -= 1 continue #print("index is %d and value is %s" % (idx, val)) #print("Index: {}".format(idx)) #print(intInput) if debug: print("") if debug: printIndexValue(intInput, idx) #readOpCode(val) if val == 1: if debug: print("add({}, {}, {})".format(intInput[idx+1], intInput[idx+2], intInput[idx+3])) if debug: print("L[{}] = {} + {} = {}".format(intInput[idx+3], intInput[intInput[idx+1]], intInput[intInput[idx+2]], intInput[intInput[idx+1]] + intInput[intInput[idx+2]])) intInput[intInput[idx+3]] = intInput[intInput[idx+1]] + intInput[intInput[idx+2]] ignore = 3 elif val == 2: if debug: print("mul({}, {}, {})".format(intInput[idx+1], intInput[idx+2], intInput[idx+3])) if debug: print("L[{}] = {} * {} = {}".format(intInput[idx+3], intInput[intInput[idx+1]], intInput[intInput[idx+2]], intInput[intInput[idx+1]] * intInput[intInput[idx+2]])) intInput[intInput[idx+3]] = intInput[intInput[idx+1]] * intInput[intInput[idx+2]] ignore = 3 elif val == 99: if debug: print("break") return(intInput) def runDay2PartOne(): intInput2 = [1,1,1,4,99,5,6,0,99] runCode(intInput2) intCode = loadintCode('input_day2') print(intCode) intCode[1] = 12 intCode[2] = 2 print(intCode) print("**************************************************") runCode(intCode) print("result should be:") print([30,1,1,4,2,5,6,0,99]) def runDay2PartTwo(): for noun in range(100): for verb in range(100): print("noun: {:3d} verb: {:3d}".format(noun, verb), end='') intCode = loadintCode('input_day2') intCode[1] = noun intCode[2] = verb result = runIntcode(intCode, False) print(" {}".format(result[0])) if result[0] == 19690720: return 100*noun + verb def runPartOne(): print(runCode([1002,4,3,4,33])) runCode([3,0,4,0,99]) intCode = loadintCode('input') runCode(intCode, debug=False) if __name__ == '__main__': #runDay2PartOne() #runDay2PartTwo() runPartOne()
def loadint_code(fname='input'): with open(fname, 'r') as f: l = list(f.read().split(',')) p = [int(x) for x in l] return p def print_index_value(L, pos=0): longest = len(str(max(L))) print('[', end='') for (idx, val) in enumerate(L): print('{:{width}d},'.format(val, width=longest + 1), end='') print(']') indices = list(range(len(L))) indices[pos] = '^' * (longest + 1) print('(', end='') for idx in indices: print('{:^{width}s},'.format(str(idx), width=longest + 1), end='') print(')') def add(vals): if len(vals) != 2: raise TypeError (a, b) = vals return a + b def mul(vals): if len(vals) != 2: raise TypeError (a, b) = vals return a * b def inp(vals, sim=None): if sim is not None: print('simulate input value: {}'.format(sim)) return sim else: print('Enter input: ') sim = int(input()) return sim def out(vals): if len(vals) != 1: raise TypeError print('Output is: {}'.format(vals[0])) def jpt(vals): if vals[0] != 0: return True else: return False def jpf(vals): if vals[0] == 0: return True else: return False def les(vals): if vals[0] < vals[1]: return 1 else: return 0 def eql(vals): if vals[0] == vals[1]: return 1 else: return 0 def end(): return 'END' instr_set = {1: (ADD, 3, True, False), 2: (MUL, 3, True, False), 3: (INP, 1, True, False), 4: (OUT, 1, False, False), 5: (JPT, 2, False, True), 6: (JPF, 2, False, True), 7: (LES, 3, True, False), 8: (EQL, 3, True, False), 99: (END, 0, False, True)} def decode(val): if val in instrSet.keys(): return instrSet[val] else: return None def run_code(intInput, debug=False): ignore = 0 idx = 0 while idx <= len(intInput): val = intInput[idx] if ignore > 0: ignore -= 1 idx += 1 continue if debug: print_index_value(intInput, idx) cmd = val % 100 (op, num_var, writes, jumps) = decode(cmd) if op == END: op() return intInput modes = val // 100 mod = [] while modes > 0: tmp = modes % 10 if tmp not in [0, 1]: raise TypeError mod.append(tmp) modes = modes // 10 vars = [] for i in range(numVar): try: m = mod[i] except IndexError: m = 0 if m == 0: vars.append(intInput[intInput[idx + 1 + i]]) elif m == 1: vars.append(intInput[idx + 1 + i]) else: raise RuntimeError if writes: intInput[intInput[idx + numVar]] = op(vars[:-1]) elif jumps: print('JUMP') if op(vars[:-1]): idx = vars[-1] continue else: op(vars) ignore = numVar idx += 1 def run_intcode(intInput, debug=False): ignore = 0 for (idx, val) in enumerate(intInput): if ignore > 0: ignore -= 1 continue if debug: print('') if debug: print_index_value(intInput, idx) if val == 1: if debug: print('add({}, {}, {})'.format(intInput[idx + 1], intInput[idx + 2], intInput[idx + 3])) if debug: print('L[{}] = {} + {} = {}'.format(intInput[idx + 3], intInput[intInput[idx + 1]], intInput[intInput[idx + 2]], intInput[intInput[idx + 1]] + intInput[intInput[idx + 2]])) intInput[intInput[idx + 3]] = intInput[intInput[idx + 1]] + intInput[intInput[idx + 2]] ignore = 3 elif val == 2: if debug: print('mul({}, {}, {})'.format(intInput[idx + 1], intInput[idx + 2], intInput[idx + 3])) if debug: print('L[{}] = {} * {} = {}'.format(intInput[idx + 3], intInput[intInput[idx + 1]], intInput[intInput[idx + 2]], intInput[intInput[idx + 1]] * intInput[intInput[idx + 2]])) intInput[intInput[idx + 3]] = intInput[intInput[idx + 1]] * intInput[intInput[idx + 2]] ignore = 3 elif val == 99: if debug: print('break') return intInput def run_day2_part_one(): int_input2 = [1, 1, 1, 4, 99, 5, 6, 0, 99] run_code(intInput2) int_code = loadint_code('input_day2') print(intCode) intCode[1] = 12 intCode[2] = 2 print(intCode) print('**************************************************') run_code(intCode) print('result should be:') print([30, 1, 1, 4, 2, 5, 6, 0, 99]) def run_day2_part_two(): for noun in range(100): for verb in range(100): print('noun: {:3d} verb: {:3d}'.format(noun, verb), end='') int_code = loadint_code('input_day2') intCode[1] = noun intCode[2] = verb result = run_intcode(intCode, False) print(' {}'.format(result[0])) if result[0] == 19690720: return 100 * noun + verb def run_part_one(): print(run_code([1002, 4, 3, 4, 33])) run_code([3, 0, 4, 0, 99]) int_code = loadint_code('input') run_code(intCode, debug=False) if __name__ == '__main__': run_part_one()
class Phone(object): def __init__(self, phone_number): phone_number = [char for char in phone_number if char.isdigit()] if phone_number[:1] == ['1']: phone_number = phone_number[1:] if len(phone_number) != 10: raise ValueError("Insufficient Digits") if (int(phone_number[0]) > 1) and (int(phone_number[3]) > 1): self.number = "".join(phone_number) else: raise ValueError("Typo on a telephone") @property def area_code(self): return self.number[:3] def pretty(self): number = self.number return f"({number[:3]}) {number[3:6]}-{number[6:]}"
class Phone(object): def __init__(self, phone_number): phone_number = [char for char in phone_number if char.isdigit()] if phone_number[:1] == ['1']: phone_number = phone_number[1:] if len(phone_number) != 10: raise value_error('Insufficient Digits') if int(phone_number[0]) > 1 and int(phone_number[3]) > 1: self.number = ''.join(phone_number) else: raise value_error('Typo on a telephone') @property def area_code(self): return self.number[:3] def pretty(self): number = self.number return f'({number[:3]}) {number[3:6]}-{number[6:]}'
# -*- coding: utf-8 -*- __title__ = u'django-flexisettings' # semantic versioning, check http://semver.org/ __version__ = u'0.3.1' __author__ = u'Stefan Berder <stefan.berder@ledapei.com>' __copyright__ = u'Copyright 2012-2013, Heatwave fashion Ltd., ' \ u'all rights reserved'
__title__ = u'django-flexisettings' __version__ = u'0.3.1' __author__ = u'Stefan Berder <stefan.berder@ledapei.com>' __copyright__ = u'Copyright 2012-2013, Heatwave fashion Ltd., all rights reserved'
def solution(p): answer = p + 1 while(not isBeautifulYear(answer)): answer += 1 return answer def isBeautifulYear(year): years = list(map(int, str(year))) return len(set([x for x in years])) == len(years) print(solution(1987))
def solution(p): answer = p + 1 while not is_beautiful_year(answer): answer += 1 return answer def is_beautiful_year(year): years = list(map(int, str(year))) return len(set([x for x in years])) == len(years) print(solution(1987))
def split_and_add(numbers, n): temp=[] count=0 while count<n: for i in range(0,len(numbers)//2): temp.append(numbers[0]) numbers.pop(0) if not temp: return numbers if len(temp)<len(numbers): for i in range(0,len(temp)): numbers[i+1]+=temp[i] elif len(temp)==len(numbers): for i in range(0,len(temp)): numbers[i]+=temp[i] temp=[] count+=1 return numbers
def split_and_add(numbers, n): temp = [] count = 0 while count < n: for i in range(0, len(numbers) // 2): temp.append(numbers[0]) numbers.pop(0) if not temp: return numbers if len(temp) < len(numbers): for i in range(0, len(temp)): numbers[i + 1] += temp[i] elif len(temp) == len(numbers): for i in range(0, len(temp)): numbers[i] += temp[i] temp = [] count += 1 return numbers
if __name__ == "__main__": with open("file.txt", "r", encoding="utf-8") as f: a = f.readlines() for i in a: if "," in i: print(i)
if __name__ == '__main__': with open('file.txt', 'r', encoding='utf-8') as f: a = f.readlines() for i in a: if ',' in i: print(i)
description='HRPT Graphit Filter via SPS-S5' devices = dict( graphit=device('nicos_sinq.amor.devices.sps_switch.SpsSwitch', description='Graphit filter controlled by SPS', epicstimeout=3.0, readpv='SQ:HRPT:SPS1:DigitalInput', commandpv='SQ:HRPT:SPS1:Push', commandstr="S0001", byte=4, bit=4, mapping={'OFF': False, 'ON': True}, lowlevel=True ), sps1=device( 'nicos_ess.devices.epics.extensions.EpicsCommandReply', epicstimeout=3.0, description='Controller of the counter box', commandpv='SQ:HRPT:spsdirect.AOUT', replypv='SQ:HRPT:spsdirect.AINP', ), )
description = 'HRPT Graphit Filter via SPS-S5' devices = dict(graphit=device('nicos_sinq.amor.devices.sps_switch.SpsSwitch', description='Graphit filter controlled by SPS', epicstimeout=3.0, readpv='SQ:HRPT:SPS1:DigitalInput', commandpv='SQ:HRPT:SPS1:Push', commandstr='S0001', byte=4, bit=4, mapping={'OFF': False, 'ON': True}, lowlevel=True), sps1=device('nicos_ess.devices.epics.extensions.EpicsCommandReply', epicstimeout=3.0, description='Controller of the counter box', commandpv='SQ:HRPT:spsdirect.AOUT', replypv='SQ:HRPT:spsdirect.AINP'))
""" Notes: This is more "find maximum profit" rather than finding best times to buy and sell stock. """ class Solution: def max_profit(self, prices: [int]) -> int: profit = 0 for stock in range(len(prices)-1): if prices[stock+1] > prices[stock]: profit += prices[stock+1] - prices[stock] return profit test = Solution() prices = [1, 3, 5, 2, 10, 2, 1] print("max_profit():", test.max_profit(prices)) """ max_profit(): 12 """ """ Time complexity: O(n). We traverse the list containing "n" elements only once. Space complexity: O(1). Constant space is used. """
""" Notes: This is more "find maximum profit" rather than finding best times to buy and sell stock. """ class Solution: def max_profit(self, prices: [int]) -> int: profit = 0 for stock in range(len(prices) - 1): if prices[stock + 1] > prices[stock]: profit += prices[stock + 1] - prices[stock] return profit test = solution() prices = [1, 3, 5, 2, 10, 2, 1] print('max_profit():', test.max_profit(prices)) '\nmax_profit(): 12\n' '\nTime complexity: O(n). We traverse the list containing "n" elements only once.\nSpace complexity: O(1). Constant space is used.\n'
# BUILD FILE SYNTAX: SKYLARK SE_VERSION = '3.11.0'
se_version = '3.11.0'
def main(filepath): rows = [] #file load with open(filepath) as file: for line in file: rows.append(line) counter = 0 counter2 = 0 for entry in rows: entry = entry.split(" ") letter = entry[1][0] entry[0] = entry[0].split("-") low = entry[0][0] high = entry[0][1] internalcount = 0 for char in entry[2]: if char == letter: internalcount+=1 if internalcount >= int(low) and internalcount <= int(high): counter+=1 if (entry[2][int(low)-1] == letter) and not entry[2][int(high)-1] == letter: counter2+=1 if not entry[2][int(low)-1] == letter and entry[2][int(high)-1] == letter: counter2+=1 print("Part a solution: "+ str(counter)) print("Part b solution: "+ str(counter2)) return
def main(filepath): rows = [] with open(filepath) as file: for line in file: rows.append(line) counter = 0 counter2 = 0 for entry in rows: entry = entry.split(' ') letter = entry[1][0] entry[0] = entry[0].split('-') low = entry[0][0] high = entry[0][1] internalcount = 0 for char in entry[2]: if char == letter: internalcount += 1 if internalcount >= int(low) and internalcount <= int(high): counter += 1 if entry[2][int(low) - 1] == letter and (not entry[2][int(high) - 1] == letter): counter2 += 1 if not entry[2][int(low) - 1] == letter and entry[2][int(high) - 1] == letter: counter2 += 1 print('Part a solution: ' + str(counter)) print('Part b solution: ' + str(counter2)) return
class Solution: def maxSumSubmatrix(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ if not any(matrix): return 0 m, n = len(matrix), len(matrix[0]) res = float('-inf') for left in range(n): curcums = [0] * m right = left while right < n: for i in range(m): curcums[i] += matrix[i][right] curarrmax = self.maxSubArrayLessK(curcums, k) res = max(res, curarrmax) right += 1 return res def maxSubArrayLessK(self, nums, k): cumset = [0] maxsum = float('-inf') cursum = 0 for i in range(len(nums)): cursum += nums[i] idx = bisect.bisect_left(cumset, cursum - k) if 0 <= idx < len(cumset): maxsum = max(maxsum, cursum - cumset[idx]) bisect.insort(cumset, cursum) return maxsum
class Solution: def max_sum_submatrix(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ if not any(matrix): return 0 (m, n) = (len(matrix), len(matrix[0])) res = float('-inf') for left in range(n): curcums = [0] * m right = left while right < n: for i in range(m): curcums[i] += matrix[i][right] curarrmax = self.maxSubArrayLessK(curcums, k) res = max(res, curarrmax) right += 1 return res def max_sub_array_less_k(self, nums, k): cumset = [0] maxsum = float('-inf') cursum = 0 for i in range(len(nums)): cursum += nums[i] idx = bisect.bisect_left(cumset, cursum - k) if 0 <= idx < len(cumset): maxsum = max(maxsum, cursum - cumset[idx]) bisect.insort(cumset, cursum) return maxsum
# coding: utf-8 """***************************************************************************** * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************""" ################################################################################################### ########################################## Callbacks ############################################# ################################################################################################### def onAttachmentConnected(source, target): global sercomSym_OperationMode localComponent = source["component"] remoteComponent = target["component"] remoteID = remoteComponent.getID() connectID = source["id"] targetID = target["id"] if connectID == uartCapabilityId: localComponent.setCapabilityEnabled(uartCapabilityId, True) localComponent.setCapabilityEnabled(spiCapabilityId, False) localComponent.setCapabilityEnabled(i2cCapabilityId, False) sercomSym_OperationMode.setSelectedKey("USART_INT", 2) elif connectID == spiCapabilityId: localComponent.setCapabilityEnabled(uartCapabilityId, False) localComponent.setCapabilityEnabled(spiCapabilityId, True) localComponent.setCapabilityEnabled(i2cCapabilityId, False) sercomSym_OperationMode.setSelectedKey("SPIM", 2) elif connectID == i2cCapabilityId: localComponent.setCapabilityEnabled(uartCapabilityId, False) localComponent.setCapabilityEnabled(spiCapabilityId, False) localComponent.setCapabilityEnabled(i2cCapabilityId, True) sercomSym_OperationMode.setSelectedKey("I2CM", 2) sercomSym_OperationMode.setReadOnly(True) def onAttachmentDisconnected(source, target): global sercomSym_OperationMode localComponent = source["component"] remoteComponent = target["component"] remoteID = remoteComponent.getID() connectID = source["id"] targetID = target["id"] localComponent.setCapabilityEnabled(uartCapabilityId, True) localComponent.setCapabilityEnabled(spiCapabilityId, True) localComponent.setCapabilityEnabled(i2cCapabilityId, True) sercomSym_OperationMode.setReadOnly(False) def updateSERCOMCodeGenerationProperty(symbol, event): symObj = event["symbol"] component = symbol.getComponent() component.getSymbolByID("SERCOM_USART_HEADER").setEnabled(False) component.getSymbolByID("SERCOM_USART_SOURCE").setEnabled(False) component.getSymbolByID("SERCOM_USART_COMMON_HEADER").setEnabled(False) component.getSymbolByID("SERCOM_SPIM_SOURCE").setEnabled(False) component.getSymbolByID("SERCOM_SPIM_HEADER").setEnabled(False) component.getSymbolByID("SERCOM_SPIM_COMMON_HEADER").setEnabled(False) component.getSymbolByID("SERCOM_I2CM_SOURCE").setEnabled(False) component.getSymbolByID("SERCOM_I2CM_HEADER").setEnabled(False) component.getSymbolByID("SERCOM_I2CM_MASTER_HEADER").setEnabled(False) if symObj.getSelectedKey() == "USART_INT": component.getSymbolByID("SERCOM_USART_HEADER").setEnabled(True) component.getSymbolByID("SERCOM_USART_SOURCE").setEnabled(True) component.getSymbolByID("SERCOM_USART_COMMON_HEADER").setEnabled(True) elif symObj.getSelectedKey() == "SPIM": component.getSymbolByID("SERCOM_SPIM_SOURCE").setEnabled(True) component.getSymbolByID("SERCOM_SPIM_HEADER").setEnabled(True) component.getSymbolByID("SERCOM_SPIM_COMMON_HEADER").setEnabled(True) elif symObj.getSelectedKey() == "I2CM": component.getSymbolByID("SERCOM_I2CM_SOURCE").setEnabled(True) component.getSymbolByID("SERCOM_I2CM_HEADER").setEnabled(True) component.getSymbolByID("SERCOM_I2CM_MASTER_HEADER").setEnabled(True) elif symObj.getSelectedKey() == "I2CS": # To be implemented pass elif symObj.getSelectedKey() == "SPIS": # To be implemented pass elif symObj.getSelectedKey() == "USART_EXT": # To be implemented pass def setSERCOMInterruptData(status, sercomMode): for id in InterruptVector: Database.setSymbolValue("core", id, status, 1) for id in InterruptHandlerLock: Database.setSymbolValue("core", id, status, 1) for id in InterruptHandler: interruptName = id.split("_INTERRUPT_HANDLER")[0] if status == True: Database.setSymbolValue("core", id, sercomInstanceName.getValue() + "_" + sercomMode + "_InterruptHandler", 1) else: Database.setSymbolValue("core", id, interruptName + "_Handler", 1) def updateSERCOMInterruptData(symbol, event): global i2cSym_Interrupt_Mode global spiSym_Interrupt_Mode global usartSym_Interrupt_Mode global sercomSym_OperationMode global sercomSym_IntEnComment sercomMode = "" status = False sercomUSARTMode = (sercomSym_OperationMode.getSelectedKey() == "USART_INT") and (usartSym_Interrupt_Mode.getValue() == True) sercomSPIMode = (sercomSym_OperationMode.getSelectedKey() == "SPIM") and (spiSym_Interrupt_Mode.getValue() == True) sercomI2CMode = (sercomSym_OperationMode.getSelectedKey() == "I2CM") and (i2cSym_Interrupt_Mode.getValue() == True) if event["id"] == "SERCOM_MODE": if sercomSym_OperationMode.getSelectedKey() == "I2CS": # To be implemented pass elif sercomSym_OperationMode.getSelectedKey() == "SPIS": # To be implemented pass elif sercomSym_OperationMode.getSelectedKey() == "USART_EXT": # To be implemented pass else: sercomInterruptStatus = False if sercomUSARTMode == True: sercomMode = "USART" sercomInterruptStatus = True elif sercomSPIMode == True: sercomMode = "SPI" sercomInterruptStatus = True elif sercomI2CMode == True: sercomMode = "I2C" sercomInterruptStatus = True setSERCOMInterruptData(sercomInterruptStatus, sercomMode) elif "INTERRUPT_MODE" in event["id"]: if sercomSym_OperationMode.getSelectedKey() == "USART_INT": sercomMode = "USART" elif sercomSym_OperationMode.getSelectedKey() == "SPIM": sercomMode = "SPI" elif sercomSym_OperationMode.getSelectedKey() == "I2CM": sercomMode = "I2C" setSERCOMInterruptData(event["value"], sercomMode) for id in InterruptVectorUpdate: id = id.replace("core.", "") if Database.getSymbolValue("core", id) == True: status = True break if (sercomUSARTMode == True or sercomSPIMode == True or sercomI2CMode == True) and status == True: symbol.setVisible(True) else: symbol.setVisible(False) def updateSERCOMClockWarningStatus(symbol, event): symbol.setVisible(not event["value"]) def updateSERCOMDMATransferRegister(symbol, event): symObj = event["symbol"] if symObj.getSelectedKey() == "USART_INT": symbol.setValue("&(" + sercomInstanceName.getValue() + "_REGS->USART_INT.SERCOM_DATA)", 2) elif symObj.getSelectedKey() == "SPIM": symbol.setValue("&(" + sercomInstanceName.getValue() + "_REGS->SPIM.SERCOM_DATA)", 2) elif symObj.getSelectedKey() == "I2CS": # To be implemented pass elif symObj.getSelectedKey() == "SPIS": # To be implemented pass elif symObj.getSelectedKey() == "USART_EXT": # To be implemented pass else: symbol.setValue("", 1) ################################################################################################### ########################################## Component ############################################# ################################################################################################### def instantiateComponent(sercomComponent): global uartCapabilityId global spiCapabilityId global i2cCapabilityId global InterruptVector global InterruptHandler global InterruptHandlerLock global InterruptVectorUpdate global sercomInstanceName global sercomSym_OperationMode global sercomClkFrequencyId InterruptVector = [] InterruptHandler = [] InterruptHandlerLock = [] InterruptVectorUpdate = [] sercomInstanceName = sercomComponent.createStringSymbol("SERCOM_INSTANCE_NAME", None) sercomInstanceName.setVisible(False) sercomInstanceName.setDefaultValue(sercomComponent.getID().upper()) Log.writeInfoMessage("Running " + sercomInstanceName.getValue()) uartCapabilityId = sercomInstanceName.getValue() + "_UART" spiCapabilityId = sercomInstanceName.getValue() + "_SPI" i2cCapabilityId = sercomInstanceName.getValue() + "_I2C" sercomClkFrequencyId = sercomInstanceName.getValue() + "_CORE_CLOCK_FREQUENCY" #Clock enable Database.setSymbolValue("core", sercomInstanceName.getValue() + "_CORE_CLOCK_ENABLE", True, 2) #SERCOM operation mode Menu - Serial Communication Interfaces sercomSym_OperationMode = sercomComponent.createKeyValueSetSymbol("SERCOM_MODE", None) sercomSym_OperationMode.setLabel("Select SERCOM Operation Mode") sercomSym_OperationMode.addKey("USART_INT", "1", "USART with internal Clock") sercomSym_OperationMode.addKey("SPIM", "3", "SPI Master") sercomSym_OperationMode.addKey("I2CM", "5", "I2C Master") sercomSym_OperationMode.setDefaultValue(0) sercomSym_OperationMode.setOutputMode("Key") sercomSym_OperationMode.setDisplayMode("Description") #SERCOM code generation dependecy based on selected mode sercomSym_CodeGeneration = sercomComponent.createBooleanSymbol("SERCOM_CODE_GENERATION", sercomSym_OperationMode) sercomSym_CodeGeneration.setVisible(False) sercomSym_CodeGeneration.setDependencies(updateSERCOMCodeGenerationProperty, ["SERCOM_MODE"]) #SERCOM Transmit data register sercomSym_TxRegister = sercomComponent.createStringSymbol("TRANSMIT_DATA_REGISTER", sercomSym_OperationMode) sercomSym_TxRegister.setDefaultValue("&(" + sercomInstanceName.getValue() + "_REGS->USART_INT.SERCOM_DATA)") sercomSym_TxRegister.setVisible(False) sercomSym_TxRegister.setDependencies(updateSERCOMDMATransferRegister, ["SERCOM_MODE"]) #SERCOM Receive data register sercomSym_RxRegister = sercomComponent.createStringSymbol("RECEIVE_DATA_REGISTER", sercomSym_OperationMode) sercomSym_RxRegister.setDefaultValue("&(" + sercomInstanceName.getValue() + "_REGS->USART_INT.SERCOM_DATA)") sercomSym_RxRegister.setVisible(False) sercomSym_RxRegister.setDependencies(updateSERCOMDMATransferRegister, ["SERCOM_MODE"]) syncbusyNode = ATDF.getNode('/avr-tools-device-file/modules/module@[name="SERCOM"]/register-group@[name="SERCOM"]/register@[modes="USART_INT",name="SYNCBUSY"]') #SERCOM is SYNCBUSY present sercomSym_SYNCBUSY = sercomComponent.createBooleanSymbol("SERCOM_SYNCBUSY", sercomSym_OperationMode) sercomSym_SYNCBUSY.setVisible(False) sercomSym_SYNCBUSY.setDefaultValue((syncbusyNode != None)) ################################################################################################### ########################################## SERCOM MODE ############################################ ################################################################################################### execfile(Variables.get("__CORE_DIR") + "/../peripheral/sercom_u2201/config/sercom_usart.py") execfile(Variables.get("__CORE_DIR") + "/../peripheral/sercom_u2201/config/sercom_spi_master.py") execfile(Variables.get("__CORE_DIR") + "/../peripheral/sercom_u2201/config/sercom_i2c_master.py") ############################################################################ #### Dependency #### ############################################################################ interruptValues = ATDF.getNode("/avr-tools-device-file/devices/device/interrupts").getChildren() for index in range(len(interruptValues)): moduleInstance = list(str(interruptValues[index].getAttribute("module-instance")).split(" ")) if sercomInstanceName.getValue() in moduleInstance: # check weather sub-vectors or multiple peripherals are present at same interrupt line if len(moduleInstance) == 1: name = str(interruptValues[index].getAttribute("name")) else: name = sercomInstanceName.getValue() InterruptVector.append(name + "_INTERRUPT_ENABLE") InterruptHandler.append(name + "_INTERRUPT_HANDLER") InterruptHandlerLock.append(name + "_INTERRUPT_HANDLER_LOCK") InterruptVectorUpdate.append("core." + name + "_INTERRUPT_ENABLE_UPDATE") # Initial settings for Interrupt setSERCOMInterruptData(True, "USART") # Interrupt Warning status sercomSym_IntEnComment = sercomComponent.createCommentSymbol("SERCOM_INTERRUPT_ENABLE_COMMENT", None) sercomSym_IntEnComment.setVisible(False) sercomSym_IntEnComment.setLabel("Warning!!! " + sercomInstanceName.getValue() + " Interrupt is Disabled in Interrupt Manager") sercomSym_IntEnComment.setDependencies(updateSERCOMInterruptData, ["SERCOM_MODE", "USART_INTERRUPT_MODE", "SPI_INTERRUPT_MODE"] + InterruptVectorUpdate) # Clock Warning status sercomSym_ClkEnComment = sercomComponent.createCommentSymbol("SERCOM_CLOCK_ENABLE_COMMENT", None) sercomSym_ClkEnComment.setLabel("Warning!!! " + sercomInstanceName.getValue() + " Peripheral Clock is Disabled in Clock Manager") sercomSym_ClkEnComment.setVisible(False) sercomSym_ClkEnComment.setDependencies(updateSERCOMClockWarningStatus, ["core." + sercomInstanceName.getValue() + "_CORE_CLOCK_ENABLE"]) ################################################################################################### ####################################### Code Generation ########################################## ################################################################################################### configName = Variables.get("__CONFIGURATION_NAME") usartHeaderFile = sercomComponent.createFileSymbol("SERCOM_USART_HEADER", None) usartHeaderFile.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_usart.h.ftl") usartHeaderFile.setOutputName("plib_" + sercomInstanceName.getValue().lower() + "_usart.h") usartHeaderFile.setDestPath("/peripheral/sercom/usart/") usartHeaderFile.setProjectPath("config/" + configName + "/peripheral/sercom/usart/") usartHeaderFile.setType("HEADER") usartHeaderFile.setMarkup(True) usartHeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == "USART_INT") usartCommonHeaderFile = sercomComponent.createFileSymbol("SERCOM_USART_COMMON_HEADER", None) usartCommonHeaderFile.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_usart_common.h") usartCommonHeaderFile.setOutputName("plib_sercom_usart_common.h") usartCommonHeaderFile.setDestPath("/peripheral/sercom/usart/") usartCommonHeaderFile.setProjectPath("config/" + configName + "/peripheral/sercom/usart/") usartCommonHeaderFile.setType("HEADER") usartCommonHeaderFile.setMarkup(True) usartCommonHeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == "USART_INT") usartSourceFile = sercomComponent.createFileSymbol("SERCOM_USART_SOURCE", None) usartSourceFile.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_usart.c.ftl") usartSourceFile.setOutputName("plib_" + sercomInstanceName.getValue().lower() + "_usart.c") usartSourceFile.setDestPath("/peripheral/sercom/usart/") usartSourceFile.setProjectPath("config/" + configName + "/peripheral/sercom/usart/") usartSourceFile.setType("SOURCE") usartSourceFile.setMarkup(True) usartSourceFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == "USART_INT") spiSym_HeaderFile = sercomComponent.createFileSymbol("SERCOM_SPIM_HEADER", None) spiSym_HeaderFile.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_spi.h.ftl") spiSym_HeaderFile.setOutputName("plib_" + sercomInstanceName.getValue().lower() + "_spi.h") spiSym_HeaderFile.setDestPath("/peripheral/sercom/spim/") spiSym_HeaderFile.setProjectPath("config/" + configName + "/peripheral/sercom/spim/") spiSym_HeaderFile.setType("HEADER") spiSym_HeaderFile.setMarkup(True) spiSym_HeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == "SPIM") spiSym_Header1File = sercomComponent.createFileSymbol("SERCOM_SPIM_COMMON_HEADER", None) spiSym_Header1File.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_spi_common.h") spiSym_Header1File.setOutputName("plib_sercom_spi_common.h") spiSym_Header1File.setDestPath("/peripheral/sercom/spim/") spiSym_Header1File.setProjectPath("config/" + configName + "/peripheral/sercom/spim/") spiSym_Header1File.setType("HEADER") spiSym_Header1File.setMarkup(True) spiSym_Header1File.setEnabled(sercomSym_OperationMode.getSelectedKey() == "SPIM") spiSym_SourceFile = sercomComponent.createFileSymbol("SERCOM_SPIM_SOURCE", None) spiSym_SourceFile.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_spi.c.ftl") spiSym_SourceFile.setOutputName("plib_" + sercomInstanceName.getValue().lower() + "_spi.c") spiSym_SourceFile.setDestPath("/peripheral/sercom/spim/") spiSym_SourceFile.setProjectPath("config/" + configName + "/peripheral/sercom/spim/") spiSym_SourceFile.setType("SOURCE") spiSym_SourceFile.setMarkup(True) spiSym_SourceFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == "SPIM") i2cmMasterHeaderFile = sercomComponent.createFileSymbol("SERCOM_I2CM_MASTER_HEADER", None) i2cmMasterHeaderFile.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_i2c_master.h") i2cmMasterHeaderFile.setOutputName("plib_sercom_i2c_master.h") i2cmMasterHeaderFile.setDestPath("/peripheral/sercom/i2cm/") i2cmMasterHeaderFile.setProjectPath("config/" + configName + "/peripheral/sercom/i2cm/") i2cmMasterHeaderFile.setType("HEADER") i2cmMasterHeaderFile.setMarkup(True) i2cmMasterHeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == "I2CM") i2cmHeaderFile = sercomComponent.createFileSymbol("SERCOM_I2CM_HEADER", None) i2cmHeaderFile.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_i2c.h.ftl") i2cmHeaderFile.setOutputName("plib_" + sercomInstanceName.getValue().lower() + "_i2c.h") i2cmHeaderFile.setDestPath("/peripheral/sercom/i2cm/") i2cmHeaderFile.setProjectPath("config/" + configName + "/peripheral/sercom/i2cm/") i2cmHeaderFile.setType("HEADER") i2cmHeaderFile.setMarkup(True) i2cmHeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == "I2CM") i2cmSourceFile = sercomComponent.createFileSymbol("SERCOM_I2CM_SOURCE", None) i2cmSourceFile.setSourcePath("../peripheral/sercom_u2201/templates/plib_sercom_i2c.c.ftl") i2cmSourceFile.setOutputName("plib_" + sercomInstanceName.getValue().lower() + "_i2c.c") i2cmSourceFile.setDestPath("/peripheral/sercom/i2cm/") i2cmSourceFile.setProjectPath("config/" + configName + "/peripheral/sercom/i2cm/") i2cmSourceFile.setType("SOURCE") i2cmSourceFile.setMarkup(True) i2cmSourceFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == "I2CM") sercomSystemInitFile = sercomComponent.createFileSymbol("SERCOM_SYS_INIT", None) sercomSystemInitFile.setType("STRING") sercomSystemInitFile.setOutputName("core.LIST_SYSTEM_INIT_C_SYS_INITIALIZE_PERIPHERALS") sercomSystemInitFile.setSourcePath("../peripheral/sercom_u2201/templates/system/initialization.c.ftl") sercomSystemInitFile.setMarkup(True) sercomSystemDefFile = sercomComponent.createFileSymbol("SERCOM_SYS_DEF", None) sercomSystemDefFile.setType("STRING") sercomSystemDefFile.setOutputName("core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES") sercomSystemDefFile.setSourcePath("../peripheral/sercom_u2201/templates/system/definitions.h.ftl") sercomSystemDefFile.setMarkup(True)
"""***************************************************************************** * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************""" def on_attachment_connected(source, target): global sercomSym_OperationMode local_component = source['component'] remote_component = target['component'] remote_id = remoteComponent.getID() connect_id = source['id'] target_id = target['id'] if connectID == uartCapabilityId: localComponent.setCapabilityEnabled(uartCapabilityId, True) localComponent.setCapabilityEnabled(spiCapabilityId, False) localComponent.setCapabilityEnabled(i2cCapabilityId, False) sercomSym_OperationMode.setSelectedKey('USART_INT', 2) elif connectID == spiCapabilityId: localComponent.setCapabilityEnabled(uartCapabilityId, False) localComponent.setCapabilityEnabled(spiCapabilityId, True) localComponent.setCapabilityEnabled(i2cCapabilityId, False) sercomSym_OperationMode.setSelectedKey('SPIM', 2) elif connectID == i2cCapabilityId: localComponent.setCapabilityEnabled(uartCapabilityId, False) localComponent.setCapabilityEnabled(spiCapabilityId, False) localComponent.setCapabilityEnabled(i2cCapabilityId, True) sercomSym_OperationMode.setSelectedKey('I2CM', 2) sercomSym_OperationMode.setReadOnly(True) def on_attachment_disconnected(source, target): global sercomSym_OperationMode local_component = source['component'] remote_component = target['component'] remote_id = remoteComponent.getID() connect_id = source['id'] target_id = target['id'] localComponent.setCapabilityEnabled(uartCapabilityId, True) localComponent.setCapabilityEnabled(spiCapabilityId, True) localComponent.setCapabilityEnabled(i2cCapabilityId, True) sercomSym_OperationMode.setReadOnly(False) def update_sercom_code_generation_property(symbol, event): sym_obj = event['symbol'] component = symbol.getComponent() component.getSymbolByID('SERCOM_USART_HEADER').setEnabled(False) component.getSymbolByID('SERCOM_USART_SOURCE').setEnabled(False) component.getSymbolByID('SERCOM_USART_COMMON_HEADER').setEnabled(False) component.getSymbolByID('SERCOM_SPIM_SOURCE').setEnabled(False) component.getSymbolByID('SERCOM_SPIM_HEADER').setEnabled(False) component.getSymbolByID('SERCOM_SPIM_COMMON_HEADER').setEnabled(False) component.getSymbolByID('SERCOM_I2CM_SOURCE').setEnabled(False) component.getSymbolByID('SERCOM_I2CM_HEADER').setEnabled(False) component.getSymbolByID('SERCOM_I2CM_MASTER_HEADER').setEnabled(False) if symObj.getSelectedKey() == 'USART_INT': component.getSymbolByID('SERCOM_USART_HEADER').setEnabled(True) component.getSymbolByID('SERCOM_USART_SOURCE').setEnabled(True) component.getSymbolByID('SERCOM_USART_COMMON_HEADER').setEnabled(True) elif symObj.getSelectedKey() == 'SPIM': component.getSymbolByID('SERCOM_SPIM_SOURCE').setEnabled(True) component.getSymbolByID('SERCOM_SPIM_HEADER').setEnabled(True) component.getSymbolByID('SERCOM_SPIM_COMMON_HEADER').setEnabled(True) elif symObj.getSelectedKey() == 'I2CM': component.getSymbolByID('SERCOM_I2CM_SOURCE').setEnabled(True) component.getSymbolByID('SERCOM_I2CM_HEADER').setEnabled(True) component.getSymbolByID('SERCOM_I2CM_MASTER_HEADER').setEnabled(True) elif symObj.getSelectedKey() == 'I2CS': pass elif symObj.getSelectedKey() == 'SPIS': pass elif symObj.getSelectedKey() == 'USART_EXT': pass def set_sercom_interrupt_data(status, sercomMode): for id in InterruptVector: Database.setSymbolValue('core', id, status, 1) for id in InterruptHandlerLock: Database.setSymbolValue('core', id, status, 1) for id in InterruptHandler: interrupt_name = id.split('_INTERRUPT_HANDLER')[0] if status == True: Database.setSymbolValue('core', id, sercomInstanceName.getValue() + '_' + sercomMode + '_InterruptHandler', 1) else: Database.setSymbolValue('core', id, interruptName + '_Handler', 1) def update_sercom_interrupt_data(symbol, event): global i2cSym_Interrupt_Mode global spiSym_Interrupt_Mode global usartSym_Interrupt_Mode global sercomSym_OperationMode global sercomSym_IntEnComment sercom_mode = '' status = False sercom_usart_mode = sercomSym_OperationMode.getSelectedKey() == 'USART_INT' and usartSym_Interrupt_Mode.getValue() == True sercom_spi_mode = sercomSym_OperationMode.getSelectedKey() == 'SPIM' and spiSym_Interrupt_Mode.getValue() == True sercom_i2_c_mode = sercomSym_OperationMode.getSelectedKey() == 'I2CM' and i2cSym_Interrupt_Mode.getValue() == True if event['id'] == 'SERCOM_MODE': if sercomSym_OperationMode.getSelectedKey() == 'I2CS': pass elif sercomSym_OperationMode.getSelectedKey() == 'SPIS': pass elif sercomSym_OperationMode.getSelectedKey() == 'USART_EXT': pass else: sercom_interrupt_status = False if sercomUSARTMode == True: sercom_mode = 'USART' sercom_interrupt_status = True elif sercomSPIMode == True: sercom_mode = 'SPI' sercom_interrupt_status = True elif sercomI2CMode == True: sercom_mode = 'I2C' sercom_interrupt_status = True set_sercom_interrupt_data(sercomInterruptStatus, sercomMode) elif 'INTERRUPT_MODE' in event['id']: if sercomSym_OperationMode.getSelectedKey() == 'USART_INT': sercom_mode = 'USART' elif sercomSym_OperationMode.getSelectedKey() == 'SPIM': sercom_mode = 'SPI' elif sercomSym_OperationMode.getSelectedKey() == 'I2CM': sercom_mode = 'I2C' set_sercom_interrupt_data(event['value'], sercomMode) for id in InterruptVectorUpdate: id = id.replace('core.', '') if Database.getSymbolValue('core', id) == True: status = True break if (sercomUSARTMode == True or sercomSPIMode == True or sercomI2CMode == True) and status == True: symbol.setVisible(True) else: symbol.setVisible(False) def update_sercom_clock_warning_status(symbol, event): symbol.setVisible(not event['value']) def update_sercomdma_transfer_register(symbol, event): sym_obj = event['symbol'] if symObj.getSelectedKey() == 'USART_INT': symbol.setValue('&(' + sercomInstanceName.getValue() + '_REGS->USART_INT.SERCOM_DATA)', 2) elif symObj.getSelectedKey() == 'SPIM': symbol.setValue('&(' + sercomInstanceName.getValue() + '_REGS->SPIM.SERCOM_DATA)', 2) elif symObj.getSelectedKey() == 'I2CS': pass elif symObj.getSelectedKey() == 'SPIS': pass elif symObj.getSelectedKey() == 'USART_EXT': pass else: symbol.setValue('', 1) def instantiate_component(sercomComponent): global uartCapabilityId global spiCapabilityId global i2cCapabilityId global InterruptVector global InterruptHandler global InterruptHandlerLock global InterruptVectorUpdate global sercomInstanceName global sercomSym_OperationMode global sercomClkFrequencyId interrupt_vector = [] interrupt_handler = [] interrupt_handler_lock = [] interrupt_vector_update = [] sercom_instance_name = sercomComponent.createStringSymbol('SERCOM_INSTANCE_NAME', None) sercomInstanceName.setVisible(False) sercomInstanceName.setDefaultValue(sercomComponent.getID().upper()) Log.writeInfoMessage('Running ' + sercomInstanceName.getValue()) uart_capability_id = sercomInstanceName.getValue() + '_UART' spi_capability_id = sercomInstanceName.getValue() + '_SPI' i2c_capability_id = sercomInstanceName.getValue() + '_I2C' sercom_clk_frequency_id = sercomInstanceName.getValue() + '_CORE_CLOCK_FREQUENCY' Database.setSymbolValue('core', sercomInstanceName.getValue() + '_CORE_CLOCK_ENABLE', True, 2) sercom_sym__operation_mode = sercomComponent.createKeyValueSetSymbol('SERCOM_MODE', None) sercomSym_OperationMode.setLabel('Select SERCOM Operation Mode') sercomSym_OperationMode.addKey('USART_INT', '1', 'USART with internal Clock') sercomSym_OperationMode.addKey('SPIM', '3', 'SPI Master') sercomSym_OperationMode.addKey('I2CM', '5', 'I2C Master') sercomSym_OperationMode.setDefaultValue(0) sercomSym_OperationMode.setOutputMode('Key') sercomSym_OperationMode.setDisplayMode('Description') sercom_sym__code_generation = sercomComponent.createBooleanSymbol('SERCOM_CODE_GENERATION', sercomSym_OperationMode) sercomSym_CodeGeneration.setVisible(False) sercomSym_CodeGeneration.setDependencies(updateSERCOMCodeGenerationProperty, ['SERCOM_MODE']) sercom_sym__tx_register = sercomComponent.createStringSymbol('TRANSMIT_DATA_REGISTER', sercomSym_OperationMode) sercomSym_TxRegister.setDefaultValue('&(' + sercomInstanceName.getValue() + '_REGS->USART_INT.SERCOM_DATA)') sercomSym_TxRegister.setVisible(False) sercomSym_TxRegister.setDependencies(updateSERCOMDMATransferRegister, ['SERCOM_MODE']) sercom_sym__rx_register = sercomComponent.createStringSymbol('RECEIVE_DATA_REGISTER', sercomSym_OperationMode) sercomSym_RxRegister.setDefaultValue('&(' + sercomInstanceName.getValue() + '_REGS->USART_INT.SERCOM_DATA)') sercomSym_RxRegister.setVisible(False) sercomSym_RxRegister.setDependencies(updateSERCOMDMATransferRegister, ['SERCOM_MODE']) syncbusy_node = ATDF.getNode('/avr-tools-device-file/modules/module@[name="SERCOM"]/register-group@[name="SERCOM"]/register@[modes="USART_INT",name="SYNCBUSY"]') sercom_sym_syncbusy = sercomComponent.createBooleanSymbol('SERCOM_SYNCBUSY', sercomSym_OperationMode) sercomSym_SYNCBUSY.setVisible(False) sercomSym_SYNCBUSY.setDefaultValue(syncbusyNode != None) execfile(Variables.get('__CORE_DIR') + '/../peripheral/sercom_u2201/config/sercom_usart.py') execfile(Variables.get('__CORE_DIR') + '/../peripheral/sercom_u2201/config/sercom_spi_master.py') execfile(Variables.get('__CORE_DIR') + '/../peripheral/sercom_u2201/config/sercom_i2c_master.py') interrupt_values = ATDF.getNode('/avr-tools-device-file/devices/device/interrupts').getChildren() for index in range(len(interruptValues)): module_instance = list(str(interruptValues[index].getAttribute('module-instance')).split(' ')) if sercomInstanceName.getValue() in moduleInstance: if len(moduleInstance) == 1: name = str(interruptValues[index].getAttribute('name')) else: name = sercomInstanceName.getValue() InterruptVector.append(name + '_INTERRUPT_ENABLE') InterruptHandler.append(name + '_INTERRUPT_HANDLER') InterruptHandlerLock.append(name + '_INTERRUPT_HANDLER_LOCK') InterruptVectorUpdate.append('core.' + name + '_INTERRUPT_ENABLE_UPDATE') set_sercom_interrupt_data(True, 'USART') sercom_sym__int_en_comment = sercomComponent.createCommentSymbol('SERCOM_INTERRUPT_ENABLE_COMMENT', None) sercomSym_IntEnComment.setVisible(False) sercomSym_IntEnComment.setLabel('Warning!!! ' + sercomInstanceName.getValue() + ' Interrupt is Disabled in Interrupt Manager') sercomSym_IntEnComment.setDependencies(updateSERCOMInterruptData, ['SERCOM_MODE', 'USART_INTERRUPT_MODE', 'SPI_INTERRUPT_MODE'] + InterruptVectorUpdate) sercom_sym__clk_en_comment = sercomComponent.createCommentSymbol('SERCOM_CLOCK_ENABLE_COMMENT', None) sercomSym_ClkEnComment.setLabel('Warning!!! ' + sercomInstanceName.getValue() + ' Peripheral Clock is Disabled in Clock Manager') sercomSym_ClkEnComment.setVisible(False) sercomSym_ClkEnComment.setDependencies(updateSERCOMClockWarningStatus, ['core.' + sercomInstanceName.getValue() + '_CORE_CLOCK_ENABLE']) config_name = Variables.get('__CONFIGURATION_NAME') usart_header_file = sercomComponent.createFileSymbol('SERCOM_USART_HEADER', None) usartHeaderFile.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_usart.h.ftl') usartHeaderFile.setOutputName('plib_' + sercomInstanceName.getValue().lower() + '_usart.h') usartHeaderFile.setDestPath('/peripheral/sercom/usart/') usartHeaderFile.setProjectPath('config/' + configName + '/peripheral/sercom/usart/') usartHeaderFile.setType('HEADER') usartHeaderFile.setMarkup(True) usartHeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'USART_INT') usart_common_header_file = sercomComponent.createFileSymbol('SERCOM_USART_COMMON_HEADER', None) usartCommonHeaderFile.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_usart_common.h') usartCommonHeaderFile.setOutputName('plib_sercom_usart_common.h') usartCommonHeaderFile.setDestPath('/peripheral/sercom/usart/') usartCommonHeaderFile.setProjectPath('config/' + configName + '/peripheral/sercom/usart/') usartCommonHeaderFile.setType('HEADER') usartCommonHeaderFile.setMarkup(True) usartCommonHeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'USART_INT') usart_source_file = sercomComponent.createFileSymbol('SERCOM_USART_SOURCE', None) usartSourceFile.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_usart.c.ftl') usartSourceFile.setOutputName('plib_' + sercomInstanceName.getValue().lower() + '_usart.c') usartSourceFile.setDestPath('/peripheral/sercom/usart/') usartSourceFile.setProjectPath('config/' + configName + '/peripheral/sercom/usart/') usartSourceFile.setType('SOURCE') usartSourceFile.setMarkup(True) usartSourceFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'USART_INT') spi_sym__header_file = sercomComponent.createFileSymbol('SERCOM_SPIM_HEADER', None) spiSym_HeaderFile.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_spi.h.ftl') spiSym_HeaderFile.setOutputName('plib_' + sercomInstanceName.getValue().lower() + '_spi.h') spiSym_HeaderFile.setDestPath('/peripheral/sercom/spim/') spiSym_HeaderFile.setProjectPath('config/' + configName + '/peripheral/sercom/spim/') spiSym_HeaderFile.setType('HEADER') spiSym_HeaderFile.setMarkup(True) spiSym_HeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'SPIM') spi_sym__header1_file = sercomComponent.createFileSymbol('SERCOM_SPIM_COMMON_HEADER', None) spiSym_Header1File.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_spi_common.h') spiSym_Header1File.setOutputName('plib_sercom_spi_common.h') spiSym_Header1File.setDestPath('/peripheral/sercom/spim/') spiSym_Header1File.setProjectPath('config/' + configName + '/peripheral/sercom/spim/') spiSym_Header1File.setType('HEADER') spiSym_Header1File.setMarkup(True) spiSym_Header1File.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'SPIM') spi_sym__source_file = sercomComponent.createFileSymbol('SERCOM_SPIM_SOURCE', None) spiSym_SourceFile.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_spi.c.ftl') spiSym_SourceFile.setOutputName('plib_' + sercomInstanceName.getValue().lower() + '_spi.c') spiSym_SourceFile.setDestPath('/peripheral/sercom/spim/') spiSym_SourceFile.setProjectPath('config/' + configName + '/peripheral/sercom/spim/') spiSym_SourceFile.setType('SOURCE') spiSym_SourceFile.setMarkup(True) spiSym_SourceFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'SPIM') i2cm_master_header_file = sercomComponent.createFileSymbol('SERCOM_I2CM_MASTER_HEADER', None) i2cmMasterHeaderFile.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_i2c_master.h') i2cmMasterHeaderFile.setOutputName('plib_sercom_i2c_master.h') i2cmMasterHeaderFile.setDestPath('/peripheral/sercom/i2cm/') i2cmMasterHeaderFile.setProjectPath('config/' + configName + '/peripheral/sercom/i2cm/') i2cmMasterHeaderFile.setType('HEADER') i2cmMasterHeaderFile.setMarkup(True) i2cmMasterHeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'I2CM') i2cm_header_file = sercomComponent.createFileSymbol('SERCOM_I2CM_HEADER', None) i2cmHeaderFile.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_i2c.h.ftl') i2cmHeaderFile.setOutputName('plib_' + sercomInstanceName.getValue().lower() + '_i2c.h') i2cmHeaderFile.setDestPath('/peripheral/sercom/i2cm/') i2cmHeaderFile.setProjectPath('config/' + configName + '/peripheral/sercom/i2cm/') i2cmHeaderFile.setType('HEADER') i2cmHeaderFile.setMarkup(True) i2cmHeaderFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'I2CM') i2cm_source_file = sercomComponent.createFileSymbol('SERCOM_I2CM_SOURCE', None) i2cmSourceFile.setSourcePath('../peripheral/sercom_u2201/templates/plib_sercom_i2c.c.ftl') i2cmSourceFile.setOutputName('plib_' + sercomInstanceName.getValue().lower() + '_i2c.c') i2cmSourceFile.setDestPath('/peripheral/sercom/i2cm/') i2cmSourceFile.setProjectPath('config/' + configName + '/peripheral/sercom/i2cm/') i2cmSourceFile.setType('SOURCE') i2cmSourceFile.setMarkup(True) i2cmSourceFile.setEnabled(sercomSym_OperationMode.getSelectedKey() == 'I2CM') sercom_system_init_file = sercomComponent.createFileSymbol('SERCOM_SYS_INIT', None) sercomSystemInitFile.setType('STRING') sercomSystemInitFile.setOutputName('core.LIST_SYSTEM_INIT_C_SYS_INITIALIZE_PERIPHERALS') sercomSystemInitFile.setSourcePath('../peripheral/sercom_u2201/templates/system/initialization.c.ftl') sercomSystemInitFile.setMarkup(True) sercom_system_def_file = sercomComponent.createFileSymbol('SERCOM_SYS_DEF', None) sercomSystemDefFile.setType('STRING') sercomSystemDefFile.setOutputName('core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES') sercomSystemDefFile.setSourcePath('../peripheral/sercom_u2201/templates/system/definitions.h.ftl') sercomSystemDefFile.setMarkup(True)
x = range(1, 5, 9) for n in x: print(n)
x = range(1, 5, 9) for n in x: print(n)
class StudySeries(object): def __init__(self, study_object, study_data=None): ''' Takes study object ''' assert hasattr(study_object, "__call__"), "invalid study object" self.study = study_object if study_data: self.update(study_data) def update(self, study_data, nLimit): self.series = [] dtlist = [dt for dt in study_data[:nLimit] if study_data[dt]] dtlist.sort(Reverse=True) for dt in dtlist: val = self.study(study_data[dt]) self.series.append((dt, val)) return self.series class ExpMA(object): def __init__(self, n, seed=None): self.length_ = n self.factor = 2. / (float(n) + 1.) self.value_ = seed def __call__(self, observation): if self.value_ is None: self.value_ = observation else: prv = self.value_ self.value_ = (observation - prv) * self.factor + prv return self.value_
class Studyseries(object): def __init__(self, study_object, study_data=None): """ Takes study object """ assert hasattr(study_object, '__call__'), 'invalid study object' self.study = study_object if study_data: self.update(study_data) def update(self, study_data, nLimit): self.series = [] dtlist = [dt for dt in study_data[:nLimit] if study_data[dt]] dtlist.sort(Reverse=True) for dt in dtlist: val = self.study(study_data[dt]) self.series.append((dt, val)) return self.series class Expma(object): def __init__(self, n, seed=None): self.length_ = n self.factor = 2.0 / (float(n) + 1.0) self.value_ = seed def __call__(self, observation): if self.value_ is None: self.value_ = observation else: prv = self.value_ self.value_ = (observation - prv) * self.factor + prv return self.value_
TRPOconfig = { 'cg_damping': 1e-3, 'GAE_lambda': 0., 'reward_decay': 0.98, 'max_kl_divergence': 2e-5, 'hidden_layers': [256, 256, 256], 'hidden_layers_v': [256, 256, 256], 'max_grad_norm': None, 'value_lr': 5e-4, 'train_v_iters': 20, 'lr_pi': 5e-4, 'steps_per_iter': 3200, 'value_func_type': 'FC', } TRPOconfig['memory_size'] = TRPOconfig['steps_per_iter']
trp_oconfig = {'cg_damping': 0.001, 'GAE_lambda': 0.0, 'reward_decay': 0.98, 'max_kl_divergence': 2e-05, 'hidden_layers': [256, 256, 256], 'hidden_layers_v': [256, 256, 256], 'max_grad_norm': None, 'value_lr': 0.0005, 'train_v_iters': 20, 'lr_pi': 0.0005, 'steps_per_iter': 3200, 'value_func_type': 'FC'} TRPOconfig['memory_size'] = TRPOconfig['steps_per_iter']
transverse_run5 = [ 6165044, 6165046, 6165047, 6165055, 6165058, 6165059, 6165063, 6166051, 6166052, 6166054, 6166055, 6166056, 6166057, 6166059, 6166060, 6166061, 6166070, 6166071, 6166073, 6166074, 6166075, 6166076, 6166090, 6166091, #6166101, ## no relative luminosities 6167079, 6167083, 6167088 ] ## transverse runs from IUCF cache transverse_run6_iucf = [ 7098001, 7098002, 7098004, 7098006, 7098007, 7098024, 7098025, 7098027, 7098028, 7098029, 7098038, 7098039, 7098040, 7098041, 7098053, 7098065, 7098066, 7098067, 7098072, 7098073, 7098082, 7098083, 7099003, 7099006, 7099014, 7099025, 7099026, 7099027, 7099030, 7099033, 7099047, 7100052, 7100058, 7100062, 7100064, 7100072, 7100075, 7100077 ] transverse_run6 = [ #7097009, ## no scalars #7097010, ## no scalars #7097014, ## no scalars #7097017, ## no scalars #7097018, ## no scalars #7097019, ## no scalars #7097020, ## no scalars #7097021, ## no scalars #7097024, ## no scalars #7097025, ## no scalars #7097026, ## no scalars #7097027, ## no scalars #7097032, ## no scalars #7097050, ## no scalars #7097051, ## no scalars #7097053, ## no scalars #7097056, ## no scalars 7097093, 7097094, #7097095, ## no scalars 7097096, 7097097, 7097099, 7097102, 7097103, 7097104, 7097105, #7098001, ## no scalars 7098002, 7098004, 7098006, 7098007, 7098008, #7098014, ## no scalars 7098015, 7098018, 7098024, 7098025, ## board 6 scalars 7098027, 7098028, 7098029, 7098031, 7098032, 7098033, 7098034, 7098036, 7098038, 7098039, 7098040, 7098041, 7098053, 7098055, ## board 6 scalars 7098061, 7098062, 7098064, ## board 6 scalars 7098065, 7098066, 7098067, 7098072, #7098073, ## no scalars 7098074, 7098075, 7098079, #7098080, ## no scalars 7098081, 7098082, 7098083, #7099003, ## murad rejected 7099006, #7099014, ## murad rejected #7099015, ## murad rejected #7099021, ## no scalars 7099022, #7099024, ## murad rejected 7099025, 7099026, 7099027, 7099030, ## board 6 scalars 7099031, 7099033, 7099034, 7099035, 7099036, #7099045, ## no scalars #7099046, ## no scalars #7099047, ## no scalars 7100014, 7100016, #7100028, ## no scalars 7100031, #7100052, ## murad rejected #7100058, ## murad rejected #7100062, ## no scalars #7100064, ## murad rejected #7100067, ## no scalars 7100068, #7100070, ## no scalars 7100071, 7100072, 7100075, #7100076, ## no scalars 7100077, #7100078, ## no scalars #7101013, ## murad rejected #7101015, ## no scalars 7101019, 7101023, 7101025, #7101039, ## no scalars 7101041, 7101042, ## board 6 scalars 7101046, 7101050, 7101052, 7101054, 7101075, 7101078, 7101082, 7101085, 7101086, 7103006, 7103007, 7103008, 7103013, 7103014, #7103016, ## no scalars 7103017, 7103018, 7103024, 7103026, 7103027, 7103030, 7103040, 7103072, 7103073, 7103075, 7103080, 7103082, 7103086, #7103088, ## no scalars 7103089, 7103090, 7103093, 7103095, 7103099, 7104014, 7104016, 7115085, 7115086, 7115087, 7115088, 7115095, 7115097, 7115099, 7115101, 7115103, 7115106, 7115111, 7115113, ## board 6 scalars 7115114, ## board 6 scalars 7115115, 7115116, 7115117, 7115121, 7115124, 7115125, 7115126, 7115134, #7116050, ## murad rejected 7116052, 7116057, 7116059, 7117002, 7117008, 7117009, 7117010, 7117011, 7117015, 7117016, 7117017, 7117027, 7117050, 7117056, 7117057, 7117058, 7117060, 7117063, 7117064, #7117067, ## no scalars 7117071, 7118002, 7118003, 7118004, 7118008, 7118009, 7118010, #7118014, ## murad rejected 7118016, 7118017, #7118024, ## murad rejected 7118032, 7118033, 7118035, 7118038, 7118039, 7118041, #7118042, ## no scalars 7118044, 7118045, 7118048, 7118049, 7118050, 7118051, 7118053, 7118073, ## board 6 scalars 7118075, 7118077, 7118083, 7118084, 7118085, 7118087, 7118088, 7118092, 7119001, 7119002, 7119003, 7119004, 7119019, 7119020, 7119021, 7119022, #7119023, ## murad rejected #7119025, ## murad rejected #7119028, ## murad rejected #7119032, ## murad rejected 7119035, ## board 6 scalars 7119038, 7119065, #7119068, ## murad rejected 7119069, 7119079, 7119080, 7119082, #7119084, ## murad rejected 7119085, #7119088, ## murad rejected 7119090, 7119091, #7120023, ## no scalars #7120045, ## no scalars #7120046, ## no scalars #7120047, ## no scalars #7120049, ## no scalars #7120053, ## no scalars #7120082, ## no scalars 7120088, ## board 6 scalars 7120089, ## board 6 scalars 7120091, ## board 6 scalars 7120092, ## board 6 scalars 7120100, ## board 6 scalars 7120101, ## board 6 scalars 7120112, ## board 6 scalars 7120113, ## board 6 scalars 7120116, ## board 6 scalars #7120117, ## needed to reproduce, drop it 7120121, ## board 6 scalars 7120128, ## board 6 scalars #7120129, ## no scalars 7120131, ## board 6 scalars 7120132, ## board 6 scalars 7120133, ## board 6 scalars 7121001, ## board 6 scalars 7121007, ## board 6 scalars 7121012, ## board 6 scalars 7121013, ## board 6 scalars 7121015, ## board 6 scalars 7121016, ## board 6 scalars 7121020, ## board 6 scalars 7121021, ## board 6 scalars #7121038, ## no scalars 7121041, ## board 6 scalars 7121043, ## board 6 scalars #7121118, ## no scalars #7121119, ## no scalars #7121120, ## no scalars #7121122, ## no scalars #7122002, ## no scalars #7122003, ## no scalars #7122035, ## no scalars #7122037, ## no scalars #7122043, ## no scalars #7122044, ## no scalars #7122045, ## no scalars #7122047, ## no scalars #7122048, ## no scalars #7122049, ## no scalars #7122053, ## no scalars #7122054, ## no scalars #7122056, ## no scalars #7122057, ## no scalars #7122058, ## no scalars #7122069, ## no scalars #7122070, ## no scalars #7123011, ## no scalars #7123014, ## no scalars #7123015, ## no scalars #7123019, ## no scalars #7123020, ## no scalars #7123022, ## no scalars #7123024, ## no scalars #7123027, ## no scalars #7123028, ## no scalars #7123030, ## no scalars #7123031, ## no scalars #7123032, ## no scalars #7124009, ## no scalars #7124016, ## no scalars #7124018, ## no scalars #7124021, ## no scalars #7124024, ## no scalars #7124026, ## no scalars #7124029, ## no scalars #7124034, ## no scalars #7124063, ## no scalars 7125005, 7125013, 7125014, 7125015, 7125016, 7125017, 7125021, 7125022, 7125023, ## board 6 scalars 7125028, #7125044, ## murad rejected #7125046, ## murad rejected 7125052, 7125055, 7125056, 7125057, 7125058, #7125059, ## murad rejected 7125061, 7125066, 7125067, 7125069, 7125070, 7126008, 7126009, 7126010, 7126011, 7126012, 7126016, 7126019, 7126022, 7126023, 7126036, 7126037, 7126056, 7126057, 7126058, 7126059, 7126062, 7126063, 7126064, 7126065, 7127001, 7127005, 7127006, 7127007, 7127010, 7127011, ## board 6 scalars #7127024, ## murad rejected #7127037, ## murad rejected #7127038, ## murad rejected #7127039, ## murad rejected #7127041, ## murad rejected #7127042, ## murad rejected #7127046, ## murad rejected #7127049, ## murad rejected 7127067, 7127069, 7127072, 7127073, 7127075, 7127076, 7127077, 7127080, 7127087, 7127090, 7127092, 7127096, 7128001, 7128002, #7128005, ## needed to reproduce, drop it 7128006, 7128007, 7128008, 7128009, 7128013, #7128023, ## murad rejected 7128028, 7128032, 7128045, 7128046, 7128048, 7128050, 7128051, 7128057, 7128059, 7128061, 7128063, 7129001, 7129002, 7129003, 7129009, 7129018, 7129020, 7129021, 7129023, 7129027, 7129031, 7129032, 7129035, 7129036, 7129041 ] long2_run6 = [ 7132001, 7132005, 7132007, 7132009, 7132010, 7132018, 7132023, 7132026, 7132062, 7132066, 7132068, 7132071, 7133008, 7133011, 7133012, 7133018, 7133019, 7133022, 7133025, 7133035, 7133036, 7133039, 7133041, 7133043, 7133044, 7133045, 7133046, 7133047, 7133049, 7133050, 7133052, 7133064, 7133065, 7133066, 7133068, 7134001, 7134005, 7134006, 7134007, 7134009, # 7134010, ## non-null offset 7134013, 7134015, 7134043, 7134046, 7134047, 7134048, 7134049, 7134052, 7134055, 7134056, 7134065, 7134066, 7134067, 7134068, 7134072, 7134074, 7134075, 7134076, 7135003, 7135004, # 7135016, ## no final polarizations for F7858 # 7135018, ## no final polarizations for F7858 # 7135019, ## no final polarizations for F7858 # 7135022, ## no final polarizations for F7858 # 7135023, ## no final polarizations for F7858 # 7135024, ## no final polarizations for F7858 # 7135025, ## no final polarizations for F7858 # 7135028, ## no final polarizations for F7858 7136017, 7136022, 7136023, 7136024, 7136027, 7136031, 7136033, 7136034, 7136035, 7136039, 7136040, 7136041, 7136042, 7136045, 7136073, 7136075, 7136076, 7136079, 7136080, 7136084, 7137012, 7137013, 7137035, 7137036, 7138001, 7138002, 7138003, 7138004, 7138008, 7138009, 7138010, 7138011, 7138012, 7138017, 7138029, 7138032, 7138034, 7138043, #7139017, ## Murad -- failed : jets, jntows, jntrks, jrt, jtrkdca, jtrkdcaz, zv 7139018, 7139019, 7139022, 7139024, 7139025, 7139031, 7139032, 7139033, 7139034, 7139035, 7139036, 7139037, 7139043, 7140007, 7140008, 7140009, 7140010, 7140011, 7140014, 7140015, 7140016, 7140017, 7140018, 7140022, 7140023, 7140024, 7140042, 7140045, 7140046, #7140050, ## no relative luminosities 7140051, 7140052, #7140053, ## no relative luminosities 7141010, 7141011, 7141015, 7141016, 7141034, 7141038, 7141039, 7141042, 7141043, 7141044, 7141064, 7141066, #7141068, ## Murad -- short run - 1 minute long 7141069, 7141070, 7141071, 7141074, 7141075, 7141076, 7141077, 7142001, 7142005, #7142006, ## Murad -- No tpc #7142012, ## Murad -- failed : bbc, jets, jntows, jntrks, jpt, jrt, jtrkpt, j ## towpt, jtrkdca, zv #7142014, ## no relative luminosities #7142015, ## no relative luminosities 7142016, 7142017, 7142018, 7142022, #7142023, ## no relative luminosities 7142024, 7142025, 7142028, 7142029, 7142033, 7142034, 7142035, 7142036, 7142045, 7142046, 7142047, 7142048, 7142049, #7142052, ## no relative luminosities #7142059, ## Murad -- failed : bbc, jets, jntows, jntrks, jpt, jrt, jtrkpt, ## jtowpt, jtrkdca, jtrkdcaxy #7142060, ## Murad -- failed : bbc, jets, jntows, jntrks, jpt, jrt, jtrkpt, ## jtowpt, jtrkdca, zv 7142061, 7143001, 7143004, 7143005, 7143006, 7143007, 7143008, 7143011, 7143012, 7143013, 7143014, 7143025, #7143031, ## Murad -- No tpc 7143043, 7143044, # 7143045, ## non-null offset # 7143046, ## non-null offset 7143047, # 7143048, ## non-null offset 7143049, 7143054, 7143055, 7143056, 7143057, 7143060, 7144011, 7144014, 7144015, 7144018, 7145007, 7145009, 7145010, 7145013, 7145017, 7145018, 7145019, 7145022, 7145023, 7145024, 7145025, 7145026, 7145030, 7145057, 7145064, 7145067, 7145068, 7145069, 7145070, 7146001, 7146004, 7146006, 7146008, 7146009, # 7146016, ## non-null offset 7146017, 7146019, 7146020, 7146024, 7146025, 7146066, 7146067, 7146068, 7146069, 7146075, 7146076, 7146077, 7146078, 7147052, 7147055, 7147083, 7148020, 7148024, 7148027, 7148028, 7148032, 7148036, 7148063, 7148064, 7148065, 7148066, 7148067, 7149003, 7149004, 7149005, 7149018, 7149019, 7149023, 7149026, 7150007, 7150008, 7150013, 7152035, 7152037, 7152049, 7152051, 7152062, 7153001, 7153002, 7153008, 7153014, 7153015, 7153021, 7153025, 7153032, 7153035, 7153103, 7154005, 7154051, 7154068, 7154069, 7154070, 7155009, 7155010, 7155011, 7155013, 7155016, 7155018, 7155019, 7155022, 7155023, 7155042, 7155043, 7155044, 7155048, 7155052, 7156006, 7156010, 7156017, 7156018, 7156019, 7156024, 7156025, 7156026, 7156027, 7156028 ] golden_runlist_c = [ 6120032,6120037,6120038,6120039,6120040,6120042,6120043,6120044,6120045,6120049, 6120054,6120066,6120070,6121009,6121010,6121013,6121014,6121015,6121016,6121018, 6121022,6121036,6121060,6121061,6121068,6121070,6121071,6121072,6121073,6121075, 6122001,6122002,6122011,6122013,6122014,6122018,6130054,6130055,6130056,6130060, 6130061,6130063,6130064,6130069,6130070,6130071,6131007,6131008,6131009,6131013, 6131049,6131052,6131053,6131056,6133009,6133010,6133011,6133012,6133013,6133014, 6133016,6133017,6133018,6133022,6133049,6133072,6134001,6134002,6134003,6134004, 6134005,6134006,6134007,6134008,6134010,6134011,6134024,6134047,6134060,6135001, 6135002,6135005,6135006,6135007,6135008,6135009,6135010,6135013,6135014,6135033, 6135034,6135035,6135036,6136014,6136015,6136017,6136018,6136028,6136029,6136030, 6136031,6136032,6136034,6136035,6136037,6136041,6136042,6136043,6136119,6136130, 6136131,6137009,6137011,6137158,6137160,6137163,6137164,6137166,6137167,6137169, 6137170,6137171,6137172,6137173,6138001,6138002,6138003,6138005,6138010,6138011, 6138012,6138013,6138014,6138017,6138018,6138019,6138020,6138059,6138061,6138062, 6138067,6139001,6139002,6139004,6139005,6139007,6139008,6139009,6139010,6139012, 6139013,6139054,6139055,6139056,6139061,6139063,6139064,6139065,6139071,6140002, 6140003,6140004,6140005,6140019,6140020,6140021,6140022,6140023,6140024,6140025, 6140026,6140028,6140029,6140030,6140031,6140032,6140033,6140034,6140035,6140036, 6140054,6140066,6140067,6140068,6140074,6140075,6140076,6141009,6141010,6141011, 6141022,6141023,6141026,6141027,6141028,6141029,6141030,6141031,6141032,6141033, 6141061,6141062,6141063,6141064,6141065,6141066,6141068,6141069,6142001,6142002, 6142003,6142004,6142005,6142006,6142007,6142010,6142011,6142012,6142013,6142014, 6142015,6142016,6142017,6142018,6142020,6142021,6142022,6142024,6142026,6142027, 6142038,6142039,6142040,6142041,6142042,6142043,6142044,6142045,6142049,6142050, 6142051,6142052,6142053,6142054,6142055,6142056,6142057,6142060,6142063,6142064, 6142077,6142078,6142079,6142080,6142081,6142082,6142084,6142087,6142088,6142089, 6142093,6142094,6142097,6143001,6143002,6143012,6143013,6143014,6143015,6143016, 6143017,6143018,6143019,6143022,6143023,6143024,6143025,6143027,6143028,6143033, 6144017,6144019,6144020,6144021,6144022,6144023,6144024,6144028,6144051,6144052, 6144053,6144054,6144057,6144058,6144059,6144060,6144061,6144063,6144066,6144067, 6145011,6145018,6145019,6145041,6145053,6145054,6145055,6145056,6145057,6145058, 6146017,6146018,6146019,6146020,6146021,6146024,6146025,6146044,6147009,6147029, 6147031,6148008,6148009,6148010,6148011,6148012,6148013,6148014,6148018,6148019, 6148020,6148021,6148022,6148024,6148026,6148027,6148037,6148040,6148041,6148059, 6148063,6148064,6149004,6149007,6149009,6149016,6149017,6149019,6149020,6149021, 6149024,6149025,6149029,6149030,6149031,6149032,6149036,6149050,6149055,6149056, 6149057,6150005,6150018,6150028,6150029,6150037,6150038,6151001,6151002,6151005, 6151008,6151009,6151011,6151012,6151014,6151015,6151017,6151018,6151020,6151021, 6151022,6151023,6151024,6151026,6151028,6151029,6151030,6155004,6155026,6155027, 6155029,6156004,6156010,6156011,6156012,6156013,6156014,6156016,6156019,6156027, 6156028,6156029,6156034,6156036,6158014,6158015,6158019,6158020,6158024,6158025, 6158057,6158059,6158060,6158061,6158062,6158063,6158076,6158077,6158081,6158084, 6158085,6158086,6161001,6161006,6161007,6161035,6161038,6161042,6161043,6161046, 6161047,6161091,6161092,6161093,6161094,6161097,6161100,6161101,6161102,6161104, 6161105,6162005,6162006,6162007,6162027,6162028,6162030,6162031,6162032,6162039, 6162040,6162041,6162042,6162043,6162044,6162045,6162046,6162058,6162062,6162063, 6162064,6162068,6162069,6162070,6162071,6162072,6162075,6162076,6163012,6163013, 6163016,6163017,6163018,6163021,6163022,6163023,6163024,6163025,6163035,6163038, 6163039,6163040,6163041,6163043,6163044,6163045,6163048,6163050,6163051,6163053, 6163054,6163056,6163057,6163058,6164002,6164003,6164004,6164013,6164016,6164017, 6164018,6164021,6164022,6164024,6167141,6168002,6168018,6168019,6168022,6168023, 6168036,6168044,6168068,6168069,6168072,6168073,6168083,6168084,6168085,6168086, 6168104,6168107,6168108,6168111,6168112,6169001,6169002,6169003,6169006,6169007, 6169008,6169020,6169026,6169027,6169030,6169031,6169035,6169037,6169041,6169043, 6169048,6169049,6169051,6169052,6169053,6169055,6169056,6169057,6169058,6169060, 6169073,6169079,6169080,6169082,6169084,6169088,6169089,6169090,6169091,6169092, 6169094,6169096,6169097,6169103,6169105,6169106,6169107,6170002,6170006,6170010, 6170011,6170012,6170013,6170014,6170015,6170016,6170017,6170031,6170032,6170033, 6170035,6170038,6170039,6170041,6170045,6171022,6171024,6171034,6171039,6171041, 6171043,6171044,6171045,6171046,6171048,6171049,6171062,6171063,6172001,6172002, 6172003,6172006,6172007,6172015,6172016,6172069,6172085,6172086,6172087,6172092, 6172093,6174010,6174011,6174012,6174013,6174014,6174017,6174018,6174019,6174020, 6174021,6174025,6174026,6174027,6174031,6174044,6174045,6174046,6174047,6174048, 6174049,6174053,6174054,6174055,6174056,6174057,6174058,6174060,6174069,6174070, 6174072,6175009,6175010,6175011,6175012,6175016,6175017,6175020 ] minbias_runs = [ 6120044, 6120054, #6130069, ## polarizations #6130070, #6130071, #6135014, ## even/odd stagger problem 6138019, 6138020, 6139013, 6140004, 6140005, 6141069, 6142020, 6142021, 6142022, #6142060, ## ZDC/BBC ratio 3sigma from zero #6142063, #6142064, 6143028, 6143033, 6144028, 6144067, 6145011, 6145041, 6147009, 6147031, 6148021, 6148022, 6148024, 6148026, 6148027, 6148037, 6148040, 6148041, 6149009, 6149055, 6149056, 6149057, 6151030, 6155004, 6155026, 6155027, 6155029, 6158024, 6163035, 6164021, 6168002, 6168111, 6169073, 6170016, 6170017, 6172015, ## bx111 6172016, ## bx111 6174025 ## bx111 ] run6a = [ #7132001, #7132005, #7132006, #7132007, #7132008, #7132009, #7132010, #7132018, #7132023, #7132024, #7132025, #7132026, #7132027, #7132062, #7132066, #7132068, #7132071, #7133008, #7133011, #7133012, #7133016, #7133018, #7133019, #7133022, #7133025, #7133035, #7133036, #7133039, #7133041, #7133043, #7133044, #7133045, #7133046, #7133047, #7133049, #7133050, #7133052, #7133064, #7133065, #7133066, #7133068, #7134001, #7134005, #7134006, #7134007, #7134009, #7134010, #7134013, #7134015, #7134026, #7134027, #7134030, #7134043, #7134046, #7134047, #7134048, #7134049, #7134052, #7134055, #7134056, #7134065, #7134066, #7134067, #7134068, #7134072, #7134074, #7134075, #7134076, #7135003, #7135004, #7135016, #7135018, #7135019, #7135022, #7135023, #7135024, #7135025, #7135028, #7136017, #7136022, #7136023, #7136024, #7136027, #7136031, #7136033, #7136034, #7136035, #7136039, #7136040, #7136041, #7136042, #7136045, #7136073, #7136075, #7136076, #7136079, #7136080, #7136084, #7137012, #7137013, #7137035, #7137036, #7138001, 7138002, 7138003, 7138004, 7138008, 7138009, 7138010, 7138011, 7138012, 7138017, 7138029, 7138032, 7138034, 7138043, 7139018, 7139019, 7139025, 7139031, 7139032, 7139033, 7139034, 7139035, 7139036, 7139037, 7139043, 7140007, 7140008, 7140009, 7140010, 7140011, 7140015, 7140016, 7140017, 7140018, 7140022, 7140023, 7140024, 7140042, 7140045, 7140051, 7140052, 7140053, 7141010, 7141011, 7141015, 7141016, 7141034, 7141038, 7141039, 7141042, 7141043, 7141044, 7141064, 7141066, 7141069, 7141070, 7141071, 7141074, 7141075, 7141076, 7141077, 7142001, 7142005, 7142014, 7142015, 7142016, 7142017, 7142018, 7142022, 7142023, 7142024, 7142025, 7142028, 7142029, 7142033, 7142034, 7142035, 7142036, 7142045, 7142046, 7142047, 7142048, 7142049, 7142059, 7142060, 7142061, 7143001, 7143004, 7143005, 7143006, 7143007, 7143008, 7143011, 7143012, 7143013, 7143014, 7143025, 7144011, 7144014, 7144015, 7144018, 7145007, 7145009, 7145010, 7145013, 7145016, 7145018, 7145019, 7145022, 7145023, 7145024, 7145025, 7145026, 7145030, 7145057, 7145064, 7145067, 7145068, 7145069, 7145070, 7146001, 7146004, 7146006, 7146008, 7146009, 7146016, 7146017, 7146019, 7146020, 7146024, 7146025, 7146066, 7146067, 7146068, 7146069, 7146075, 7146076, 7146077, 7146078, 7147017, 7147020, 7147023, 7147024, 7147028, 7147029, 7147032, 7147033, 7147052, 7147055, 7147082, 7147083, 7147084, 7148020, 7148024, 7148027, 7148028, 7148032, 7148036, 7148037, 7148054, 7148057, 7148059, 7148063, 7148064, 7148065, 7148066, 7148067, 7149003, 7149004, 7149005, 7149006, 7149012, 7149017, 7149018, 7149019, 7149023, 7149026, 7150007, 7150008, 7150013, 7152035, 7152037, 7152049, 7152051, 7152062, 7153001, 7153002, 7153008, 7153014, 7153015, 7153021, 7153025, 7153032, 7153035, 7153095, 7153103, 7154005, 7154010, 7154011, 7154040, 7154044, 7154047, 7154051, 7154068, 7154069, 7154070, 7155010, 7155011, 7155013, 7155016, 7155019, 7155022, 7155023, 7155043, 7155044, 7155048, 7156006, 7156010, 7156017, 7156018, 7156019, 7156024, 7156025, 7156026, 7156027, 7156028 ] final_runlist_run5_no_minbias = [ 6119032, 6119038, 6119039, 6119063, 6119064, 6119065, 6119066, 6119067, 6119069, 6119071, 6119072, 6120009, 6120010, 6120011, 6120015, 6120016, 6120017, 6120019, 6120022, 6120032, 6120037, 6120038, 6120039, 6120040, 6120042, 6120043, 6120045, 6120049, 6120066, 6120070, 6120071, 6121009, 6121010, 6121013, 6121014, 6121015, 6121016, 6121018, 6121021, 6121022, 6121033, 6121036, 6121060, 6121061, 6121068, 6121070, 6121071, 6121072, 6121073, 6121075, 6121076, 6122001, 6122002, 6122010, 6122011, 6122013, 6122014, 6122018, 6127035, 6127036, 6127037, 6128005, 6128006, 6128007, 6128009, 6128011, 6128012, 6128013, 6128014, 6128015, 6128016, 6128022, 6128023, 6128024, 6128026, 6128027, 6128028, 6128029, 6128030, 6128031, 6128032, #6128043, ## even/odd stagger problem (case with no reliable ZDC info) #6128051, #6128052, #6128053, #6128054, #6128055, #6128056, #6128057, #6128058, #6128059, #6128062, #6128063, #6130054, ## no final polarizations available #6130055, #6130056, #6130060, #6130061, #6130063, #6130064, #6130065, 6131007, 6131008, 6131009, 6131013, 6131048, 6131049, 6131052, 6131053, 6131054, 6131056, 6131057, 6131092, #6132019, ## no final polarizations available #6132020, #6132021, #6132025, #6132026, 6133006, 6133009, 6133010, 6133011, 6133012, 6133013, 6133014, 6133015, 6133016, 6133017, 6133018, 6133022, 6133026, 6133049, 6133071, 6133072, 6134001, 6134002, 6134003, 6134004, 6134005, 6134006, 6134007, 6134008, 6134010, 6134011, 6134024, 6134047, 6134060, ## bx111 #6135001, ## even/odd stagger problems #6135002, #6135005, #6135006, #6135007, #6135008, #6135009, #6135010, #6135013, #6135033, ## ZDC/BBC ratio 3sigma from zero #6135034, #6135035, #6135036, #6135037, #6135038, #6135052, ## even/odd stagger problem #6135053, 6136014, 6136015, 6136017, 6136018, 6136028, 6136029, 6136030, 6136031, 6136032, 6136034, 6136035, 6136037, 6136041, 6136042, 6136043, 6136119, 6136130, 6136131, 6137009, 6137011, 6137149, 6137157, 6137158, 6137159, 6137160, 6137163, 6137164, 6137166, 6137167, 6137169, 6137170, 6137171, 6137172, 6137173, 6138001, 6138002, 6138003, 6138004, 6138005, 6138010, 6138011, 6138012, 6138013, 6138014, 6138017, 6138018, 6138059, 6138061, 6138062, 6138067, 6139001, 6139002, 6139004, 6139005, 6139007, 6139008, 6139009, 6139010, 6139012, 6139018, 6139019, 6139020, 6139021, 6139022, 6139025, 6139026, 6139027, 6139028, 6139029, 6139030, 6139034, 6139036, 6139039, 6139041, 6139054, 6139055, 6139056, 6139061, 6139063, 6139064, 6139065, 6139071, 6140002, 6140003, 6140018, 6140019, 6140020, 6140021, 6140022, 6140023, 6140024, 6140025, 6140026, 6140028, 6140029, 6140030, 6140031, 6140032, 6140033, 6140034, 6140035, 6140036, 6140054, 6140065, 6140066, 6140067, 6140068, 6140069, 6140074, 6140075, 6140076, 6141009, 6141010, 6141011, 6141021, 6141022, 6141023, 6141026, 6141027, 6141028, 6141029, 6141030, 6141031, 6141032, 6141033, 6141047, 6141049, 6141050, 6141051, 6141052, 6141053, 6141058, 6141061, 6141062, 6141063, 6141064, 6141065, 6141066, 6141068, 6142001, 6142002, 6142003, 6142004, 6142005, 6142006, 6142007, 6142008, 6142010, 6142011, 6142012, 6142013, 6142014, 6142015, 6142016, 6142017, 6142018, 6142024, 6142025, 6142026, 6142027, #6142038, ## ZDC/BBC ratio 3sigma from zero #6142039, #6142040, #6142041, #6142042, #6142043, #6142044, #6142045, #6142049, #6142050, #6142051, #6142052, #6142053, #6142054, #6142055, #6142056, #6142057, 6142077, 6142078, 6142079, 6142080, 6142081, 6142082, 6142084, 6142087, 6142088, 6142089, 6142093, 6142094, 6142097, 6143001, 6143002, 6143012, 6143013, 6143014, 6143015, 6143016, 6143017, 6143018, 6143019, 6143021, 6143022, 6143023, 6143024, 6143025, 6143027, 6144017, 6144019, 6144020, 6144021, 6144022, 6144023, 6144024, 6144026, 6144051, 6144052, 6144053, 6144054, 6144057, 6144058, 6144059, 6144060, 6144061, 6144063, 6144066, 6145013, 6145015, 6145018, 6145019, 6145020, 6145023, 6145025, 6145027, 6145028, 6145045, 6145053, 6145054, 6145055, 6145056, 6145057, 6145058, 6145068, 6146017, 6146018, 6146019, 6146020, 6146021, 6146024, 6146025, 6147029, 6147030, 6148008, 6148009, 6148010, 6148011, 6148012, 6148013, 6148014, 6148017, 6148018, 6148019, 6148020, 6148054, 6148055, 6148056, 6148057, 6148058, 6148059, 6148060, 6148063, 6148064, 6149003, 6149004, 6149007, 6149016, 6149017, 6149018, 6149019, 6149020, 6149021, 6149024, 6149025, 6149029, 6149030, 6149031, 6149032, 6149036, 6149048, 6149050, 6149051, 6149052, 6150005, 6150006, 6150014, 6150015, 6150016, 6150017, 6150018, 6150019, 6150022, 6150023, 6150024, 6150025, 6150026, 6150027, 6150028, 6150029, 6150037, 6150038, 6151001, 6151002, 6151005, 6151008, 6151009, 6151011, 6151012, 6151013, 6151014, 6151015, 6151017, 6151018, 6151020, 6151021, 6151022, 6151023, 6151024, 6151026, 6151028, 6151029, 6156004, 6156010, 6156011, 6156012, 6156013, 6156014, 6156015, 6156016, 6156019, 6156027, 6156028, 6156029, 6156030, 6156034, 6156036, 6157050, 6157051, 6158014, 6158015, 6158019, 6158020, 6158025, 6158041, 6158057, 6158059, 6158060, 6158061, 6158062, 6158063, 6158076, 6158077, 6158081, 6158084, 6158085, 6158086, 6160039, 6160040, 6160041, 6160044, 6160048, 6160056, 6160057, 6160058, 6160061, 6160062, 6160065, 6160068, 6160069, 6160070, 6160071, 6160072, 6160082, 6160083, 6161001, 6161006, 6161007, 6161035, 6161038, 6161042, 6161043, 6161044, 6161046, 6161047, 6161091, 6161092, 6161093, 6161094, 6161097, 6161098, 6161099, 6161100, 6161101, 6161102, 6161104, 6161105, 6162005, 6162006, 6162007, 6162014, 6162027, 6162028, 6162029, 6162030, 6162031, 6162032, 6162039, 6162040, 6162041, 6162042, 6162043, 6162044, 6162045, 6162046, 6162056, 6162058, 6162061, 6162062, 6162063, 6162064, 6162068, 6162069, 6162070, 6162071, 6162072, 6162075, 6162076, 6163012, 6163013, 6163015, 6163016, 6163017, 6163018, 6163021, 6163022, 6163023, 6163024, 6163025, 6163038, 6163039, 6163040, 6163041, 6163043, 6163044, 6163045, 6163048, 6163050, 6163051, 6163053, 6163054, 6163056, 6163057, 6163058, 6164002, 6164003, 6164004, 6164013, 6164016, 6164017, 6164018, 6164022, 6164023, 6164024, 6167115, 6167116, 6167119, 6167131, 6167134, 6167140, 6167141, 6168018, 6168019, 6168022, 6168023, 6168024, 6168036, 6168044, 6168068, 6168069, 6168072, 6168073, 6168083, 6168084, 6168085, 6168086, 6168089, 6168090, 6168099, 6168100, 6168101, 6168102, 6168103, 6168104, 6168107, 6168108, 6168112, 6169001, 6169002, 6169003, 6169006, 6169007, 6169008, 6169020, 6169025, 6169026, 6169027, 6169028, 6169029, 6169030, 6169031, 6169035, 6169036, 6169037, 6169038, 6169039, 6169041, 6169043, 6169044, 6169047, 6169048, 6169049, 6169050, 6169051, 6169052, 6169053, 6169055, 6169056, 6169057, 6169058, 6169060, 6169079, 6169080, 6169082, 6169083, 6169084, 6169088, 6169089, 6169090, 6169091, 6169092, 6169093, 6169094, 6169096, 6169097, 6169101, 6169103, 6169104, 6169105, 6169106, 6169107, 6170002, 6170006, 6170009, 6170010, 6170011, 6170012, 6170013, 6170014, 6170015, 6170018, 6170031, ## bx111 6170032, ## bx111 6170033, ## bx111 6170034, ## bx111 6170035, ## bx111 6170038, ## bx111 6170039, ## bx111 6170040, ## bx111 6170041, ## bx111 6170045, ## bx111 6171022, ## bx111 6171024, ## bx111 6171034, ## bx111 6171039, ## bx111 6171040, ## bx111 6171041, ## bx111 6171043, ## bx111 6171044, ## bx111 6171045, ## bx111 6171046, ## bx111 6171048, ## bx111 6171049, ## bx111 6171062, ## bx111 6171063, ## bx111 6172001, ## bx111 6172002, ## bx111 6172003, ## bx111 6172006, ## bx111 6172007, ## bx111 6172010, ## bx111 6172069, ## bx111 6172085, ## bx111 6172086, ## bx111 6172087, ## bx111 6172092, ## bx111 6172093, ## bx111 6174010, ## bx111 6174011, ## bx111 6174012, ## bx111 6174013, ## bx111 6174014, ## bx111 6174017, ## bx111 6174018, ## bx111 6174019, ## bx111 6174020, ## bx111 6174021, ## bx111 6174026, ## bx111 6174027, ## bx111 6174031, ## bx111 6174044, 6174045, 6174046, 6174047, 6174048, 6174049, 6174053, 6174054, 6174055, 6174056, 6174057, 6174058, 6174059, 6174060, 6174069, 6174070, 6174072, #6175009, ## no final polarizations available #6175010, #6175011, #6175012, #6175016, #6175017, #6175020 ] final_runlist_run5 = final_runlist_run5_no_minbias + minbias_runs final_runlist_run5.sort() __all__ = ['transverse_run5', 'transverse_run6_iucf', 'transverse_run6', 'long2_run6', 'golden_runlist_c', 'minbias_runs', 'final_runlist_run5']
transverse_run5 = [6165044, 6165046, 6165047, 6165055, 6165058, 6165059, 6165063, 6166051, 6166052, 6166054, 6166055, 6166056, 6166057, 6166059, 6166060, 6166061, 6166070, 6166071, 6166073, 6166074, 6166075, 6166076, 6166090, 6166091, 6167079, 6167083, 6167088] transverse_run6_iucf = [7098001, 7098002, 7098004, 7098006, 7098007, 7098024, 7098025, 7098027, 7098028, 7098029, 7098038, 7098039, 7098040, 7098041, 7098053, 7098065, 7098066, 7098067, 7098072, 7098073, 7098082, 7098083, 7099003, 7099006, 7099014, 7099025, 7099026, 7099027, 7099030, 7099033, 7099047, 7100052, 7100058, 7100062, 7100064, 7100072, 7100075, 7100077] transverse_run6 = [7097093, 7097094, 7097096, 7097097, 7097099, 7097102, 7097103, 7097104, 7097105, 7098002, 7098004, 7098006, 7098007, 7098008, 7098015, 7098018, 7098024, 7098025, 7098027, 7098028, 7098029, 7098031, 7098032, 7098033, 7098034, 7098036, 7098038, 7098039, 7098040, 7098041, 7098053, 7098055, 7098061, 7098062, 7098064, 7098065, 7098066, 7098067, 7098072, 7098074, 7098075, 7098079, 7098081, 7098082, 7098083, 7099006, 7099022, 7099025, 7099026, 7099027, 7099030, 7099031, 7099033, 7099034, 7099035, 7099036, 7100014, 7100016, 7100031, 7100068, 7100071, 7100072, 7100075, 7100077, 7101019, 7101023, 7101025, 7101041, 7101042, 7101046, 7101050, 7101052, 7101054, 7101075, 7101078, 7101082, 7101085, 7101086, 7103006, 7103007, 7103008, 7103013, 7103014, 7103017, 7103018, 7103024, 7103026, 7103027, 7103030, 7103040, 7103072, 7103073, 7103075, 7103080, 7103082, 7103086, 7103089, 7103090, 7103093, 7103095, 7103099, 7104014, 7104016, 7115085, 7115086, 7115087, 7115088, 7115095, 7115097, 7115099, 7115101, 7115103, 7115106, 7115111, 7115113, 7115114, 7115115, 7115116, 7115117, 7115121, 7115124, 7115125, 7115126, 7115134, 7116052, 7116057, 7116059, 7117002, 7117008, 7117009, 7117010, 7117011, 7117015, 7117016, 7117017, 7117027, 7117050, 7117056, 7117057, 7117058, 7117060, 7117063, 7117064, 7117071, 7118002, 7118003, 7118004, 7118008, 7118009, 7118010, 7118016, 7118017, 7118032, 7118033, 7118035, 7118038, 7118039, 7118041, 7118044, 7118045, 7118048, 7118049, 7118050, 7118051, 7118053, 7118073, 7118075, 7118077, 7118083, 7118084, 7118085, 7118087, 7118088, 7118092, 7119001, 7119002, 7119003, 7119004, 7119019, 7119020, 7119021, 7119022, 7119035, 7119038, 7119065, 7119069, 7119079, 7119080, 7119082, 7119085, 7119090, 7119091, 7120088, 7120089, 7120091, 7120092, 7120100, 7120101, 7120112, 7120113, 7120116, 7120121, 7120128, 7120131, 7120132, 7120133, 7121001, 7121007, 7121012, 7121013, 7121015, 7121016, 7121020, 7121021, 7121041, 7121043, 7125005, 7125013, 7125014, 7125015, 7125016, 7125017, 7125021, 7125022, 7125023, 7125028, 7125052, 7125055, 7125056, 7125057, 7125058, 7125061, 7125066, 7125067, 7125069, 7125070, 7126008, 7126009, 7126010, 7126011, 7126012, 7126016, 7126019, 7126022, 7126023, 7126036, 7126037, 7126056, 7126057, 7126058, 7126059, 7126062, 7126063, 7126064, 7126065, 7127001, 7127005, 7127006, 7127007, 7127010, 7127011, 7127067, 7127069, 7127072, 7127073, 7127075, 7127076, 7127077, 7127080, 7127087, 7127090, 7127092, 7127096, 7128001, 7128002, 7128006, 7128007, 7128008, 7128009, 7128013, 7128028, 7128032, 7128045, 7128046, 7128048, 7128050, 7128051, 7128057, 7128059, 7128061, 7128063, 7129001, 7129002, 7129003, 7129009, 7129018, 7129020, 7129021, 7129023, 7129027, 7129031, 7129032, 7129035, 7129036, 7129041] long2_run6 = [7132001, 7132005, 7132007, 7132009, 7132010, 7132018, 7132023, 7132026, 7132062, 7132066, 7132068, 7132071, 7133008, 7133011, 7133012, 7133018, 7133019, 7133022, 7133025, 7133035, 7133036, 7133039, 7133041, 7133043, 7133044, 7133045, 7133046, 7133047, 7133049, 7133050, 7133052, 7133064, 7133065, 7133066, 7133068, 7134001, 7134005, 7134006, 7134007, 7134009, 7134013, 7134015, 7134043, 7134046, 7134047, 7134048, 7134049, 7134052, 7134055, 7134056, 7134065, 7134066, 7134067, 7134068, 7134072, 7134074, 7134075, 7134076, 7135003, 7135004, 7136017, 7136022, 7136023, 7136024, 7136027, 7136031, 7136033, 7136034, 7136035, 7136039, 7136040, 7136041, 7136042, 7136045, 7136073, 7136075, 7136076, 7136079, 7136080, 7136084, 7137012, 7137013, 7137035, 7137036, 7138001, 7138002, 7138003, 7138004, 7138008, 7138009, 7138010, 7138011, 7138012, 7138017, 7138029, 7138032, 7138034, 7138043, 7139018, 7139019, 7139022, 7139024, 7139025, 7139031, 7139032, 7139033, 7139034, 7139035, 7139036, 7139037, 7139043, 7140007, 7140008, 7140009, 7140010, 7140011, 7140014, 7140015, 7140016, 7140017, 7140018, 7140022, 7140023, 7140024, 7140042, 7140045, 7140046, 7140051, 7140052, 7141010, 7141011, 7141015, 7141016, 7141034, 7141038, 7141039, 7141042, 7141043, 7141044, 7141064, 7141066, 7141069, 7141070, 7141071, 7141074, 7141075, 7141076, 7141077, 7142001, 7142005, 7142016, 7142017, 7142018, 7142022, 7142024, 7142025, 7142028, 7142029, 7142033, 7142034, 7142035, 7142036, 7142045, 7142046, 7142047, 7142048, 7142049, 7142061, 7143001, 7143004, 7143005, 7143006, 7143007, 7143008, 7143011, 7143012, 7143013, 7143014, 7143025, 7143043, 7143044, 7143047, 7143049, 7143054, 7143055, 7143056, 7143057, 7143060, 7144011, 7144014, 7144015, 7144018, 7145007, 7145009, 7145010, 7145013, 7145017, 7145018, 7145019, 7145022, 7145023, 7145024, 7145025, 7145026, 7145030, 7145057, 7145064, 7145067, 7145068, 7145069, 7145070, 7146001, 7146004, 7146006, 7146008, 7146009, 7146017, 7146019, 7146020, 7146024, 7146025, 7146066, 7146067, 7146068, 7146069, 7146075, 7146076, 7146077, 7146078, 7147052, 7147055, 7147083, 7148020, 7148024, 7148027, 7148028, 7148032, 7148036, 7148063, 7148064, 7148065, 7148066, 7148067, 7149003, 7149004, 7149005, 7149018, 7149019, 7149023, 7149026, 7150007, 7150008, 7150013, 7152035, 7152037, 7152049, 7152051, 7152062, 7153001, 7153002, 7153008, 7153014, 7153015, 7153021, 7153025, 7153032, 7153035, 7153103, 7154005, 7154051, 7154068, 7154069, 7154070, 7155009, 7155010, 7155011, 7155013, 7155016, 7155018, 7155019, 7155022, 7155023, 7155042, 7155043, 7155044, 7155048, 7155052, 7156006, 7156010, 7156017, 7156018, 7156019, 7156024, 7156025, 7156026, 7156027, 7156028] golden_runlist_c = [6120032, 6120037, 6120038, 6120039, 6120040, 6120042, 6120043, 6120044, 6120045, 6120049, 6120054, 6120066, 6120070, 6121009, 6121010, 6121013, 6121014, 6121015, 6121016, 6121018, 6121022, 6121036, 6121060, 6121061, 6121068, 6121070, 6121071, 6121072, 6121073, 6121075, 6122001, 6122002, 6122011, 6122013, 6122014, 6122018, 6130054, 6130055, 6130056, 6130060, 6130061, 6130063, 6130064, 6130069, 6130070, 6130071, 6131007, 6131008, 6131009, 6131013, 6131049, 6131052, 6131053, 6131056, 6133009, 6133010, 6133011, 6133012, 6133013, 6133014, 6133016, 6133017, 6133018, 6133022, 6133049, 6133072, 6134001, 6134002, 6134003, 6134004, 6134005, 6134006, 6134007, 6134008, 6134010, 6134011, 6134024, 6134047, 6134060, 6135001, 6135002, 6135005, 6135006, 6135007, 6135008, 6135009, 6135010, 6135013, 6135014, 6135033, 6135034, 6135035, 6135036, 6136014, 6136015, 6136017, 6136018, 6136028, 6136029, 6136030, 6136031, 6136032, 6136034, 6136035, 6136037, 6136041, 6136042, 6136043, 6136119, 6136130, 6136131, 6137009, 6137011, 6137158, 6137160, 6137163, 6137164, 6137166, 6137167, 6137169, 6137170, 6137171, 6137172, 6137173, 6138001, 6138002, 6138003, 6138005, 6138010, 6138011, 6138012, 6138013, 6138014, 6138017, 6138018, 6138019, 6138020, 6138059, 6138061, 6138062, 6138067, 6139001, 6139002, 6139004, 6139005, 6139007, 6139008, 6139009, 6139010, 6139012, 6139013, 6139054, 6139055, 6139056, 6139061, 6139063, 6139064, 6139065, 6139071, 6140002, 6140003, 6140004, 6140005, 6140019, 6140020, 6140021, 6140022, 6140023, 6140024, 6140025, 6140026, 6140028, 6140029, 6140030, 6140031, 6140032, 6140033, 6140034, 6140035, 6140036, 6140054, 6140066, 6140067, 6140068, 6140074, 6140075, 6140076, 6141009, 6141010, 6141011, 6141022, 6141023, 6141026, 6141027, 6141028, 6141029, 6141030, 6141031, 6141032, 6141033, 6141061, 6141062, 6141063, 6141064, 6141065, 6141066, 6141068, 6141069, 6142001, 6142002, 6142003, 6142004, 6142005, 6142006, 6142007, 6142010, 6142011, 6142012, 6142013, 6142014, 6142015, 6142016, 6142017, 6142018, 6142020, 6142021, 6142022, 6142024, 6142026, 6142027, 6142038, 6142039, 6142040, 6142041, 6142042, 6142043, 6142044, 6142045, 6142049, 6142050, 6142051, 6142052, 6142053, 6142054, 6142055, 6142056, 6142057, 6142060, 6142063, 6142064, 6142077, 6142078, 6142079, 6142080, 6142081, 6142082, 6142084, 6142087, 6142088, 6142089, 6142093, 6142094, 6142097, 6143001, 6143002, 6143012, 6143013, 6143014, 6143015, 6143016, 6143017, 6143018, 6143019, 6143022, 6143023, 6143024, 6143025, 6143027, 6143028, 6143033, 6144017, 6144019, 6144020, 6144021, 6144022, 6144023, 6144024, 6144028, 6144051, 6144052, 6144053, 6144054, 6144057, 6144058, 6144059, 6144060, 6144061, 6144063, 6144066, 6144067, 6145011, 6145018, 6145019, 6145041, 6145053, 6145054, 6145055, 6145056, 6145057, 6145058, 6146017, 6146018, 6146019, 6146020, 6146021, 6146024, 6146025, 6146044, 6147009, 6147029, 6147031, 6148008, 6148009, 6148010, 6148011, 6148012, 6148013, 6148014, 6148018, 6148019, 6148020, 6148021, 6148022, 6148024, 6148026, 6148027, 6148037, 6148040, 6148041, 6148059, 6148063, 6148064, 6149004, 6149007, 6149009, 6149016, 6149017, 6149019, 6149020, 6149021, 6149024, 6149025, 6149029, 6149030, 6149031, 6149032, 6149036, 6149050, 6149055, 6149056, 6149057, 6150005, 6150018, 6150028, 6150029, 6150037, 6150038, 6151001, 6151002, 6151005, 6151008, 6151009, 6151011, 6151012, 6151014, 6151015, 6151017, 6151018, 6151020, 6151021, 6151022, 6151023, 6151024, 6151026, 6151028, 6151029, 6151030, 6155004, 6155026, 6155027, 6155029, 6156004, 6156010, 6156011, 6156012, 6156013, 6156014, 6156016, 6156019, 6156027, 6156028, 6156029, 6156034, 6156036, 6158014, 6158015, 6158019, 6158020, 6158024, 6158025, 6158057, 6158059, 6158060, 6158061, 6158062, 6158063, 6158076, 6158077, 6158081, 6158084, 6158085, 6158086, 6161001, 6161006, 6161007, 6161035, 6161038, 6161042, 6161043, 6161046, 6161047, 6161091, 6161092, 6161093, 6161094, 6161097, 6161100, 6161101, 6161102, 6161104, 6161105, 6162005, 6162006, 6162007, 6162027, 6162028, 6162030, 6162031, 6162032, 6162039, 6162040, 6162041, 6162042, 6162043, 6162044, 6162045, 6162046, 6162058, 6162062, 6162063, 6162064, 6162068, 6162069, 6162070, 6162071, 6162072, 6162075, 6162076, 6163012, 6163013, 6163016, 6163017, 6163018, 6163021, 6163022, 6163023, 6163024, 6163025, 6163035, 6163038, 6163039, 6163040, 6163041, 6163043, 6163044, 6163045, 6163048, 6163050, 6163051, 6163053, 6163054, 6163056, 6163057, 6163058, 6164002, 6164003, 6164004, 6164013, 6164016, 6164017, 6164018, 6164021, 6164022, 6164024, 6167141, 6168002, 6168018, 6168019, 6168022, 6168023, 6168036, 6168044, 6168068, 6168069, 6168072, 6168073, 6168083, 6168084, 6168085, 6168086, 6168104, 6168107, 6168108, 6168111, 6168112, 6169001, 6169002, 6169003, 6169006, 6169007, 6169008, 6169020, 6169026, 6169027, 6169030, 6169031, 6169035, 6169037, 6169041, 6169043, 6169048, 6169049, 6169051, 6169052, 6169053, 6169055, 6169056, 6169057, 6169058, 6169060, 6169073, 6169079, 6169080, 6169082, 6169084, 6169088, 6169089, 6169090, 6169091, 6169092, 6169094, 6169096, 6169097, 6169103, 6169105, 6169106, 6169107, 6170002, 6170006, 6170010, 6170011, 6170012, 6170013, 6170014, 6170015, 6170016, 6170017, 6170031, 6170032, 6170033, 6170035, 6170038, 6170039, 6170041, 6170045, 6171022, 6171024, 6171034, 6171039, 6171041, 6171043, 6171044, 6171045, 6171046, 6171048, 6171049, 6171062, 6171063, 6172001, 6172002, 6172003, 6172006, 6172007, 6172015, 6172016, 6172069, 6172085, 6172086, 6172087, 6172092, 6172093, 6174010, 6174011, 6174012, 6174013, 6174014, 6174017, 6174018, 6174019, 6174020, 6174021, 6174025, 6174026, 6174027, 6174031, 6174044, 6174045, 6174046, 6174047, 6174048, 6174049, 6174053, 6174054, 6174055, 6174056, 6174057, 6174058, 6174060, 6174069, 6174070, 6174072, 6175009, 6175010, 6175011, 6175012, 6175016, 6175017, 6175020] minbias_runs = [6120044, 6120054, 6138019, 6138020, 6139013, 6140004, 6140005, 6141069, 6142020, 6142021, 6142022, 6143028, 6143033, 6144028, 6144067, 6145011, 6145041, 6147009, 6147031, 6148021, 6148022, 6148024, 6148026, 6148027, 6148037, 6148040, 6148041, 6149009, 6149055, 6149056, 6149057, 6151030, 6155004, 6155026, 6155027, 6155029, 6158024, 6163035, 6164021, 6168002, 6168111, 6169073, 6170016, 6170017, 6172015, 6172016, 6174025] run6a = [7138002, 7138003, 7138004, 7138008, 7138009, 7138010, 7138011, 7138012, 7138017, 7138029, 7138032, 7138034, 7138043, 7139018, 7139019, 7139025, 7139031, 7139032, 7139033, 7139034, 7139035, 7139036, 7139037, 7139043, 7140007, 7140008, 7140009, 7140010, 7140011, 7140015, 7140016, 7140017, 7140018, 7140022, 7140023, 7140024, 7140042, 7140045, 7140051, 7140052, 7140053, 7141010, 7141011, 7141015, 7141016, 7141034, 7141038, 7141039, 7141042, 7141043, 7141044, 7141064, 7141066, 7141069, 7141070, 7141071, 7141074, 7141075, 7141076, 7141077, 7142001, 7142005, 7142014, 7142015, 7142016, 7142017, 7142018, 7142022, 7142023, 7142024, 7142025, 7142028, 7142029, 7142033, 7142034, 7142035, 7142036, 7142045, 7142046, 7142047, 7142048, 7142049, 7142059, 7142060, 7142061, 7143001, 7143004, 7143005, 7143006, 7143007, 7143008, 7143011, 7143012, 7143013, 7143014, 7143025, 7144011, 7144014, 7144015, 7144018, 7145007, 7145009, 7145010, 7145013, 7145016, 7145018, 7145019, 7145022, 7145023, 7145024, 7145025, 7145026, 7145030, 7145057, 7145064, 7145067, 7145068, 7145069, 7145070, 7146001, 7146004, 7146006, 7146008, 7146009, 7146016, 7146017, 7146019, 7146020, 7146024, 7146025, 7146066, 7146067, 7146068, 7146069, 7146075, 7146076, 7146077, 7146078, 7147017, 7147020, 7147023, 7147024, 7147028, 7147029, 7147032, 7147033, 7147052, 7147055, 7147082, 7147083, 7147084, 7148020, 7148024, 7148027, 7148028, 7148032, 7148036, 7148037, 7148054, 7148057, 7148059, 7148063, 7148064, 7148065, 7148066, 7148067, 7149003, 7149004, 7149005, 7149006, 7149012, 7149017, 7149018, 7149019, 7149023, 7149026, 7150007, 7150008, 7150013, 7152035, 7152037, 7152049, 7152051, 7152062, 7153001, 7153002, 7153008, 7153014, 7153015, 7153021, 7153025, 7153032, 7153035, 7153095, 7153103, 7154005, 7154010, 7154011, 7154040, 7154044, 7154047, 7154051, 7154068, 7154069, 7154070, 7155010, 7155011, 7155013, 7155016, 7155019, 7155022, 7155023, 7155043, 7155044, 7155048, 7156006, 7156010, 7156017, 7156018, 7156019, 7156024, 7156025, 7156026, 7156027, 7156028] final_runlist_run5_no_minbias = [6119032, 6119038, 6119039, 6119063, 6119064, 6119065, 6119066, 6119067, 6119069, 6119071, 6119072, 6120009, 6120010, 6120011, 6120015, 6120016, 6120017, 6120019, 6120022, 6120032, 6120037, 6120038, 6120039, 6120040, 6120042, 6120043, 6120045, 6120049, 6120066, 6120070, 6120071, 6121009, 6121010, 6121013, 6121014, 6121015, 6121016, 6121018, 6121021, 6121022, 6121033, 6121036, 6121060, 6121061, 6121068, 6121070, 6121071, 6121072, 6121073, 6121075, 6121076, 6122001, 6122002, 6122010, 6122011, 6122013, 6122014, 6122018, 6127035, 6127036, 6127037, 6128005, 6128006, 6128007, 6128009, 6128011, 6128012, 6128013, 6128014, 6128015, 6128016, 6128022, 6128023, 6128024, 6128026, 6128027, 6128028, 6128029, 6128030, 6128031, 6128032, 6131007, 6131008, 6131009, 6131013, 6131048, 6131049, 6131052, 6131053, 6131054, 6131056, 6131057, 6131092, 6133006, 6133009, 6133010, 6133011, 6133012, 6133013, 6133014, 6133015, 6133016, 6133017, 6133018, 6133022, 6133026, 6133049, 6133071, 6133072, 6134001, 6134002, 6134003, 6134004, 6134005, 6134006, 6134007, 6134008, 6134010, 6134011, 6134024, 6134047, 6134060, 6136014, 6136015, 6136017, 6136018, 6136028, 6136029, 6136030, 6136031, 6136032, 6136034, 6136035, 6136037, 6136041, 6136042, 6136043, 6136119, 6136130, 6136131, 6137009, 6137011, 6137149, 6137157, 6137158, 6137159, 6137160, 6137163, 6137164, 6137166, 6137167, 6137169, 6137170, 6137171, 6137172, 6137173, 6138001, 6138002, 6138003, 6138004, 6138005, 6138010, 6138011, 6138012, 6138013, 6138014, 6138017, 6138018, 6138059, 6138061, 6138062, 6138067, 6139001, 6139002, 6139004, 6139005, 6139007, 6139008, 6139009, 6139010, 6139012, 6139018, 6139019, 6139020, 6139021, 6139022, 6139025, 6139026, 6139027, 6139028, 6139029, 6139030, 6139034, 6139036, 6139039, 6139041, 6139054, 6139055, 6139056, 6139061, 6139063, 6139064, 6139065, 6139071, 6140002, 6140003, 6140018, 6140019, 6140020, 6140021, 6140022, 6140023, 6140024, 6140025, 6140026, 6140028, 6140029, 6140030, 6140031, 6140032, 6140033, 6140034, 6140035, 6140036, 6140054, 6140065, 6140066, 6140067, 6140068, 6140069, 6140074, 6140075, 6140076, 6141009, 6141010, 6141011, 6141021, 6141022, 6141023, 6141026, 6141027, 6141028, 6141029, 6141030, 6141031, 6141032, 6141033, 6141047, 6141049, 6141050, 6141051, 6141052, 6141053, 6141058, 6141061, 6141062, 6141063, 6141064, 6141065, 6141066, 6141068, 6142001, 6142002, 6142003, 6142004, 6142005, 6142006, 6142007, 6142008, 6142010, 6142011, 6142012, 6142013, 6142014, 6142015, 6142016, 6142017, 6142018, 6142024, 6142025, 6142026, 6142027, 6142077, 6142078, 6142079, 6142080, 6142081, 6142082, 6142084, 6142087, 6142088, 6142089, 6142093, 6142094, 6142097, 6143001, 6143002, 6143012, 6143013, 6143014, 6143015, 6143016, 6143017, 6143018, 6143019, 6143021, 6143022, 6143023, 6143024, 6143025, 6143027, 6144017, 6144019, 6144020, 6144021, 6144022, 6144023, 6144024, 6144026, 6144051, 6144052, 6144053, 6144054, 6144057, 6144058, 6144059, 6144060, 6144061, 6144063, 6144066, 6145013, 6145015, 6145018, 6145019, 6145020, 6145023, 6145025, 6145027, 6145028, 6145045, 6145053, 6145054, 6145055, 6145056, 6145057, 6145058, 6145068, 6146017, 6146018, 6146019, 6146020, 6146021, 6146024, 6146025, 6147029, 6147030, 6148008, 6148009, 6148010, 6148011, 6148012, 6148013, 6148014, 6148017, 6148018, 6148019, 6148020, 6148054, 6148055, 6148056, 6148057, 6148058, 6148059, 6148060, 6148063, 6148064, 6149003, 6149004, 6149007, 6149016, 6149017, 6149018, 6149019, 6149020, 6149021, 6149024, 6149025, 6149029, 6149030, 6149031, 6149032, 6149036, 6149048, 6149050, 6149051, 6149052, 6150005, 6150006, 6150014, 6150015, 6150016, 6150017, 6150018, 6150019, 6150022, 6150023, 6150024, 6150025, 6150026, 6150027, 6150028, 6150029, 6150037, 6150038, 6151001, 6151002, 6151005, 6151008, 6151009, 6151011, 6151012, 6151013, 6151014, 6151015, 6151017, 6151018, 6151020, 6151021, 6151022, 6151023, 6151024, 6151026, 6151028, 6151029, 6156004, 6156010, 6156011, 6156012, 6156013, 6156014, 6156015, 6156016, 6156019, 6156027, 6156028, 6156029, 6156030, 6156034, 6156036, 6157050, 6157051, 6158014, 6158015, 6158019, 6158020, 6158025, 6158041, 6158057, 6158059, 6158060, 6158061, 6158062, 6158063, 6158076, 6158077, 6158081, 6158084, 6158085, 6158086, 6160039, 6160040, 6160041, 6160044, 6160048, 6160056, 6160057, 6160058, 6160061, 6160062, 6160065, 6160068, 6160069, 6160070, 6160071, 6160072, 6160082, 6160083, 6161001, 6161006, 6161007, 6161035, 6161038, 6161042, 6161043, 6161044, 6161046, 6161047, 6161091, 6161092, 6161093, 6161094, 6161097, 6161098, 6161099, 6161100, 6161101, 6161102, 6161104, 6161105, 6162005, 6162006, 6162007, 6162014, 6162027, 6162028, 6162029, 6162030, 6162031, 6162032, 6162039, 6162040, 6162041, 6162042, 6162043, 6162044, 6162045, 6162046, 6162056, 6162058, 6162061, 6162062, 6162063, 6162064, 6162068, 6162069, 6162070, 6162071, 6162072, 6162075, 6162076, 6163012, 6163013, 6163015, 6163016, 6163017, 6163018, 6163021, 6163022, 6163023, 6163024, 6163025, 6163038, 6163039, 6163040, 6163041, 6163043, 6163044, 6163045, 6163048, 6163050, 6163051, 6163053, 6163054, 6163056, 6163057, 6163058, 6164002, 6164003, 6164004, 6164013, 6164016, 6164017, 6164018, 6164022, 6164023, 6164024, 6167115, 6167116, 6167119, 6167131, 6167134, 6167140, 6167141, 6168018, 6168019, 6168022, 6168023, 6168024, 6168036, 6168044, 6168068, 6168069, 6168072, 6168073, 6168083, 6168084, 6168085, 6168086, 6168089, 6168090, 6168099, 6168100, 6168101, 6168102, 6168103, 6168104, 6168107, 6168108, 6168112, 6169001, 6169002, 6169003, 6169006, 6169007, 6169008, 6169020, 6169025, 6169026, 6169027, 6169028, 6169029, 6169030, 6169031, 6169035, 6169036, 6169037, 6169038, 6169039, 6169041, 6169043, 6169044, 6169047, 6169048, 6169049, 6169050, 6169051, 6169052, 6169053, 6169055, 6169056, 6169057, 6169058, 6169060, 6169079, 6169080, 6169082, 6169083, 6169084, 6169088, 6169089, 6169090, 6169091, 6169092, 6169093, 6169094, 6169096, 6169097, 6169101, 6169103, 6169104, 6169105, 6169106, 6169107, 6170002, 6170006, 6170009, 6170010, 6170011, 6170012, 6170013, 6170014, 6170015, 6170018, 6170031, 6170032, 6170033, 6170034, 6170035, 6170038, 6170039, 6170040, 6170041, 6170045, 6171022, 6171024, 6171034, 6171039, 6171040, 6171041, 6171043, 6171044, 6171045, 6171046, 6171048, 6171049, 6171062, 6171063, 6172001, 6172002, 6172003, 6172006, 6172007, 6172010, 6172069, 6172085, 6172086, 6172087, 6172092, 6172093, 6174010, 6174011, 6174012, 6174013, 6174014, 6174017, 6174018, 6174019, 6174020, 6174021, 6174026, 6174027, 6174031, 6174044, 6174045, 6174046, 6174047, 6174048, 6174049, 6174053, 6174054, 6174055, 6174056, 6174057, 6174058, 6174059, 6174060, 6174069, 6174070, 6174072] final_runlist_run5 = final_runlist_run5_no_minbias + minbias_runs final_runlist_run5.sort() __all__ = ['transverse_run5', 'transverse_run6_iucf', 'transverse_run6', 'long2_run6', 'golden_runlist_c', 'minbias_runs', 'final_runlist_run5']
class Details: def __init__(self, details): self.details = details def __getattr__(self, attr): if attr in self.details: return self.details[attr] else: raise AttributeError('{attr} is not a valid attribute of Details'.format(attr)) @property def all(self): return self.details
class Details: def __init__(self, details): self.details = details def __getattr__(self, attr): if attr in self.details: return self.details[attr] else: raise attribute_error('{attr} is not a valid attribute of Details'.format(attr)) @property def all(self): return self.details
# Aula 18 - Listas (Parte 2) teste = list() teste.append('Marieliton') teste.append(33) galera = list() #galera.append(teste) # fazer isso cria uma dependencia entre as listas galera.append(teste[:]) # isso faz a copia da lista sem criar dependencia print(galera) teste[0] = 'Maria' teste[1] = 22 print(teste) galera.append(teste) print(galera) # --------------------- galera = [['Joao', 19], ['Ana', 31], ['Manoel', 42], ['Maria', 51]] #print(galera[3][0]) #print(galera[2][1]) for pessoa in galera: print(f'{pessoa[0]} tem {pessoa[1]} anos de idade.') # --------------------- galera = list() dado = [] demaior = demenor = 0 for c in range(0, 3): dado.append(str(input('Nome: '))) dado.append(int(input('Idade: '))) galera.append(dado[:]) dado.clear() for pessoa in galera: if pessoa[1] >= 21: print(f'{pessoa[0]} eh maior de idade.') demaior += 1 else: print(f'{pessoa[0]} eh menor de idade.') demenor += 1 print(f'Temos {demaior} maiores e {demenor} menores de idade.')
teste = list() teste.append('Marieliton') teste.append(33) galera = list() galera.append(teste[:]) print(galera) teste[0] = 'Maria' teste[1] = 22 print(teste) galera.append(teste) print(galera) galera = [['Joao', 19], ['Ana', 31], ['Manoel', 42], ['Maria', 51]] for pessoa in galera: print(f'{pessoa[0]} tem {pessoa[1]} anos de idade.') galera = list() dado = [] demaior = demenor = 0 for c in range(0, 3): dado.append(str(input('Nome: '))) dado.append(int(input('Idade: '))) galera.append(dado[:]) dado.clear() for pessoa in galera: if pessoa[1] >= 21: print(f'{pessoa[0]} eh maior de idade.') demaior += 1 else: print(f'{pessoa[0]} eh menor de idade.') demenor += 1 print(f'Temos {demaior} maiores e {demenor} menores de idade.')
expected_output = { "Ethernet1/1": { "advertising_code": "Passive Cu", "cable_attenuation": "0/0/0/0/0 dB for bands 5/7/12.9/25.8/56 " "GHz", "cable_length": 2.0, "cis_part_number": "37-1843-01", "cis_product_id": "QDD-400-CU2M", "cis_version_id": "V01", "cisco_id": "0x18", "clei": "CMPQAGSCAA", "cmis_ver": 4, "date_code": "20031400", "dom_supported": False, "far_end_lanes": "8 lanes aaaaaaaa", "host_electrical_intf": "Undefined", "max_power": 1.5, "media_interface": "copper cable unequalized", "name": "CISCO-LEONI", "near_end_lanes": "none", "nominal_bitrate": 425000, "part_number": "L45593-K218-C20", "power_class": "1 (1.5 W maximum)", "revision": "00", "serial_number": "LCC2411GG1W-A", "vendor_oui": "a8b0ae", "transceiver_present": True, "transceiver_type": "QSFP-DD-400G-COPPER", } }
expected_output = {'Ethernet1/1': {'advertising_code': 'Passive Cu', 'cable_attenuation': '0/0/0/0/0 dB for bands 5/7/12.9/25.8/56 GHz', 'cable_length': 2.0, 'cis_part_number': '37-1843-01', 'cis_product_id': 'QDD-400-CU2M', 'cis_version_id': 'V01', 'cisco_id': '0x18', 'clei': 'CMPQAGSCAA', 'cmis_ver': 4, 'date_code': '20031400', 'dom_supported': False, 'far_end_lanes': '8 lanes aaaaaaaa', 'host_electrical_intf': 'Undefined', 'max_power': 1.5, 'media_interface': 'copper cable unequalized', 'name': 'CISCO-LEONI', 'near_end_lanes': 'none', 'nominal_bitrate': 425000, 'part_number': 'L45593-K218-C20', 'power_class': '1 (1.5 W maximum)', 'revision': '00', 'serial_number': 'LCC2411GG1W-A', 'vendor_oui': 'a8b0ae', 'transceiver_present': True, 'transceiver_type': 'QSFP-DD-400G-COPPER'}}
a=input().split();r=5000 for i in a: if i=='1': r-=500 elif i=='2': r-=800 else: r-=1000 print(r)
a = input().split() r = 5000 for i in a: if i == '1': r -= 500 elif i == '2': r -= 800 else: r -= 1000 print(r)
# -*- coding: utf-8 -*- """ Created on Fri Apr 16 14:25:12 2021 @author: ELCOT """ class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1.0 if n == 1: return x if n == 2: return x*x isNeg = 0 if n < 0: isNeg = 1 ans = self.helperfunc(x, abs(n)) if isNeg: return 1/ans return ans # helper function to use divide and conquer DP strategy def helperfunc(self, num, p): if p == 1: return num if p%2 == 0: return self.helperfunc(num , p//2) * self.helperfunc(num , p//2) else: print(num) return self.helperfunc(num , (p-1)//2) * self.helperfunc(num , (p-1)//2) * num Solution().myPow(0.00001,47) """ class Solution: def myPow(self, x: float, n: int) -> float: def function(base = x, exponent = abs(n)): if exponent == 0: return 1 elif exponent % 2 == 0: return function(base * base, exponent // 2) else: return base * function(base * base, (exponent - 1) // 2) f = function() return float(f) if n >= 0 else 1/f """
""" Created on Fri Apr 16 14:25:12 2021 @author: ELCOT """ class Solution: def my_pow(self, x: float, n: int) -> float: if n == 0: return 1.0 if n == 1: return x if n == 2: return x * x is_neg = 0 if n < 0: is_neg = 1 ans = self.helperfunc(x, abs(n)) if isNeg: return 1 / ans return ans def helperfunc(self, num, p): if p == 1: return num if p % 2 == 0: return self.helperfunc(num, p // 2) * self.helperfunc(num, p // 2) else: print(num) return self.helperfunc(num, (p - 1) // 2) * self.helperfunc(num, (p - 1) // 2) * num solution().myPow(1e-05, 47) '\nclass Solution:\n def myPow(self, x: float, n: int) -> float:\n\n def function(base = x, exponent = abs(n)):\n if exponent == 0:\n return 1\n elif exponent % 2 == 0:\n return function(base * base, exponent // 2)\n else:\n return base * function(base * base, (exponent - 1) // 2)\n\n f = function()\n \n return float(f) if n >= 0 else 1/f\n'
# https://leetcode.com/problems/clone-graph/description/ # # algorithms # Medium (25.08%) # Total Accepted: 180.2K # Total Submissions: 718.5K # beats 50.23% of python submissions # Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def __init__(self): self.hash_map = {} def cloneGraph(self, node): if not node: return node new_node = UndirectedGraphNode(node.label) self.hash_map[node.label] = new_node for neighbor in node.neighbors: if neighbor.label in self.hash_map: new_node.neighbors.append(self.hash_map[neighbor.label]) else: new_node.neighbors.append(self.cloneGraph(neighbor)) return new_node
class Solution: def __init__(self): self.hash_map = {} def clone_graph(self, node): if not node: return node new_node = undirected_graph_node(node.label) self.hash_map[node.label] = new_node for neighbor in node.neighbors: if neighbor.label in self.hash_map: new_node.neighbors.append(self.hash_map[neighbor.label]) else: new_node.neighbors.append(self.cloneGraph(neighbor)) return new_node
class Preprocessor(object): """ Preprocessor: Apply simple preprocessing operations to real-valued numerical datasets (min-max normalization) """ def __init__(self, data): """ Initializes the Preprocessor according to the provided dataset Arguments: data {np.ndarray} -- dataset used to determined the parameters for the normalization An N x K dimensional dataset (N samples, K features) """ self._num_features = data.shape[1] # Number of features per sample self._data_mins = data.min(axis=0) # Minimum value per feature self._data_ranges = data.ptp(axis=0) # Range per feature (peak-to-peak) def apply(self, data): """ Apply the pre-processing operations to the provided dataset (min-max normalization over the range [0, 1]) Arguments: data {np.ndarray} -- dataset to be normalized Returns: {np.ndarray} normalized dataset """ assert data.shape[1] == self._num_features return (data - self._data_mins) / self._data_ranges def revert(self, data): """ Revert the pre-processing operations to retrieve original dataset (min-max normalization over the range [0, 1]) Arguments: data {np.ndarray} -- dataset for which to revert normalization Returns: {np.ndarray} reverted dataset """ assert data.shape[1] == self._num_features return (data * self._data_ranges) + self._data_mins
class Preprocessor(object): """ Preprocessor: Apply simple preprocessing operations to real-valued numerical datasets (min-max normalization) """ def __init__(self, data): """ Initializes the Preprocessor according to the provided dataset Arguments: data {np.ndarray} -- dataset used to determined the parameters for the normalization An N x K dimensional dataset (N samples, K features) """ self._num_features = data.shape[1] self._data_mins = data.min(axis=0) self._data_ranges = data.ptp(axis=0) def apply(self, data): """ Apply the pre-processing operations to the provided dataset (min-max normalization over the range [0, 1]) Arguments: data {np.ndarray} -- dataset to be normalized Returns: {np.ndarray} normalized dataset """ assert data.shape[1] == self._num_features return (data - self._data_mins) / self._data_ranges def revert(self, data): """ Revert the pre-processing operations to retrieve original dataset (min-max normalization over the range [0, 1]) Arguments: data {np.ndarray} -- dataset for which to revert normalization Returns: {np.ndarray} reverted dataset """ assert data.shape[1] == self._num_features return data * self._data_ranges + self._data_mins
def preprocess_input(date, state_holiday): day, month = (int(date.split(" ")[0]), int(date.split(" ")[1])) if state_holiday == 'a': state_holiday = 1 elif state_holiday == 'b': state_holiday = 2 elif state_holiday == 'c': state_holiday = 3 else: state_holiday = 0 return day, month, state_holiday
def preprocess_input(date, state_holiday): (day, month) = (int(date.split(' ')[0]), int(date.split(' ')[1])) if state_holiday == 'a': state_holiday = 1 elif state_holiday == 'b': state_holiday = 2 elif state_holiday == 'c': state_holiday = 3 else: state_holiday = 0 return (day, month, state_holiday)
class dotDrawText_t(object): # no doc aText=None Color=None Location=None
class Dotdrawtext_T(object): a_text = None color = None location = None
numeros = [-12, 84, 13, 20, -33, 101, 9] def separar(lista): pares = [] impares = [] for numero in lista: if numero%2 == 0: pares.append(numero) else: impares.append(numero) return pares, impares pares, impares = separar(numeros) print(pares) print(impares)
numeros = [-12, 84, 13, 20, -33, 101, 9] def separar(lista): pares = [] impares = [] for numero in lista: if numero % 2 == 0: pares.append(numero) else: impares.append(numero) return (pares, impares) (pares, impares) = separar(numeros) print(pares) print(impares)
# callback handlers: reloaded each time triggered def message1(): # change me print('spamSpamSPAM') # or could build a dialog... def message2(self): print('Ni! Ni!') # change me self.method1() # access the 'Hello' instance...
def message1(): print('spamSpamSPAM') def message2(self): print('Ni! Ni!') self.method1()
class DetailModel: class Mesh: def __init__(self): self.vertices_count = None self.indices_count = None self.uv_map_name = 'Texture' self.bpy_mesh = None self.bpy_material = None def __init__(self): self.shader = None self.texture = None self.mode = None self.mesh = self.Mesh() VERTICES_COUNT_LIMIT = 0x10000
class Detailmodel: class Mesh: def __init__(self): self.vertices_count = None self.indices_count = None self.uv_map_name = 'Texture' self.bpy_mesh = None self.bpy_material = None def __init__(self): self.shader = None self.texture = None self.mode = None self.mesh = self.Mesh() vertices_count_limit = 65536
def fibonacci_numbers(ul: int) -> int: numbers: list = [] a: int = 0 b: int = 1 total: int = 0 while (total <= ul): numbers.append(total) a = b b = total total = a + b return sum(filter(lambda x: not x % 2, numbers)) if __name__ == '__main__': t: int = int(input().strip()) for _x in range(t): n: int = int(input().strip()) print(fibonacci_numbers(n))
def fibonacci_numbers(ul: int) -> int: numbers: list = [] a: int = 0 b: int = 1 total: int = 0 while total <= ul: numbers.append(total) a = b b = total total = a + b return sum(filter(lambda x: not x % 2, numbers)) if __name__ == '__main__': t: int = int(input().strip()) for _x in range(t): n: int = int(input().strip()) print(fibonacci_numbers(n))
nm = input().split() n = int(nm[0]) m = int(nm[1]) mt = [] for _ in range(n): matrix_item = input() mt.append(matrix_item) p=0 print(mt) k = int(input()) for i in range(n): for j in range(m): if(mt[i][j]=="M"): print(i,j) for i in range(n): for j in range(m): print(i,j) if(mt[i][j]=='x'): p=p+1 if(mt[i+1][j]!='x' and i!=n): i=i+1 elif(mt[i-1][j]!='x'): i=i-1 elif(mt[i][j+1]!='x'): j=j+1 if(mt[i][j-1]!='x'): j=j+1 elif(mt[i][j]=='*'): break print(p) if(p==k): print("g") else: print("b")
nm = input().split() n = int(nm[0]) m = int(nm[1]) mt = [] for _ in range(n): matrix_item = input() mt.append(matrix_item) p = 0 print(mt) k = int(input()) for i in range(n): for j in range(m): if mt[i][j] == 'M': print(i, j) for i in range(n): for j in range(m): print(i, j) if mt[i][j] == 'x': p = p + 1 if mt[i + 1][j] != 'x' and i != n: i = i + 1 elif mt[i - 1][j] != 'x': i = i - 1 elif mt[i][j + 1] != 'x': j = j + 1 if mt[i][j - 1] != 'x': j = j + 1 elif mt[i][j] == '*': break print(p) if p == k: print('g') else: print('b')
class TwoSum: def __init__(self): self.numberCountMap = {} """ @param number: An integer @return: nothing """ def add(self, number): count = 1 if number in self.numberCountMap : count = self.numberCountMap[number]+1 self.numberCountMap[number] = count """ @param value: An integer @return: Find if there exists any pair of numbers which sum is equal to the value. """ def find(self, value): for node in self.numberCountMap : rest = value-node if rest == node : if self.numberCountMap[node]>1 : return True elif rest in self.numberCountMap: return True return False
class Twosum: def __init__(self): self.numberCountMap = {} '\n @param number: An integer\n @return: nothing\n ' def add(self, number): count = 1 if number in self.numberCountMap: count = self.numberCountMap[number] + 1 self.numberCountMap[number] = count '\n @param value: An integer\n @return: Find if there exists any pair of numbers which sum is equal to the value.\n ' def find(self, value): for node in self.numberCountMap: rest = value - node if rest == node: if self.numberCountMap[node] > 1: return True elif rest in self.numberCountMap: return True return False
class Formatter: def __init__(self): pass def format(self, args, data): if args.vba: self.format_VBA(args,data) elif args.csharp: self.format_CSharp(args,data) elif args.cpp: self.format_CPP(args,data) elif args.raw: print(f"[+] will write raw transformed data into [{args.output_file}]") self.format_raw(args,data) else: print(f"[-] no data transformation was provided! exitting.") def format_CPP(self, args, data): shellcode = "\\x" shellcode += "\\x".join(format(b, '02x') for b in data) if args.verbose: print("Your formatted payload is: \n") print(shellcode+ "\n") if args.output_file: self.write_to_file(args, shellcode) return shellcode def format_CSharp(self, args, data): shellcode = '0x' shellcode += ',0x'.join(format(b, '02x') for b in data) if args.verbose: print("Your formatted payload is: \n") print(shellcode + "\n") if args.output_file: self.write_to_file(args, shellcode) return shellcode def format_VBA(self, args, data): shellcode = ','.join(format(b,'') for b in data) shellcode_splitted = shellcode.split(',') for index in range(len(shellcode_splitted)): if index != 0 and index % 50 == 0: shellcode_splitted.insert(index, ' _\n') shellcode = ",".join(shellcode_splitted) shellcode = shellcode.replace("_\n,", "_\n") if args.verbose: print("Your formatted payload is: \n") print(shellcode+ "\n") if args.output_file: self.write_to_file(args, shellcode) return shellcode def format_raw(self, args,data): if args.verbose: print("Your formatted payload is: \n") print(str(data) + "\n") if args.output_file: self.write_to_file(args, data) return data def write_to_file(self, args, data): if args.raw: open(args.output_file, 'wb').write(data) else: open(args.output_file, 'w').write(data) print(f"[+] data written to {args.output_file} successfully!")
class Formatter: def __init__(self): pass def format(self, args, data): if args.vba: self.format_VBA(args, data) elif args.csharp: self.format_CSharp(args, data) elif args.cpp: self.format_CPP(args, data) elif args.raw: print(f'[+] will write raw transformed data into [{args.output_file}]') self.format_raw(args, data) else: print(f'[-] no data transformation was provided! exitting.') def format_cpp(self, args, data): shellcode = '\\x' shellcode += '\\x'.join((format(b, '02x') for b in data)) if args.verbose: print('Your formatted payload is: \n') print(shellcode + '\n') if args.output_file: self.write_to_file(args, shellcode) return shellcode def format_c_sharp(self, args, data): shellcode = '0x' shellcode += ',0x'.join((format(b, '02x') for b in data)) if args.verbose: print('Your formatted payload is: \n') print(shellcode + '\n') if args.output_file: self.write_to_file(args, shellcode) return shellcode def format_vba(self, args, data): shellcode = ','.join((format(b, '') for b in data)) shellcode_splitted = shellcode.split(',') for index in range(len(shellcode_splitted)): if index != 0 and index % 50 == 0: shellcode_splitted.insert(index, ' _\n') shellcode = ','.join(shellcode_splitted) shellcode = shellcode.replace('_\n,', '_\n') if args.verbose: print('Your formatted payload is: \n') print(shellcode + '\n') if args.output_file: self.write_to_file(args, shellcode) return shellcode def format_raw(self, args, data): if args.verbose: print('Your formatted payload is: \n') print(str(data) + '\n') if args.output_file: self.write_to_file(args, data) return data def write_to_file(self, args, data): if args.raw: open(args.output_file, 'wb').write(data) else: open(args.output_file, 'w').write(data) print(f'[+] data written to {args.output_file} successfully!')
"""This module contains code for computing variant statistics and pedigree checks. It provides similar functionality to Peddy but works with a database backend. Peddy is described in Pedersen & Quinlan (2017). """
"""This module contains code for computing variant statistics and pedigree checks. It provides similar functionality to Peddy but works with a database backend. Peddy is described in Pedersen & Quinlan (2017). """
"""The all pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest path problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will represent the minimum distance from any node to all other nodes in the graph. """ """For better understanding watch the video https://www.youtube.com/watch?v=oNI0rf2P9gE""" inf = float('INF') vertices = 4 graph = [[0, 3, inf, 7], [8, 0, 2, inf], [5, inf, 0, 1], [2, inf, inf, 0]] for k in range(vertices): for i in range(vertices): for j in range(vertices): if graph[i][j] != 0: graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]) print(graph)
"""The all pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest path problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will represent the minimum distance from any node to all other nodes in the graph. """ 'For better understanding watch the video https://www.youtube.com/watch?v=oNI0rf2P9gE' inf = float('INF') vertices = 4 graph = [[0, 3, inf, 7], [8, 0, 2, inf], [5, inf, 0, 1], [2, inf, inf, 0]] for k in range(vertices): for i in range(vertices): for j in range(vertices): if graph[i][j] != 0: graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]) print(graph)
M = int(input()) N = int(input())+1 numbers = [] for i in range(M,N): c = 0 for j in range(1,i+1): if i%j == 0: c += 1 if c > 2: break if c == 2: numbers.append(i) if sum(numbers) == 0: print(-1) else: print(sum(numbers),min(numbers),sep='\n')
m = int(input()) n = int(input()) + 1 numbers = [] for i in range(M, N): c = 0 for j in range(1, i + 1): if i % j == 0: c += 1 if c > 2: break if c == 2: numbers.append(i) if sum(numbers) == 0: print(-1) else: print(sum(numbers), min(numbers), sep='\n')
# Runtime: 176 ms # Beats 77.94% of Python submissions # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(): def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ if not nums: return None if len(nums) == 1: return TreeNode(nums[0]) curr_max, max_index = self.max(nums) root = TreeNode(curr_max) root.left = self.constructMaximumBinaryTree(nums[:max_index]) root.right = self.constructMaximumBinaryTree(nums[max_index + 1:]) return root def max(self, nums): curr_max = nums[0] max_index = 0 for i in range(1, len(nums)): if nums[i] > curr_max: curr_max = nums[i] max_index = i return curr_max, max_index
class Solution: def construct_maximum_binary_tree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ if not nums: return None if len(nums) == 1: return tree_node(nums[0]) (curr_max, max_index) = self.max(nums) root = tree_node(curr_max) root.left = self.constructMaximumBinaryTree(nums[:max_index]) root.right = self.constructMaximumBinaryTree(nums[max_index + 1:]) return root def max(self, nums): curr_max = nums[0] max_index = 0 for i in range(1, len(nums)): if nums[i] > curr_max: curr_max = nums[i] max_index = i return (curr_max, max_index)