content
stringlengths
7
1.05M
s = 1 c = maior = menor = cont = k = 0 while c != 'N': s = int(input('Digite um número: ')) c = str(input('Quer continuar? [S/N] ')).strip().upper() cont += 1 k += s if cont == 1: maior = menor = s else: if s > maior: maior = s if s < menor: menor = s media = k / cont print('Você digitou {} números e a média entre eles é {:.1f}'.format(cont, media)) print('O maior número digitado foi {} e o menor foi {}'.format(maior, menor))
chemin = r'c:\temp\demo.txt' fichier = open(chemin,'r') ligne = fichier.readline() while ligne: print(ligne, end='') ligne = fichier.readline() fichier.close()
def index(r): pass def sum(r): pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 13 13:00:03 2018 @author: Khaled Nakhleh """ if __name__ == "__main__": print("\n\tThis file only contains internal functions. Please use main.py to run the program.\n") exit
""" Search in Rotated Sorted Array Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. Your algorithm's runtime complexity must be in the order of O(log n). --------------------------------------------------------------------------------- Explanation algorithm: In classic binary search, we compare val with the midpoint to figure out if val belongs on the low or the high side. The complication here is that the array is rotated and may have an inflection point. Consider, for example: Array1: [10, 15, 20, 0, 5] Array2: [50, 5, 20, 30, 40] Note that both arrays have a midpoint of 20, but 5 appears on the left side of one and on the right side of the other. Therefore, comparing val with the midpoint is insufficient. However, if we look a bit deeper, we can see that one half of the array must be ordered normally(increasing order). We can therefore look at the normally ordered half to determine whether we should search the low or hight side. For example, if we are searching for 5 in Array1, we can look at the left element (10) and middle element (20). Since 10 < 20, the left half must be ordered normally. And, since 5 is not between those, we know that we must search the right half In array2, we can see that since 50 > 20, the right half must be ordered normally. We turn to the middle 20, and right 40 element to check if 5 would fall between them. The value 5 would not Therefore, we search the left half. There are 2 possible solution: iterative and recursion. Recursion helps you understand better the above algorithm explanation """ def search_rotate(array, val): """ Finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot. """ low, high = 0, len(array) - 1 while low <= high: mid = (low + high) // 2 if val == array[mid]: return mid if array[low] <= array[mid]: if array[low] <= val <= array[mid]: high = mid - 1 else: low = mid + 1 else: if array[mid] <= val <= array[high]: low = mid + 1 else: high = mid - 1 return -1 # Recursion technique def search_rotate_recur(array, low, high, val): """ Finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot. """ if low >= high: return -1 mid = (low + high) // 2 if val == array[mid]: # found element return mid if array[low] <= array[mid]: if array[low] <= val <= array[mid]: return search_rotate_recur(array, low, mid - 1, val) # Search left return search_rotate_recur(array, mid + 1, high, val) # Search right if array[mid] <= val <= array[high]: return search_rotate_recur(array, mid + 1, high, val) # Search right return search_rotate_recur(array, low, mid - 1, val) # Search left
class Planet: def count_age(self, earth_years, planet): if type(earth_years) is int and type(planet) is str: if earth_years < 0: raise Exception('Wiek nie moze byc ujemny') stala = earth_years / 31557600 if planet == 'Ziemia': return round(stala, 2) elif planet == 'Merkury': return round(stala / 0.2408467, 2) elif planet == 'Wenus': return round(stala / 0.61519726, 2) elif planet == 'Mars': return round(stala / 1.8808158, 2) elif planet == 'Jowisz': return round(stala / 11.862615, 2) elif planet == 'Saturn': return round(stala / 29.447498, 2) elif planet == 'Uran': return round(stala / 84.016846, 2) elif planet == 'Neptun': return round(stala / 164.79132, 2) else: return 'Planeta nie istnieje' else: raise Exception('Zle typy')
imports = ["base.py"] train_option = { "n_train_iteration": 6000, "interval_iter": 2000, } train_artifact_dir = "artifacts/train" evaluate_artifact_dir = "artifacts/evaluate" reference = False model = torch.nn.Sequential( modules=collections.OrderedDict( items=[ [ "encoder", torch.nn.Sequential( modules=collections.OrderedDict( items=[ [ "encoder", Apply( in_keys=[["test_case_tensor", "x"]], out_key="input_feature", module=mlprogram.nn.CNN2d( in_channel=1, out_channel=16, hidden_channel=32, n_conv_per_block=2, n_block=2, pool=2, ), ), ], [ "reduction", Apply( in_keys=[["input_feature", "input"]], out_key="input_feature", module=torch.Mean( dim=1, ), ), ], ], ), ), ], [ "decoder", torch.nn.Sequential( modules=collections.OrderedDict( items=[ [ "action_embedding", Apply( module=mlprogram.nn.action_sequence.PreviousActionsEmbedding( n_rule=encoder._rule_encoder.vocab_size, n_token=encoder._token_encoder.vocab_size, embedding_size=256, ), in_keys=["previous_actions"], out_key="action_features", ), ], [ "decoder", Apply( module=mlprogram.nn.action_sequence.LSTMDecoder( inject_input=mlprogram.nn.action_sequence.CatInput(), input_feature_size=mul( x=16, y=mul( x=n_feature_pixel, y=n_feature_pixel, ), ), action_feature_size=256, output_feature_size=512, dropout=0.1, ), in_keys=[ "input_feature", "action_features", "hidden_state", "state", ], out_key=[ "action_features", "hidden_state", "state", ], ), ], [ "predictor", Apply( module=mlprogram.nn.action_sequence.Predictor( feature_size=512, reference_feature_size=1, rule_size=encoder._rule_encoder.vocab_size, token_size=encoder._token_encoder.vocab_size, hidden_size=512, ), in_keys=[ "reference_features", "action_features", ], out_key=[ "rule_probs", "token_probs", "reference_probs", ], ), ], ], ), ), ], ], ), ) collate = mlprogram.utils.data.Collate( test_case_tensor=mlprogram.utils.data.CollateOptions( use_pad_sequence=False, dim=0, padding_value=0, ), input_feature=mlprogram.utils.data.CollateOptions( use_pad_sequence=False, dim=0, padding_value=0, ), reference_features=mlprogram.utils.data.CollateOptions( use_pad_sequence=True, dim=0, padding_value=0, ), previous_actions=mlprogram.utils.data.CollateOptions( use_pad_sequence=True, dim=0, padding_value=-1, ), hidden_state=mlprogram.utils.data.CollateOptions( use_pad_sequence=False, dim=0, padding_value=0, ), state=mlprogram.utils.data.CollateOptions( use_pad_sequence=False, dim=0, padding_value=0, ), ground_truth_actions=mlprogram.utils.data.CollateOptions( use_pad_sequence=True, dim=0, padding_value=-1, ), ) transform_input = mlprogram.functools.Sequence( funcs=collections.OrderedDict( items=[ [ "add_reference", Apply( module=mlprogram.transforms.action_sequence.AddEmptyReference(), in_keys=[], out_key=["reference", "reference_features"], ), ], [ "transform_canvas", Apply( module=mlprogram.languages.csg.transforms.TransformInputs(), in_keys=["test_cases"], out_key="test_case_tensor", ), ], ], ), ) transform_action_sequence = mlprogram.functools.Sequence( funcs=collections.OrderedDict( items=[ [ "add_previous_actions", Apply( module=mlprogram.transforms.action_sequence.AddPreviousActions( action_sequence_encoder=encoder, n_dependent=1, ), in_keys=["action_sequence", "reference", "train"], out_key="previous_actions", ), ], [ "add_state", mlprogram.transforms.action_sequence.AddState(key="state"), ], [ "add_hidden_state", mlprogram.transforms.action_sequence.AddState(key="hidden_state"), ], ], ), ) transform = mlprogram.functools.Sequence( funcs=collections.OrderedDict( items=[ [ "set_train", Apply(module=Constant(value=True), in_keys=[], out_key="train"), ], ["transform_input", transform_input], [ "transform_code", Apply( module=mlprogram.transforms.action_sequence.GroundTruthToActionSequence( parser=parser, ), in_keys=["ground_truth"], out_key="action_sequence", ), ], ["transform_action_sequence", transform_action_sequence], [ "transform_ground_truth", Apply( module=mlprogram.transforms.action_sequence.EncodeActionSequence( action_sequence_encoder=encoder, ), in_keys=["action_sequence", "reference"], out_key="ground_truth_actions", ), ], ], ), ) sampler = mlprogram.samplers.transform( sampler=mlprogram.samplers.ActionSequenceSampler( encoder=encoder, is_subtype=mlprogram.languages.csg.IsSubtype(), transform_input=transform_input, transform_action_sequence=mlprogram.functools.Sequence( funcs=collections.OrderedDict( items=[ [ "set_train", Apply( module=Constant(value=False), in_keys=[], out_key="train" ), ], ["transform", transform_action_sequence], ] ) ), collate=collate, module=model, ), transform=parser.unparse, ) base_synthesizer = mlprogram.synthesizers.SMC( max_step_size=mul( x=5, y=mul( x=5, y=dataset_option.evaluate_max_object, ), ), initial_particle_size=100, max_try_num=50, sampler=sampler, to_key=Pick( key="action_sequence", ), )
class Node(object): def __init__(self, children=None, is_root=False): if isinstance(children, Node): children = [children] self.is_root = is_root self.children = list(children) if children else [] @classmethod def precedence(self): return 0 @classmethod def is_logical(self): return False def add(self, child): self.children.append(child) return child def pop(self): return self.children.pop() def dump(self, indent=0): isroot = '(root)' if self.is_root else '' result = [(indent * ' ') + self.__class__.__name__ + isroot] for child in self.children: result += child.dump(indent+1) if self.is_root: return '\n'.join(result) return result def each(self, func, node_type=None): """ Runs func once for every node in the object tree. If node_type is not None, only call func for nodes with the given type. """ if node_type is None or isinstance(self, node_type): func(self) for child in self.children: child.each(func, node_type)
""" Base class for exceptions in this module. This class was created for better extensibility should more features be added and need treatment. """ class Error(Exception): pass """ Exception raised for errors in the input. Attributes: msg -- explanation of the error """ class InputError(Error): def __init__(self, msg): self.msg = msg
# Tratando valores v1 while num = cont = soma = 0 while num != 999: num = int(input('[Pare digitando 999] Digite um número: ')) soma += num cont += 1 print('Você digitou {} números e a soma entre eles foi {}.'.format(cont-1, soma-999)) '''num = cont = soma = 0 num = int(input('[Pare digitando 999] Digite um número: ')) while num != 999: soma += num cont += 1 num = int(input('[Pare digitando 999] Digite um número: ')) print('Você digitou {} números e a soma entre eles foi {}.'.format(cont, soma))'''
# Copyright (c) 2010-2013 OpenStack, LLC. # # 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. class ClientException(Exception): def __init__(self, msg, http_scheme='', http_host='', http_port='', http_path='', http_query='', http_status=0, http_reason='', http_device='', http_response_content=''): Exception.__init__(self, msg) self.msg = msg self.http_scheme = http_scheme self.http_host = http_host self.http_port = http_port self.http_path = http_path self.http_query = http_query self.http_status = http_status self.http_reason = http_reason self.http_device = http_device self.http_response_content = http_response_content def __str__(self): a = self.msg b = '' if self.http_scheme: b += '%s://' % self.http_scheme if self.http_host: b += self.http_host if self.http_port: b += ':%s' % self.http_port if self.http_path: b += self.http_path if self.http_query: b += '?%s' % self.http_query if self.http_status: if b: b = '%s %s' % (b, self.http_status) else: b = str(self.http_status) if self.http_reason: if b: b = '%s %s' % (b, self.http_reason) else: b = '- %s' % self.http_reason if self.http_device: if b: b = '%s: device %s' % (b, self.http_device) else: b = 'device %s' % self.http_device if self.http_response_content: if len(self.http_response_content) <= 60: b += ' %s' % self.http_response_content else: b += ' [first 60 chars of response] %s' \ % self.http_response_content[:60] return b and '%s: %s' % (a, b) or a class InvalidHeadersException(Exception): pass
# Programinha simples para converter temperatura ºF em ºC tempF = float(input('Qual o valor da temperatura em F? ')) tempC = ((tempF - 32) * 5) / 9 print('A temperatura em Celsius é {:.2f}ºC'.format(tempC))
class Solution: def regionsBySlashes(self, grid: List[str]) -> int: def dfs(i, j, k): if 0 <= i < n > j >= 0 and not matrix[i][j][k]: if grid[i][j] == "*": if k <= 1: matrix[i][j][0] = matrix[i][j][1] = cnt dfs(i - 1, j, 2) dfs(i, j + 1, 3) else: matrix[i][j][2] = matrix[i][j][3] = cnt dfs(i + 1, j, 0) dfs(i, j - 1, 1) elif grid[i][j] == "/": if 1 <= k <= 2: matrix[i][j][1] = matrix[i][j][2] = cnt dfs(i, j + 1, 3) dfs(i + 1, j, 0) else: matrix[i][j][0] = matrix[i][j][3] = cnt dfs(i - 1, j, 2) dfs(i, j - 1, 1) else: matrix[i][j][0] = matrix[i][j][1] = matrix[i][j][2] = matrix[i][j][3] = cnt dfs(i - 1, j, 2) dfs(i, j + 1, 3) dfs(i + 1, j, 0) dfs(i, j - 1, 1) grid, n = [row.replace("\\", "*") for row in grid], len(grid) matrix, cnt = [[[0, 0, 0, 0] for j in range(n)] for i in range(n)], 0 for i in range(n): for j in range(n): for k in range(4): if not matrix[i][j][k]: cnt += 1 dfs(i, j, k) return cnt
# The MIT License (MIT) # # Copyright (c) 2016 Scott Shawcroft for Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # pylint: disable=too-few-public-methods """ `adafruit_register.spi_bit` ==================================================== Single bit registers * Author(s): Scott Shawcroft * Adaptation by Max Holliday """ class RWBit: """ Single bit register that is readable and writeable. Values are `bool` :param int register_address: The register address to read the bit from :param type bit: The bit index within the byte at ``register_address`` :param int register_width: The number of bytes in the register. Defaults to 1. :param bool lsb_first: Is the first byte we read from spi the LSB? Defaults to true """ def __init__(self, register_address, bit, register_width=1, lsb_first=True): self.bit_mask = 1 << (bit%8) # the bitmask *within* the byte! self.buffer = bytearray(1 + register_width) self.buffer[0] = register_address self.buffer[1] = register_width-1 if lsb_first: self.byte = bit // 8 + 1 # the byte number within the buffer else: self.byte = register_width - (bit // 8) # the byte number within the buffer def __get__(self, obj, objtype=None): with obj.spi_device as spi: spi.write(self.buffer, end=2) spi.readinto(self.buffer, start=1) return bool(self.buffer[self.byte] & self.bit_mask) def __set__(self, obj, value): with obj.spi_device as spi: spi.write(self.buffer, end=2) spi.readinto(self.buffer, start=1) if value: self.buffer[self.byte] |= self.bit_mask else: self.buffer[self.byte] &= ~self.bit_mask spi.write(self.buffer) class ROBit(RWBit): """Single bit register that is read only. Subclass of `RWBit`. Values are `bool` :param int register_address: The register address to read the bit from :param type bit: The bit index within the byte at ``register_address`` :param int register_width: The number of bytes in the register. Defaults to 1. """ def __set__(self, obj, value): raise AttributeError()
class SubroutineDeclaration: def __init__(self, header, varrefs, body, function=False): ''' @param header: a tuple of (name, arglist) @param body: a tuple of (subroutine statements string, span in source file); The span is a (startpos, endpos) tuple. ''' self.name = header[0] self.arglist = header[1] self.varrefs = varrefs self.body = body[0] self.bodyspan = body[1] # the location span self.function = function # designates whether subroutine is function or procedure return def __repr__(self): buf = 'subroutine:' buf += str(self.name) + '\n' + str(self.arglist) + '\n' + str(self.varrefs) + \ '\n' + str(self.body) + '\n' + str(self.bodyspan) return buf def inline(self, params): ''' Rewrite the body to contain actual arguments in place of the formal parameters. @param params: the list of actual parameters in the same order as the formal parameters in the subroutine definition ''' starpos = self.bodyspan[0] for v in self.varrefs: arg = v[0] # the variable name argspan = v[1] # begin and end position return # end of class SubroutineDefinition class SubroutineDefinition(SubroutineDeclaration): pass
class AccessDeniedException(Exception): def __init__(self, message): pass # Call the base class constructor # super().__init__(message, None) # Now custom code # self.errors = errors class InvalidEndpointException(Exception): def __init__(self, message): self.message = message class BucketMightNotExistException(Exception): def __init__(self): pass
def includeme(config): config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('login', '/login') config.add_route('launchpad', '/launchpad') config.add_route('request_rx', '/request_rx') config.add_route('rx_portal', '/rx_portal') config.add_route('pending_rx', '/pending_rx') config.add_route('write_rx', '/write_rx') config.add_route('write_rx_form', '/write_rx_form')
class DocumentTemplate: def __init__(self): pass @staticmethod def create_db_template(server, db_id, label, **kwargs): db_url = "{}{}".format(server, db_id) comment = kwargs.get("comment") language = kwargs.get("language", "en") allow_origin = kwargs.get("allow_origin", "*") temp = { "@context": { "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "terminus": "http://terminusdb.com/schema/terminus#", "_": db_url, }, "terminus:document": { "@type": "terminus:Database", "rdfs:label": {"@language": language, "@value": label}, "terminus:allow_origin": { "@type": "xsd:string", "@value": allow_origin, }, "@id": db_url, }, "@type": "terminus:APIUpdate", } if comment: temp["rdfs:comment"] = {"@language": language, "@value": comment} return temp @staticmethod def format_document(doc, schema_url, options=None, url_id=None): document = {} if isinstance(doc, dict): document["@context"] = doc["@context"] # add blank node prefix as document base url if ("@context" in doc) and ("@id" in doc): document["@context"]["_"] = doc["@id"] if ( options and options.get("terminus:encoding") and options["terminus:encoding"] == "terminus:turtle" ): document["terminus:turtle"] = doc # document['terminus:schema'] = schema_url del document["terminus:turtle"]["@context"] else: document["terminus:document"] = doc del document["terminus:document"]["@context"] document["@type"] = "terminus:APIUpdate" if url_id: document["@id"] = url_id return document
def DistanceToPlane(plane, point): """Returns the distance from a 3D point to a plane Parameters: plane (plane): the plane point (point): List of 3 numbers or Point3d Returns: number: The distance if successful, otherwise None Example: import rhinoscriptsyntax as rs point = rs.GetPoint("Point to test") if point: plane = rs.ViewCPlane() if plane: distance = rs.DistanceToPlane(plane, point) if distance is not None: print("Distance to plane: ", distance) See Also: Distance PlaneClosestPoint """ def EvaluatePlane(plane, parameter): """Evaluates a plane at a U,V parameter Parameters: plane (plane): the plane to evaluate parameter ([number, number]): list of two numbers defining the U,V parameter to evaluate Returns: point: Point3d on success Example: import rhinoscriptsyntax as rs view = rs.CurrentView() plane = rs.ViewCPlane(view) point = rs.EvaluatePlane(plane, (5,5)) rs.AddPoint( point ) See Also: PlaneClosestPoint """ def IntersectPlanes(plane1, plane2, plane3): """Calculates the intersection of three planes Parameters: plane1 (plane): the 1st plane to intersect plane2 (plane): the 2nd plane to intersect plane3 (plane): the 3rd plane to intersect Returns: point: the intersection point between the 3 planes on success None: on error Example: import rhinoscriptsyntax as rs plane1 = rs.WorldXYPlane() plane2 = rs.WorldYZPlane() plane3 = rs.WorldZXPlane() point = rs.IntersectPlanes(plane1, plane2, plane3) if point: rs.AddPoint(point) See Also: LineLineIntersection LinePlaneIntersection PlanePlaneIntersection """ def MovePlane(plane, origin): """Moves the origin of a plane Parameters: plane (plane): Plane or ConstructionPlane origin (point): Point3d or list of three numbers Returns: plane: moved plane Example: import rhinoscriptsyntax as rs origin = rs.GetPoint("CPlane origin") if origin: plane = rs.ViewCPlane() plane = rs.MovePlane(plane,origin) rs.ViewCplane(plane) See Also: PlaneFromFrame PlaneFromNormal RotatePlane """ def PlaneClosestPoint(plane, point, return_point=True): """Returns the point on a plane that is closest to a test point. Parameters: plane (plane): The plane point (point): The 3-D point to test. return_point (bool, optional): If omitted or True, then the point on the plane that is closest to the test point is returned. If False, then the parameter of the point on the plane that is closest to the test point is returned. Returns: point: If return_point is omitted or True, then the 3-D point point: If return_point is False, then an array containing the U,V parameters of the point None: if not successful, or on error. Example: import rhinoscriptsyntax as rs point = rs.GetPoint("Point to test") if point: plane = rs.ViewCPlane() if plane: print(rs.PlaneClosestPoint(plane, point)) See Also: DistanceToPlane EvaluatePlane """ def PlaneCurveIntersection(plane, curve, tolerance=None): """Intersect an infinite plane and a curve object Parameters: plane (plane): The plane to intersect. curve (guid): The identifier of the curve object torerance (number, optional): The intersection tolerance. If omitted, the document's absolute tolerance is used. Returns: A list of intersection information tuple if successful. The list will contain one or more of the following tuple: Element Type Description [0] Number The intersection event type, either Point (1) or Overlap (2). [1] Point3d If the event type is Point (1), then the intersection point on the curve. If the event type is Overlap (2), then intersection start point on the curve. [2] Point3d If the event type is Point (1), then the intersection point on the curve. If the event type is Overlap (2), then intersection end point on the curve. [3] Point3d If the event type is Point (1), then the intersection point on the plane. If the event type is Overlap (2), then intersection start point on the plane. [4] Point3d If the event type is Point (1), then the intersection point on the plane. If the event type is Overlap (2), then intersection end point on the plane. [5] Number If the event type is Point (1), then the curve parameter. If the event type is Overlap (2), then the start value of the curve parameter range. [6] Number If the event type is Point (1), then the curve parameter. If the event type is Overlap (2), then the end value of the curve parameter range. [7] Number If the event type is Point (1), then the U plane parameter. If the event type is Overlap (2), then the U plane parameter for curve at (n, 5). [8] Number If the event type is Point (1), then the V plane parameter. If the event type is Overlap (2), then the V plane parameter for curve at (n, 5). [9] Number If the event type is Point (1), then the U plane parameter. If the event type is Overlap (2), then the U plane parameter for curve at (n, 6). [10] Number If the event type is Point (1), then the V plane parameter. If the event type is Overlap (2), then the V plane parameter for curve at (n, 6). None: on error Example: import rhinoscriptsyntax as rs curve = rs.GetObject("Select curve", rs.filter.curve) if curve: plane = rs.WorldXYPlane() intersections = rs.PlaneCurveIntersection(plane, curve) if intersections: for intersection in intersections: rs.AddPoint(intersection[1]) See Also: IntersectPlanes PlanePlaneIntersection PlaneSphereIntersection """ def PlaneEquation(plane): """Returns the equation of a plane as a tuple of four numbers. The standard equation of a plane with a non-zero vector is Ax+By+Cz+D=0 Parameters: plane (plane): the plane to deconstruct Returns: tuple(number, number, number, number): containing four numbers that represent the coefficients of the equation (A, B, C, D) if successful None: if not successful Example: import rhinoscriptsyntax as rs plane = rs.ViewCPlane() equation = rs.PlaneEquation(plane) print("A =", equation[0]) print("B =", equation[1]) print("C =", equation[2]) print("D =", equation[3]) See Also: PlaneFromFrame PlaneFromNormal PlaneFromPoints """ def PlaneFitFromPoints(points): """Returns a plane that was fit through an array of 3D points. Parameters: points (point): An array of 3D points. Returns: plane: The plane if successful None: if not successful Example: import rhinoscriptsyntax as rs points = rs.GetPoints() if points: plane = rs.PlaneFitFromPoints(points) if plane: magX = plane.XAxis.Length magY = plane.YAxis.Length rs.AddPlaneSurface( plane, magX, magY ) See Also: PlaneFromFrame PlaneFromNormal PlaneFromPoints """ def PlaneFromFrame(origin, x_axis, y_axis): """Construct a plane from a point, and two vectors in the plane. Parameters: origin (point): A 3D point identifying the origin of the plane. x_axis (vector): A non-zero 3D vector in the plane that determines the X axis direction. y_axis (vector): A non-zero 3D vector not parallel to x_axis that is used to determine the Y axis direction. Note, y_axis does not have to be perpendicular to x_axis. Returns: plane: The plane if successful. Example: import rhinoscriptsyntax as rs origin = rs.GetPoint("CPlane origin") if origin: xaxis = (1,0,0) yaxis = (0,0,1) plane = rs.PlaneFromFrame( origin, xaxis, yaxis ) rs.ViewCPlane(None, plane) See Also: MovePlane PlaneFromNormal PlaneFromPoints RotatePlane """ def PlaneFromNormal(origin, normal, xaxis=None): """Creates a plane from an origin point and a normal direction vector. Parameters: origin (point): A 3D point identifying the origin of the plane. normal (vector): A 3D vector identifying the normal direction of the plane. xaxis (vector, optional): optional vector defining the plane's x-axis Returns: plane: The plane if successful. Example: import rhinoscriptsyntax as rs origin = rs.GetPoint("CPlane origin") if origin: direction = rs.GetPoint("CPlane direction") if direction: normal = direction - origin normal = rs.VectorUnitize(normal) rs.ViewCPlane( None, rs.PlaneFromNormal(origin, normal) ) See Also: MovePlane PlaneFromFrame PlaneFromPoints RotatePlane """ def PlaneFromPoints(origin, x, y): """Creates a plane from three non-colinear points Parameters: origin (point): origin point of the plane x, y (point): points on the plane's x and y axes Returns: plane: The plane if successful, otherwise None Example: import rhinoscriptsyntax as rs corners = rs.GetRectangle() if corners: rs.ViewCPlane( rs.PlaneFromPoints(corners[0], corners[1], corners[3])) See Also: PlaneFromFrame PlaneFromNormal """ def PlanePlaneIntersection(plane1, plane2): """Calculates the intersection of two planes Parameters: plane1 (plane): the 1st plane to intersect plane2 (plane): the 2nd plane to intersect Returns: line: a line with two 3d points identifying the starting/ending points of the intersection None: on error Example: import rhinoscriptsyntax as rs plane1 = rs.WorldXYPlane() plane2 = rs.WorldYZPlane() line = rs.PlanePlaneIntersection(plane1, plane2) if line: rs.AddLine(line[0], line[1]) See Also: IntersectPlanes LineLineIntersection LinePlaneIntersection """ def PlaneSphereIntersection(plane, sphere_plane, sphere_radius): """Calculates the intersection of a plane and a sphere Parameters: plane (plane): the plane to intersect sphere_plane (plane): equatorial plane of the sphere. origin of the plane is the center of the sphere sphere_radius (number): radius of the sphere Returns: list(number, point|plane, number): of intersection results Element Type Description [0] number The type of intersection, where 0 = point and 1 = circle. [1] point or plane If a point intersection, the a Point3d identifying the 3-D intersection location. If a circle intersection, then the circle's plane. The origin of the plane will be the center point of the circle [2] number If a circle intersection, then the radius of the circle. None: on error Example: import rhinoscriptsyntax as rs plane = rs.WorldXYPlane() radius = 10 results = rs.PlaneSphereIntersection(plane, plane, radius) if results: if results[0]==0: rs.AddPoint(results[1]) else: rs.AddCircle(results[1], results[2]) See Also: IntersectPlanes LinePlaneIntersection PlanePlaneIntersection """ def PlaneTransform(plane, xform): """Transforms a plane Parameters: plane (plane): Plane to transform xform (transform): Transformation to apply Returns: plane:the resulting plane if successful None: if not successful Example: import rhinoscriptsyntax as rs plane = rs.ViewCPlane() xform = rs.XformRotation(45.0, plane.Zaxis, plane.Origin) plane = rs.PlaneTransform(plane, xform) rs.ViewCPlane(None, plane) See Also: PlaneFromFrame PlaneFromNormal PlaneFromPoints """ def RotatePlane(plane, angle_degrees, axis): """Rotates a plane Parameters: plane (plane): Plane to rotate angle_degrees (number): rotation angle in degrees axis (vector): Axis of rotation or list of three numbers Returns: plane: rotated plane on success Example: import rhinoscriptsyntax as rs plane = rs.ViewCPlane() rotated = rs.RotatePlane(plane, 45.0, plane.XAxis) rs.ViewCPlane( None, rotated ) See Also: MovePlane PlaneFromFrame PlaneFromNormal """ def WorldXYPlane(): """Returns Rhino's world XY plane Returns: plane: Rhino's world XY plane Example: import rhinoscriptsyntax as rs view = rs.CurrentView() rs.ViewCPlane( view, rs.WorldXYPlane() ) See Also: WorldYZPlane WorldZXPlane """ def WorldYZPlane(): """Returns Rhino's world YZ plane Returns: plane: Rhino's world YZ plane Example: import rhinoscriptsyntax as rs view = rs.CurrentView() rs.ViewCPlane( view, rs.WorldYZPlane() ) See Also: WorldXYPlane WorldZXPlane """ def WorldZXPlane(): """Returns Rhino's world ZX plane Returns: plane: Rhino's world ZX plane Example: import rhinoscriptsyntax as rs view = rs.CurrentView() rs.ViewCPlane( view, rs.WorldZXPlane() ) See Also: WorldXYPlane WorldYZPlane """
inp = input().split(" ") C = int(inp[0]) H = int(inp[1]) O = int(inp[2]) #Определяю на сколько молекул хватит этих веществ. C_enough = C // 2 H_enough = H // 6 O_enough = O print(min(C_enough, H_enough, O_enough))
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] #using list comprehension to make square of given numbers in list squared_numbers=[ n * n for n in numbers] print(squared_numbers)
m=float(input('Digite a medida')) km=m/1000 hm=m/100 dm=m/10 dcm=m*10 cm=m*100 mm=m*1000 print('A mediada em km é {} e em hectometros é {} e em decametros é {} e em decimetros é {} cms é {} e em mm é {}'.format(km,hm,dm,dcm,cm,mm))
class NothingToProcess(ValueError): pass class FileAlreadyProcessed(ValueError): pass
# kpbochenek@gmail.com def most_difference(*args): if not args: return 0 mn = min(args) mx = max(args) return mx - mn if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing def almost_equal(checked, correct, significant_digits): precision = 0.1 ** significant_digits return correct - precision < checked < correct + precision assert almost_equal(most_difference(1, 2, 3), 2, 3), "3-1=2" assert almost_equal(most_difference(5, 5), 0, 3), "5-5=0" assert almost_equal(most_difference(10.2, 2.2, 0.00001, 1.1, 0.5), 10.199, 3), "10.2-(0.00001)=10.19999" assert almost_equal(most_difference(), 0, 3), "Empty"
scope_configuration = dict( drivers = ( # order is important! ('stand', 'leica.stand.Stand'), ('stage', 'leica.stage.Stage'), #('nosepiece', 'leica.nosepiece.MotorizedNosepieceWithSafeMode'), # dm6000 #('nosepiece', 'leica.nosepiece.MotorizedNosepiece'), # dmi8 #('nosepiece', 'leica.nosepiece.ManualNosepiece'), # dm6 #('il', 'leica.illumination_axes.IL'), # dmi8 #('il', 'leica.illumination_axes.FieldWheel_IL'), # dm6000 dm6 #('tl', 'leica.illumination_axes.TL'), # dm6000 dm6 #('_shutter_watcher', 'leica.illumination_axes.ShutterWatcher'), # dm6000 dm6 ('iotool', 'iotool.IOTool'), #('il.spectra', 'spectra.Spectra'), # dm6 #('il.spectra', 'spectra.SpectraX'), # dm6000 dmi8 ('tl.lamp', 'tl_lamp.SutterLED_Lamp'), # ('camera', 'andor.Zyla'), # ('camera', 'andor.Sona'), ('camera.acquisition_sequencer', 'acquisition_sequencer.AcquisitionSequencer'), ('camera.autofocus', 'autofocus.Autofocus'), #('temperature_controller', 'temp_control.Peltier'), # dm6000 #('temperature_controller', 'temp_control.Circulator'), # dm6 #('humidity_controller', 'humidity_control.HumidityController'), # dm6, dm6000 ('job_runner', 'runner_device.JobRunner') ), server = dict( LOCALHOST = '127.0.0.1', PUBLICHOST = '*', RPC_PORT = '6000', RPC_INTERRUPT_PORT = '6001', PROPERTY_PORT = '6002', IMAGE_TRANSFER_RPC_PORT = '6003', ), stand = dict( SERIAL_PORT = '/dev/ttyScope', SERIAL_ARGS = dict( baudrate = 115200 ), TL_FIELD_DEFAULTS = { #'5': 12, # dm6 #'5': 10, # dm6000 #'10': 16 # dm6 #'10': 18 # dm6000 }, TL_APERTURE_DEFAULTS = { '5': 28, # dm6, dm6000 #'10': 26 # dm6 #'10': 22 # dm6000 } ), camera = dict( IOTOOL_PINS = dict( trigger = 'B0', arm = 'B1', aux_out1 = 'B2' ), ), iotool = dict( SERIAL_PORT = '/dev/ttyIOTool', SERIAL_ARGS = dict( baudrate=115200 ) ), spectra = dict( SERIAL_PORT = '/dev/ttySpectra', SERIAL_ARGS = {}, IOTOOL_LAMP_PINS = dict( uv = 'D6', blue = 'D5', cyan = 'D3', teal = 'D4', green_yellow = 'D2', #red = 'D1' # dm6000 dmi8 ), #IOTOOL_GREEN_YELLOW_SWITCH_PIN = 'D1', # dm6 # TIMING: depends *strongly* on how recently the last time the # lamp was turned on was. 100 ms ago vs. 10 sec ago changes the on-latency # by as much as 100 us. # Some lamps have different rise times vs. latencies. # All lamps have ~6 us off latency and 9-13 us fall. # With 100 ms delay between off and on: # Lamp On-Latency Rise Off-Latency Fall # Red 90 us 16 us 6 us 11 us # Green 83 19 10 13 # Cyan 96 11 6 9 # UV 98 11 6 11 # # With 5 sec delay, cyan and green on-latency goes to 123 usec. # With 20 sec delay, it is at 130 us. # Plug in sort-of average values below, assuming 5 sec delay: TIMING = dict( on_latency_ms = 0.120, # Time from trigger signal to start of rise rise_ms = 0.015, # Time from start of rise to end of rise off_latency_ms = 0.01, # Time from end of trigger to start of fall fall_ms = 0.015 # Time from start of fall to end of fall ), #FILTER_SWITCH_DELAY = 0.15 # dm6 ), sutter_led = dict( IOTOOL_ENABLE_PIN = 'E6', IOTOOL_PWM_PIN = 'D0', IOTOOL_PWM_MAX = 255, INITIAL_INTENSITY = 86, TIMING = dict( on_latency_ms = 0.025, # Time from trigger signal to start of rise rise_ms = 0.06, # Time from start of rise to end of rise off_latency_ms = 0.06, # Time from end of trigger to start of fall fall_ms = 0.013 # Time from start of fall to end of fall ), ), # peltier = dict( # SERIAL_PORT = '/dev/ttyPeltier', # SERIAL_ARGS = dict( # baudrate = 2400 # ) # ), # # circulator = dict( # SERIAL_PORT = '/dev/ttyCirculator', # SERIAL_ARGS = dict( # baudrate=9600 # ) # ), # # humidifier = dict( # SERIAL_PORT = '/dev/ttyHumidifier', # SERIAL_ARGS = dict( # baudrate=19200 # ) # ), mail_relay = 'osmtp.wustl.edu' )
a = set(input().split()) n = int(input()) for _ in range(n): b = set(input().split()) if not a.issuperset(b): print(False) break else: print(True)
v = int(input('Insira a velocidade do carro em Km/h: ')) multa = (v-80) valormulta = multa*7 if v >= 80: print('Você foi multado em R$: {:.2f}'.format(valormulta)) else: print('Você está dirigindo de maneira segura!')
def move(disks, source, auxiliary, target): if disks > 0: # move `N-1` discs from source to auxiliary using the target # as an intermediate pole move(disks - 1, source, target, auxiliary) print("Move disk {} from {} to {}".format(disks, source, target)) # move `N-1` discs from auxiliary to target using the source # as an intermediate pole move(disks - 1, auxiliary, source, target) # Tower of Hanoi Problem if __name__ == '__main__': N = 3 move(N, 1, 2, 3)
# Runners group runners = ['harry', 'ron', 'harmoine'] our_group = ['mukul'] while runners: athlete = runners.pop() print("Adding user: " + athlete.title()) our_group.append(athlete) print("That's our group:- ") for our_group in our_group: print(our_group.title() + " from harry potter!") Dream_vacation = {} polling_active = True while polling_active: name = input("\nWhat is your name?") location = input("Which is your dream vacation ?") Dream_vacation[name] = location repeat = input("would you like to let another person respond? (yes/ no)") if repeat == 'no': polling_active = False print("\n ---- Poll Results ---- ") for name, location in Dream_vacation.items(): print(name + " ok you want to go " + location.title() + " !")
n = int(input(" ")) S = 0 a = list(map(int,input(" ").split())) #A massiv for i in range(-n,0): S+=a[i] for i in range(-n,0): if a[i] <= S/n: print(" ",a[i])
class FunctionPluginError(RuntimeError): """Error raised when there's a problem with a function plugin itself.""" class FunctionArgError(ValueError): """Error raised when a function plugin has a problem with the function arguments."""
class User: ''' User class for user input ''' user_list = [] # User Empty list def __init__(self, username, password): self.username = username self.password = password def save_user(self): ''' save_usermethod saves user objects into user_list ''' User.user_list.append(self) @classmethod def user_exists(cls, characters): ''' Method to che if a user exists args: character:username to search if it exist return: Boolean: true or false depending o the search outcome ''' for user in cls.user_list: if user.password == characters: return True return False
#==================== Engine ==================== def run(code): state = EngineState() while True: ip = state.ip if ip >= len(code): break state.ip = ip + 1 (fun,arg) = code[ip] fun(state, arg) class EngineState: def __init__(self): self.ip = 0 self.gctx = [] self.lctx = [] self.stack = [] self.ctxStack = [] def push(self, v): self.stack.append(v) def pop(self): return self.stack.pop() def peek(self): return self.stack[-1] def swap(self): st = self.stack (st[-1],st[-2]) = (st[-2],st[-1]) #==================== Instructions ==================== #==================== Stack manipulation def i_dup(state,arg): state.push(state.peek()) def i_pop(state,arg): state.pop() def i_swap(state,arg): state.swap() def i_pushInteger(state,arg): state.push(arg) def i_pushMarker(state,arg): pass #==================== Arithmetic def i_add(state,arg): state.push(state.pop() + state.pop()) def i_sub(state,arg): state.push(state.pop() - state.pop()) def i_mul(state,arg): state.push(state.pop() * state.pop()) def i_div(state,arg): pass #==================== I/O def i_input(state,arg): pass def i_output(state,arg): v = state.pop() printIOList(v) def i_printDebugDump(state,arg): print("/---- DUMP:") print("Stack: %s" % (state.stack,)) print("\\----") def printIOList(v): if type(v) == type(0): print(chr(v)) else: for x in v: printIOList(x) #==================== Flow control def i_branch(state,arg): pass def i_branchIfPositive(state,arg): pass def i_call(state,arg): pass def i_return(state,arg): pass #==================== Arrays def i_createArray(state,arg): pass def i_arrayFetch(state,arg): pass def i_arrayStore(state,arg): pass def i_arrayGetSize(state,arg): pass def i_arrayResize(state,arg): pass #==================== Context access def i_pushLocalContext(state,arg): pass def i_pushGlobalContext(state,arg): pass def i_enterScope(state,arg): pass def i_exitScope(state,arg): pass def i_(state,arg): pass
""" # Definition for a Node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ class Solution: def __init__(self): self.head = None self.prev = None def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]': if not root: return None self.treetoDoublyHelper(root) self.prev.right = self.head self.head.left = self.prev return self.head def treetoDoublyHelper(self, node): if not node: return self.treetoDoublyHelper(node.left) if self.prev: node.left = self.prev self.prev.right = node else: self.head = node self.prev = node self.treetoDoublyHelper(node.right)
# GET /app/hello_world print("hello world!")
# Time: O(n + w^2), n = w * l, # n is the length of S, # w is the number of word, # l is the average length of word # Space: O(n) # A sentence S is given, composed of words separated by spaces. # Each word consists of lowercase and uppercase letters only. # # We would like to convert the sentence to "Goat Latin" # (a made-up language similar to Pig Latin.) # # The rules of Goat Latin are as follows: # # If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of # the word. # For example, the word 'apple' becomes 'applema'. # # If a word begins with a consonant (i.e. not a vowel), # remove the first letter and append it to the end, then add "ma". # For example, the word "goat" becomes "oatgma". # # Add one letter 'a' to the end of each word per its word index in the # sentence, # starting with 1. # For example, the first word gets "a" added to the end, # the second word gets "aa" added to the end and so on. # Return the final sentence representing the conversion from S to Goat Latin. # # Example 1: # # Input: "I speak Goat Latin" # Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" # Example 2: # # Input: "The quick brown fox jumped over the lazy dog" # Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa # overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" # # Notes: # - S contains only uppercase, lowercase and spaces. Exactly one space between # each word. # - 1 <= S.length <= 100. class Solution(object): def toGoatLatin(self, S): """ :type S: str :rtype: str """ def convert(S): vowel = set('aeiouAEIOU') for i, word in enumerate(S.split(), 1): if word[0] not in vowel: word = word[1:] + word[:1] yield word + 'ma' + 'a'*i return " ".join(convert(S))
class Solution(object): def combinationSum(self, candidates, target): return self.helper(candidates, target, [], set()) def helper(self, arr, target, comb, result): for num in arr: if target - num == 0: result.add(tuple(sorted(comb[:] + [num]))) elif target - num > 0: self.helper(arr, target-num, comb[:]+[num], result) return result
# Consider a list (list = []). # You can perform the following commands: # insert i e: Insert integer 'e' at position 'i'. # print: Print the list. # remove e: Delete the first occurrence of integer . # append e: Insert integer at the end of the list. # sort: Sort the list. # pop: Pop the last element from the list. # reverse: Reverse the list. # Initialize your list and read in the value of 'n' followed # by 'n' lines of commands where each command will be of the # 7 types listed above. # Iterate through each command in order and perform the # corresponding operation on your list. if __name__ == '__main__': N = int(input()) my_list = [] # 3 sub problems: # - reading inputs # - parsing input strings # - mapping command string to logic for _ in range(0,N): command = input() command_parts = command.split() key_word = command_parts[0] if key_word == "insert": index = int(command_parts[1]) value = int(command_parts[2]) my_list.insert(index, value) elif key_word == "remove": value = int(command_parts[1]) my_list.remove(value) elif key_word == "append": value = int(command_parts[1]) my_list.append(value) elif key_word == "print": print(my_list) elif key_word == "reverse": my_list.reverse() elif key_word == "pop": my_list.pop() elif key_word == "sort": my_list.sort()
n = int(input()) arr = input().split() for i in range(0,len(arr)): arr[i] = int(arr[i]) count = 0 Max = max(arr) for i in range(0,len(arr)): if(arr[i]==Max): count +=1 print(str(count))
def alphabet_position(character): alphabet = 'abcdefghijklmnopqrstuvwxyz' lower = character.lower() return alphabet.index(lower) def rotate_string_13(text): rotated = '' alphabet = 'abcdefghijklmnopqrstuvwxyz' for char in text: rotated_idx = (alphabet_position(char) + 13) % 26 if char.isupper(): rotated = rotated + alphabet[rotated_idx].upper() else: rotated = rotated + alphabet[rotated_idx] return rotated def rotate_character(char, rot): alphabet = 'abcdefghijklmnopqrstuvwxyz' rotated_idx = (alphabet_position(char) + rot) % 26 if char.isupper(): return alphabet[rotated_idx].upper() else: return alphabet[rotated_idx] def rotate_string(text, rot): rotated = '' for char in text: if (char.isalpha()): rotated = rotated + rotate_character(char, rot) else: rotated = rotated + char return rotated
description = 'Additional rotation table' group = 'optional' tango_base = 'tango://motorbox05.stressi.frm2.tum.de:10000/box/' devices = dict( addphi_m = device('nicos.devices.entangle.Motor', tangodevice = tango_base + 'channel4/motor', fmtstr = '%.2f', visibility = (), speed = 4, ), addphi = device('nicos.devices.generic.Axis', description = 'Additional rotation table', motor = 'addphi_m', precision = 0.01, ), )
NEW2OLD = {'AD': 'ADCY8', 'DP': 'DPYS', 'GA': 'GARL1', 'HA9': 'HOXA9', 'GR': 'GRM6', 'H12': 'HOXD12', 'HD9': 'HOXD9', 'PR': 'PRAC', 'PT': 'PTGDR', 'SA': 'SALL3', 'SI': 'SIX6', 'SL': 'SLC6A2', 'TL': 'TLX3', 'TR': 'TRIM58', 'ZF': 'ZFP41'} OLD2NEW = {NEW2OLD[i]: i for i in NEW2OLD.keys() if NEW2OLD[i] is not None} def short_2_full(short): return NEW2OLD[short.strip().upper()] def full_2_short(full): return OLD2NEW[full.strip().upper()]
# Single Responsibility Principle (SRP) or Separation Of Concerns (SOC) class Journal(): def __init__(self): self.entries = [] self.count = 0 def add_entry(self, text): self.count += 1 self.entries.append(f'{self.count}: {text}') def remove_entry(self, index): self.count -= 1 self.entries.pop(index) def __str__(self): return '\n'.join(self.entries) # def save(self, filename): # with open(filename, 'w') as f: # f.write(str(self)) # def load(self): # pass # def load_from_web(self): # pass class PersistanceManager: @staticmethod def save_to_file(filename, journal): with open(filename, 'w+') as f: f.write(str(journal)) journal = Journal() journal.add_entry('I love programming') journal.add_entry('I always ask right questions') # journal.save('sample.txt') print(journal) PersistanceManager.save_to_file('sample.txt', journal)
# why=None # what=why # while what is why: # try: # what=int (input ("what? " ) ) # except ValueError : # print( "no.") # def abc(z): # if(z<=1):return False # for(x)in(range(2 ,int(z**.5)+1)) : # if z % x==0: # return False # return True # for who in range (1 ,what+ 1): # how=abc (who) # if how : # print("{}???".format(who),":)") # else: # print ("{}???" . format(who) , ":(") """This program will check all integers up to a specified limit for primality""" max_number = None # letting user input a number up to which to check while max_number is None: try: # try to convert user input to integer max_number = int(input("Up to which number would you like to check? ")) except ValueError: # if input is invalid, let them try again print("Please enter an integer.") def is_prime(n): """Checks if the argument n is a prime number. Returns True if it is, False otherwise.""" # 1 is not prime by definition if n <= 1: return False # check up to sqrt(n) + 1 if there exists a number that divides n for divisor in range(2, int(n ** 0.5) + 1): if n % divisor == 0: # if divisor is found, n is not prime return False # if all checks up to here fail, n is prime return True # check all numbers up to max_number and print result for n in range(1, max_number + 1): if is_prime(n): print(n, "is a prime number!") else: print(n, "is NOT a prime number.")
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthreshold Leakage': 0.0691322, 'Subthreshold Leakage with power gating': 0.0259246}, 'Core': [{'Area': 32.6082, 'Execution Unit/Area': 8.2042, 'Execution Unit/Complex ALUs/Area': 0.235435, 'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646, 'Execution Unit/Complex ALUs/Peak Dynamic': 0.0648189, 'Execution Unit/Complex ALUs/Runtime Dynamic': 0.2536, 'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111, 'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163, 'Execution Unit/Floating Point Units/Area': 4.6585, 'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156, 'Execution Unit/Floating Point Units/Peak Dynamic': 0.381762, 'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033, 'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829, 'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061, 'Execution Unit/Gate Leakage': 0.122718, 'Execution Unit/Instruction Scheduler/Area': 2.17927, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.328073, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.00115349, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.20978, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.189343, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.017004, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00962066, 'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00730101, 'Execution Unit/Instruction Scheduler/Instruction Window/Area': 1.00996, 'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00529112, 'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 2.07911, 'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.327873, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0800117, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0455351, 'Execution Unit/Instruction Scheduler/Peak Dynamic': 4.84781, 'Execution Unit/Instruction Scheduler/ROB/Area': 0.841232, 'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.000856399, 'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.55892, 'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.188044, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.0178624, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00897339, 'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.70526, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.114878, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.0641291, 'Execution Unit/Integer ALUs/Area': 0.47087, 'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291, 'Execution Unit/Integer ALUs/Peak Dynamic': 0.128628, 'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344, 'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222, 'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833, 'Execution Unit/Peak Dynamic': 5.77849, 'Execution Unit/Register Files/Area': 0.570804, 'Execution Unit/Register Files/Floating Point RF/Area': 0.208131, 'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788, 'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0721231, 'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00686382, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968, 'Execution Unit/Register Files/Gate Leakage': 0.000622708, 'Execution Unit/Register Files/Integer RF/Area': 0.362673, 'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992, 'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0726115, 'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0507621, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675, 'Execution Unit/Register Files/Peak Dynamic': 0.144735, 'Execution Unit/Register Files/Runtime Dynamic': 0.0576259, 'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387, 'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643, 'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0442632, 'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00607074, 'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.193217, 'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.542007, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.0920413, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0345155, 'Execution Unit/Runtime Dynamic': 1.96387, 'Execution Unit/Subthreshold Leakage': 1.83518, 'Execution Unit/Subthreshold Leakage with power gating': 0.709678, 'Gate Leakage': 0.372997, 'Instruction Fetch Unit/Area': 5.86007, 'Instruction Fetch Unit/Branch Predictor/Area': 0.138516, 'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.000127827, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.000127827, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000110579, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 4.23925e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045, 'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838, 'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732, 'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05, 'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602, 'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000729202, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733, 'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00109543, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282, 'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954, 'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758, 'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867, 'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.00125267, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357, 'Instruction Fetch Unit/Gate Leakage': 0.0590479, 'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323, 'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05, 'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827, 'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0487989, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682, 'Instruction Fetch Unit/Instruction Cache/Area': 3.14635, 'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931, 'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 3.10403, 'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.117802, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386, 'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799, 'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493, 'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404, 'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.165743, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104, 'Instruction Fetch Unit/Peak Dynamic': 5.4755, 'Instruction Fetch Unit/Runtime Dynamic': 0.334692, 'Instruction Fetch Unit/Subthreshold Leakage': 0.932587, 'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.408542, 'L2/Area': 4.53318, 'L2/Gate Leakage': 0.015464, 'L2/Peak Dynamic': 0.139584, 'L2/Runtime Dynamic': 0.0373435, 'L2/Subthreshold Leakage': 0.834142, 'L2/Subthreshold Leakage with power gating': 0.401066, 'Load Store Unit/Area': 8.80969, 'Load Store Unit/Data Cache/Area': 6.84535, 'Load Store Unit/Data Cache/Gate Leakage': 0.0279261, 'Load Store Unit/Data Cache/Peak Dynamic': 3.28224, 'Load Store Unit/Data Cache/Runtime Dynamic': 1.02999, 'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675, 'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085, 'Load Store Unit/Gate Leakage': 0.0351387, 'Load Store Unit/LoadQ/Area': 0.0836782, 'Load Store Unit/LoadQ/Gate Leakage': 0.00059896, 'Load Store Unit/LoadQ/Peak Dynamic': 0.0661645, 'Load Store Unit/LoadQ/Runtime Dynamic': 0.0661645, 'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961, 'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918, 'Load Store Unit/Peak Dynamic': 3.59596, 'Load Store Unit/Runtime Dynamic': 1.42245, 'Load Store Unit/StoreQ/Area': 0.322079, 'Load Store Unit/StoreQ/Gate Leakage': 0.00329971, 'Load Store Unit/StoreQ/Peak Dynamic': 0.16315, 'Load Store Unit/StoreQ/Runtime Dynamic': 0.326301, 'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621, 'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004, 'Load Store Unit/Subthreshold Leakage': 0.591622, 'Load Store Unit/Subthreshold Leakage with power gating': 0.283406, 'Memory Management Unit/Area': 0.434579, 'Memory Management Unit/Dtlb/Area': 0.0879726, 'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729, 'Memory Management Unit/Dtlb/Peak Dynamic': 0.0579026, 'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0599921, 'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699, 'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485, 'Memory Management Unit/Gate Leakage': 0.00813591, 'Memory Management Unit/Itlb/Area': 0.301552, 'Memory Management Unit/Itlb/Gate Leakage': 0.00393464, 'Memory Management Unit/Itlb/Peak Dynamic': 0.192997, 'Memory Management Unit/Itlb/Runtime Dynamic': 0.0193326, 'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758, 'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842, 'Memory Management Unit/Peak Dynamic': 0.451598, 'Memory Management Unit/Runtime Dynamic': 0.0793248, 'Memory Management Unit/Subthreshold Leakage': 0.0769113, 'Memory Management Unit/Subthreshold Leakage with power gating': 0.0399462, 'Peak Dynamic': 20.0028, 'Renaming Unit/Area': 0.369768, 'Renaming Unit/FP Front End RAT/Area': 0.168486, 'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00489731, 'Renaming Unit/FP Front End RAT/Peak Dynamic': 3.33511, 'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.251621, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0437281, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.024925, 'Renaming Unit/Free List/Area': 0.0414755, 'Renaming Unit/Free List/Gate Leakage': 4.15911e-05, 'Renaming Unit/Free List/Peak Dynamic': 0.0401324, 'Renaming Unit/Free List/Runtime Dynamic': 0.0127098, 'Renaming Unit/Free List/Subthreshold Leakage': 0.000670426, 'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000377987, 'Renaming Unit/Gate Leakage': 0.00863632, 'Renaming Unit/Int Front End RAT/Area': 0.114751, 'Renaming Unit/Int Front End RAT/Gate Leakage': 0.00038343, 'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.86945, 'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0953364, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00611897, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781, 'Renaming Unit/Peak Dynamic': 4.56169, 'Renaming Unit/Runtime Dynamic': 0.359667, 'Renaming Unit/Subthreshold Leakage': 0.070483, 'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779, 'Runtime Dynamic': 4.19735, 'Subthreshold Leakage': 6.21877, 'Subthreshold Leakage with power gating': 2.58311}, {'Area': 32.0201, 'Execution Unit/Area': 7.68434, 'Execution Unit/Complex ALUs/Area': 0.235435, 'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646, 'Execution Unit/Complex ALUs/Peak Dynamic': 0.0236579, 'Execution Unit/Complex ALUs/Runtime Dynamic': 0.22127, 'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111, 'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163, 'Execution Unit/Floating Point Units/Area': 4.6585, 'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156, 'Execution Unit/Floating Point Units/Peak Dynamic': 0.135499, 'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033, 'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829, 'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061, 'Execution Unit/Gate Leakage': 0.120359, 'Execution Unit/Instruction Scheduler/Area': 1.66526, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.0547817, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519, 'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913, 'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223, 'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562, 'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763, 'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.0883609, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964, 'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262, 'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388, 'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608, 'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451, 'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.0446016, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446, 'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.187744, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346, 'Execution Unit/Integer ALUs/Area': 0.47087, 'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291, 'Execution Unit/Integer ALUs/Peak Dynamic': 0.0418806, 'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344, 'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222, 'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833, 'Execution Unit/Peak Dynamic': 4.13895, 'Execution Unit/Register Files/Area': 0.570804, 'Execution Unit/Register Files/Floating Point RF/Area': 0.208131, 'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788, 'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0255986, 'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00229779, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968, 'Execution Unit/Register Files/Gate Leakage': 0.000622708, 'Execution Unit/Register Files/Integer RF/Area': 0.362673, 'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992, 'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0251584, 'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0169936, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675, 'Execution Unit/Register Files/Peak Dynamic': 0.050757, 'Execution Unit/Register Files/Runtime Dynamic': 0.0192914, 'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387, 'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643, 'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912, 'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402, 'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0589175, 'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.162657, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543, 'Execution Unit/Runtime Dynamic': 0.99634, 'Execution Unit/Subthreshold Leakage': 1.79543, 'Execution Unit/Subthreshold Leakage with power gating': 0.688821, 'Gate Leakage': 0.368936, 'Instruction Fetch Unit/Area': 5.85939, 'Instruction Fetch Unit/Branch Predictor/Area': 0.138516, 'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 4.58393e-05, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 4.58393e-05, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 4.00752e-05, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 1.55954e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045, 'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838, 'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732, 'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05, 'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602, 'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000244114, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733, 'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.000375868, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282, 'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954, 'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758, 'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867, 'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.000434173, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357, 'Instruction Fetch Unit/Gate Leakage': 0.0589979, 'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323, 'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05, 'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827, 'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0163364, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682, 'Instruction Fetch Unit/Instruction Cache/Area': 3.14635, 'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931, 'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 1.03913, 'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0400109, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386, 'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799, 'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493, 'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404, 'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.0554856, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104, 'Instruction Fetch Unit/Peak Dynamic': 3.30808, 'Instruction Fetch Unit/Runtime Dynamic': 0.112643, 'Instruction Fetch Unit/Subthreshold Leakage': 0.932286, 'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843, 'L2/Area': 4.53318, 'L2/Gate Leakage': 0.015464, 'L2/Peak Dynamic': 0.0430097, 'L2/Runtime Dynamic': 0.0128205, 'L2/Subthreshold Leakage': 0.834142, 'L2/Subthreshold Leakage with power gating': 0.401066, 'Load Store Unit/Area': 8.80901, 'Load Store Unit/Data Cache/Area': 6.84535, 'Load Store Unit/Data Cache/Gate Leakage': 0.0279261, 'Load Store Unit/Data Cache/Peak Dynamic': 1.92916, 'Load Store Unit/Data Cache/Runtime Dynamic': 0.350503, 'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675, 'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085, 'Load Store Unit/Gate Leakage': 0.0350888, 'Load Store Unit/LoadQ/Area': 0.0836782, 'Load Store Unit/LoadQ/Gate Leakage': 0.00059896, 'Load Store Unit/LoadQ/Peak Dynamic': 0.0223891, 'Load Store Unit/LoadQ/Runtime Dynamic': 0.022389, 'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961, 'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918, 'Load Store Unit/Peak Dynamic': 2.03488, 'Load Store Unit/Runtime Dynamic': 0.483307, 'Load Store Unit/StoreQ/Area': 0.322079, 'Load Store Unit/StoreQ/Gate Leakage': 0.00329971, 'Load Store Unit/StoreQ/Peak Dynamic': 0.0552077, 'Load Store Unit/StoreQ/Runtime Dynamic': 0.110415, 'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621, 'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004, 'Load Store Unit/Subthreshold Leakage': 0.591321, 'Load Store Unit/Subthreshold Leakage with power gating': 0.283293, 'Memory Management Unit/Area': 0.4339, 'Memory Management Unit/Dtlb/Area': 0.0879726, 'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729, 'Memory Management Unit/Dtlb/Peak Dynamic': 0.0195934, 'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0202369, 'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699, 'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485, 'Memory Management Unit/Gate Leakage': 0.00808595, 'Memory Management Unit/Itlb/Area': 0.301552, 'Memory Management Unit/Itlb/Gate Leakage': 0.00393464, 'Memory Management Unit/Itlb/Peak Dynamic': 0.0646095, 'Memory Management Unit/Itlb/Runtime Dynamic': 0.0065664, 'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758, 'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842, 'Memory Management Unit/Peak Dynamic': 0.254376, 'Memory Management Unit/Runtime Dynamic': 0.0268033, 'Memory Management Unit/Subthreshold Leakage': 0.0766103, 'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333, 'Peak Dynamic': 13.3688, 'Renaming Unit/Area': 0.303608, 'Renaming Unit/FP Front End RAT/Area': 0.131045, 'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123, 'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468, 'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0673379, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885, 'Renaming Unit/Free List/Area': 0.0340654, 'Renaming Unit/Free List/Gate Leakage': 2.5481e-05, 'Renaming Unit/Free List/Peak Dynamic': 0.0306032, 'Renaming Unit/Free List/Runtime Dynamic': 0.00329109, 'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144, 'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064, 'Renaming Unit/Gate Leakage': 0.00708398, 'Renaming Unit/Int Front End RAT/Area': 0.0941223, 'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242, 'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965, 'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0269533, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228, 'Renaming Unit/Peak Dynamic': 3.58947, 'Renaming Unit/Runtime Dynamic': 0.0975823, 'Renaming Unit/Subthreshold Leakage': 0.0552466, 'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461, 'Runtime Dynamic': 1.7295, 'Subthreshold Leakage': 6.16288, 'Subthreshold Leakage with power gating': 2.55328}, {'Area': 32.0201, 'Execution Unit/Area': 7.68434, 'Execution Unit/Complex ALUs/Area': 0.235435, 'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646, 'Execution Unit/Complex ALUs/Peak Dynamic': 0.0234066, 'Execution Unit/Complex ALUs/Runtime Dynamic': 0.221073, 'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111, 'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163, 'Execution Unit/Floating Point Units/Area': 4.6585, 'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156, 'Execution Unit/Floating Point Units/Peak Dynamic': 0.132683, 'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033, 'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829, 'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061, 'Execution Unit/Gate Leakage': 0.120359, 'Execution Unit/Instruction Scheduler/Area': 1.66526, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.0535458, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519, 'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913, 'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223, 'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562, 'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763, 'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.0863674, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964, 'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262, 'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388, 'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608, 'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451, 'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.0435954, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446, 'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.183509, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346, 'Execution Unit/Integer ALUs/Area': 0.47087, 'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291, 'Execution Unit/Integer ALUs/Peak Dynamic': 0.0408985, 'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344, 'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222, 'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833, 'Execution Unit/Peak Dynamic': 4.1329, 'Execution Unit/Register Files/Area': 0.570804, 'Execution Unit/Register Files/Floating Point RF/Area': 0.208131, 'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788, 'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0250666, 'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00224595, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968, 'Execution Unit/Register Files/Gate Leakage': 0.000622708, 'Execution Unit/Register Files/Integer RF/Area': 0.362673, 'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992, 'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0247487, 'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0166102, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675, 'Execution Unit/Register Files/Peak Dynamic': 0.0498153, 'Execution Unit/Register Files/Runtime Dynamic': 0.0188561, 'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387, 'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643, 'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912, 'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402, 'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0579915, 'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.159175, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543, 'Execution Unit/Runtime Dynamic': 0.98799, 'Execution Unit/Subthreshold Leakage': 1.79543, 'Execution Unit/Subthreshold Leakage with power gating': 0.688821, 'Gate Leakage': 0.368936, 'Instruction Fetch Unit/Area': 5.85939, 'Instruction Fetch Unit/Branch Predictor/Area': 0.138516, 'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 4.43237e-05, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 4.43237e-05, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 3.87605e-05, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 1.50894e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045, 'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838, 'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732, 'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05, 'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602, 'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000238607, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733, 'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.000366015, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282, 'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954, 'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758, 'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867, 'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.000419445, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357, 'Instruction Fetch Unit/Gate Leakage': 0.0589979, 'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323, 'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05, 'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827, 'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0159678, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682, 'Instruction Fetch Unit/Instruction Cache/Area': 3.14635, 'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931, 'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 1.01569, 'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0389099, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386, 'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799, 'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493, 'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404, 'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.0542338, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104, 'Instruction Fetch Unit/Peak Dynamic': 3.2835, 'Instruction Fetch Unit/Runtime Dynamic': 0.109897, 'Instruction Fetch Unit/Subthreshold Leakage': 0.932286, 'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843, 'L2/Area': 4.53318, 'L2/Gate Leakage': 0.015464, 'L2/Peak Dynamic': 0.0418086, 'L2/Runtime Dynamic': 0.0124139, 'L2/Subthreshold Leakage': 0.834142, 'L2/Subthreshold Leakage with power gating': 0.401066, 'Load Store Unit/Area': 8.80901, 'Load Store Unit/Data Cache/Area': 6.84535, 'Load Store Unit/Data Cache/Gate Leakage': 0.0279261, 'Load Store Unit/Data Cache/Peak Dynamic': 1.91422, 'Load Store Unit/Data Cache/Runtime Dynamic': 0.342888, 'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675, 'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085, 'Load Store Unit/Gate Leakage': 0.0350888, 'Load Store Unit/LoadQ/Area': 0.0836782, 'Load Store Unit/LoadQ/Gate Leakage': 0.00059896, 'Load Store Unit/LoadQ/Peak Dynamic': 0.0219057, 'Load Store Unit/LoadQ/Runtime Dynamic': 0.0219056, 'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961, 'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918, 'Load Store Unit/Peak Dynamic': 2.01766, 'Load Store Unit/Runtime Dynamic': 0.472824, 'Load Store Unit/StoreQ/Area': 0.322079, 'Load Store Unit/StoreQ/Gate Leakage': 0.00329971, 'Load Store Unit/StoreQ/Peak Dynamic': 0.0540158, 'Load Store Unit/StoreQ/Runtime Dynamic': 0.108031, 'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621, 'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004, 'Load Store Unit/Subthreshold Leakage': 0.591321, 'Load Store Unit/Subthreshold Leakage with power gating': 0.283293, 'Memory Management Unit/Area': 0.4339, 'Memory Management Unit/Dtlb/Area': 0.0879726, 'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729, 'Memory Management Unit/Dtlb/Peak Dynamic': 0.0191704, 'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0197958, 'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699, 'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485, 'Memory Management Unit/Gate Leakage': 0.00808595, 'Memory Management Unit/Itlb/Area': 0.301552, 'Memory Management Unit/Itlb/Gate Leakage': 0.00393464, 'Memory Management Unit/Itlb/Peak Dynamic': 0.063152, 'Memory Management Unit/Itlb/Runtime Dynamic': 0.006386, 'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758, 'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842, 'Memory Management Unit/Peak Dynamic': 0.252192, 'Memory Management Unit/Runtime Dynamic': 0.0261818, 'Memory Management Unit/Subthreshold Leakage': 0.0766103, 'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333, 'Peak Dynamic': 13.3175, 'Renaming Unit/Area': 0.303608, 'Renaming Unit/FP Front End RAT/Area': 0.131045, 'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123, 'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468, 'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0659386, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885, 'Renaming Unit/Free List/Area': 0.0340654, 'Renaming Unit/Free List/Gate Leakage': 2.5481e-05, 'Renaming Unit/Free List/Peak Dynamic': 0.0306032, 'Renaming Unit/Free List/Runtime Dynamic': 0.0032183, 'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144, 'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064, 'Renaming Unit/Gate Leakage': 0.00708398, 'Renaming Unit/Int Front End RAT/Area': 0.0941223, 'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242, 'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965, 'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0263421, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228, 'Renaming Unit/Peak Dynamic': 3.58947, 'Renaming Unit/Runtime Dynamic': 0.095499, 'Renaming Unit/Subthreshold Leakage': 0.0552466, 'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461, 'Runtime Dynamic': 1.70481, 'Subthreshold Leakage': 6.16288, 'Subthreshold Leakage with power gating': 2.55328}, {'Area': 32.0201, 'Execution Unit/Area': 7.68434, 'Execution Unit/Complex ALUs/Area': 0.235435, 'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646, 'Execution Unit/Complex ALUs/Peak Dynamic': 0.0233442, 'Execution Unit/Complex ALUs/Runtime Dynamic': 0.221024, 'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111, 'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163, 'Execution Unit/Floating Point Units/Area': 4.6585, 'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156, 'Execution Unit/Floating Point Units/Peak Dynamic': 0.132974, 'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033, 'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829, 'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061, 'Execution Unit/Gate Leakage': 0.120359, 'Execution Unit/Instruction Scheduler/Area': 1.66526, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.0534981, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453, 'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519, 'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913, 'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223, 'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562, 'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763, 'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.0862904, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755, 'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964, 'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262, 'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388, 'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608, 'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451, 'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.0435565, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853, 'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446, 'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.183345, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892, 'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346, 'Execution Unit/Integer ALUs/Area': 0.47087, 'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291, 'Execution Unit/Integer ALUs/Peak Dynamic': 0.0408007, 'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344, 'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222, 'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833, 'Execution Unit/Peak Dynamic': 4.13286, 'Execution Unit/Register Files/Area': 0.570804, 'Execution Unit/Register Files/Floating Point RF/Area': 0.208131, 'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788, 'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0251216, 'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00224395, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698, 'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968, 'Execution Unit/Register Files/Gate Leakage': 0.000622708, 'Execution Unit/Register Files/Integer RF/Area': 0.362673, 'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992, 'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0246857, 'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0165954, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175, 'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675, 'Execution Unit/Register Files/Peak Dynamic': 0.0498073, 'Execution Unit/Register Files/Runtime Dynamic': 0.0188393, 'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387, 'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643, 'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912, 'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402, 'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0578433, 'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.159149, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478, 'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543, 'Execution Unit/Runtime Dynamic': 0.987734, 'Execution Unit/Subthreshold Leakage': 1.79543, 'Execution Unit/Subthreshold Leakage with power gating': 0.688821, 'Gate Leakage': 0.368936, 'Instruction Fetch Unit/Area': 5.85939, 'Instruction Fetch Unit/Branch Predictor/Area': 0.138516, 'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 4.47676e-05, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 4.47676e-05, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719, 'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 3.91457e-05, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344, 'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 1.52378e-05, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347, 'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045, 'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838, 'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732, 'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05, 'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602, 'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000238394, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505, 'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733, 'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.000367075, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703, 'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282, 'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954, 'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758, 'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867, 'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.000423753, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682, 'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357, 'Instruction Fetch Unit/Gate Leakage': 0.0589979, 'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323, 'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05, 'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827, 'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0159536, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885, 'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682, 'Instruction Fetch Unit/Instruction Cache/Area': 3.14635, 'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931, 'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 1.01478, 'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0390004, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022, 'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386, 'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799, 'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493, 'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404, 'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.0541855, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943, 'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104, 'Instruction Fetch Unit/Peak Dynamic': 3.28255, 'Instruction Fetch Unit/Runtime Dynamic': 0.10993, 'Instruction Fetch Unit/Subthreshold Leakage': 0.932286, 'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843, 'L2/Area': 4.53318, 'L2/Gate Leakage': 0.015464, 'L2/Peak Dynamic': 0.0420224, 'L2/Runtime Dynamic': 0.0125557, 'L2/Subthreshold Leakage': 0.834142, 'L2/Subthreshold Leakage with power gating': 0.401066, 'Load Store Unit/Area': 8.80901, 'Load Store Unit/Data Cache/Area': 6.84535, 'Load Store Unit/Data Cache/Gate Leakage': 0.0279261, 'Load Store Unit/Data Cache/Peak Dynamic': 1.91408, 'Load Store Unit/Data Cache/Runtime Dynamic': 0.343009, 'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675, 'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085, 'Load Store Unit/Gate Leakage': 0.0350888, 'Load Store Unit/LoadQ/Area': 0.0836782, 'Load Store Unit/LoadQ/Gate Leakage': 0.00059896, 'Load Store Unit/LoadQ/Peak Dynamic': 0.0219013, 'Load Store Unit/LoadQ/Runtime Dynamic': 0.0219014, 'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961, 'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918, 'Load Store Unit/Peak Dynamic': 2.0175, 'Load Store Unit/Runtime Dynamic': 0.472921, 'Load Store Unit/StoreQ/Area': 0.322079, 'Load Store Unit/StoreQ/Gate Leakage': 0.00329971, 'Load Store Unit/StoreQ/Peak Dynamic': 0.0540048, 'Load Store Unit/StoreQ/Runtime Dynamic': 0.10801, 'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621, 'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004, 'Load Store Unit/Subthreshold Leakage': 0.591321, 'Load Store Unit/Subthreshold Leakage with power gating': 0.283293, 'Memory Management Unit/Area': 0.4339, 'Memory Management Unit/Dtlb/Area': 0.0879726, 'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729, 'Memory Management Unit/Dtlb/Peak Dynamic': 0.0191665, 'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0197953, 'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699, 'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485, 'Memory Management Unit/Gate Leakage': 0.00808595, 'Memory Management Unit/Itlb/Area': 0.301552, 'Memory Management Unit/Itlb/Gate Leakage': 0.00393464, 'Memory Management Unit/Itlb/Peak Dynamic': 0.0630956, 'Memory Management Unit/Itlb/Runtime Dynamic': 0.00640077, 'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758, 'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842, 'Memory Management Unit/Peak Dynamic': 0.252129, 'Memory Management Unit/Runtime Dynamic': 0.026196, 'Memory Management Unit/Subthreshold Leakage': 0.0766103, 'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333, 'Peak Dynamic': 13.3165, 'Renaming Unit/Area': 0.303608, 'Renaming Unit/FP Front End RAT/Area': 0.131045, 'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123, 'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468, 'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0660832, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571, 'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885, 'Renaming Unit/Free List/Area': 0.0340654, 'Renaming Unit/Free List/Gate Leakage': 2.5481e-05, 'Renaming Unit/Free List/Peak Dynamic': 0.0306032, 'Renaming Unit/Free List/Runtime Dynamic': 0.0032179, 'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144, 'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064, 'Renaming Unit/Gate Leakage': 0.00708398, 'Renaming Unit/Int Front End RAT/Area': 0.0941223, 'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242, 'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965, 'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0263098, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488, 'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228, 'Renaming Unit/Peak Dynamic': 3.58947, 'Renaming Unit/Runtime Dynamic': 0.0956109, 'Renaming Unit/Subthreshold Leakage': 0.0552466, 'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461, 'Runtime Dynamic': 1.70495, 'Subthreshold Leakage': 6.16288, 'Subthreshold Leakage with power gating': 2.55328}], 'DRAM': {'Area': 0, 'Gate Leakage': 0, 'Peak Dynamic': 8.547924110383947, 'Runtime Dynamic': 8.547924110383947, 'Subthreshold Leakage': 4.252, 'Subthreshold Leakage with power gating': 4.252}, 'L3': [{'Area': 61.9075, 'Gate Leakage': 0.0484137, 'Peak Dynamic': 0.455911, 'Runtime Dynamic': 0.177455, 'Subthreshold Leakage': 6.80085, 'Subthreshold Leakage with power gating': 3.32364}], 'Processor': {'Area': 191.908, 'Gate Leakage': 1.53485, 'Peak Dynamic': 60.4616, 'Peak Power': 93.5738, 'Runtime Dynamic': 9.51406, 'Subthreshold Leakage': 31.5774, 'Subthreshold Leakage with power gating': 13.9484, 'Total Cores/Area': 128.669, 'Total Cores/Gate Leakage': 1.4798, 'Total Cores/Peak Dynamic': 60.0057, 'Total Cores/Runtime Dynamic': 9.3366, 'Total Cores/Subthreshold Leakage': 24.7074, 'Total Cores/Subthreshold Leakage with power gating': 10.2429, 'Total L3s/Area': 61.9075, 'Total L3s/Gate Leakage': 0.0484137, 'Total L3s/Peak Dynamic': 0.455911, 'Total L3s/Runtime Dynamic': 0.177455, 'Total L3s/Subthreshold Leakage': 6.80085, 'Total L3s/Subthreshold Leakage with power gating': 3.32364, 'Total Leakage': 33.1122, 'Total NoCs/Area': 1.33155, 'Total NoCs/Gate Leakage': 0.00662954, 'Total NoCs/Peak Dynamic': 0.0, 'Total NoCs/Runtime Dynamic': 0.0, 'Total NoCs/Subthreshold Leakage': 0.0691322, 'Total NoCs/Subthreshold Leakage with power gating': 0.0259246}}
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, # Override to dynamically link the cras (ChromeOS audio) library. 'use_cras%': 0, # Option e.g. for Linux distributions to link pulseaudio directly # (DT_NEEDED) instead of using dlopen. This helps with automated # detection of ABI mismatches and prevents silent errors. 'linux_link_pulseaudio%': 0, 'conditions': [ ['OS == "android" or OS == "ios"', { # Android and iOS don't use ffmpeg. 'media_use_ffmpeg%': 0, # Android and iOS don't use libvpx. 'media_use_libvpx%': 0, }, { # 'OS != "android" and OS != "ios"' 'media_use_ffmpeg%': 1, 'media_use_libvpx%': 1, }], # Screen capturer works only on Windows, OSX and Linux (with X11). ['OS=="win" or OS=="mac" or (OS=="linux" and use_x11==1)', { 'screen_capture_supported%': 1, }, { 'screen_capture_supported%': 0, }], # ALSA usage. ['OS=="linux" or OS=="freebsd" or OS=="solaris"', { 'use_alsa%': 1, }, { 'use_alsa%': 0, }], ['os_posix == 1 and OS != "mac" and OS != "ios" and OS != "android" and chromeos != 1', { 'use_pulseaudio%': 1, }, { 'use_pulseaudio%': 0, }], ], }, 'targets': [ { 'target_name': 'media', 'type': '<(component)', 'dependencies': [ '../base/base.gyp:base', '../build/temp_gyp/googleurl.gyp:googleurl', '../crypto/crypto.gyp:crypto', '../skia/skia.gyp:skia', '../third_party/opus/opus.gyp:opus', '../ui/ui.gyp:ui', ], 'defines': [ 'MEDIA_IMPLEMENTATION', ], 'include_dirs': [ '..', ], 'sources': [ 'audio/android/audio_manager_android.cc', 'audio/android/audio_manager_android.h', 'audio/android/opensles_input.cc', 'audio/android/opensles_input.h', 'audio/android/opensles_output.cc', 'audio/android/opensles_output.h', 'audio/async_socket_io_handler.h', 'audio/async_socket_io_handler_posix.cc', 'audio/async_socket_io_handler_win.cc', 'audio/audio_buffers_state.cc', 'audio/audio_buffers_state.h', 'audio/audio_device_name.cc', 'audio/audio_device_name.h', 'audio/audio_device_thread.cc', 'audio/audio_device_thread.h', 'audio/audio_input_controller.cc', 'audio/audio_input_controller.h', 'audio/audio_input_device.cc', 'audio/audio_input_device.h', 'audio/audio_input_ipc.cc', 'audio/audio_input_ipc.h', 'audio/audio_input_stream_impl.cc', 'audio/audio_input_stream_impl.h', 'audio/audio_io.h', 'audio/audio_manager.cc', 'audio/audio_manager.h', 'audio/audio_manager_base.cc', 'audio/audio_manager_base.h', 'audio/audio_output_controller.cc', 'audio/audio_output_controller.h', 'audio/audio_output_device.cc', 'audio/audio_output_device.h', 'audio/audio_output_dispatcher.cc', 'audio/audio_output_dispatcher.h', 'audio/audio_output_dispatcher_impl.cc', 'audio/audio_output_dispatcher_impl.h', 'audio/audio_output_ipc.cc', 'audio/audio_output_ipc.h', 'audio/audio_output_proxy.cc', 'audio/audio_output_proxy.h', 'audio/audio_output_resampler.cc', 'audio/audio_output_resampler.h', 'audio/audio_silence_detector.cc', 'audio/audio_silence_detector.h', 'audio/audio_source_diverter.h', 'audio/audio_util.cc', 'audio/audio_util.h', 'audio/cras/audio_manager_cras.cc', 'audio/cras/audio_manager_cras.h', 'audio/cras/cras_input.cc', 'audio/cras/cras_input.h', 'audio/cras/cras_unified.cc', 'audio/cras/cras_unified.h', 'audio/cross_process_notification.cc', 'audio/cross_process_notification.h', 'audio/cross_process_notification_posix.cc', 'audio/cross_process_notification_win.cc', 'audio/fake_audio_consumer.cc', 'audio/fake_audio_consumer.h', 'audio/fake_audio_input_stream.cc', 'audio/fake_audio_input_stream.h', 'audio/fake_audio_output_stream.cc', 'audio/fake_audio_output_stream.h', 'audio/ios/audio_manager_ios.h', 'audio/ios/audio_manager_ios.mm', 'audio/ios/audio_session_util_ios.h', 'audio/ios/audio_session_util_ios.mm', 'audio/linux/alsa_input.cc', 'audio/linux/alsa_input.h', 'audio/linux/alsa_output.cc', 'audio/linux/alsa_output.h', 'audio/linux/alsa_util.cc', 'audio/linux/alsa_util.h', 'audio/linux/alsa_wrapper.cc', 'audio/linux/alsa_wrapper.h', 'audio/linux/audio_manager_linux.cc', 'audio/linux/audio_manager_linux.h', 'audio/mac/aggregate_device_manager.cc', 'audio/mac/aggregate_device_manager.h', 'audio/mac/audio_auhal_mac.cc', 'audio/mac/audio_auhal_mac.h', 'audio/mac/audio_device_listener_mac.cc', 'audio/mac/audio_device_listener_mac.h', 'audio/mac/audio_input_mac.cc', 'audio/mac/audio_input_mac.h', 'audio/mac/audio_low_latency_input_mac.cc', 'audio/mac/audio_low_latency_input_mac.h', 'audio/mac/audio_low_latency_output_mac.cc', 'audio/mac/audio_low_latency_output_mac.h', 'audio/mac/audio_manager_mac.cc', 'audio/mac/audio_manager_mac.h', 'audio/mac/audio_synchronized_mac.cc', 'audio/mac/audio_synchronized_mac.h', 'audio/mac/audio_unified_mac.cc', 'audio/mac/audio_unified_mac.h', 'audio/null_audio_sink.cc', 'audio/null_audio_sink.h', 'audio/openbsd/audio_manager_openbsd.cc', 'audio/openbsd/audio_manager_openbsd.h', 'audio/pulse/audio_manager_pulse.cc', 'audio/pulse/audio_manager_pulse.h', 'audio/pulse/pulse_output.cc', 'audio/pulse/pulse_output.h', 'audio/pulse/pulse_input.cc', 'audio/pulse/pulse_input.h', 'audio/pulse/pulse_unified.cc', 'audio/pulse/pulse_unified.h', 'audio/pulse/pulse_util.cc', 'audio/pulse/pulse_util.h', 'audio/sample_rates.cc', 'audio/sample_rates.h', 'audio/scoped_loop_observer.cc', 'audio/scoped_loop_observer.h', 'audio/simple_sources.cc', 'audio/simple_sources.h', 'audio/virtual_audio_input_stream.cc', 'audio/virtual_audio_input_stream.h', 'audio/virtual_audio_output_stream.cc', 'audio/virtual_audio_output_stream.h', 'audio/win/audio_device_listener_win.cc', 'audio/win/audio_device_listener_win.h', 'audio/win/audio_low_latency_input_win.cc', 'audio/win/audio_low_latency_input_win.h', 'audio/win/audio_low_latency_output_win.cc', 'audio/win/audio_low_latency_output_win.h', 'audio/win/audio_manager_win.cc', 'audio/win/audio_manager_win.h', 'audio/win/audio_unified_win.cc', 'audio/win/audio_unified_win.h', 'audio/win/avrt_wrapper_win.cc', 'audio/win/avrt_wrapper_win.h', 'audio/win/device_enumeration_win.cc', 'audio/win/device_enumeration_win.h', 'audio/win/core_audio_util_win.cc', 'audio/win/core_audio_util_win.h', 'audio/win/wavein_input_win.cc', 'audio/win/wavein_input_win.h', 'audio/win/waveout_output_win.cc', 'audio/win/waveout_output_win.h', 'base/android/media_player_manager.cc', 'base/android/media_player_manager.h', 'base/android/media_resource_getter.cc', 'base/android/media_resource_getter.h', 'base/audio_capturer_source.h', 'base/audio_converter.cc', 'base/audio_converter.h', 'base/audio_decoder.cc', 'base/audio_decoder.h', 'base/audio_decoder_config.cc', 'base/audio_decoder_config.h', 'base/audio_fifo.cc', 'base/audio_fifo.h', 'base/audio_hardware_config.cc', 'base/audio_hardware_config.h', 'base/audio_hash.cc', 'base/audio_hash.h', 'base/audio_pull_fifo.cc', 'base/audio_pull_fifo.h', 'base/audio_renderer.cc', 'base/audio_renderer.h', 'base/audio_renderer_sink.h', 'base/audio_renderer_mixer.cc', 'base/audio_renderer_mixer.h', 'base/audio_renderer_mixer_input.cc', 'base/audio_renderer_mixer_input.h', 'base/audio_splicer.cc', 'base/audio_splicer.h', 'base/audio_timestamp_helper.cc', 'base/audio_timestamp_helper.h', 'base/bind_to_loop.h', 'base/bitstream_buffer.h', 'base/bit_reader.cc', 'base/bit_reader.h', 'base/buffers.h', 'base/byte_queue.cc', 'base/byte_queue.h', 'base/channel_mixer.cc', 'base/channel_mixer.h', 'base/clock.cc', 'base/clock.h', 'base/data_buffer.cc', 'base/data_buffer.h', 'base/data_source.cc', 'base/data_source.h', 'base/decoder_buffer.cc', 'base/decoder_buffer.h', 'base/decoder_buffer_queue.cc', 'base/decoder_buffer_queue.h', 'base/decryptor.cc', 'base/decryptor.h', 'base/decrypt_config.cc', 'base/decrypt_config.h', 'base/demuxer.cc', 'base/demuxer.h', 'base/demuxer_stream.cc', 'base/demuxer_stream.h', 'base/djb2.cc', 'base/djb2.h', 'base/filter_collection.cc', 'base/filter_collection.h', 'base/media.cc', 'base/media.h', 'base/media_log.cc', 'base/media_log.h', 'base/media_log_event.h', 'base/media_posix.cc', 'base/media_switches.cc', 'base/media_switches.h', 'base/media_win.cc', 'base/multi_channel_resampler.cc', 'base/multi_channel_resampler.h', 'base/pipeline.cc', 'base/pipeline.h', 'base/pipeline_status.cc', 'base/pipeline_status.h', 'base/ranges.cc', 'base/ranges.h', 'base/scoped_histogram_timer.h', 'base/seekable_buffer.cc', 'base/seekable_buffer.h', 'base/serial_runner.cc', 'base/serial_runner.h', 'base/sinc_resampler.cc', 'base/sinc_resampler.h', 'base/stream_parser.cc', 'base/stream_parser.h', 'base/stream_parser_buffer.cc', 'base/stream_parser_buffer.h', 'base/video_decoder.cc', 'base/video_decoder.h', 'base/video_decoder_config.cc', 'base/video_decoder_config.h', 'base/video_frame.cc', 'base/video_frame.h', 'base/video_renderer.cc', 'base/video_renderer.h', 'base/video_util.cc', 'base/video_util.h', 'crypto/aes_decryptor.cc', 'crypto/aes_decryptor.h', 'ffmpeg/ffmpeg_common.cc', 'ffmpeg/ffmpeg_common.h', 'filters/audio_decoder_selector.cc', 'filters/audio_decoder_selector.h', 'filters/audio_file_reader.cc', 'filters/audio_file_reader.h', 'filters/audio_renderer_algorithm.cc', 'filters/audio_renderer_algorithm.h', 'filters/audio_renderer_impl.cc', 'filters/audio_renderer_impl.h', 'filters/blocking_url_protocol.cc', 'filters/blocking_url_protocol.h', 'filters/chunk_demuxer.cc', 'filters/chunk_demuxer.h', 'filters/decrypting_audio_decoder.cc', 'filters/decrypting_audio_decoder.h', 'filters/decrypting_demuxer_stream.cc', 'filters/decrypting_demuxer_stream.h', 'filters/decrypting_video_decoder.cc', 'filters/decrypting_video_decoder.h', 'filters/fake_demuxer_stream.cc', 'filters/fake_demuxer_stream.h', 'filters/ffmpeg_audio_decoder.cc', 'filters/ffmpeg_audio_decoder.h', 'filters/ffmpeg_demuxer.cc', 'filters/ffmpeg_demuxer.h', 'filters/ffmpeg_glue.cc', 'filters/ffmpeg_glue.h', 'filters/ffmpeg_h264_to_annex_b_bitstream_converter.cc', 'filters/ffmpeg_h264_to_annex_b_bitstream_converter.h', 'filters/ffmpeg_video_decoder.cc', 'filters/ffmpeg_video_decoder.h', 'filters/file_data_source.cc', 'filters/file_data_source.h', 'filters/gpu_video_decoder.cc', 'filters/gpu_video_decoder.h', 'filters/h264_to_annex_b_bitstream_converter.cc', 'filters/h264_to_annex_b_bitstream_converter.h', 'filters/in_memory_url_protocol.cc', 'filters/in_memory_url_protocol.h', 'filters/opus_audio_decoder.cc', 'filters/opus_audio_decoder.h', 'filters/skcanvas_video_renderer.cc', 'filters/skcanvas_video_renderer.h', 'filters/source_buffer_stream.cc', 'filters/source_buffer_stream.h', 'filters/stream_parser_factory.cc', 'filters/stream_parser_factory.h', 'filters/video_decoder_selector.cc', 'filters/video_decoder_selector.h', 'filters/video_frame_stream.cc', 'filters/video_frame_stream.h', 'filters/video_renderer_base.cc', 'filters/video_renderer_base.h', 'filters/vpx_video_decoder.cc', 'filters/vpx_video_decoder.h', 'video/capture/android/video_capture_device_android.cc', 'video/capture/android/video_capture_device_android.h', 'video/capture/fake_video_capture_device.cc', 'video/capture/fake_video_capture_device.h', 'video/capture/linux/video_capture_device_linux.cc', 'video/capture/linux/video_capture_device_linux.h', 'video/capture/mac/video_capture_device_mac.h', 'video/capture/mac/video_capture_device_mac.mm', 'video/capture/mac/video_capture_device_qtkit_mac.h', 'video/capture/mac/video_capture_device_qtkit_mac.mm', 'video/capture/screen/differ.cc', 'video/capture/screen/differ.h', 'video/capture/screen/differ_block.cc', 'video/capture/screen/differ_block.h', 'video/capture/screen/mac/desktop_configuration.h', 'video/capture/screen/mac/desktop_configuration.mm', 'video/capture/screen/mac/scoped_pixel_buffer_object.cc', 'video/capture/screen/mac/scoped_pixel_buffer_object.h', 'video/capture/screen/mouse_cursor_shape.h', 'video/capture/screen/screen_capture_device.cc', 'video/capture/screen/screen_capture_device.h', 'video/capture/screen/screen_capture_frame_queue.cc', 'video/capture/screen/screen_capture_frame_queue.h', 'video/capture/screen/screen_capturer.h', 'video/capture/screen/screen_capturer_fake.cc', 'video/capture/screen/screen_capturer_fake.h', 'video/capture/screen/screen_capturer_helper.cc', 'video/capture/screen/screen_capturer_helper.h', 'video/capture/screen/screen_capturer_mac.mm', 'video/capture/screen/screen_capturer_null.cc', 'video/capture/screen/screen_capturer_win.cc', 'video/capture/screen/screen_capturer_x11.cc', 'video/capture/screen/shared_desktop_frame.cc', 'video/capture/screen/shared_desktop_frame.h', 'video/capture/screen/win/desktop.cc', 'video/capture/screen/win/desktop.h', 'video/capture/screen/win/scoped_thread_desktop.cc', 'video/capture/screen/win/scoped_thread_desktop.h', 'video/capture/screen/x11/x_server_pixel_buffer.cc', 'video/capture/screen/x11/x_server_pixel_buffer.h', 'video/capture/video_capture.h', 'video/capture/video_capture_device.h', 'video/capture/video_capture_device_dummy.cc', 'video/capture/video_capture_device_dummy.h', 'video/capture/video_capture_proxy.cc', 'video/capture/video_capture_proxy.h', 'video/capture/video_capture_types.h', 'video/capture/win/capability_list_win.cc', 'video/capture/win/capability_list_win.h', 'video/capture/win/filter_base_win.cc', 'video/capture/win/filter_base_win.h', 'video/capture/win/pin_base_win.cc', 'video/capture/win/pin_base_win.h', 'video/capture/win/sink_filter_observer_win.h', 'video/capture/win/sink_filter_win.cc', 'video/capture/win/sink_filter_win.h', 'video/capture/win/sink_input_pin_win.cc', 'video/capture/win/sink_input_pin_win.h', 'video/capture/win/video_capture_device_mf_win.cc', 'video/capture/win/video_capture_device_mf_win.h', 'video/capture/win/video_capture_device_win.cc', 'video/capture/win/video_capture_device_win.h', 'video/picture.cc', 'video/picture.h', 'video/video_decode_accelerator.cc', 'video/video_decode_accelerator.h', 'webm/webm_audio_client.cc', 'webm/webm_audio_client.h', 'webm/webm_cluster_parser.cc', 'webm/webm_cluster_parser.h', 'webm/webm_constants.cc', 'webm/webm_constants.h', 'webm/webm_content_encodings.cc', 'webm/webm_content_encodings.h', 'webm/webm_content_encodings_client.cc', 'webm/webm_content_encodings_client.h', 'webm/webm_crypto_helpers.cc', 'webm/webm_crypto_helpers.h', 'webm/webm_info_parser.cc', 'webm/webm_info_parser.h', 'webm/webm_parser.cc', 'webm/webm_parser.h', 'webm/webm_stream_parser.cc', 'webm/webm_stream_parser.h', 'webm/webm_tracks_parser.cc', 'webm/webm_tracks_parser.h', 'webm/webm_video_client.cc', 'webm/webm_video_client.h', ], 'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'conditions': [ ['arm_neon == 1', { 'defines': [ 'USE_NEON' ], }], ['OS != "linux" or use_x11 == 1', { 'sources!': [ 'video/capture/screen/screen_capturer_null.cc', ] }], ['OS != "ios"', { 'dependencies': [ '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', 'shared_memory_support', 'yuv_convert', ], }], ['media_use_ffmpeg == 1', { 'dependencies': [ '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', ], }, { # media_use_ffmpeg == 0 # Exclude the sources that depend on ffmpeg. 'sources!': [ 'base/media_posix.cc', 'ffmpeg/ffmpeg_common.cc', 'ffmpeg/ffmpeg_common.h', 'filters/audio_file_reader.cc', 'filters/audio_file_reader.h', 'filters/blocking_url_protocol.cc', 'filters/blocking_url_protocol.h', 'filters/ffmpeg_audio_decoder.cc', 'filters/ffmpeg_audio_decoder.h', 'filters/ffmpeg_demuxer.cc', 'filters/ffmpeg_demuxer.h', 'filters/ffmpeg_glue.cc', 'filters/ffmpeg_glue.h', 'filters/ffmpeg_h264_to_annex_b_bitstream_converter.cc', 'filters/ffmpeg_h264_to_annex_b_bitstream_converter.h', 'filters/ffmpeg_video_decoder.cc', 'filters/ffmpeg_video_decoder.h', ], }], ['media_use_libvpx == 1', { 'dependencies': [ '<(DEPTH)/third_party/libvpx/libvpx.gyp:libvpx', ], }, { # media_use_libvpx == 0 'direct_dependent_settings': { 'defines': [ 'MEDIA_DISABLE_LIBVPX', ], }, # Exclude the sources that depend on libvpx. 'sources!': [ 'filters/vpx_video_decoder.cc', 'filters/vpx_video_decoder.h', ], }], ['OS == "ios"', { 'includes': [ # For shared_memory_support_sources variable. 'shared_memory_support.gypi', ], 'sources': [ 'base/media_stub.cc', # These sources are normally built via a dependency on the # shared_memory_support target, but that target is not built on iOS. # Instead, directly build only the files that are needed for iOS. '<@(shared_memory_support_sources)', ], 'sources/': [ # Exclude everything but iOS-specific files. ['exclude', '\\.(cc|mm)$'], ['include', '_ios\\.(cc|mm)$'], ['include', '(^|/)ios/'], # Re-include specific pieces. # iOS support is limited to audio input only. ['include', '^audio/audio_buffers_state\\.'], ['include', '^audio/audio_input_controller\\.'], ['include', '^audio/audio_manager\\.'], ['include', '^audio/audio_manager_base\\.'], ['include', '^audio/audio_parameters\\.'], ['include', '^audio/fake_audio_consumer\\.'], ['include', '^audio/fake_audio_input_stream\\.'], ['include', '^audio/fake_audio_output_stream\\.'], ['include', '^base/audio_bus\\.'], ['include', '^base/channel_layout\\.'], ['include', '^base/media\\.cc$'], ['include', '^base/media_stub\\.cc$'], ['include', '^base/media_switches\\.'], ['include', '^base/vector_math\\.'], ], 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AudioToolbox.framework', '$(SDKROOT)/System/Library/Frameworks/AVFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreAudio.framework', ], }, }], ['OS == "android"', { 'link_settings': { 'libraries': [ '-lOpenSLES', ], }, 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/media', ], 'dependencies': [ 'media_android_jni_headers', 'player_android', 'video_capture_android_jni_headers', ], 'sources': [ 'base/media.cc', 'base/media.h', ], 'conditions': [ ['android_webview_build == 0', { 'dependencies': [ 'media_java', ], }], ['use_openmax_dl_fft==1', { # FFT library requires Neon support, so we enable # WebAudio only if Neon is detected at runtime. 'sources': [ 'base/media_android.cc', ], 'includes': [ '../build/android/cpufeatures.gypi', ], }, { 'sources': [ 'base/media_stub.cc', ], }], ], }], # A simple WebM encoder for animated avatars on ChromeOS. ['chromeos==1', { 'dependencies': [ '../third_party/libvpx/libvpx.gyp:libvpx', '../third_party/libyuv/libyuv.gyp:libyuv', ], 'sources': [ 'webm/chromeos/ebml_writer.cc', 'webm/chromeos/ebml_writer.h', 'webm/chromeos/webm_encoder.cc', 'webm/chromeos/webm_encoder.h', ], }], ['use_alsa==1', { 'link_settings': { 'libraries': [ '-lasound', ], }, }, { # use_alsa==0 'sources/': [ ['exclude', '/alsa_' ], ['exclude', '/audio_manager_linux' ] ], }], ['OS!="openbsd"', { 'sources!': [ 'audio/openbsd/audio_manager_openbsd.cc', 'audio/openbsd/audio_manager_openbsd.h', ], }], ['OS=="linux"', { 'variables': { 'conditions': [ ['sysroot!=""', { 'pkg-config': '../build/linux/pkg-config-wrapper "<(sysroot)" "<(target_arch)"', }, { 'pkg-config': 'pkg-config' }], ], }, 'conditions': [ ['use_x11 == 1', { 'link_settings': { 'libraries': [ '-lX11', '-lXdamage', '-lXext', '-lXfixes', ], }, }], ['use_cras == 1', { 'cflags': [ '<!@(<(pkg-config) --cflags libcras)', ], 'link_settings': { 'libraries': [ '<!@(<(pkg-config) --libs libcras)', ], }, 'defines': [ 'USE_CRAS', ], }, { # else: use_cras == 0 'sources!': [ 'audio/cras/audio_manager_cras.cc', 'audio/cras/audio_manager_cras.h', 'audio/cras/cras_input.cc', 'audio/cras/cras_input.h', 'audio/cras/cras_unified.cc', 'audio/cras/cras_unified.h', ], }], ], }], ['OS!="linux"', { 'sources!': [ 'audio/cras/audio_manager_cras.cc', 'audio/cras/audio_manager_cras.h', 'audio/cras/cras_input.cc', 'audio/cras/cras_input.h', 'audio/cras/cras_unified.cc', 'audio/cras/cras_unified.h', ], }], ['use_pulseaudio==1', { 'cflags': [ '<!@(pkg-config --cflags libpulse)', ], 'defines': [ 'USE_PULSEAUDIO', ], 'conditions': [ ['linux_link_pulseaudio==0', { 'defines': [ 'DLOPEN_PULSEAUDIO', ], 'variables': { 'generate_stubs_script': '../tools/generate_stubs/generate_stubs.py', 'extra_header': 'audio/pulse/pulse_stub_header.fragment', 'sig_files': ['audio/pulse/pulse.sigs'], 'outfile_type': 'posix_stubs', 'stubs_filename_root': 'pulse_stubs', 'project_path': 'media/audio/pulse', 'intermediate_dir': '<(INTERMEDIATE_DIR)', 'output_root': '<(SHARED_INTERMEDIATE_DIR)/pulse', }, 'include_dirs': [ '<(output_root)', ], 'actions': [ { 'action_name': 'generate_stubs', 'inputs': [ '<(generate_stubs_script)', '<(extra_header)', '<@(sig_files)', ], 'outputs': [ '<(intermediate_dir)/<(stubs_filename_root).cc', '<(output_root)/<(project_path)/<(stubs_filename_root).h', ], 'action': ['python', '<(generate_stubs_script)', '-i', '<(intermediate_dir)', '-o', '<(output_root)/<(project_path)', '-t', '<(outfile_type)', '-e', '<(extra_header)', '-s', '<(stubs_filename_root)', '-p', '<(project_path)', '<@(_inputs)', ], 'process_outputs_as_sources': 1, 'message': 'Generating Pulse stubs for dynamic loading.', }, ], 'conditions': [ # Linux/Solaris need libdl for dlopen() and friends. ['OS == "linux" or OS == "solaris"', { 'link_settings': { 'libraries': [ '-ldl', ], }, }], ], }, { # else: linux_link_pulseaudio==0 'link_settings': { 'ldflags': [ '<!@(pkg-config --libs-only-L --libs-only-other libpulse)', ], 'libraries': [ '<!@(pkg-config --libs-only-l libpulse)', ], }, }], ], }, { # else: use_pulseaudio==0 'sources!': [ 'audio/pulse/audio_manager_pulse.cc', 'audio/pulse/audio_manager_pulse.h', 'audio/pulse/pulse_input.cc', 'audio/pulse/pulse_input.h', 'audio/pulse/pulse_output.cc', 'audio/pulse/pulse_output.h', 'audio/pulse/pulse_unified.cc', 'audio/pulse/pulse_unified.h', 'audio/pulse/pulse_util.cc', 'audio/pulse/pulse_util.h', ], }], ['os_posix == 1', { 'sources!': [ 'video/capture/video_capture_device_dummy.cc', 'video/capture/video_capture_device_dummy.h', ], }], ['OS=="mac"', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AudioToolbox.framework', '$(SDKROOT)/System/Library/Frameworks/AudioUnit.framework', '$(SDKROOT)/System/Library/Frameworks/CoreAudio.framework', '$(SDKROOT)/System/Library/Frameworks/CoreVideo.framework', '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework', '$(SDKROOT)/System/Library/Frameworks/QTKit.framework', ], }, }], ['OS=="win"', { 'sources!': [ 'video/capture/video_capture_device_dummy.cc', 'video/capture/video_capture_device_dummy.h', ], 'link_settings': { 'libraries': [ '-lmf.lib', '-lmfplat.lib', '-lmfreadwrite.lib', '-lmfuuid.lib', ], }, # Specify delayload for media.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'mf.dll', 'mfplat.dll', 'mfreadwrite.dll', ], }, }, # Specify delayload for components that link with media.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'mf.dll', 'mfplat.dll', 'mfreadwrite.dll', ], }, }, }, # TODO(wolenetz): Fix size_t to int truncations in win64. See # http://crbug.com/171009 'conditions': [ ['target_arch == "x64"', { 'msvs_disabled_warnings': [ 4267, ], }], ], }], ['proprietary_codecs==1 or branding=="Chrome"', { 'sources': [ 'mp4/aac.cc', 'mp4/aac.h', 'mp4/avc.cc', 'mp4/avc.h', 'mp4/box_definitions.cc', 'mp4/box_definitions.h', 'mp4/box_reader.cc', 'mp4/box_reader.h', 'mp4/cenc.cc', 'mp4/cenc.h', 'mp4/es_descriptor.cc', 'mp4/es_descriptor.h', 'mp4/mp4_stream_parser.cc', 'mp4/mp4_stream_parser.h', 'mp4/offset_byte_queue.cc', 'mp4/offset_byte_queue.h', 'mp4/track_run_iterator.cc', 'mp4/track_run_iterator.h', ], }], [ 'screen_capture_supported==1', { 'dependencies': [ '../third_party/webrtc/modules/modules.gyp:desktop_capture', ], }, { 'sources/': [ ['exclude', '^video/capture/screen/'], ], }], [ 'screen_capture_supported==1 and (target_arch=="ia32" or target_arch=="x64")', { 'dependencies': [ 'differ_block_sse2', ], }], ['toolkit_uses_gtk==1', { 'dependencies': [ '../build/linux/system.gyp:gtk', ], }], # ios check is necessary due to http://crbug.com/172682. ['OS != "ios" and (target_arch == "ia32" or target_arch == "x64")', { 'dependencies': [ 'media_sse', ], }], ['google_tv == 1', { 'defines': [ 'ENABLE_EAC3_PLAYBACK', ], }], ], 'target_conditions': [ ['OS == "ios"', { 'sources/': [ # Pull in specific Mac files for iOS (which have been filtered out # by file name rules). ['include', '^audio/mac/audio_input_mac\\.'], ], }], ], }, { 'target_name': 'media_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ 'media', 'media_test_support', '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_base', '../skia/skia.gyp:skia', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../ui/ui.gyp:ui', ], 'sources': [ 'audio/async_socket_io_handler_unittest.cc', 'audio/audio_input_controller_unittest.cc', 'audio/audio_input_device_unittest.cc', 'audio/audio_input_unittest.cc', 'audio/audio_input_volume_unittest.cc', 'audio/audio_low_latency_input_output_unittest.cc', 'audio/audio_output_controller_unittest.cc', 'audio/audio_output_device_unittest.cc', 'audio/audio_output_proxy_unittest.cc', 'audio/audio_parameters_unittest.cc', 'audio/audio_silence_detector_unittest.cc', 'audio/cross_process_notification_unittest.cc', 'audio/fake_audio_consumer_unittest.cc', 'audio/ios/audio_manager_ios_unittest.cc', 'audio/linux/alsa_output_unittest.cc', 'audio/mac/audio_auhal_mac_unittest.cc', 'audio/mac/audio_device_listener_mac_unittest.cc', 'audio/mac/audio_low_latency_input_mac_unittest.cc', 'audio/simple_sources_unittest.cc', 'audio/virtual_audio_input_stream_unittest.cc', 'audio/virtual_audio_output_stream_unittest.cc', 'audio/win/audio_device_listener_win_unittest.cc', 'audio/win/audio_low_latency_input_win_unittest.cc', 'audio/win/audio_low_latency_output_win_unittest.cc', 'audio/win/audio_output_win_unittest.cc', 'audio/win/audio_unified_win_unittest.cc', 'audio/win/core_audio_util_win_unittest.cc', 'base/android/media_codec_bridge_unittest.cc', 'base/audio_bus_unittest.cc', 'base/audio_converter_unittest.cc', 'base/audio_fifo_unittest.cc', 'base/audio_hardware_config_unittest.cc', 'base/audio_hash_unittest.cc', 'base/audio_pull_fifo_unittest.cc', 'base/audio_renderer_mixer_input_unittest.cc', 'base/audio_renderer_mixer_unittest.cc', 'base/audio_splicer_unittest.cc', 'base/audio_timestamp_helper_unittest.cc', 'base/bind_to_loop_unittest.cc', 'base/bit_reader_unittest.cc', 'base/channel_mixer_unittest.cc', 'base/clock_unittest.cc', 'base/data_buffer_unittest.cc', 'base/decoder_buffer_queue_unittest.cc', 'base/decoder_buffer_unittest.cc', 'base/djb2_unittest.cc', 'base/gmock_callback_support_unittest.cc', 'base/multi_channel_resampler_unittest.cc', 'base/pipeline_unittest.cc', 'base/ranges_unittest.cc', 'base/run_all_unittests.cc', 'base/scoped_histogram_timer_unittest.cc', 'base/seekable_buffer_unittest.cc', 'base/sinc_resampler_unittest.cc', 'base/test_data_util.cc', 'base/test_data_util.h', 'base/vector_math_testing.h', 'base/vector_math_unittest.cc', 'base/video_frame_unittest.cc', 'base/video_util_unittest.cc', 'base/yuv_convert_unittest.cc', 'crypto/aes_decryptor_unittest.cc', 'ffmpeg/ffmpeg_common_unittest.cc', 'filters/audio_decoder_selector_unittest.cc', 'filters/audio_file_reader_unittest.cc', 'filters/audio_renderer_algorithm_unittest.cc', 'filters/audio_renderer_impl_unittest.cc', 'filters/blocking_url_protocol_unittest.cc', 'filters/chunk_demuxer_unittest.cc', 'filters/decrypting_audio_decoder_unittest.cc', 'filters/decrypting_demuxer_stream_unittest.cc', 'filters/decrypting_video_decoder_unittest.cc', 'filters/fake_demuxer_stream_unittest.cc', 'filters/ffmpeg_audio_decoder_unittest.cc', 'filters/ffmpeg_demuxer_unittest.cc', 'filters/ffmpeg_glue_unittest.cc', 'filters/ffmpeg_h264_to_annex_b_bitstream_converter_unittest.cc', 'filters/ffmpeg_video_decoder_unittest.cc', 'filters/file_data_source_unittest.cc', 'filters/h264_to_annex_b_bitstream_converter_unittest.cc', 'filters/pipeline_integration_test.cc', 'filters/pipeline_integration_test_base.cc', 'filters/skcanvas_video_renderer_unittest.cc', 'filters/source_buffer_stream_unittest.cc', 'filters/video_decoder_selector_unittest.cc', 'filters/video_frame_stream_unittest.cc', 'filters/video_renderer_base_unittest.cc', 'video/capture/screen/differ_block_unittest.cc', 'video/capture/screen/differ_unittest.cc', 'video/capture/screen/screen_capture_device_unittest.cc', 'video/capture/screen/screen_capturer_helper_unittest.cc', 'video/capture/screen/screen_capturer_mac_unittest.cc', 'video/capture/screen/screen_capturer_unittest.cc', 'video/capture/video_capture_device_unittest.cc', 'webm/cluster_builder.cc', 'webm/cluster_builder.h', 'webm/tracks_builder.cc', 'webm/tracks_builder.h', 'webm/webm_cluster_parser_unittest.cc', 'webm/webm_content_encodings_client_unittest.cc', 'webm/webm_parser_unittest.cc', 'webm/webm_tracks_parser_unittest.cc', ], 'conditions': [ ['arm_neon == 1', { 'defines': [ 'USE_NEON' ], }], ['OS != "ios"', { 'dependencies': [ 'shared_memory_support', 'yuv_convert', ], }], ['media_use_ffmpeg == 1', { 'dependencies': [ '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', ], }], ['os_posix==1 and OS!="mac" and OS!="ios"', { 'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], ['OS == "ios"', { 'sources/': [ ['exclude', '.*'], ['include', '^audio/audio_input_controller_unittest\\.cc$'], ['include', '^audio/audio_input_unittest\\.cc$'], ['include', '^audio/audio_parameters_unittest\\.cc$'], ['include', '^audio/ios/audio_manager_ios_unittest\\.cc$'], ['include', '^base/mock_reader\\.h$'], ['include', '^base/run_all_unittests\\.cc$'], ], }], ['OS=="android"', { 'sources!': [ 'audio/audio_input_volume_unittest.cc', 'base/test_data_util.cc', 'base/test_data_util.h', 'ffmpeg/ffmpeg_common_unittest.cc', 'filters/audio_file_reader_unittest.cc', 'filters/blocking_url_protocol_unittest.cc', 'filters/chunk_demuxer_unittest.cc', 'filters/ffmpeg_audio_decoder_unittest.cc', 'filters/ffmpeg_demuxer_unittest.cc', 'filters/ffmpeg_glue_unittest.cc', 'filters/ffmpeg_h264_to_annex_b_bitstream_converter_unittest.cc', 'filters/ffmpeg_video_decoder_unittest.cc', 'filters/pipeline_integration_test.cc', 'filters/pipeline_integration_test_base.cc', 'mp4/mp4_stream_parser_unittest.cc', 'webm/webm_cluster_parser_unittest.cc', ], 'conditions': [ ['gtest_target_type == "shared_library"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', 'player_android', ], }], ], }], ['OS == "linux"', { 'conditions': [ ['use_cras == 1', { 'sources': [ 'audio/cras/cras_input_unittest.cc', 'audio/cras/cras_unified_unittest.cc', ], 'defines': [ 'USE_CRAS', ], }], ], }], ['use_alsa==0', { 'sources!': [ 'audio/linux/alsa_output_unittest.cc', 'audio/audio_low_latency_input_output_unittest.cc', ], }], ['OS != "ios" and (target_arch=="ia32" or target_arch=="x64")', { 'sources': [ 'base/simd/convert_rgb_to_yuv_unittest.cc', ], 'dependencies': [ 'media_sse', ], }], ['screen_capture_supported==1', { 'dependencies': [ '../third_party/webrtc/modules/modules.gyp:desktop_capture', ], }, { 'sources/': [ ['exclude', '^video/capture/screen/'], ], }], ['proprietary_codecs==1 or branding=="Chrome"', { 'sources': [ 'mp4/aac_unittest.cc', 'mp4/avc_unittest.cc', 'mp4/box_reader_unittest.cc', 'mp4/es_descriptor_unittest.cc', 'mp4/mp4_stream_parser_unittest.cc', 'mp4/offset_byte_queue_unittest.cc', 'mp4/track_run_iterator_unittest.cc', ], }], # TODO(wolenetz): Fix size_t to int truncations in win64. See # http://crbug.com/171009 ['OS=="win" and target_arch=="x64"', { 'msvs_disabled_warnings': [ 4267, ], }], ], }, { 'target_name': 'media_test_support', 'type': 'static_library', 'dependencies': [ 'media', '../base/base.gyp:base', '../skia/skia.gyp:skia', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', ], 'sources': [ 'audio/mock_audio_manager.cc', 'audio/mock_audio_manager.h', 'audio/test_audio_input_controller_factory.cc', 'audio/test_audio_input_controller_factory.h', 'base/fake_audio_render_callback.cc', 'base/fake_audio_render_callback.h', 'base/gmock_callback_support.h', 'base/mock_audio_renderer_sink.cc', 'base/mock_audio_renderer_sink.h', 'base/mock_data_source_host.cc', 'base/mock_data_source_host.h', 'base/mock_demuxer_host.cc', 'base/mock_demuxer_host.h', 'base/mock_filters.cc', 'base/mock_filters.h', 'base/test_helpers.cc', 'base/test_helpers.h', 'video/capture/screen/screen_capturer_mock_objects.cc', 'video/capture/screen/screen_capturer_mock_objects.h', ], 'conditions': [ [ 'screen_capture_supported == 1', { 'dependencies': [ '../third_party/webrtc/modules/modules.gyp:desktop_capture', ], }, { 'sources/': [ ['exclude', '^video/capture/screen/'], ], }], ], }, ], 'conditions': [ ['OS != "ios" and target_arch != "arm"', { 'targets': [ { 'target_name': 'yuv_convert_simd_x86', 'type': 'static_library', 'include_dirs': [ '..', ], 'sources': [ 'base/simd/convert_rgb_to_yuv_c.cc', 'base/simd/convert_rgb_to_yuv_sse2.cc', 'base/simd/convert_rgb_to_yuv_ssse3.asm', 'base/simd/convert_rgb_to_yuv_ssse3.cc', 'base/simd/convert_rgb_to_yuv_ssse3.inc', 'base/simd/convert_yuv_to_rgb_c.cc', 'base/simd/convert_yuv_to_rgb_mmx.asm', 'base/simd/convert_yuv_to_rgb_mmx.inc', 'base/simd/convert_yuv_to_rgb_sse.asm', 'base/simd/convert_yuv_to_rgb_x86.cc', 'base/simd/convert_yuva_to_argb_mmx.asm', 'base/simd/convert_yuva_to_argb_mmx.inc', 'base/simd/empty_register_state_mmx.asm', 'base/simd/filter_yuv.h', 'base/simd/filter_yuv_c.cc', 'base/simd/filter_yuv_sse2.cc', 'base/simd/linear_scale_yuv_to_rgb_mmx.asm', 'base/simd/linear_scale_yuv_to_rgb_mmx.inc', 'base/simd/linear_scale_yuv_to_rgb_sse.asm', 'base/simd/scale_yuv_to_rgb_mmx.asm', 'base/simd/scale_yuv_to_rgb_mmx.inc', 'base/simd/scale_yuv_to_rgb_sse.asm', 'base/simd/yuv_to_rgb_table.cc', 'base/simd/yuv_to_rgb_table.h', ], 'conditions': [ # TODO(jschuh): Get MMX enabled on Win64. crbug.com/179657 [ 'OS!="win" or target_arch=="ia32"', { 'sources': [ 'base/simd/filter_yuv_mmx.cc', ], }], [ 'target_arch == "x64"', { # Source files optimized for X64 systems. 'sources': [ 'base/simd/linear_scale_yuv_to_rgb_mmx_x64.asm', 'base/simd/scale_yuv_to_rgb_sse2_x64.asm', ], 'variables': { 'yasm_flags': [ '-DARCH_X86_64', ], }, }], [ 'os_posix == 1 and OS != "mac" and OS != "android"', { 'cflags': [ '-msse2', ], }], [ 'OS == "mac"', { 'configurations': { 'Debug': { 'xcode_settings': { # gcc on the mac builds horribly unoptimized sse code in # debug mode. Since this is rarely going to be debugged, # run with full optimizations in Debug as well as Release. 'GCC_OPTIMIZATION_LEVEL': '3', # -O3 }, }, }, 'variables': { 'yasm_flags': [ '-DPREFIX', '-DMACHO', ], }, }], [ 'os_posix==1 and OS!="mac"', { 'variables': { 'conditions': [ [ 'target_arch=="ia32"', { 'yasm_flags': [ '-DX86_32', '-DELF', ], }, { 'yasm_flags': [ '-DELF', '-DPIC', ], }], ], }, }], ], 'variables': { 'yasm_output_path': '<(SHARED_INTERMEDIATE_DIR)/media', 'yasm_flags': [ '-DCHROMIUM', # In addition to the same path as source asm, let yasm %include # search path be relative to src/ per Chromium policy. '-I..', ], }, 'msvs_2010_disable_uldi_when_referenced': 1, 'includes': [ '../third_party/yasm/yasm_compile.gypi', ], }, ], # targets }], ['OS != "ios"', { 'targets': [ { # Minimal target for NaCl and other renderer side media clients which # only need to send audio data across the shared memory to the browser # process. 'target_name': 'shared_memory_support', 'type': '<(component)', 'dependencies': [ '../base/base.gyp:base', ], 'defines': [ 'MEDIA_IMPLEMENTATION', ], 'include_dirs': [ '..', ], 'includes': [ 'shared_memory_support.gypi', ], 'sources': [ '<@(shared_memory_support_sources)', ], 'conditions': [ [ 'target_arch == "ia32" or target_arch == "x64"', { 'dependencies': [ 'media_sse', ], }], ['arm_neon == 1', { 'defines': [ 'USE_NEON' ], }], ], }, { 'target_name': 'yuv_convert', 'type': 'static_library', 'include_dirs': [ '..', ], 'conditions': [ [ 'target_arch == "ia32" or target_arch == "x64"', { 'dependencies': [ 'yuv_convert_simd_x86', ], }], [ 'target_arch == "arm" or target_arch == "mipsel"', { 'dependencies': [ 'yuv_convert_simd_c', ], }], ], 'sources': [ 'base/yuv_convert.cc', 'base/yuv_convert.h', ], }, { 'target_name': 'yuv_convert_simd_c', 'type': 'static_library', 'include_dirs': [ '..', ], 'sources': [ 'base/simd/convert_rgb_to_yuv.h', 'base/simd/convert_rgb_to_yuv_c.cc', 'base/simd/convert_yuv_to_rgb.h', 'base/simd/convert_yuv_to_rgb_c.cc', 'base/simd/filter_yuv.h', 'base/simd/filter_yuv_c.cc', 'base/simd/yuv_to_rgb_table.cc', 'base/simd/yuv_to_rgb_table.h', ], }, { 'target_name': 'seek_tester', 'type': 'executable', 'dependencies': [ 'media', '../base/base.gyp:base', ], 'sources': [ 'tools/seek_tester/seek_tester.cc', ], }, { 'target_name': 'demuxer_bench', 'type': 'executable', 'dependencies': [ 'media', '../base/base.gyp:base', ], 'sources': [ 'tools/demuxer_bench/demuxer_bench.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ], }, ], }], ['(OS == "win" or toolkit_uses_gtk == 1) and use_aura != 1', { 'targets': [ { 'target_name': 'shader_bench', 'type': 'executable', 'dependencies': [ 'media', 'yuv_convert', '../base/base.gyp:base', '../ui/gl/gl.gyp:gl', '../ui/ui.gyp:ui', ], 'sources': [ 'tools/shader_bench/cpu_color_painter.cc', 'tools/shader_bench/cpu_color_painter.h', 'tools/shader_bench/gpu_color_painter.cc', 'tools/shader_bench/gpu_color_painter.h', 'tools/shader_bench/gpu_painter.cc', 'tools/shader_bench/gpu_painter.h', 'tools/shader_bench/painter.cc', 'tools/shader_bench/painter.h', 'tools/shader_bench/shader_bench.cc', 'tools/shader_bench/window.cc', 'tools/shader_bench/window.h', ], 'conditions': [ ['toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gtk', ], 'sources': [ 'tools/shader_bench/window_linux.cc', ], }], ['OS=="win"', { 'dependencies': [ '../third_party/angle/src/build_angle.gyp:libEGL', '../third_party/angle/src/build_angle.gyp:libGLESv2', ], 'sources': [ 'tools/shader_bench/window_win.cc', ], }], ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ], }, ], }], ['use_x11 == 1', { 'targets': [ { 'target_name': 'player_x11', 'type': 'executable', 'dependencies': [ 'media', 'yuv_convert', '../base/base.gyp:base', '../ui/gl/gl.gyp:gl', '../ui/ui.gyp:ui', ], 'link_settings': { 'libraries': [ '-ldl', '-lX11', '-lXrender', '-lXext', ], }, 'sources': [ 'tools/player_x11/data_source_logger.cc', 'tools/player_x11/data_source_logger.h', 'tools/player_x11/gl_video_renderer.cc', 'tools/player_x11/gl_video_renderer.h', 'tools/player_x11/player_x11.cc', 'tools/player_x11/x11_video_renderer.cc', 'tools/player_x11/x11_video_renderer.h', ], }, ], }], # Special target to wrap a gtest_target_type==shared_library # media_unittests into an android apk for execution. ['OS == "android" and gtest_target_type == "shared_library"', { 'targets': [ { 'target_name': 'media_unittests_apk', 'type': 'none', 'dependencies': [ 'media_java', 'media_unittests', ], 'variables': { 'test_suite_name': 'media_unittests', 'input_shlib_path': '<(SHARED_LIB_DIR)/<(SHARED_LIB_PREFIX)media_unittests<(SHARED_LIB_SUFFIX)', }, 'includes': [ '../build/apk_test.gypi' ], }, ], }], ['OS == "android"', { 'targets': [ { 'target_name': 'media_player_jni_headers', 'type': 'none', 'variables': { 'jni_gen_package': 'media', 'input_java_class': 'android/media/MediaPlayer.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi' ], }, { 'target_name': 'media_android_jni_headers', 'type': 'none', 'dependencies': [ 'media_player_jni_headers', ], 'sources': [ 'base/android/java/src/org/chromium/media/AudioManagerAndroid.java', 'base/android/java/src/org/chromium/media/MediaPlayerBridge.java', 'base/android/java/src/org/chromium/media/MediaPlayerListener.java', 'base/android/java/src/org/chromium/media/WebAudioMediaCodecBridge.java', ], 'variables': { 'jni_gen_package': 'media', }, 'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name': 'video_capture_android_jni_headers', 'type': 'none', 'sources': [ 'base/android/java/src/org/chromium/media/VideoCapture.java', ], 'variables': { 'jni_gen_package': 'media', }, 'includes': [ '../build/jni_generator.gypi' ], }, { 'target_name': 'media_codec_jni_headers', 'type': 'none', 'variables': { 'jni_gen_package': 'media', 'input_java_class': 'android/media/MediaCodec.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi' ], }, { 'target_name': 'media_format_jni_headers', 'type': 'none', 'variables': { 'jni_gen_package': 'media', 'input_java_class': 'android/media/MediaFormat.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi' ], }, { 'target_name': 'player_android', 'type': 'static_library', 'sources': [ 'base/android/media_codec_bridge.cc', 'base/android/media_codec_bridge.h', 'base/android/media_jni_registrar.cc', 'base/android/media_jni_registrar.h', 'base/android/media_player_android.cc', 'base/android/media_player_android.h', 'base/android/media_player_bridge.cc', 'base/android/media_player_bridge.h', 'base/android/media_player_listener.cc', 'base/android/media_player_listener.h', 'base/android/webaudio_media_codec_bridge.cc', 'base/android/webaudio_media_codec_bridge.h', 'base/android/webaudio_media_codec_info.h', ], 'conditions': [ ['google_tv == 1', { 'sources': [ 'base/android/demuxer_stream_player_params.cc', 'base/android/demuxer_stream_player_params.h', ], }], ], 'dependencies': [ '../base/base.gyp:base', 'media_android_jni_headers', 'media_codec_jni_headers', 'media_format_jni_headers', ], 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/media', ], }, { 'target_name': 'media_java', 'type': 'none', 'dependencies': [ '../base/base.gyp:base', ], 'export_dependent_settings': [ '../base/base.gyp:base', ], 'variables': { 'java_in_dir': 'base/android/java', }, 'includes': [ '../build/java.gypi' ], }, ], }], ['media_use_ffmpeg == 1', { 'targets': [ { 'target_name': 'ffmpeg_unittests', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:base_i18n', '../base/base.gyp:test_support_base', '../base/base.gyp:test_support_perf', '../testing/gtest.gyp:gtest', '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', 'media', 'media_test_support', ], 'sources': [ 'ffmpeg/ffmpeg_unittest.cc', ], 'conditions': [ ['toolkit_uses_gtk == 1', { 'dependencies': [ # Needed for the following #include chain: # base/run_all_unittests.cc # ../base/test_suite.h # gtk/gtk.h '../build/linux/system.gyp:gtk', ], 'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], ], }, { 'target_name': 'ffmpeg_regression_tests', 'type': 'executable', 'dependencies': [ '../base/base.gyp:test_support_base', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', 'media', 'media_test_support', ], 'sources': [ 'base/run_all_unittests.cc', 'base/test_data_util.cc', 'ffmpeg/ffmpeg_regression_tests.cc', 'filters/pipeline_integration_test_base.cc', ], 'conditions': [ ['os_posix==1 and OS!="mac"', { 'conditions': [ ['linux_use_tcmalloc==1', { 'dependencies': [ '../base/allocator/allocator.gyp:allocator', ], }], ], }], ], }, { 'target_name': 'ffmpeg_tests', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', 'media', ], 'sources': [ 'test/ffmpeg_tests/ffmpeg_tests.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ], }, { 'target_name': 'media_bench', 'type': 'executable', 'dependencies': [ '../base/base.gyp:base', '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', 'media', ], 'sources': [ 'tools/media_bench/media_bench.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ], }, ], }], [ 'screen_capture_supported==1 and (target_arch=="ia32" or target_arch=="x64")', { 'targets': [ { 'target_name': 'differ_block_sse2', 'type': 'static_library', 'conditions': [ [ 'os_posix == 1 and OS != "mac"', { 'cflags': [ '-msse2', ], }], ], 'include_dirs': [ '..', ], 'sources': [ 'video/capture/screen/differ_block_sse2.cc', 'video/capture/screen/differ_block_sse2.h', ], }, # end of target differ_block_sse2 ], }], # ios check is necessary due to http://crbug.com/172682. ['OS != "ios" and (target_arch=="ia32" or target_arch=="x64")', { 'targets': [ { 'target_name': 'media_sse', 'type': 'static_library', 'cflags': [ '-msse', ], 'include_dirs': [ '..', ], 'defines': [ 'MEDIA_IMPLEMENTATION', ], 'sources': [ 'base/simd/sinc_resampler_sse.cc', 'base/simd/vector_math_sse.cc', ], }, # end of target media_sse ], }], ], }
class Node: def __init__(self, data): self.data = data self.next = None class Solution: def insert(self, head, data): p = Node(data) if head is None: head = p elif head.next is None: head.next = p else: start = head while start.next is not None: start = start.next start.next = p return head def display(self, head): current = head while current: print(current.data, end=' ') current = current.next def removeDuplicates(self, head): """ Removes duplicates from the linked list. Head variable points to a start point of the list. Initialises 2 pointers (current and runner) to keep track of the previous and current node values. The current node is used for traversing through the linked list. The pointer node is used to compare the elements in the linked list. In case data is equal, the link moves to a next node. Repeat this till the current node is not None. Time Complexity: O(n²) Space Complexity: O(1) """ current = head while current: pointer = current while pointer.next: if current.data == pointer.next.data: pointer.next = pointer.next.next else: pointer = pointer.next current = current.next return head def removeDuplicates_dict(self, head): """ Removes duplicates from the linked list. Head variable points to a start point of the list. Traverse through the linked list. Have 2 variables to track previous and current values. Store values from each node in an additional data structure - hash map. Check if the node value already exists in the dictionary. If yes assign previous node’s next to current node’s next which eliminates the current node. In other words, the duplicate node gets deleted. Repeat this till the current node is not None. Time Complexity: O(n) Space Complexity: O(n) """ current = head prev = None dd = {} while current: if current.data not in dd: dd[current.data] = None prev = current else: prev.next = current.next current = current.next return head mylist = Solution() # T = int(input()) T = 6 lst = [1, 2, 2, 3, 3, 4] head = None for i in range(T): data = int(lst[i]) head = mylist.insert(head, data) # head = mylist.removeDuplicates(head) head = mylist.removeDuplicates_dict(head) mylist.display(head)
def replaceSlice(string, l_index, r_index, replaceable): string = string[0:l_index] + string[r_index - 1:] string = string[0:l_index] + replaceable + string[r_index:] return string def correctSpaces(expression): return expression.replace(" ", "") def replaceAlternateOperationSigns(expression): return expression.replace("**", "^") def correctUnaryBraces(expression): pass
def changeFeather(value): for s in nuke.selectedNodes(): selNode = nuke.selectedNode() if s.Class() == "Roto" or s.Class() == "RotoPaint": for item in s['curves'].rootLayer: attr = item.getAttributes() attr.set('ff',value) feather_value = 0 changeFeather(feather_value)
def mongoify(doc): if 'id' in doc: doc['_id'] = doc['id'] del doc['id'] return doc def demongoify(doc): if "_id" in doc: doc['id'] = doc['_id'] del doc['_id'] return doc
def get_elapsed_time_description(name, exercise_number, elapsed_time): is_probably_female = name[-1] == 'a' female_verb_suffix = 'a' if is_probably_female else '' elapsed_seconds = elapsed_time / 1000 return f"{name} wykonał{female_verb_suffix} zadanie nr {exercise_number} w {elapsed_seconds:.3f}s." print(get_elapsed_time_description('Agata', 2, 12305200)) print(get_elapsed_time_description('Tomek', 1, 123052))
def main() -> None: # fermat's little theorem n, k, m = map(int, input().split()) # m^(k^n) MOD = 998_244_353 m %= MOD print(pow(m, pow(k, n, MOD - 1), MOD)) if __name__ == "__main__": main()
class Solution: def reversePrefix(self, word: str, ch: str) -> str: try: idx = word.index(ch) + 1 except Exception: return word return ''.join(word[:idx][::-1] + word[idx:])
# -*- coding: utf-8 -*- """Top-level package for Crime_term_project.""" __author__ = """Catalina Cardelle""" __email__ = 'cardelle.c@husky.neu.edu' __version__ = '0.1.0'
print(f'\033[33m{"—"*30:^30}\033[m') print(f'\033[36m{"EXERCÍCIO Nº 3":^30}\033[m') print(f'\033[33m{"—"*30:^30}\033[m') print("Soma de dois números") n1 = int(input("Digite o primeiro número: ")) n2 = int(input("Digite o segundo número: ")) s = n1 + n2 print(f"A soma entre {n1} e {n2} equivale a {s}.")
rest_days = int(input()) year_in_days = 365 work_days = year_in_days - rest_days play_time = (work_days * 63 + rest_days * 127) if play_time <= 30000: play_time1 = 30000 - play_time else: play_time1 = play_time - 30000 hours = play_time1 // 60 minutes = play_time1 % 60 if play_time > 30000: print(f"Tom will run away\n{hours} hours and {minutes} minutes more for play") else: print(f"Tom sleeps well\n{hours} hours and {minutes} minutes less for play")
# -*- coding: utf-8 -*- __author__ = 'guti' ''' Default configurations for the Web application. ''' configs = { 'db': { 'host': '127.0.0.1', 'port': 5432, 'user': 'test_usr', 'password': 'test_pw', 'database': 'test_db' }, 'session': { 'secret': '0IH9c71HS86KSnqmQFAbBiwnEUqMYEo9vAQFb+DA9Ns=' } }
class Nodo: def __init__(self, estado, pai=None, acao=None, custo=0): self.estado = estado self.pai = pai self.acao = acao self.custo = custo def split_string(self): liststate = [] for char in self.estado: liststate.append(char) return liststate def swap(self, pos1, pos2): liststate = self.split_string() liststate[pos1], liststate[pos2] = liststate[pos2], liststate[pos1] return ''.join(map(str, liststate)) def successor(self): options = [] space_pos = self.estado.find('_') if space_pos != 2 and space_pos != 5 and space_pos != 8: # self.acao = 'Direita' # options.append((self.acao, self.swap(space_pos, space_pos + 1))) # -->Direita options.append(('Direita', self.swap(space_pos, space_pos + 1))) if space_pos != 0 and space_pos != 3 and space_pos != 6: # self.acao = 'Esquerda' # options.append((self.acao, self.swap(space_pos, space_pos - 1))) # -->Esquerda options.append(('Esquerda', self.swap(space_pos, space_pos - 1))) if space_pos < 6: # self.acao = 'Abaixo' # options.append((self.acao, self.swap(space_pos, space_pos + 3))) # -->Abaixo options.append(('Abaixo', self.swap(space_pos, space_pos + 3))) if space_pos > 2: # self.acao = 'Acima' # options.append((self.acao, self.swap(space_pos, space_pos - 3))) # -->Acima options.append(('Acima', self.swap(space_pos, space_pos - 3))) return options def expande(self): """ Recebe um nodo (objeto da classe Nodo) e retorna um iterable de nodos. Cada nodo do iterable é contém um estado sucessor do nó recebido. :param nodo: objeto da classe Nodo :return: array de nodos """ succ = self.successor() return [ Nodo(s[1],self,s[0],self.custo + 1) for s in succ ] teste = Nodo('1234_6785') a = teste.successor() print(teste.acao) print(a) # Teste de expande print(teste.__dict__) for i in teste.expande(): print(i.__dict__)
salario = float(input('Salario: ')) if salario <= 1250: novo = salario + (salario * 15 / 100) else: novo = salario +(salario * 10 /100) print('Seu salário com aumento de 10% vai ser de {}'.format(novo))
class UnetOptions: def __init__(self): self.in_channels=1 self.n_classes=2 self.depth=5 self.wf=6 self.padding=False self.up_mode='upconv' self.batch_norm=True self.non_neg = True self.pose_predict_mode = False self.pretrained_mode = False self.weight_map_mode = False def setto(self): self.in_channels=3 self.n_classes=6 self.depth=5 self.wf=2 self.padding=True self.up_mode='upsample' ## TODO: normalizing using std ## TODO: changing length scale ## TODO: batch norm class LossOptions: def __init__(self, unetoptions): self.color_in_cost = False # self.diff_mode = False # self.min_grad_mode = True # self.min_dist_mode = True # distance between functions # # self.kernalize = True # self.sparsify_mode = 2 # 1 fix L2 of each pixel, 2 max L2 fix L1 of each channel, 3 min L1, 4 min L2 across channels, 5 fix L1 of each channel, # # 6 no normalization, no norm output # self.L_norm = 2 # 1, 2, (1,2) #when using (1,2), sparsify mode 2 or 5 are the same # ## before 10/23/2019, use L_norm=1, sparsify_mode=5, kernalize=True, batch_norm=False, dist_coef = 0.1 # ## L_norm=1, sparsify_mode=2, kernalize=True, batch_norm=False, dist_coef = 0.1, feat_scale_after_normalize = 1e-1 # ## L_norm=2, sparsify_mode=2, kernalize=True, batch_norm=False, dist_coef = 0.1, feat_scale_after_normalize = 1e1 self.norm_in_loss = False self.pca_in_loss = False self.subset_in_loss = False self.zero_edge_region = True self.normalize_inprod_over_pts = False self.data_aug_rotate180 = True self.keep_scale_consistent = False self.eval_full_size = False ## This option matters only when keep_scale_consistent is True self.test_no_log = False self.trial_mode = False self.run_eval = False self.continue_train = False self.visualize_pcd = False self.top_k_list = [3000] self.grid_list = [1] self.sample_aug_list = [-1] self.opt_unet = unetoptions self.dist_coef = {} self.dist_coef['xyz_align'] = 0.2 # 0.1 self.dist_coef['xyz_noisy'] = 0.2 # 0.1 self.dist_coef['xyz'] = 0.2 # 0.1 self.dist_coef['img'] = 0.5 # originally I used 0.1, but Justin used 0.5 here # self.dist_coef['feature'] = 0.1 ###? self.dist_coef_feature = 0.1 self.lr = 1e-5 self.lr_decay_iter = 20000 self.batch_size = 1 self.effective_batch_size = 2 self.iter_between_update = int(self.effective_batch_size / self.batch_size) self.epochs = 1 self.total_iters = 20000 def set_loss_from_options(self): self.kernalize = not self.opt_unet.non_neg if self.keep_scale_consistent: self.width = 640 self.height = 480 if self.run_eval: self.height_split = 1 self.width_split = 1 else: self.height_split = 5 self.width_split = 5 self.effective_width = int(self.width / self.width_split) self.effective_height = int(self.height / self.height_split) else: if self.run_eval: self.width = 640 self.height = 480 else: self.width = 128 # (72*96) [[96, 128]] (240, 320) self.height = 96 self.effective_width = self.width self.effective_height = self.height if self.effective_width > 128: self.no_inner_prod = True else: self.no_inner_prod = False self.source='TUM' if self.source=='CARLA': self.root_dir = '/mnt/storage/minghanz_data/CARLA(with_pose)/_out' elif self.source == 'TUM': # self.root_dir = '/mnt/storage/minghanz_data/TUM/RGBD' # self.root_dir = '/media/minghanz/Seagate_Backup_Plus_Drive/TUM/rgbd_dataset/untarred' self.root_dir = '/home/minghanz/Datasets/TUM/rgbd/untarred' # if self.run_eval or self.continue_train: # self.pretrained_weight_path = 'saved_models/with_color_Fri Nov 8 22:21:30 2019/epoch00_20000.pth' if self.run_eval: self.folders = ['rgbd_dataset_freiburg1_desk'] else: self.folders = None # if self.L_norm == 1: # self.feat_scale_after_normalize = 1e-2 ## the mean abs of a channel across all selected pixels (pre_gramian) # elif self.L_norm == 2: # self.feat_scale_after_normalize = 1e1 # elif self.L_norm == (1,2): # self.feat_scale_after_normalize = 1e-1 if self.kernalize: # rbf self.sparsify_mode = 2 # norm_dim=2, centralize, normalize self.L_norm = 2 # make variance 1 of all channels self.feat_scale_after_normalize = 1e-1 # sdv 1e-1 self.reg_norm_mode = False else: # dot product self.sparsify_mode = 2 # 3, norm_dim=2, centralize, doesn't normalize (use the norm as loss) self.L_norm = (1,2) # (1,2) # mean L2 norm of all pixel features if self.self_sparse_mode: self.feat_scale_after_normalize = 1e-1 else: self.feat_scale_after_normalize = 1e0 self.reg_norm_mode = False self.feat_norm_per_pxl = 1 ## the L2 norm of feature vector of a pixel (pre_gramian). 1 means this value has no extra effect self.set_loss_from_mode() return def set_loss_from_mode(self): ## loss function setting self.loss_item = [] self.loss_weight = [] if self.min_dist_mode: self.loss_item.extend(["cos_sim", "func_dist"]) if self.normalize_inprod_over_pts: self.loss_weight.extend([1, 100]) else: if self.kernalize: self.loss_weight.extend([1, 1e-5]) # 1e6, 1 # 1e-4: dots, 1e-6: blocks elif self.self_trans: self.loss_weight.extend([0,-1e-6]) else: self.loss_weight.extend([1, 1e-6]) # 1e6, 1 if self.diff_mode: self.loss_item.extend(["cos_diff", "dist_diff"]) if self.normalize_inprod_over_pts: self.loss_weight.extend([1, 100]) else: if self.kernalize: self.loss_weight.extend([1, 1e-6]) # 1e6, 1 else: self.loss_weight.extend([1, 1e-4]) # 1e6, 1 if self.min_grad_mode: self.loss_item.extend(["w_angle", "v_angle"]) self.loss_weight.extend([1, 1]) if self.reg_norm_mode: self.loss_item.append("feat_norm") self.loss_weight.append(1e-1) # self.reg_norm_weight if self.self_sparse_mode: self.loss_item.extend(["cos_sim", "func_dist"]) self.loss_weight.extend([0, 1]) # 1e6, 1 self.samp_pt = self.min_grad_mode return def set_from_manual(self, overwrite_opt): manual_keys = overwrite_opt.__dict__.keys() # http://www.blog.pythonlibrary.org/2013/01/11/how-to-get-a-list-of-class-attributes/ for key in manual_keys: vars(self)[key] = vars(overwrite_opt)[key] # https://stackoverflow.com/questions/11637293/iterate-over-object-attributes-in-python self.dist_coef['feature'] = self.dist_coef_feature return def set_eval_full_size(self): if self.eval_full_size == False: self.eval_full_size = True self.no_inner_prod_ori = self.no_inner_prod self.visualize_pca_chnl_ori = self.visualize_pca_chnl self.no_inner_prod = True self.visualize_pca_chnl = False def unset_eval_full_size(self): if self.eval_full_size == True: self.eval_full_size = False self.no_inner_prod = self.no_inner_prod_ori self.visualize_pca_chnl = self.visualize_pca_chnl_ori
# Python - 2.7.6 def find_next_square(sq): num = int(sq ** 0.5) return (num + 1) ** 2 if (num ** 2) == sq else -1
# value of A represent its position in C # value of C represent its position in B def count_sort(A, k): B = [0 for i in range(len(A))] C = [0 for i in range(k)] # count the frequency of each elements in A and save them in the coresponding position in B for i in range(0, len(A)): C[A[i] - 1] += 1 # accumulated sum of C, indicating where we should put in Aay B for i in range(1, k, 1): C[i] = C[i - 1] + C[i] # count the for i in range(len(A)-1, -1, -1): B[C[A[i]-1]-1] = A[i] C[A[i]-1] -= 1 return B B = count_sort([4, 1, 3, 4, 3], 4) print(B)
class Params: # ------------------------------- # GENERAL # ------------------------------- gpu_ewc = '4' # GPU number gpu_rewc = '3' # GPU number data_size = 224 # Data size batch_size = 32 # Batch size nb_cl = 50 # Classes per group nb_groups = 4 # Number of groups 200 = 50*4 nb_val = 0 # Number of images for val epochs = 50 # Total number of epochs num_samples = 5 # Samples per class to compute the Fisher information lr_init = 0.001 # Initial learning rate lr_strat = [40,80] # Epochs where learning rate gets decreased lr_factor = 5. # Learning rate decrease factor wght_decay = 0.00001 # Weight Decay ratio = 100.0 # ratio = lwf loss / softmax loss # ------------------------------- # Parameters for test # ------------------------------- eval_single = True # Evaluate different task in Single head setting # ------------------------------- # Parameters for path # ------------------------------- save_path = './checkpoints/' # Model saving path train_path = '/data/Datasets/CUB_200_2011/CUB_200_2011/' # Data path
place_needed = int(input().split()[1]) scores = [j for j in reversed(sorted([int(i) for i in input().split() if int(i) > 0]))] try: score_needed = scores[place_needed - 1] except IndexError: score_needed = 0 amount = 0 for i in scores: if i >= score_needed: amount += 1 print(amount)
# List aa images with query stringa available def list_all_images_subparser(subparser): list_all_images = subparser.add_parser( 'list-all-images', description=('***List all' ' images of' ' producers/consumers' ' account'), help=('List all' ' images of' ' producers/consumers' ' account')) group_key = list_all_images.add_mutually_exclusive_group(required=True) group_key.add_argument('-pn', '--producer-username', help="Producer\'s(source account) username") group_key.add_argument('-cn', '--consumer-username', dest='producer_username', metavar='CONSUMER_USERNAME', help="Consumer\'s(destination account) username") group_apikey = list_all_images.add_mutually_exclusive_group(required=True) group_apikey.add_argument('-pa', '--producer-apikey', help="Producer\'s(source account) apikey") group_apikey.add_argument('-ca', '--consumer-apikey', dest='producer_apikey', metavar='CONSUMER_APIKEY', help="Consumer\'s(destination account) apikey") list_all_images.add_argument('--visibility', nargs=1, help='[shared][private][public]') list_all_images.add_argument('--member-status', nargs=1, help='[pending][accepted][rejected][all]') list_all_images.add_argument('--owner', nargs=1, help='Owner Id')
info = { "name": "gv", "date_order": "YMD", "january": [ "j-guer", "jerrey-geuree" ], "february": [ "t-arree", "toshiaght-arree" ], "march": [ "mayrnt" ], "april": [ "averil", "avrril" ], "may": [ "boaldyn" ], "june": [ "m-souree", "mean-souree" ], "july": [ "j-souree", "jerrey-souree" ], "august": [ "luanistyn" ], "september": [ "m-fouyir", "mean-fouyir" ], "october": [ "j-fouyir", "jerrey-fouyir" ], "november": [ "m-houney", "mee houney" ], "december": [ "m-nollick", "mee ny nollick" ], "monday": [ "jel", "jelhein" ], "tuesday": [ "jem", "jemayrt" ], "wednesday": [ "jerc", "jercean" ], "thursday": [ "jerd", "jerdein" ], "friday": [ "jeh", "jeheiney" ], "saturday": [ "jes", "jesarn" ], "sunday": [ "jed", "jedoonee" ], "am": [ "am" ], "pm": [ "pm" ], "year": [ "year" ], "month": [ "month" ], "week": [ "week" ], "day": [ "day" ], "hour": [ "hour" ], "minute": [ "minute" ], "second": [ "second" ], "relative-type": { "0 day ago": [ "today" ], "0 hour ago": [ "this hour" ], "0 minute ago": [ "this minute" ], "0 month ago": [ "this month" ], "0 second ago": [ "now" ], "0 week ago": [ "this week" ], "0 year ago": [ "this year" ], "1 day ago": [ "yesterday" ], "1 month ago": [ "last month" ], "1 week ago": [ "last week" ], "1 year ago": [ "last year" ], "in 1 day": [ "tomorrow" ], "in 1 month": [ "next month" ], "in 1 week": [ "next week" ], "in 1 year": [ "next year" ] }, "locale_specific": {}, "skip": [ " ", ".", ",", ";", "-", "/", "'", "|", "@", "[", "]", "," ] }
# No good name, sorry, lol :) def combinations(list, k): return 0 print( combinations([1, 2, 3, 4], 3) )
#Find the difference between the sum of the squares of the first one hundred natural numbers # and the square of the sum. #Generating a list with natural numbers 1-100. nums = list(range(101)) #print(nums) #Find the square of the sum (1+...+100). # The following is old code: (that does work.) #LIST = nums #x = 0 #total = 0 #while x < 101: # print('index: ', x) # print('total sum thus far: ', total) # hold = LIST[x] # total = total + hold # x += 1 #print('the sum of 1-100 is:', total) LIST = list(range(101)) #Funtion for the trianuglar numbers: def tri_num(n): n = int(n) sum = n * (n+1) sum = sum / 2 sum = int(sum) return sum a = tri_num(100) print(a) print(a*a) #Function for the triangular numbers but every term is squared, (e.g. 1^2 + 2^2 + ...) def tri_num_sqrd(n): n = int(n) sum = n * (n+1) * ((2*n)+1) sum = sum / 6 sum = int(sum) return sum b = tri_num_sqrd(100) print(b) print() print("The answer to problem 6 is: ") print((a*a) - b)
class Message: # type id_message id_device timestamp type = 'default' id = 0 source_id = 0 source_timestamp = 0 payload = bytearray(0) def __init__(self, type, id, source_id, source_timestamp, payload): self.type = type self.id = id self.source_id = source_id self.source_timestamp self.payload = payload def header_to_string(self): return '%s %s %s %s' % (self.type, self.id, self.source_id, self.source_timestamp) def payload_to_string(self): if isinstance(self.payload, bytearray): return self.payload.decode(errors='replace').rstrip('\x00') else: return '%s' % self.payload
num = (int(input('Digite um valor: ')), int(input('Digite outro valor: ')), int(input('Digite outro valor: ')), int(input('Digite outro valor: '))) print('O número 9 apareceu {} vezes'.format(num.count(9))) if 3 in num: print('O valor 3 apareceu na posição {}'.format(num.index(3) + 1)) else: print('O valor 3 não foi digitado') print('Os valores pares digitados foram:') for i in num: if i % 2 == 0: print(i, end=' ')
class Solution: def cloneTree(self, root: 'Node') -> 'Node': """Tree. """ if not root: return None croot = Node(root.val) m = {root: croot} nodes = deque([root]) cnodes = deque([croot]) while nodes: n = nodes.popleft() cn = cnodes.popleft() for ch in n.children: cch = Node(ch.val) cn.children.append(cch) nodes.append(ch) cnodes.append(cch) return croot
# Copyright (C) 2020 Square, Inc. # # 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. def metadata( group_id, artifact_id, version, target, license, github_slug, developers = [], description = None, name = None): """ Generates a known struct which can be consumed to generate release packaging. """ if not developers: fail("Must specify at least one developer.") return struct( name = name if name != None else artifact_id, description = description, group_id = group_id, artifact_id = artifact_id, version = version, target = target, github_slug = github_slug, license = license, developers = developers, ) def developer(id, name, email, url = None): """ Generates an id/string pair which can be consumed by maven_pom""" if not url: url = "http://github.com/{id}".format(id = id) return "{id}::{name}::{email}::{url}".format(id = id, name = name, email = email, url = url)
{ 'targets': [ { 'target_name': 'xwalk_extensions_unittest', 'type': 'executable', 'dependencies': [ '../../base/base.gyp:base', '../../base/base.gyp:run_all_unittests', '../../testing/gtest.gyp:gtest', 'extensions.gyp:xwalk_extensions', ], 'sources': [ 'browser/xwalk_extension_function_handler_unittest.cc', 'common/xwalk_extension_server_unittest.cc', ], }, { 'target_name': 'xwalk_extensions_browsertest', 'type': 'executable', 'dependencies': [ '../../base/base.gyp:base', '../../content/content.gyp:content_browser', '../../content/content_shell_and_tests.gyp:test_support_content', '../../net/net.gyp:net', '../../skia/skia.gyp:skia', '../../testing/gtest.gyp:gtest', '../test/base/base.gyp:xwalk_test_base', '../xwalk.gyp:xwalk_runtime', 'extensions.gyp:xwalk_extensions', 'extensions_resources.gyp:xwalk_extensions_resources', 'external_extension_sample.gyp:*', ], 'defines': [ 'HAS_OUT_OF_PROC_TEST_RUNNER', ], 'variables': { 'jsapi_component': 'extensions', }, 'includes': [ '../xwalk_jsapi.gypi', ], 'sources': [ 'test/bad_extension_test.cc', 'test/conflicting_entry_points.cc', 'test/context_destruction.cc', 'test/crash_extension_process.cc', 'test/export_object.cc', 'test/extension_in_iframe.cc', 'test/external_extension.cc', 'test/external_extension_multi_process.cc', 'test/in_process_threads_browsertest.cc', 'test/internal_extension_browsertest.cc', 'test/internal_extension_browsertest.h', 'test/nested_namespace.cc', 'test/namespace_read_only.cc', 'test/test.idl', 'test/v8tools_module.cc', 'test/xwalk_extensions_browsertest.cc', 'test/xwalk_extensions_test_base.cc', 'test/xwalk_extensions_test_base.h', ], }, ], }
def preprocess(df, standardize = False): """Splits the data into training and validation sets. arguments: df: the dataframe of training and test data you want to split. standardize: if True returns standardized data. """ #split the data train, test = train_test_split(df, train_size=0.8, random_state = 42) #sort the data train = train.sort_values(by = ["x1"]) test = test.sort_values(by = ["x1"]) train.describe() X_train, y_train = train[["x1"]], train["y"] X_test, y_test = test[["x1"]], test["y"] X_train_N = add_higher_order_polynomial_terms(X_train, N=15) X_test_N = add_higher_order_polynomial_terms(X_test, N=15) if standardize: scaler = StandardScaler().fit(X_train_N) X_train_N = scaler.transform(X_train_N) X_test_N = scaler.transform(X_test_N) #"X_val" : X_val_N, "y_val" : y_val, datasets = {"X_train": X_train_N, "y_train": y_train, "X_test" : X_test_N, "y_test": y_test} return(datasets) def fit_ridge_and_lasso_cv(X_train, y_train, X_test, y_test, k = None, alphas = [10**9], best_OLS_r2 = best_least_squares_r2 ): #X_val, y_val, """ takes in train and validation test sets and reports the best selected model using ridge and lasso regression. Arguments: X_train: the train design matrix y_train: the reponse variable for the training set X_val: the validation design matrix y_train: the reponse variable for the validation set k: the number of k-fold cross validation sections to be fed to Ridge and Lasso Regularization. """ # Let us do k-fold cross validation fitted_ridge = RidgeCV(alphas=alphas, cv = k).fit(X_train, y_train) fitted_lasso = LassoCV(alphas=alphas, cv = k).fit(X_train, y_train) print('R^2 score for our original OLS model: {}\n'.format(best_OLS_r2)) ridge_a = fitted_ridge.alpha_ ridge_score = fitted_ridge.score(X_test, y_test) print('Best alpha for ridge: {}'.format(ridge_a)) print('R^2 score for Ridge with alpha={}: {}\n'.format(ridge_a, ridge_score)) lasso_a = fitted_lasso.alpha_ lasso_score = fitted_lasso.score(X_test, y_test) print('Best alpha for lasso: {}'.format(lasso_a)) print('R^2 score for Lasso with alpha={}: {}'.format(lasso_a, lasso_score)) r2_df = pd.DataFrame({"OLS": best_OLS_r2, "Lasso" : lasso_score, "Ridge" : ridge_score}, index = [0]) r2_df = r2_df.melt() r2_df.columns = ["model", "r2_Score"] plt.title("Validation set") sns.barplot(x = "model", y = "r2_Score", data = r2_df) plt.show()
class Solution: @staticmethod def naive(n,edges): adj = {i:[] for i in range(n)} for u,v in edges: adj[u].append(v) adj[v].append(u) # no cycle, only one fully connected tree visited = set() def dfs(i,fro): if i in visited: return False visited.add(i) for child in adj[i]: if child != fro: if not dfs(child,i): return False return True if not dfs(0,-1): return False if len(visited)!=n: return False return True
def factorial(n): """ Computes the factorial of n. """ if n < 0: raise ValueError('received negative input') result = 1 for i in range(1, n + 1): result *= i return result
class CardSelectionConfigController(object): cs = None controller = None pos = None def __init__(self, cs, controller, pos=-1): self.cs = cs self.controller = controller self.pos = pos def save(self): if self.pos < 0: self.controller.add_cs(self.cs) else: self.controller.update_cs(self.cs, self.pos) def get_nth_card_text(self, n): return self.cs.cards[n].text def set_nth_card_text(self, n, text): self.cs.cards[n].text = text def get_task_text(self): return self.cs.text_p1 def set_task_text(self, txt): self.cs.text_p1 = txt def get_rule(self): return self.cs.rule def set_rule(self, txt): self.cs.rule = txt def get_extra_text(self): return self.cs.text_p2 def set_extra_text(self, txt): self.cs.text_p2 = txt def get_instructions(self): return self.cs.instructions def set_instructions(self, txt): self.cs.instructions = txt def is_fixed_position(self): return self.cs.is_fixed_position def set_is_fixed_position(self, val): self.cs.is_fixed_position = bool(val)
""" With / As Keywords """ # print("Normal Write Start") # my_write = open("textfile.txt", "w") # my_write.write("Trying to write to the file") # my_write.close() # # # print("Normal Read Start") # my_read = open("textfile.txt", "r") # print(str(my_read.read())) print("With As Write Start") with open("withas.txt", "w") as with_as_write: with_as_write.write("This is an example of with as write/read") print() print("With As Read Start") with open("withas.txt", "r") as with_as_read: print(str(with_as_read.read()))
""" A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction. 1 0 1 3 5 0 1 1 """ class Solution403: pass
"""The longest common subsequence problem is the problem of finding the longest subsequence common to all sequences in a set of sequences. It differs from the longest common substring problem: unlike substrings, subsequences are not required to occupy consecutive positions within the original sequences. """ """For better understanding watch the video https://youtu.be/sSno9rV8Rhg""" def lcs(string1, string2): m = len(string1) n = len(string2) l = [[None for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: l[i][j] = 0 elif string1[i - 1] == string2[ j - 1]: # check the alphabet of the 2 string match or not, in matrix indices are one extra therefore we reduce indices by 1 l[i][j] = 1 + l[i - 1][j - 1] # if match the condition add diagonal value by 1 and store into the current index else: l[i][j] = max(l[i - 1][j], l[i][j - 1]) # if not matches store the max value of the previous row and previous column return l string1 = "BDCB" string2 = "BACDB" a = lcs(string1, string2) print(a) print("Longest Sequences ", a[-1][-1]) l1 = len(string1) l2 = len(string2) sequence = [] val = None while val != 0: # continue the loop until you reaches to the zero value if a[l1][l2] == a[l1][l2 - 1]: # if the consecutive value of the same row is equal then reduce the column by 1 l2 -= 1 else: # if the consecutive value of the same row is not equal then reduce the column and row by 1 to go to 1 # level up val = a[l1 - 1][l2 - 1] sequence.insert(0, string2[l2 - 1]) # insert that value from where index goes up l1 -= 1 l2 -= 1 print("Sequence is", "".join(sequence))
# 3. Реализовать программу работы с органическими клетками. # Необходимо создать класс Клетка. В его конструкторе инициализировать # параметр, соответствующий количеству клеток (целое число). В классе # должны быть реализованы методы перегрузки арифметических операторов: # сложение (__add__()), вычитание (__sub__()), умножение (__mul__()), # деление (__truediv__()).Данные методы должны применяться только к # клеткам и выполнять увеличение, уменьшение, умножение и обычное # (не целочисленное) деление клеток, соответственно. В методе деления # должно осуществляться округление значения до целого числа. # Сложение. Объединение двух клеток. При этом число ячеек общей клетки # должно равняться сумме ячеек исходных двух клеток. # Вычитание. Участвуют две клетки. Операцию необходимо выполнять только # если разность количества ячеек двух клеток больше нуля, иначе выводить # соответствующее сообщение. # Умножение. Создается общая клетка из двух. Число ячеек общей клетки # определяется как произведение количества ячеек этих двух клеток. # Деление. Создается общая клетка из двух. Число ячеек общей клетки # определяется как целочисленное деление количества ячеек этих двух клеток. # В классе необходимо реализовать метод make_order(), принимающий # экземпляр класса и количество ячеек в ряду. Данный метод позволяет # организовать ячейки по рядам. # Метод должен возвращать строку вида *****\n*****\n*****..., где # количество ячеек между \n равно переданному аргументу. Если ячеек # на формирование ряда не хватает, то в последний ряд записываются # все оставшиеся. # Например, количество ячеек клетки равняется 12, количество ячеек в # ряду — 5. Тогда метод make_order() вернет строку: *****\n*****\n**. # Или, количество ячеек клетки равняется 15, количество ячеек в ряду — 5. # Тогда метод make_order() вернет строку: *****\n*****\n*****. # Подсказка: подробный список операторов для перегрузки доступен по ссылке. class Kletka: def __init__(self, count = 0): self.count = count def __add__(self, other): return Kletka(self.count + other.count) def __sub__(self, other): if (self.count - other.count) > 0: return Kletka(self.count - other.count) raise Exception("Разность количества ячеек двух клеток должна быть больше нуля!") def __mul__(self, other): return Kletka(self.count * other.count) def __truediv__(self, other): return Kletka(round(self.count / other.count)) @staticmethod def make_order(kletka, number): result = '' for a in range(1, kletka.count + 1): result += '*' if ((a % number) == 0): result += '\n' return result print(Kletka.make_order(Kletka(15), 5))
''' script que analisa o nome é apresenta o nome em maiusculo, minusculo, quantas letras possui ''' nome = input('Qual o Seu Nome completo: ') print(f'''analisando seu nome seu nome em maiusculo é {nome.upper()} seu nome em minuscula é {nome.lower()} seu nome tem ao todo {len(nome.replace(' ',''))} seu primeiro nome é {nome.split()[0]} e ele tem {nome.find(' ')} letras ''')
"""Re-exports shell rule.""" load("@bazel_skylib//lib:shell.bzl", _shell = "shell") shell = _shell
T = int(input()) for _ in range(T): n = int(input()) s = [int(s_arr) for s_arr in input().split(' ')] misere, count = 0, 0 for i in range(n): misere ^= s[i] if s[i] <= 1: count += 1 print ("Second" if (count == n and misere == 1) or (count < n and misere == 0) else "First")
# tests transition from small to large int representation by multiplication for rhs in range(2, 11): lhs = 1 for k in range(100): res = lhs * rhs print(lhs, '*', rhs, '=', res) lhs = res # below tests pos/neg combinations that overflow small int # 31-bit overflow i = 1 << 20 print(i * i) print(i * -i) print(-i * i) print(-i * -i) # 63-bit overflow i = 1 << 40 print(i * i) print(i * -i) print(-i * i) print(-i * -i)
class Reference(): metadata = {} def __init__(self, metadata: dict, figures: list): self.metadata.update(metadata) for fig in figures: setattr(self, fig.name, fig) class Figure(): """ This is the base class for figure data. """ def __init__(self, name: str, lines: list): self.name = name self.lines = lines class Line(): def __init__(self, x, y, label): self.x = x self.y = y self.label = label
# Empréstimo bancário nome = str(input('Oi, bom dia! Qual o seu nome? ')) print() salario = int(input('{}, me diga qual o valor do seu salário: '.format(nome))) print() valorcasa = int( input('Ok, {}. Qual o valor do imóvel que deseja comprar? '.format(nome))) print() tempo = int(input('Em quanto tempo deseja financiar o imóvel? ')) print() calc = valorcasa/(tempo * 12) print('Processando as informações...') print() if (calc / salario > 0.3): print('Nos desculpe {}, seu empréstimo foi negado.'.format(nome)) else: print('Parabéns, {}. Seu empréstimo foi aprovado.'.format(nome))
class Solution: def findComplement(self, num: int) -> int: r = '{:08b}'.format(num).lstrip('0') r2 = '' for i in r: if i == '0': r2 += '1' else: r2 += '0' r3 = int(r2, 2) return r3 if __name__ == '__main__': s = Solution() r = s.findComplement(5) print(r)
__copyright__ = """ Copyright 2021 Amazon.com, Inc. or its affiliates. Copyright 2021 Netflix Inc. Copyright 2021 Google LLC """ __license__ = """ 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. """ APPLICATIONS_LIST_TOPIC = "dab/applications/list" APPLICATIONS_LAUNCH_TOPIC = "dab/applications/launch" APPLICATIONS_LAUNCH_WITH_CONTENT_TOPIC = "dab/applications/launch-with-content" APPLICATIONS_EXIT_TOPIC = "dab/applications/exit" APPLICATIONS_GET_STATE_TOPIC = "dab/applications/get-state" SYSTEM_RESTART_TOPIC = "dab/system/restart" SYSTEM_LANGUAGE_LIST_TOPIC = "dab/system/language/list" SYSTEM_LANGUAGE_GET_TOPIC = "dab/system/language/get" SYSTEM_LANGUAGE_SET_TOPIC = "dab/system/language/set" DEVICE_TELEMETRY_START_TOPIC = "dab/device-telemetry/start" DEVICE_TELEMETRY_STOP_TOPIC = "dab/device-telemetry/stop" APPLICATION_TELEMETRY_START_TOPIC = "dab/app-telemetry/start" APPLICATION_TELEMETRY_STOP_TOPIC = "dab/app-telemetry/stop" INPUT_KEY_PRESS_TOPIC = "dab/input/key-press" INPUT_LONG_KEY_PRESS_TOPIC = "dab/input/long-key-press" HEALTH_CHECK_TOPIC = "dab/health-check/get" DEVICE_INFO_TOPIC = "dab/device/info" DAB_VERSION_TOPIC = "dab/version"
def filter_museums(request): sub = {'nature': 1, 'memorial': 2, 'art': 3, 'gallery': 4, 'history': 5} categories = [sub[i] for i in sub if request.GET.get(i) != 'false'] return categories
# # @lc app=leetcode.cn id=111 lang=python3 # # [111] 二叉树的最小深度 # # https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/ # # algorithms # Easy (42.69%) # Likes: 289 # Dislikes: 0 # Total Accepted: 89K # Total Submissions: 207.9K # Testcase Example: '[3,9,20,null,null,15,7]' # # 给定一个二叉树,找出其最小深度。 # # 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 # # 说明: 叶子节点是指没有子节点的节点。 # # 示例: # # 给定二叉树 [3,9,20,null,null,15,7], # # ⁠ 3 # ⁠ / \ # ⁠ 9 20 # ⁠ / \ # ⁠ 15 7 # # 返回它的最小深度  2. # # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 cur = [(root,1)] while cur: node,depth = cur.pop(0) if node.left: cur.append((node.left,depth+1)) if node.right: cur.append((node.right,depth+1)) if not node.left and not node.right: return depth # @lc code=end # def minDepth(self, root: TreeNode) -> int: 迭代 # if not root: # return 0 # queue = [[root]] # depth = 1 # while queue: # nodes = queue.pop(0) # children = [] # for cur in nodes: # if not cur.left and not cur.right: # return depth # if cur.left: # children.append(cur.left) # if cur.right: # children.append(cur.right) # depth += 1 # queue.append(children) # return depth # def minDepth(self, root: TreeNode) -> int:#递归 # if not root: # return 0 # if not root.left: # return self.minDepth(root.right) + 1 # if not root.right: # return self.minDepth(root.left) + 1 # return min(self.minDepth(root.right),self.minDepth(root.left)) + 1
for i in range(1, 70, 2): s= str(i+1) print("printf \"26\\n30\\n" + s + "\\n\" > tile.sizes") print("./polycc --tile --parallel NusValidation.cpp") print("gcc -o nus" + s + " -O2 NusValidation.cpp.pluto.c -fopenmp -lm") print("cp nus" + s + " exp") print("./exp/nus" + s)
allConfig = { 'xihan': { # 西汉南越王博物馆 'items': ['../baidu/xihan.txt', '../ctrip/xihan.txt', '../dianping/xihan.txt', '../dianping/xihan2.txt', '../mafengwo/xihan.txt', '../qunar/xihan.txt', '../tripadvisor/xihan.txt'], 'out': 'xihan.txt' }, 'chenjiaci': { 'items': ['../baidu/chenjiaci.txt', '../ctrip/chenjiaci.txt', '../dianping/chenjiaci.txt', '../mafengwo/chenjiaci.txt', '../qunar/chenjiaci.txt', '../tripadvisor/chenjiaci.txt'], 'out': 'chenjiaci.txt' } } # 注意修改这里 currentConfig = allConfig['chenjiaci'] def colAll(items, out): f_out = open(out, 'w', encoding = 'utf8') for item in items: f_in = open(item, encoding = 'utf8') for l in f_in: f_out.write(l) f_in.close() f_out.write('\n\n\n\n\n\n\n\n\n\n') f_out.close() if __name__ == '__main__': colAll(currentConfig['items'], currentConfig['out'])
# Puzzle Input with open('Day05_Input.txt') as puzzle_input: seats = puzzle_input.read().split('\n') # Converts a list containing a binary number to a decimal number def bin_to_decimal(bin_num): dec_num = 0 bin_len = len(bin_num) for pos, bit in enumerate(bin_num): if bit == 1: dec_num += 2 ** (bin_len - pos - 1) return dec_num # Calculates all the seats IDs seat_id = [] for s in seats: seat_position = [[], []] # Convert from letters to binary for letter in s[:-3]: seat_position[0] += [0] if letter == 'F' else [1] for letter in s[-3:]: seat_position[1] += [0] if letter == 'L' else [1] # Convert from binary to seat ID seat_id += [bin_to_decimal(seat_position[0]) * 8 + bin_to_decimal(seat_position[1])] print(max(seat_id))
# All traversals in one: Pre, post and inorder # Time complexity: O(3n) # Space complexity: O(4n), 4 stacks are being used class Node(): def __init__(self, key): self.left = None self.value = key self.right = None def traversal(node): if node is None: return [] stack = [[node, 1]] preorder = [] inorder = [] postorder = [] while(len(stack)!=0): curr = stack[-1][0] if(stack[-1][1] == 1): preorder.append(curr.value) stack[-1][1] += 1 if(curr.left): stack.append([curr.left, 1]) if(stack[-1][1] == 2): inorder.append(curr.value) stack[-1][1] += 1 if(curr.right): stack.append([curr.right, 1]) if(stack[-1][1] == 3): postorder.append(curr.value) stack.pop() return(preorder, inorder, postorder) root = Node(1) root.left = Node(2) root.right = Node(7) root.left.left = Node(3) root.left.left.right = Node(4) root.left.left.right.right = Node(5) root.left.left.right.right.right = Node(6) root.right.left = Node(8) root.right.right = Node(9) root.right.right.right = Node(10) preorder, inorder, postorder = traversal(root) print('Inorder traversal:', inorder) print('Preorder traversal:', preorder) print('Postorder traversal:', postorder)
file = open("/disk/lulu/database/TSGene/pro/TSG.genepos.qukong.txt") #f = open("out.txt", "w") for line in file: # print line, list = line.strip().split("\t") # print list if list[4] == "-": line1 = line.strip().replace("-", "") print (line1) # print >> f, "%s" % line1 else: print (list[0], "\t", list[1], "\t", list[2], "\t", list[3], "\t", list[5], "\t", list[6], "\t", list[7], "\t", list[8]) list1 = list[4].strip().split('|') for i in list1: print (list[0], "\t", list[1], "\t", list[2], "\t", i, "\t", list[5], "\t", list[6], "\t", list[7], "\t", list[8])
# -*- coding: utf-8 -*- class EndOfStream(Exception): pass class InvalidSyntaxError(Exception): pass class InvalidCommandFormat(InvalidSyntaxError): pass class TokenNotFound(InvalidSyntaxError): pass class DeprecatedSyntax(InvalidSyntaxError): pass class RenderingError(Exception): pass class ApertureSelectionError(Exception): pass class FeatureNotSupportedError(Exception): pass def suppress_context(exc: Exception) -> Exception: exc.__suppress_context__ = True return exc
src = [] include_tmp = [] if aos_global_config.compiler == 'armcc': src = Split(''' compilers/armlibc/armcc_libc.c ''') include_tmp = Split(''' compilers/armlibc ''') elif aos_global_config.compiler == 'rvct': src = Split(''' compilers/armlibc/armcc_libc.c ''') include_tmp = Split(''' compilers/armlibc ''') elif aos_global_config.compiler == 'iar': src = Split(''' compilers/iar/iar_libc.c ''') include_tmp = Split(''' compilers/iar ''') elif aos_global_config.board != 'linuxhost': src = Split(''' newlib_stub.c ''') component = aos_component('newlib_stub', src) for i in include_tmp: component.add_global_includes(i)
# # PySNMP MIB module CISCO-PRIVATE-VLAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-PRIVATE-VLAN-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:33:49 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") vtpVlanEntry, vtpVlanEditEntry = mibBuilder.importSymbols("CISCO-VTP-MIB", "vtpVlanEntry", "vtpVlanEditEntry") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") Counter32, IpAddress, Unsigned32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, TimeTicks, MibIdentifier, ObjectIdentity, Counter64, Integer32, Bits, iso, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "IpAddress", "Unsigned32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "TimeTicks", "MibIdentifier", "ObjectIdentity", "Counter64", "Integer32", "Bits", "iso", "NotificationType") TextualConvention, TruthValue, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "TruthValue", "DisplayString") ciscoPrivateVlanMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 173)) ciscoPrivateVlanMIB.setRevisions(('2005-09-08 00:00', '2002-07-24 00:00', '2001-05-23 00:00', '2001-04-17 00:00',)) if mibBuilder.loadTexts: ciscoPrivateVlanMIB.setLastUpdated('200509080000Z') if mibBuilder.loadTexts: ciscoPrivateVlanMIB.setOrganization('Cisco Systems, Inc.') class PrivateVlanType(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5)) namedValues = NamedValues(("normal", 1), ("primary", 2), ("isolated", 3), ("community", 4), ("twoWayCommunity", 5)) class VlanIndexOrZero(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 4095) class VlanIndexBitmap(TextualConvention, OctetString): status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 128) cpvlanMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 173, 1)) cpvlanVlanObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1)) cpvlanPortObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2)) cpvlanSVIObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 3)) cpvlanVlanTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1, 1), ) if mibBuilder.loadTexts: cpvlanVlanTable.setStatus('current') cpvlanVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1, 1, 1), ) vtpVlanEntry.registerAugmentions(("CISCO-PRIVATE-VLAN-MIB", "cpvlanVlanEntry")) cpvlanVlanEntry.setIndexNames(*vtpVlanEntry.getIndexNames()) if mibBuilder.loadTexts: cpvlanVlanEntry.setStatus('current') cpvlanVlanPrivateVlanType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1, 1, 1, 1), PrivateVlanType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cpvlanVlanPrivateVlanType.setStatus('current') cpvlanVlanAssociatedPrimaryVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1, 1, 1, 2), VlanIndexOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: cpvlanVlanAssociatedPrimaryVlan.setStatus('current') cpvlanVlanEditTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1, 2), ) if mibBuilder.loadTexts: cpvlanVlanEditTable.setStatus('current') cpvlanVlanEditEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1, 2, 1), ) vtpVlanEditEntry.registerAugmentions(("CISCO-PRIVATE-VLAN-MIB", "cpvlanVlanEditEntry")) cpvlanVlanEditEntry.setIndexNames(*vtpVlanEditEntry.getIndexNames()) if mibBuilder.loadTexts: cpvlanVlanEditEntry.setStatus('current') cpvlanVlanEditPrivateVlanType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1, 2, 1, 1), PrivateVlanType().clone('normal')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanVlanEditPrivateVlanType.setStatus('current') cpvlanVlanEditAssocPrimaryVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 1, 2, 1, 2), VlanIndexOrZero()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanVlanEditAssocPrimaryVlan.setStatus('current') cpvlanPrivatePortTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 1), ) if mibBuilder.loadTexts: cpvlanPrivatePortTable.setStatus('current') cpvlanPrivatePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: cpvlanPrivatePortEntry.setStatus('current') cpvlanPrivatePortSecondaryVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 1, 1, 1), VlanIndexOrZero()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanPrivatePortSecondaryVlan.setStatus('current') cpvlanPromPortTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 2), ) if mibBuilder.loadTexts: cpvlanPromPortTable.setStatus('current') cpvlanPromPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: cpvlanPromPortEntry.setStatus('current') cpvlanPromPortMultiPrimaryVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 2, 1, 1), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: cpvlanPromPortMultiPrimaryVlan.setStatus('current') cpvlanPromPortSecondaryRemap = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 2, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanPromPortSecondaryRemap.setStatus('current') cpvlanPromPortSecondaryRemap2k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 2, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanPromPortSecondaryRemap2k.setStatus('current') cpvlanPromPortSecondaryRemap3k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 2, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanPromPortSecondaryRemap3k.setStatus('current') cpvlanPromPortSecondaryRemap4k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 2, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanPromPortSecondaryRemap4k.setStatus('current') cpvlanPromPortTwoWayRemapCapable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 2, 1, 6), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: cpvlanPromPortTwoWayRemapCapable.setStatus('current') cpvlanPortModeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 3), ) if mibBuilder.loadTexts: cpvlanPortModeTable.setStatus('current') cpvlanPortModeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: cpvlanPortModeEntry.setStatus('current') cpvlanPortMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("nonPrivateVlan", 1), ("host", 2), ("promiscuous", 3), ("secondaryTrunk", 4), ("promiscuousTrunk", 5))).clone('nonPrivateVlan')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanPortMode.setStatus('current') cpvlanTrunkPortTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4), ) if mibBuilder.loadTexts: cpvlanTrunkPortTable.setStatus('current') cpvlanTrunkPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: cpvlanTrunkPortEntry.setStatus('current') cpvlanTrunkPortDynamicState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("on", 1), ("onNoNegotiate", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortDynamicState.setStatus('current') cpvlanTrunkPortEncapType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("dot1Q", 1), ("isl", 2), ("negotiate", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortEncapType.setStatus('current') cpvlanTrunkPortNativeVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 3), VlanIndexOrZero()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortNativeVlan.setStatus('current') cpvlanTrunkPortSecondaryVlans = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 4), VlanIndexBitmap()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortSecondaryVlans.setStatus('current') cpvlanTrunkPortSecondaryVlans2k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 5), VlanIndexBitmap()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortSecondaryVlans2k.setStatus('current') cpvlanTrunkPortSecondaryVlans3k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 6), VlanIndexBitmap()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortSecondaryVlans3k.setStatus('current') cpvlanTrunkPortSecondaryVlans4k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 7), VlanIndexBitmap()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortSecondaryVlans4k.setStatus('current') cpvlanTrunkPortNormalVlans = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 8), VlanIndexBitmap()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortNormalVlans.setStatus('current') cpvlanTrunkPortNormalVlans2k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 9), VlanIndexBitmap()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortNormalVlans2k.setStatus('current') cpvlanTrunkPortNormalVlans3k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 10), VlanIndexBitmap()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortNormalVlans3k.setStatus('current') cpvlanTrunkPortNormalVlans4k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 11), VlanIndexBitmap()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanTrunkPortNormalVlans4k.setStatus('current') cpvlanTrunkPortDynamicStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("trunking", 1), ("notTrunking", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cpvlanTrunkPortDynamicStatus.setStatus('current') cpvlanTrunkPortEncapOperType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 2, 4, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("dot1Q", 1), ("isl", 2), ("notApplicable", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cpvlanTrunkPortEncapOperType.setStatus('current') cpvlanSVIMappingTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 3, 1), ) if mibBuilder.loadTexts: cpvlanSVIMappingTable.setStatus('current') cpvlanSVIMappingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 3, 1, 1), ).setIndexNames((0, "CISCO-PRIVATE-VLAN-MIB", "cpvlanSVIMappingVlanIndex")) if mibBuilder.loadTexts: cpvlanSVIMappingEntry.setStatus('current') cpvlanSVIMappingVlanIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 3, 1, 1, 1), VlanIndexOrZero()) if mibBuilder.loadTexts: cpvlanSVIMappingVlanIndex.setStatus('current') cpvlanSVIMappingPrimarySVI = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 173, 1, 3, 1, 1, 2), VlanIndexOrZero()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cpvlanSVIMappingPrimarySVI.setStatus('current') cpvlanMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 173, 2)) cpvlanMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 1)) cpvlanMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 2)) cpvlanMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 1, 1)).setObjects() if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cpvlanMIBCompliance = cpvlanMIBCompliance.setStatus('current') cpvlanVlanGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 2, 1)).setObjects(("CISCO-PRIVATE-VLAN-MIB", "cpvlanVlanPrivateVlanType"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanVlanAssociatedPrimaryVlan"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanVlanEditPrivateVlanType"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanVlanEditAssocPrimaryVlan")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cpvlanVlanGroup = cpvlanVlanGroup.setStatus('current') cpvlanPrivatePortGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 2, 2)).setObjects(("CISCO-PRIVATE-VLAN-MIB", "cpvlanPrivatePortSecondaryVlan")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cpvlanPrivatePortGroup = cpvlanPrivatePortGroup.setStatus('current') cpvlanPromPortGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 2, 3)).setObjects(("CISCO-PRIVATE-VLAN-MIB", "cpvlanPromPortMultiPrimaryVlan"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanPromPortSecondaryRemap"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanPromPortTwoWayRemapCapable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cpvlanPromPortGroup = cpvlanPromPortGroup.setStatus('current') cpvlanPromPort4kGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 2, 4)).setObjects(("CISCO-PRIVATE-VLAN-MIB", "cpvlanPromPortSecondaryRemap2k"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanPromPortSecondaryRemap3k"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanPromPortSecondaryRemap4k")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cpvlanPromPort4kGroup = cpvlanPromPort4kGroup.setStatus('current') cpvlanPortModeGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 2, 5)).setObjects(("CISCO-PRIVATE-VLAN-MIB", "cpvlanPortMode")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cpvlanPortModeGroup = cpvlanPortModeGroup.setStatus('current') cpvlanSVIMappingGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 2, 6)).setObjects(("CISCO-PRIVATE-VLAN-MIB", "cpvlanSVIMappingPrimarySVI")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cpvlanSVIMappingGroup = cpvlanSVIMappingGroup.setStatus('current') cpvlanTrunkPortGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 173, 2, 2, 7)).setObjects(("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortDynamicState"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortEncapType"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortNativeVlan"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortSecondaryVlans"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortSecondaryVlans2k"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortSecondaryVlans3k"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortSecondaryVlans4k"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortNormalVlans"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortNormalVlans2k"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortNormalVlans3k"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortNormalVlans4k"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortDynamicStatus"), ("CISCO-PRIVATE-VLAN-MIB", "cpvlanTrunkPortEncapOperType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cpvlanTrunkPortGroup = cpvlanTrunkPortGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-PRIVATE-VLAN-MIB", cpvlanPromPortTwoWayRemapCapable=cpvlanPromPortTwoWayRemapCapable, cpvlanPortModeTable=cpvlanPortModeTable, cpvlanPromPort4kGroup=cpvlanPromPort4kGroup, VlanIndexBitmap=VlanIndexBitmap, cpvlanVlanTable=cpvlanVlanTable, cpvlanVlanEditAssocPrimaryVlan=cpvlanVlanEditAssocPrimaryVlan, cpvlanTrunkPortTable=cpvlanTrunkPortTable, cpvlanPortModeGroup=cpvlanPortModeGroup, cpvlanPromPortGroup=cpvlanPromPortGroup, cpvlanTrunkPortEncapOperType=cpvlanTrunkPortEncapOperType, cpvlanMIBConformance=cpvlanMIBConformance, cpvlanPrivatePortSecondaryVlan=cpvlanPrivatePortSecondaryVlan, cpvlanTrunkPortNormalVlans2k=cpvlanTrunkPortNormalVlans2k, cpvlanVlanPrivateVlanType=cpvlanVlanPrivateVlanType, cpvlanSVIObjects=cpvlanSVIObjects, PrivateVlanType=PrivateVlanType, cpvlanPortModeEntry=cpvlanPortModeEntry, cpvlanTrunkPortDynamicState=cpvlanTrunkPortDynamicState, cpvlanTrunkPortNativeVlan=cpvlanTrunkPortNativeVlan, VlanIndexOrZero=VlanIndexOrZero, cpvlanPromPortSecondaryRemap4k=cpvlanPromPortSecondaryRemap4k, cpvlanVlanObjects=cpvlanVlanObjects, cpvlanPromPortEntry=cpvlanPromPortEntry, cpvlanPromPortSecondaryRemap3k=cpvlanPromPortSecondaryRemap3k, cpvlanTrunkPortEncapType=cpvlanTrunkPortEncapType, cpvlanSVIMappingGroup=cpvlanSVIMappingGroup, cpvlanTrunkPortSecondaryVlans2k=cpvlanTrunkPortSecondaryVlans2k, cpvlanTrunkPortEntry=cpvlanTrunkPortEntry, cpvlanSVIMappingTable=cpvlanSVIMappingTable, cpvlanVlanGroup=cpvlanVlanGroup, cpvlanVlanEditPrivateVlanType=cpvlanVlanEditPrivateVlanType, cpvlanPortObjects=cpvlanPortObjects, cpvlanSVIMappingVlanIndex=cpvlanSVIMappingVlanIndex, PYSNMP_MODULE_ID=ciscoPrivateVlanMIB, cpvlanSVIMappingEntry=cpvlanSVIMappingEntry, cpvlanMIBCompliance=cpvlanMIBCompliance, cpvlanTrunkPortSecondaryVlans3k=cpvlanTrunkPortSecondaryVlans3k, cpvlanVlanEditTable=cpvlanVlanEditTable, cpvlanPrivatePortGroup=cpvlanPrivatePortGroup, cpvlanSVIMappingPrimarySVI=cpvlanSVIMappingPrimarySVI, cpvlanVlanEntry=cpvlanVlanEntry, cpvlanPrivatePortTable=cpvlanPrivatePortTable, cpvlanTrunkPortDynamicStatus=cpvlanTrunkPortDynamicStatus, cpvlanPromPortSecondaryRemap2k=cpvlanPromPortSecondaryRemap2k, cpvlanPromPortMultiPrimaryVlan=cpvlanPromPortMultiPrimaryVlan, cpvlanPortMode=cpvlanPortMode, cpvlanMIBCompliances=cpvlanMIBCompliances, cpvlanPromPortTable=cpvlanPromPortTable, cpvlanTrunkPortNormalVlans=cpvlanTrunkPortNormalVlans, ciscoPrivateVlanMIB=ciscoPrivateVlanMIB, cpvlanVlanAssociatedPrimaryVlan=cpvlanVlanAssociatedPrimaryVlan, cpvlanVlanEditEntry=cpvlanVlanEditEntry, cpvlanTrunkPortGroup=cpvlanTrunkPortGroup, cpvlanPromPortSecondaryRemap=cpvlanPromPortSecondaryRemap, cpvlanTrunkPortNormalVlans3k=cpvlanTrunkPortNormalVlans3k, cpvlanMIBObjects=cpvlanMIBObjects, cpvlanTrunkPortSecondaryVlans4k=cpvlanTrunkPortSecondaryVlans4k, cpvlanTrunkPortNormalVlans4k=cpvlanTrunkPortNormalVlans4k, cpvlanMIBGroups=cpvlanMIBGroups, cpvlanPrivatePortEntry=cpvlanPrivatePortEntry, cpvlanTrunkPortSecondaryVlans=cpvlanTrunkPortSecondaryVlans)
""" File contains the groovy scripts used by Nexus 3 script api as objects that may be used in the nexus3 state module. I put these here as it made it easy to sync the groovy with the module itself """ create_blobstore = """ import groovy.json.JsonSlurper parsed_args = new JsonSlurper().parseText(args) existingBlobStore = blobStore.getBlobStoreManager().get(parsed_args.name) if (existingBlobStore == null) { if (parsed_args.type == "S3") { blobStore.createS3BlobStore(parsed_args.name, parsed_args.config) msg = "S3 blobstore {} created" } else { blobStore.createFileBlobStore(parsed_args.name, parsed_args.path) msg = "Created blobstore {} created" } log.info(msg, parsed_args.name) } else { msg = "Blobstore {} already exists. Left untouched" } log.info(msg, parsed_args.name) """ create_content_selector = """ import groovy.json.JsonSlurper import org.sonatype.nexus.selector.SelectorManager import org.sonatype.nexus.selector.SelectorConfiguration parsed_args = new JsonSlurper().parseText(args) selectorManager = container.lookup(SelectorManager.class.name) def selectorConfig boolean update = true selectorConfig = selectorManager.browse().find { it -> it.name == parsed_args.name } if (selectorConfig == null) { update = false selectorConfig = new SelectorConfiguration( 'name': parsed_args.name ) } selectorConfig.setDescription(parsed_args.description) selectorConfig.setType('csel') selectorConfig.setAttributes([ 'expression': parsed_args.search_expression ] as Map<String, Object>) if (update) { selectorManager.update(selectorConfig) } else { selectorManager.create(selectorConfig) } """ create_repo_group = """ import groovy.json.JsonSlurper import org.sonatype.nexus.repository.config.Configuration parsed_args = new JsonSlurper().parseText(args) repositoryManager = repository.repositoryManager existingRepository = repositoryManager.get(parsed_args.name) if (existingRepository != null) { newConfig = existingRepository.configuration.copy() // We only update values we are allowed to change (cf. greyed out options in gui) if (parsed_args.recipe_name == 'docker-group') { newConfig.attributes['docker']['forceBasicAuth'] = parsed_args.docker_force_basic_auth newConfig.attributes['docker']['v1Enabled'] = parsed_args.docker_v1_enabled newConfig.attributes['docker']['httpPort'] = parsed_args.http_port } newConfig.attributes['group']['memberNames'] = parsed_args.member_repos newConfig.attributes['storage']['strictContentTypeValidation'] = Boolean.valueOf(parsed_args.strict_content_validation) repositoryManager.update(newConfig) } else { if (parsed_args.recipe_name == 'docker-group') { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ docker: [ forceBasicAuth: parsed_args.docker_force_basic_auth, v1Enabled : parsed_args.docker_v1_enabled, httpPort: parsed_args.docker_http_port ], group: [ memberNames: parsed_args.member_repos ], storage: [ blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ] ] ) } else { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ group : [ memberNames: parsed_args.member_repos ], storage: [ blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ] ] ) } repositoryManager.create(configuration) } """ create_repo_hosted = """ import groovy.json.JsonSlurper import org.sonatype.nexus.repository.config.Configuration parsed_args = new JsonSlurper().parseText(args) repositoryManager = repository.repositoryManager existingRepository = repositoryManager.get(parsed_args.name) msg = "Args: {}" log.debug(msg, args) if (existingRepository != null) { msg = "Repo {} already exists. Updating..." log.debug(msg, parsed_args.name) newConfig = existingRepository.configuration.copy() // We only update values we are allowed to change (cf. greyed out options in gui) if (parsed_args.recipe_name == 'docker-hosted') { newConfig.attributes['docker']['forceBasicAuth'] = parsed_args.docker_force_basic_auth newConfig.attributes['docker']['v1Enabled'] = parsed_args.docker_v1_enabled newConfig.attributes['docker']['httpPort'] = parsed_args.docker_http_port } else if (parsed_args.recipe_name == 'maven2-hosted') { newConfig.attributes['maven']['versionPolicy'] = parsed_args.maven_version_policy.toUpperCase() newConfig.attributes['maven']['layoutPolicy'] = parsed_args.maven_layout_policy.toUpperCase() } else if (parsed_args.recipe_name == 'yum-hosted') { newConfig.attributes['yum']['repodataDepth'] = parsed_args.yum_repodata_depth as Integer newConfig.attributes['yum']['deployPolicy'] = parsed_args.yum_deploy_policy.toUpperCase() } newConfig.attributes['storage']['writePolicy'] = parsed_args.write_policy.toUpperCase() newConfig.attributes['storage']['strictContentTypeValidation'] = Boolean.valueOf(parsed_args.strict_content_validation) repositoryManager.update(newConfig) } else { if (parsed_args.recipe_name == 'maven2-hosted') { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ maven: [ versionPolicy: parsed_args.maven_version_policy.toUpperCase(), layoutPolicy : parsed_args.maven_layout_policy.toUpperCase() ], storage: [ writePolicy: parsed_args.write_policy.toUpperCase(), blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ] ] ) } else if (parsed_args.recipe_name == 'docker-hosted') { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ docker: [ forceBasicAuth: parsed_args.docker_force_basic_auth, v1Enabled : parsed_args.docker_v1_enabled, httpPort: parsed_args.docker_http_port ], storage: [ writePolicy: parsed_args.write_policy.toUpperCase(), blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ] ] ) } else if (parsed_args.recipe_name == 'yum-hosted') { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ yum : [ repodataDepth : parsed_args.yum_repodata_depth.toInteger(), deployPolicy : parsed_args.yum_deploy_policy.toUpperCase() ], storage: [ writePolicy: parsed_args.write_policy.toUpperCase(), blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ] ] ) } else { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ storage: [ writePolicy: parsed_args.write_policy.toUpperCase(), blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ] ] ) } msg = "Configuration: {}" log.debug(msg, configuration) repositoryManager.create(configuration) } """ create_repo_proxy = """ import groovy.json.JsonSlurper import org.sonatype.nexus.repository.config.Configuration parsed_args = new JsonSlurper().parseText(args) repositoryManager = repository.repositoryManager authentication = parsed_args.remote_username == null ? null : [ type: 'username', username: parsed_args.remote_username, password: parsed_args.remote_password ] existingRepository = repositoryManager.get(parsed_args.name) msg = "Args: {}" log.debug(msg, args) if (existingRepository != null) { msg = "Repo {} already exists. Updating..." log.debug(msg, parsed_args.name) newConfig = existingRepository.configuration.copy() // We only update values we are allowed to change (cf. greyed out options in gui) if (parsed_args.recipe_name == 'docker-proxy') { newConfig.attributes['docker']['forceBasicAuth'] = parsed_args.docker_force_basic_auth newConfig.attributes['docker']['v1Enabled'] = parsed_args.docker_v1_enabled newConfig.attributes['dockerProxy']['indexType'] = parsed_args.docker_index_type newConfig.attributes['dockerProxy']['useTrustStoreForIndexAccess'] = parsed_args.docker_use_nexus_certificates_to_access_index newConfig.attributes['docker']['httpPort'] = parsed_args.docker_http_port } else if (parsed_args.recipe_name == 'maven2-proxy') { newConfig.attributes['maven']['versionPolicy'] = parsed_args.maven_version_policy.toUpperCase() newConfig.attributes['maven']['layoutPolicy'] = parsed_args.maven_layout_policy.toUpperCase() } newConfig.attributes['proxy']['remoteUrl'] = parsed_args.remote_url newConfig.attributes['proxy']['contentMaxAge'] = parsed_args.get('content_max_age', 1440.0) newConfig.attributes['proxy']['metadataMaxAge'] = parsed_args.get('metadata_max_age', 1440.0) newConfig.attributes['storage']['strictContentTypeValidation'] = Boolean.valueOf(parsed_args.strict_content_validation) newConfig.attributes['httpclient']['authentication'] = authentication repositoryManager.update(newConfig) } else { if (parsed_args.recipe_name == 'bower-proxy') { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ bower: [ rewritePackageUrls: true ], proxy: [ remoteUrl: parsed_args.remote_url, contentMaxAge: parsed_args.get('content_max_age', 1440.0), metadataMaxAge: parsed_args.get('metadata_max_age', 1440.0) ], httpclient: [ blocked: false, autoBlock: true, authentication: authentication ], storage: [ blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ], negativeCache: [ enabled: parsed_args.get("negative_cache_enabled", true), timeToLive: parsed_args.get("negative_cache_ttl", 1440.0) ] ] ) } else if (parsed_args.recipe_name == 'maven2-proxy') { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ maven : [ versionPolicy: parsed_args.maven_version_policy.toUpperCase(), layoutPolicy : parsed_args.maven_layout_policy.toUpperCase() ], proxy: [ remoteUrl: parsed_args.remote_url, contentMaxAge: parsed_args.get('content_max_age', 1440.0), metadataMaxAge: parsed_args.get('metadata_max_age', 1440.0) ], httpclient: [ blocked: false, autoBlock: true, authentication: authentication ], storage: [ blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ], negativeCache: [ enabled: parsed_args.get("negative_cache_enabled", true), timeToLive: parsed_args.get("negative_cache_ttl", 1440.0) ] ] ) } else if (parsed_args.recipe_name == 'docker-proxy') { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ docker: [ forceBasicAuth: parsed_args.docker_force_basic_auth, v1Enabled : parsed_args.docker_v1_enabled, httpPort: parsed_args.docker_http_port ], proxy: [ remoteUrl: parsed_args.remote_url, contentMaxAge: parsed_args.get('content_max_age', 1440.0), metadataMaxAge: parsed_args.get('metadata_max_age', 1440.0) ], dockerProxy: [ indexType: parsed_args.docker_index_type.toUpperCase(), useTrustStoreForIndexAccess: parsed_args.docker_use_nexus_certificates_to_access_index ], httpclient: [ blocked: false, autoBlock: true, authentication: authentication ], storage: [ blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ], negativeCache: [ enabled: parsed_args.get("negative_cache_enabled", true), timeToLive: parsed_args.get("negative_cache_ttl", 1440.0) ] ] ) } else { configuration = new Configuration( repositoryName: parsed_args.name, recipeName: parsed_args.recipe_name, online: true, attributes: [ proxy: [ remoteUrl: parsed_args.remote_url, contentMaxAge: parsed_args.get('content_max_age', 1440.0), metadataMaxAge: parsed_args.get('metadata_max_age', 1440.0) ], httpclient: [ blocked: false, autoBlock: true, authentication: authentication ], storage: [ blobStoreName: parsed_args.blob_store, strictContentTypeValidation: Boolean.valueOf(parsed_args.strict_content_validation) ], negativeCache: [ enabled: parsed_args.get("negative_cache_enabled", true), timeToLive: parsed_args.get("negative_cache_ttl", 1440.0) ] ] ) } msg = "Configuration: {}" log.debug(msg, configuration) repositoryManager.create(configuration) } """ create_task = """ import groovy.json.JsonSlurper import org.sonatype.nexus.scheduling.TaskConfiguration import org.sonatype.nexus.scheduling.TaskInfo import org.sonatype.nexus.scheduling.TaskScheduler import org.sonatype.nexus.scheduling.schedule.Schedule parsed_args = new JsonSlurper().parseText(args) TaskScheduler taskScheduler = container.lookup(TaskScheduler.class.getName()) TaskInfo existingTask = taskScheduler.listsTasks().find { TaskInfo taskInfo -> taskInfo.name == parsed_args.name } if (existingTask && existingTask.getCurrentState().getRunState() != null) { log.info("Could not update currently running task : " + parsed_args.name) return } TaskConfiguration taskConfiguration = taskScheduler.createTaskConfigurationInstance(parsed_args.typeId) if (existingTask) { taskConfiguration.setId(existingTask.getId()) } taskConfiguration.setName(parsed_args.name) parsed_args.taskProperties.each { key, value -> taskConfiguration.setString(key, value) } if (parsed_args.task_alert_email) { taskConfiguration.setAlertEmail(parsed_args.task_alert_email) } parsed_args.booleanTaskProperties.each { key, value -> taskConfiguration.setBoolean(key, Boolean.valueOf(value)) } Schedule schedule = taskScheduler.scheduleFactory.cron(new Date(), parsed_args.cron) taskScheduler.scheduleTask(taskConfiguration, schedule) """ delete_blobstore = """ import groovy.json.JsonSlurper parsed_args = new JsonSlurper().parseText(args) existingBlobStore = blobStore.getBlobStoreManager().get(parsed_args.name) if (existingBlobStore != null) { blobStore.getBlobStoreManager().delete(parsed_args.name) } """ delete_repo = """ import groovy.json.JsonSlurper parsed_args = new JsonSlurper().parseText(args) repository.getRepositoryManager().delete(parsed_args.name) """ setup_anonymous_access = """ import groovy.json.JsonSlurper parsed_args = new JsonSlurper().parseText(args) security.setAnonymousAccess(Boolean.valueOf(parsed_args.anonymous_access)) """ setup_base_url = """ import groovy.json.JsonSlurper parsed_args = new JsonSlurper().parseText(args) core.baseUrl(parsed_args.base_url) """ setup_capability = """ import groovy.json.JsonSlurper import org.sonatype.nexus.capability.CapabilityReference import org.sonatype.nexus.capability.CapabilityType import org.sonatype.nexus.internal.capability.DefaultCapabilityReference import org.sonatype.nexus.internal.capability.DefaultCapabilityRegistry parsed_args = new JsonSlurper().parseText(args) parsed_args.capability_properties['headerEnabled'] = parsed_args.capability_properties['headerEnabled'].toString() parsed_args.capability_properties['footerEnabled'] = parsed_args.capability_properties['footerEnabled'].toString() def capabilityRegistry = container.lookup(DefaultCapabilityRegistry.class.getName()) def capabilityType = CapabilityType.capabilityType(parsed_args.capability_typeId) DefaultCapabilityReference existing = capabilityRegistry.all.find { CapabilityReference capabilityReference -> capabilityReference.context().descriptor().type() == capabilityType } if (existing) { log.info(parsed_args.typeId + ' capability updated to: {}', capabilityRegistry.update(existing.id(), Boolean.valueOf(parsed_args.get('capability_enabled', true)), existing.notes(), parsed_args.capability_properties).toString() ) } else { log.info(parsed_args.typeId + ' capability created as: {}', capabilityRegistry. add(capabilityType, Boolean.valueOf(parsed_args.get('capability_enabled', true)), 'configured through api', parsed_args.capability_properties).toString() ) } """ setup_email = """ import groovy.json.JsonSlurper import org.sonatype.nexus.email.EmailConfiguration import org.sonatype.nexus.email.EmailManager parsed_args = new JsonSlurper().parseText(args) def emailMgr = container.lookup(EmailManager.class.getName()); emailConfig = new EmailConfiguration( enabled: parsed_args.email_server_enabled, host: parsed_args.email_server_host, port: Integer.valueOf(parsed_args.email_server_port), username: parsed_args.email_server_username, password: parsed_args.email_server_password, fromAddress: parsed_args.email_from_address, subjectPrefix: parsed_args.email_subject_prefix, startTlsEnabled: parsed_args.email_tls_enabled, startTlsRequired: parsed_args.email_tls_required, sslOnConnectEnabled: parsed_args.email_ssl_on_connect_enabled, sslCheckServerIdentityEnabled: parsed_args.email_ssl_check_server_identity_enabled, nexusTrustStoreEnabled: parsed_args.email_trust_store_enabled ) emailMgr.configuration = emailConfig """ setup_http_proxy = """ import groovy.json.JsonSlurper parsed_args = new JsonSlurper().parseText(args) core.removeHTTPProxy() if (parsed_args.with_http_proxy) { if (parsed_args.http_proxy_username) { core.httpProxyWithBasicAuth(parsed_args.http_proxy_host, parsed_args.http_proxy_port as int, parsed_args.http_proxy_username, parsed_args.http_proxy_password) } else { core.httpProxy(parsed_args.http_proxy_host, parsed_args.http_proxy_port as int) } } core.removeHTTPSProxy() if (parsed_args.with_https_proxy) { if (parsed_args.https_proxy_username) { core.httpsProxyWithBasicAuth(parsed_args.https_proxy_host, parsed_args.https_proxy_port as int, parsed_args.https_proxy_username, parsed_args.https_proxy_password) } else { core.httpsProxy(parsed_args.https_proxy_host, parsed_args.https_proxy_port as int) } } if (parsed_args.with_http_proxy || parsed_args.with_https_proxy) { core.nonProxyHosts() core.nonProxyHosts(parsed_args.proxy_exclude_hosts as String[]) } """ setup_ldap = """ import org.sonatype.nexus.ldap.persist.LdapConfigurationManager import org.sonatype.nexus.ldap.persist.entity.LdapConfiguration import org.sonatype.nexus.ldap.persist.entity.Connection import org.sonatype.nexus.ldap.persist.entity.Mapping import groovy.json.JsonSlurper parsed_args = new JsonSlurper().parseText(args) def ldapConfigMgr = container.lookup(LdapConfigurationManager.class.getName()); def ldapConfig = new LdapConfiguration() boolean update = false; // Look for existing config to update ldapConfigMgr.listLdapServerConfigurations().each { if (it.name == parsed_args.name) { ldapConfig = it update = true } } ldapConfig.setName(parsed_args.name) // Connection connection = new Connection() connection.setHost(new Connection.Host(Connection.Protocol.valueOf(parsed_args.protocol), parsed_args.hostname, Integer.valueOf(parsed_args.port))) if (parsed_args.auth == "simple") { connection.setAuthScheme("simple") connection.setSystemUsername(parsed_args.username) connection.setSystemPassword(parsed_args.password) } else { connection.setAuthScheme("none") } connection.setSearchBase(parsed_args.search_base) connection.setConnectionTimeout(30) connection.setConnectionRetryDelay(300) connection.setMaxIncidentsCount(3) ldapConfig.setConnection(connection) // Mapping mapping = new Mapping() mapping.setUserBaseDn(parsed_args.user_base_dn) mapping.setLdapFilter(parsed_args.user_ldap_filter) mapping.setUserObjectClass(parsed_args.user_object_class) mapping.setUserIdAttribute(parsed_args.user_id_attribute) mapping.setUserRealNameAttribute(parsed_args.user_real_name_attribute) mapping.setEmailAddressAttribute(parsed_args.user_email_attribute) if (parsed_args.map_groups_as_roles) { if(parsed_args.map_groups_as_roles_type == "static"){ mapping.setLdapGroupsAsRoles(true) mapping.setGroupBaseDn(parsed_args.group_base_dn) mapping.setGroupObjectClass(parsed_args.group_object_class) mapping.setGroupIdAttribute(parsed_args.group_id_attribute) mapping.setGroupMemberAttribute(parsed_args.group_member_attribute) mapping.setGroupMemberFormat(parsed_args.group_member_format) } else if (parsed_args.map_groups_as_roles_type == "dynamic") { mapping.setLdapGroupsAsRoles(true) mapping.setUserMemberOfAttribute(parsed_args.user_memberof_attribute) } } mapping.setUserSubtree(parsed_args.user_subtree) mapping.setGroupSubtree(parsed_args.group_subtree) ldapConfig.setMapping(mapping) if (update) { ldapConfigMgr.updateLdapServerConfiguration(ldapConfig) } else { ldapConfigMgr.addLdapServerConfiguration(ldapConfig) } """ setup_privilege = """ import groovy.json.JsonSlurper import org.sonatype.nexus.security.privilege.NoSuchPrivilegeException import org.sonatype.nexus.security.user.UserManager import org.sonatype.nexus.security.privilege.Privilege parsed_args = new JsonSlurper().parseText(args) authManager = security.getSecuritySystem().getAuthorizationManager(UserManager.DEFAULT_SOURCE) def privilege boolean update = true try { privilege = authManager.getPrivilege(parsed_args.name) } catch (NoSuchPrivilegeException ignored) { // could not find any existing privilege update = false privilege = new Privilege( 'id': parsed_args.name, 'name': parsed_args.name ) } privilege.setDescription(parsed_args.description) privilege.setType(parsed_args.type) privilege.setProperties([ 'format': parsed_args.format, 'contentSelector': parsed_args.contentSelector, 'repository': parsed_args.repository, 'actions': parsed_args.actions.join(',') ] as Map<String, String>) if (update) { authManager.updatePrivilege(privilege) log.info("Privilege {} updated", parsed_args.name) } else { authManager.addPrivilege(privilege) log.info("Privilege {} created", parsed_args.name) } """ setup_realms = """ import groovy.json.JsonSlurper import org.sonatype.nexus.security.realm.RealmManager parsed_args = new JsonSlurper().parseText(args) realmManager = container.lookup(RealmManager.class.getName()) if (parsed_args.realm_name == 'NuGetApiKey') { // enable/disable the NuGet API-Key Realm realmManager.enableRealm("NuGetApiKey", parsed_args.status) } if (parsed_args.realm_name == 'NpmToken') { // enable/disable the npm Bearer Token Realm realmManager.enableRealm("NpmToken", parsed_args.status) } if (parsed_args.realm_name == 'rutauth-realm') { // enable/disable the Rut Auth Realm realmManager.enableRealm("rutauth-realm", parsed_args.status) } if (parsed_args.realm_name == 'LdapRealm') { // enable/disable the LDAP Realm realmManager.enableRealm("LdapRealm", parsed_args.status) } if (parsed_args.realm_name == 'DockerToken') { // enable/disable the Docker Bearer Token Realm realmManager.enableRealm("DockerToken", parsed_args.status) } """ setup_role = """ import groovy.json.JsonSlurper import org.sonatype.nexus.security.user.UserManager import org.sonatype.nexus.security.role.NoSuchRoleException parsed_args = new JsonSlurper().parseText(args) authManager = security.getSecuritySystem().getAuthorizationManager(UserManager.DEFAULT_SOURCE) privileges = (parsed_args.privileges == null ? new HashSet() : parsed_args.privileges.toSet()) roles = (parsed_args.roles == null ? new HashSet() : parsed_args.roles.toSet()) try { existingRole = authManager.getRole(parsed_args.id) existingRole.setName(parsed_args.name) existingRole.setDescription(parsed_args.description) existingRole.setPrivileges(privileges) existingRole.setRoles(roles) authManager.updateRole(existingRole) log.info("Role {} updated", parsed_args.name) } catch (NoSuchRoleException ignored) { security.addRole(parsed_args.id, parsed_args.name, parsed_args.description, privileges.toList(), roles.toList()) log.info("Role {} created", parsed_args.name) } """ setup_user = """ import groovy.json.JsonSlurper import org.sonatype.nexus.security.user.UserManager import org.sonatype.nexus.security.user.UserNotFoundException import org.sonatype.nexus.security.user.User parsed_args = new JsonSlurper().parseText(args) state = parsed_args.state == null ? 'present' : parsed_args.state if ( state == 'absent' ) { deleteUser(parsed_args) } else { try { updateUser(parsed_args) } catch (UserNotFoundException ignored) { addUser(parsed_args) } } def updateUser(parsed_args) { User user = security.securitySystem.getUser(parsed_args.username) user.setFirstName(parsed_args.first_name) user.setLastName(parsed_args.last_name) user.setEmailAddress(parsed_args.email) security.securitySystem.updateUser(user) security.setUserRoles(parsed_args.username, parsed_args.roles) security.securitySystem.changePassword(parsed_args.username, parsed_args.password) log.info("Updated user {}", parsed_args.username) } def addUser(parsed_args) { security.addUser(parsed_args.username, parsed_args.first_name, parsed_args.last_name, parsed_args.email, true, parsed_args.password, parsed_args.roles) log.info("Created user {}", parsed_args.username) } def deleteUser(parsed_args) { try { security.securitySystem.deleteUser(parsed_args.username, UserManager.DEFAULT_SOURCE) log.info("Deleted user {}", parsed_args.username) } catch (UserNotFoundException ignored) { log.info("Delete user: user {} does not exist", parsed_args.username) } } """ update_admin_password = """ import groovy.json.JsonSlurper parsed_args = new JsonSlurper().parseText(args) security.securitySystem.changePassword('admin', parsed_args.new_password) """