code
stringlengths
1
18.2k
def get_grade_ids(self): """Gets the grade Ids in this system ranked from highest to lowest. return: (osid.id.IdList) - the list of grades Ids raise: IllegalState - is_based_on_grades() is false compliance: mandatory - This method must be implemented. """ id_list = [] for grade_map in self._my_map['grades']: id_list.ap...
def wait_and_join(self, task): """ Given a task, waits for it until it finishes :param task: Task :return: """ while not task.has_started: time.sleep(self._polling_time) task.thread.join()
def depends(self, *tasks): """ Interfaces the GraphNode `depends` method """ nodes = [x.node for x in tasks] self.node.depends(*nodes) return self
def then(self, *tasks): """ Interfaces the GraphNode `then` method """ nodes = [x.node for x in tasks] self.node.then(*nodes) return self
def add(self, *tasks): """ Interfaces the GraphNode `add` method """ nodes = [x.node for x in tasks] self.node.add(*nodes) return self
def _run(self): """ Run the task respecting dependencies """ for node in self.node.relatives: launch_node_task(node) for node in self.node.relatives: self.wait_and_join(node.task) if self.node.parent: while not self.node.parent.task.siblings_permission: time.sleep(self._polling_time) self.has_started = True self.main()...
def read_version(): """Read version from the first line starting with digit """ regex = re.compile('^(?P<number>\d.*?) .*$') with open('../CHANGELOG.rst') as f: for line in f: match = regex.match(line) if match: return match.group('number')
def get_resource_record_types(self): """Gets all the resource record types supported. return: (osid.type.TypeList) - the list of supported resource record types *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceProfile.get_resource_record_types_templ...
def get_resource_search_session_for_bin(self, bin_id): """Gets a resource search session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin return: (osid.resource.ResourceSearchSession) - ``a ResourceSearchSession`` raise: NotFound - ``bin_id`` not found raise: NullArgument - ``bin_id`` is ``null`` rais...
def get_resource_agent_session(self): """Gets the session for retrieving resource agent mappings. return: (osid.resource.ResourceAgentSession) - a ``ResourceAgentSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_resource_agent()`` is ``false`` *compliance: optional -- This ...
def get_resource_agent_assignment_session_for_bin(self, bin_id): """Gets a resource agent session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin return: (osid.resource.ResourceAgentAssignmentSession) - a ``ResourceAgentAssignmentSession`` raise: NotFound - ``bin_id`` not found raise: NullArgument - ...
def get_bin_admin_session(self): """Gets the bin administrative session for creating, updating and deleteing bins. return: (osid.resource.BinAdminSession) - a ``BinAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_admin()`` is ``false`` *compliance: optional -- Thi...
def get_bin_hierarchy_session(self): """Gets the bin hierarchy traversal session. return: (osid.resource.BinHierarchySession) - ``a BinHierarchySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_hierarchy()`` is ``false`` *compliance: optional -- This method must be impl...
def get_bin_hierarchy_design_session(self): """Gets the bin hierarchy design session. return: (osid.resource.BinHierarchyDesignSession) - a ``BinHierarchyDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_hierarchy_design()`` is ``false`` *compliance: optional -- T...
def get_resource_lookup_session(self, proxy): """Gets the ``OsidSession`` associated with the resource lookup service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceLookupSession) - ``a ResourceLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complet...
def get_resource_lookup_session_for_bin(self, bin_id, proxy): """Gets the ``OsidSession`` associated with the resource lookup service for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin arg: proxy (osid.proxy.Proxy): ``a proxy`` return: (osid.resource.ResourceLookupSession) - ``a ResourceLookupSession`` ...
def get_resource_query_session(self, proxy): """Gets a resource query session. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceQuerySession) - ``a ResourceQuerySession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``support...
def get_resource_query_session_for_bin(self, bin_id, proxy): """Gets a resource query session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceQuerySession) - ``a ResourceQuerySession`` raise: NotFound - ``bin_id`` not found raise: ...
def get_resource_search_session(self, proxy): """Gets a resource search session. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceSearchSession) - ``a ResourceSearchSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``sup...
def get_resource_admin_session(self, proxy): """Gets a resource administration session for creating, updating and deleting resources. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceAdminSession) - ``a ResourceAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unab...
def get_resource_admin_session_for_bin(self, bin_id, proxy): """Gets a resource administration session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceAdminSession) - ``a ResourceAdminSession`` raise: NotFound - ``bin_id`` not foun...
def get_resource_notification_session(self, resource_receiver, proxy): """Gets the resource notification session for the given bin. arg: resource_receiver (osid.resource.ResourceReceiver): notification callback arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceNotificationSession) - ``a ResourceNoti...
def get_resource_notification_session_for_bin(self, resource_receiver, bin_id, proxy): """Gets the resource notification session for the given bin. arg: resource_receiver (osid.resource.ResourceReceiver): notification callback arg: bin_id (osid.id.Id): the ``Id`` of the bin arg: proxy (osid.proxy.Proxy): a proxy return...
def get_resource_bin_session(self, proxy): """Gets the session for retrieving resource to bin mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceBinSession) - a ``ResourceBinSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unim...
def get_resource_bin_assignment_session(self, proxy): """Gets the session for assigning resource to bin mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceBinAssignmentSession) - a ``ResourceBinAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable t...
def get_group_hierarchy_session(self, proxy): """Gets the group hierarchy traversal session for the given resource group. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.BinHierarchySession) - ``a GroupHierarchySession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to comple...
def get_resource_agent_session_for_bin(self, bin_id, proxy): """Gets a resource agent session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceAgentSession) - a ``ResourceAgentSession`` raise: NotFound - ``bin_id`` not found raise: ...
def get_resource_agent_assignment_session(self, proxy): """Gets the session for assigning agents to resources. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.ResourceAgentAssignmentSession) - a ``ResourceAgentAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable ...
def get_bin_lookup_session(self, proxy): """Gets the bin lookup session. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.BinLookupSession) - a ``BinLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_lookup()...
def get_bin_query_session(self, proxy): """Gets the bin query session. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.BinQuerySession) - a ``BinQuerySession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_query()`` is...
def register(klass): "Register a class into the agnocomplete registry." logger.info("registering {}".format(klass.__name__)) AGNOCOMPLETE_REGISTRY[klass.slug] = klass
def gen_slide_seg_list(mm_begin, mm_end, seg_duration, slide_step): """ 生成时间片开始时刻列表,时间片以slide_step步长进行滑动 :param mm_begin: :param mm_end: :param seg_duration: :param slide_step: :return: """ seg_begin_list = [i for i in range(mm_begin, mm_end - seg_duration + 1, slide_step)] seg_list = list(map(time_util.minutes_to_time...
def get_slide_seg_list_belonged(dt_str, seg_duration, slide_step=1, fmt='%Y-%m-%d %H:%M:%S'): """ 获取该时刻所属的所有时间片列表 :param dt_str: datetime string, eg: 2016-10-31 12:22:11 :param seg_duration: 时间片长度, unit: minute :param slide_step: 滑动步长 :param fmt: datetime string format :return: 时间片列表 """ dt = time_util.str_to_datetime(...
def get_still_seg_belonged(dt_str, seg_duration, fmt='%Y-%m-%d %H:%M:%S'): """ 获取该时刻所属的非滑动时间片 :param dt_str: datetime string, eg: 2016-10-31 12:22:11 :param seg_duration: 时间片长度, unit: minute :param fmt: datetime string format :return: """ dt = time_util.str_to_datetime(dt_str, fmt) minutes_of_day = time_util.get_minute...
def lie_in_seg(dt, time_str, seg_duration): """ 判断datetime是否在time_str为起点的时间片内 :param dt: :param time_str: eg: '11:10:21' :param seg_duration: :return: """ minutes_of_day = time_util.get_minutes_of_day(dt) range_begin = time_util.time_str_to_minutes(time_str) if range_begin <= minutes_of_day < range_begin + seg_duration...
def time_seg_to_index(time_str, slide_step): """ 将时间片字符串转换为时间片索引值 :param time_str: eg: '11:10:21' :param slide_step: :return: """ minutes_idx = time_util.time_str_to_minutes(time_str) time_seg_idx = minutes_idx // slide_step return time_seg_idx
def index_to_time_seg(time_seg_idx, slide_step): """ 将时间片索引值转换为时间片字符串 :param time_seg_idx: :param slide_step: :return: """ assert (time_seg_idx * slide_step < const.MINUTES_IN_A_DAY) return time_util.minutes_to_time_str(time_seg_idx * slide_step)
def _get_covariance_symbol(self, q_counter, sp1_idx, sp2_idx): r""" Compute second order moments i.e. variances and covariances Covariances equal to 0 in univariate case :param q_counter: moment matrix :param sp1_idx: index of one species :param sp2_idx: index of another species :return: second order moments matrix of ...
def _compute_one_closed_central_moment(self, moment, covariance_matrix): r""" Compute each row of closed central moment based on Isserlis' Theorem of calculating higher order moments of multivariate normal distribution in terms of covariance matrix :param moment: moment matrix :param covariance_matrix: matrix containin...
+\mathbb{E} [x_1x_3] +\mathbb{E} [x_1x_4] # +\mathbb{E} [x_2x_3]+\mathbb{E} [x_2x_4]+\mathbb{E} [x_3x_4]' # For second order moment, there is only one way of partitioning. Hence, no need to generate partitions if moment.order == 2: return covariance_matrix[list_for_partition[0], list_for_partition[1]] # For even moment...
def _compute_closed_central_moments(self, central_from_raw_exprs, n_counter, k_counter): """ Computes parametric expressions (e.g. in terms of mean, variance, covariances) for all central moments up to max_order + 1 order. :param central_from_raw_exprs: :param n_counter: a list of :class:`~means.core.descriptors.Moment...
def connect(self): """Connect to the unix domain socket, which is passed to us as self.host This is in host because the format we use for the unix domain socket is: http+unix://%2Fpath%2Fto%2Fsocket.sock """ try: self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if has_timeout(self.timeout): self.sock.setti...
def cardinal_direction(self): """ Returns the cardinal direction of the wind as a string. Possible returned values are N, E, S, W, and None. 315 degrees to 45 degrees exclusive -> N 45 degrees to 135 degrees exclusive -> E 135 degrees to 225 degrees exclusive -> S 225 degrees to 315 degrees exclusive -> W None if no di...
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() if name in ISO_LANGUAGE_CODES: name = ISO_LANGUAGE_CODES[name] if name in ISO_MAJOR_LANGUAGE_TYPES: namespace = '639-2' lang_name = ISO_MAJOR_LANGUAGE_TYPES[name] elif ...
def normalise_filled(self, meta, val): """Only care about valid image names""" available = list(meta.everything["images"].keys()) val = sb.formatted(sb.string_spec(), formatter=MergedOptionStringFormatter).normalise(meta, val) if val not in available: raise BadConfiguration("Specified image doesn't exist", specified=va...
def create_result(self, local_path, container_path, permissions, meta, val, dividers): """Default permissions to rw""" if permissions is NotSpecified: permissions = 'rw' return Mount(local_path, container_path, permissions)
def create_result(self, env_name, other_val, meta, val, dividers): """Set default_val and set_val depending on the seperator""" args = [env_name] if other_val is NotSpecified: other_val = None if not dividers: args.extend([None, None]) elif dividers[0] == ':': args.extend([other_val, None]) elif dividers[0] == '=': arg...
def determine_2(self, container_name, container_alias, meta, val): """"Default the alias to the name of the container""" if container_alias is not NotSpecified: return container_alias return container_name[container_name.rfind(":")+1:].replace('/', '-')
def alter_1(self, given_container_name, container_name, meta, val): """Get the container_name of the container if a container is specified""" meta.container = None if not isinstance(container_name, six.string_types): meta.container = container_name container_name = container_name.container_name return container_name
def create_result(self, ip, host_port, container_port, meta, val, dividers): """ The format is the same as the default docker cli client:: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort """ if host_port in ('', NotSpecified) and container_port in ('', NotSpecified): container_por...
def get(self, k_vec, e_counter): r""" Provides the terms needed for equation 11 (see Ale et al. 2013). This gives the expressions for :math:`\frac{d\beta}{dt}` in equation 9, these are the time dependencies of the mixed moments :param k_vec: :math:`k` in eq. 11 :param e_counter: :math:`e` in eq. 11 :return: :math:`\fra...
REACTION and EACH entry in the EKCOUNTER . this is a list of scalars s_pow_e_vec = sp.Matrix([self._make_s_pow_e(reac_idx, ek.n_vector) for (reac_idx, ek) in itertools.product(range(len(self.__propensities)), e_counter)]) # compute (k choose e) for EACH REACTION and EACH entry in the EKCOUNTER . This is a list of scala...
the data into a matrix in which each row is a different vector to_sum = sp.Matrix(prod) # then we sum over the columns -> row vector mixed_moments = sum_of_cols(to_sum) return mixed_moments
def _make_f_of_x(self, k_vec, e_vec, reaction): r""" Calculates :math:`F():math:` in eq. 12 (see Ale et al. 2013) for a specific reaction , :math:`k` and :math:`e` :param k_vec: the vector :math:`k` :param e_vec: the vector :math:`e` :param reaction: the equation of the reaction {:math:`a(x) in the model} :return: :mat...
def _make_f_expectation(self, expr): """ Calculates :math:`<F>` in eq. 12 (see Ale et al. 2013) to calculate :math:`<F>` for EACH VARIABLE combination. :param expr: an expression :return: a column vector. Each row correspond to an element of counter. :rtype: :class:`sympy.Matrix` """ # compute derivatives for EACH ENTR...
def _make_s_pow_e(self, reac_idx, e_vec): """ Compute s^e in equation 11 (see Ale et al. 2013) :param reac_idx: the index (that is the column in the stoichiometry matrix) of the reaction to consider. :type reac_idx: `int` :param e_vec: the vector e :return: a scalar (s^e) """ return product([self.__stoichoimetry_matrix...
def catch_no_credentials(message, **info): """Turn a NoCredentialsError into a BadAmazon""" try: yield except NoCredentialsError as error: if hasattr(error, "response"): info['error_code'] = error.response["ResponseMetadata"]["HTTPStatusCode"] info['error_message'] = error.response["Error"]["Message"] else: info['error...
def catch_boto_400(message, **info): """Turn a BotoServerError 400 into a BadAmazon""" try: yield except ClientError as error: if str(error.response["ResponseMetadata"]["HTTPStatusCode"]).startswith("4"): error_message = error.response["Error"]["Message"] raise BadAmazon(message, error_message=error_message, error_code...
def _initialize(self, runtime): """Common initializer for OsidManager and OsidProxyManager""" if runtime is None: raise NullArgument() if self._my_runtime is not None: raise IllegalState('this manager has already been initialized.') self._my_runtime = runtime config = runtime.get_configuration() cf_public_key_param_id ...
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() try: return { 'authority': 'ISO', 'namespace': '15924', 'identifier': name, 'domain': 'ISO Script Types', 'display_name': ISO_SCRIPT_TYPES[name] + ' Script Type', 'disp...
def check_effective(func): """decorator, tests if an Assessment or Section is effective, raises error if not Side benefit: raised NotFound on AssessmentSections and AssessmentTakens """ def wrapper(*args, **kwargs): if ('assessment_section_id' in kwargs or args and 'Section' in args[1].get_identifier_namespace()): try:...
def get_first_part_id_for_assessment(assessment_id, runtime=None, proxy=None, create=False, bank_id=None): """Gets the first part id, which represents the first section, of assessment""" if create and bank_id is None: raise NullArgument('Bank Id must be provided for create option') try: return get_next_part_id(assessme...
def get_assessment_part_lookup_session(runtime, proxy, section=None): """returns an assessment part lookup session, perhaps even a magic one""" # This appears to share code with get_item_lookup_session try: config = runtime.get_configuration() parameter_id = Id('parameter:magicAssessmentPartLookupSessions@json') import...
def get_assessment_section(section_id, runtime=None, proxy=None): """Gets a Section given a section_id""" from .mixins import LoadedSection collection = JSONClientValidated('assessment', collection='AssessmentSection', runtime=runtime) result = collection.find_one(dict({'_id': ObjectId(section_id.get_identifier())})) r...
def update_parent_sequence_map(child_part, delete=False): """Updates the child map of a simple sequence assessment assessment part""" if child_part.has_parent_part(): object_map = child_part.get_assessment_part()._my_map database = 'assessment_authoring' collection_type = 'AssessmentPart' else: object_map = child_part....
def remove_from_parent_sequence_map(assessment_part_admin_session, assessment_part_id): """Updates the child map of a simple sequence assessment assessment part to remove child part""" apls = get_assessment_part_lookup_session(runtime=assessment_part_admin_session._runtime, proxy=assessment_part_admin_session._proxy) a...
def p_primary_expr_no_brace_1(self, p): """primary_expr_no_brace : identifier""" p[1]._mangle_candidate = True p[1]._in_expression = True p[0] = p[1]
def p_array_literal_2(self, p): """array_literal : LBRACKET element_list RBRACKET | LBRACKET element_list COMMA elision_opt RBRACKET """ items = p[2] if len(p) == 6: items.extend(p[4]) p[0] = ast.Array(items=items)
def p_elision(self, p): """elision : COMMA | elision COMMA """ if len(p) == 2: p[0] = [ast.Elision(p[1])] else: p[1].append(ast.Elision(p[2])) p[0] = p[1]
def p_object_literal(self, p): """object_literal : LBRACE RBRACE | LBRACE property_list RBRACE | LBRACE property_list COMMA RBRACE """ if len(p) == 3: p[0] = ast.Object() else: p[0] = ast.Object(properties=p[2])
def p_property_assignment(self, p): """property_assignment \ : property_name COLON assignment_expr | GETPROP property_name LPAREN RPAREN LBRACE function_body RBRACE | SETPROP property_name LPAREN formal_parameter_list RPAREN \ LBRACE function_body RBRACE """ if len(p) == 4: p[0] = ast.Assign(left=p[1], op=p[2], right=p...
def p_member_expr(self, p): """member_expr : primary_expr | function_expr | member_expr LBRACKET expr RBRACKET | member_expr PERIOD identifier | NEW member_expr arguments """ if len(p) == 2: p[0] = p[1] elif p[1] == 'new': p[0] = ast.NewExpr(p[2], p[3]) elif p[2] == '.': p[0] = ast.DotAccessor(p[1], p[3]) else: p[0] = ...
def p_member_expr_nobf(self, p): """member_expr_nobf : primary_expr_no_brace | function_expr | member_expr_nobf LBRACKET expr RBRACKET | member_expr_nobf PERIOD identifier | NEW member_expr arguments """ if len(p) == 2: p[0] = p[1] elif p[1] == 'new': p[0] = ast.NewExpr(p[2], p[3]) elif p[2] == '.': p[0] = ast.DotAcces...
def p_new_expr(self, p): """new_expr : member_expr | NEW new_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.NewExpr(p[2])
def p_new_expr_nobf(self, p): """new_expr_nobf : member_expr_nobf | NEW new_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.NewExpr(p[2])
def p_call_expr(self, p): """call_expr : member_expr arguments | call_expr arguments | call_expr LBRACKET expr RBRACKET | call_expr PERIOD identifier """ if len(p) == 3: p[0] = ast.FunctionCall(p[1], p[2]) elif len(p) == 4: p[0] = ast.DotAccessor(p[1], p[3]) else: p[0] = ast.BracketAccessor(p[1], p[3])
def p_call_expr_nobf(self, p): """call_expr_nobf : member_expr_nobf arguments | call_expr_nobf arguments | call_expr_nobf LBRACKET expr RBRACKET | call_expr_nobf PERIOD identifier """ if len(p) == 3: p[0] = ast.FunctionCall(p[1], p[2]) elif len(p) == 4: p[0] = ast.DotAccessor(p[1], p[3]) else: p[0] = ast.BracketAccesso...
def p_postfix_expr(self, p): """postfix_expr : left_hand_side_expr | left_hand_side_expr PLUSPLUS | left_hand_side_expr MINUSMINUS """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.UnaryOp(op=p[2], value=p[1], postfix=True)
def p_multiplicative_expr(self, p): """multiplicative_expr : unary_expr | multiplicative_expr MULT unary_expr | multiplicative_expr DIV unary_expr | multiplicative_expr MOD unary_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
def p_conditional_expr(self, p): """ conditional_expr \ : logical_or_expr | logical_or_expr CONDOP assignment_expr COLON assignment_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.Conditional( predicate=p[1], consequent=p[3], alternative=p[5])
def p_assignment_expr(self, p): """ assignment_expr \ : conditional_expr | left_hand_side_expr assignment_operator assignment_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.Assign(left=p[1], op=p[2], right=p[3])
def p_expr(self, p): """expr : assignment_expr | expr COMMA assignment_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.Comma(left=p[1], right=p[3])
def p_expr_noin(self, p): """expr_noin : assignment_expr_noin | expr_noin COMMA assignment_expr_noin """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.Comma(left=p[1], right=p[3])
def p_expr_nobf(self, p): """expr_nobf : assignment_expr_nobf | expr_nobf COMMA assignment_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.Comma(left=p[1], right=p[3])
def p_variable_declaration(self, p): """variable_declaration : identifier | identifier initializer """ if len(p) == 2: p[0] = ast.VarDecl(p[1]) else: p[0] = ast.VarDecl(p[1], p[2])
def p_variable_declaration_noin(self, p): """variable_declaration_noin : identifier | identifier initializer_noin """ if len(p) == 2: p[0] = ast.VarDecl(p[1]) else: p[0] = ast.VarDecl(p[1], p[2])
def p_if_statement_1(self, p): """if_statement : IF LPAREN expr RPAREN statement""" p[0] = ast.If(predicate=p[3], consequent=p[5])
def p_if_statement_2(self, p): """if_statement : IF LPAREN expr RPAREN statement ELSE statement""" p[0] = ast.If(predicate=p[3], consequent=p[5], alternative=p[7])
def p_iteration_statement_1(self, p): """ iteration_statement \ : DO statement WHILE LPAREN expr RPAREN SEMI | DO statement WHILE LPAREN expr RPAREN auto_semi """ p[0] = ast.DoWhile(predicate=p[5], statement=p[2])
def p_iteration_statement_2(self, p): """iteration_statement : WHILE LPAREN expr RPAREN statement""" p[0] = ast.While(predicate=p[3], statement=p[5])
def p_iteration_statement_3(self, p): """ iteration_statement \ : FOR LPAREN expr_noin_opt SEMI expr_opt SEMI expr_opt RPAREN \ statement | FOR LPAREN VAR variable_declaration_list_noin SEMI expr_opt SEMI\ expr_opt RPAREN statement """ if len(p) == 10: p[0] = ast.For(init=p[3], cond=p[5], count=p[7], statement=p[9]) el...
def p_iteration_statement_4(self, p): """ iteration_statement \ : FOR LPAREN left_hand_side_expr IN expr RPAREN statement """ p[0] = ast.ForIn(item=p[3], iterable=p[5], statement=p[7])
def p_iteration_statement_5(self, p): """ iteration_statement : \ FOR LPAREN VAR identifier IN expr RPAREN statement """ p[0] = ast.ForIn(item=ast.VarDecl(p[4]), iterable=p[6], statement=p[8])
def p_iteration_statement_6(self, p): """ iteration_statement \ : FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement """ p[0] = ast.ForIn(item=ast.VarDecl(identifier=p[4], initializer=p[5]), iterable=p[7], statement=p[9])
def p_with_statement(self, p): """with_statement : WITH LPAREN expr RPAREN statement""" p[0] = ast.With(expr=p[3], statement=p[5])
def p_switch_statement(self, p): """switch_statement : SWITCH LPAREN expr RPAREN case_block""" cases = [] default = None # iterate over return values from case_block for item in p[5]: if isinstance(item, ast.Default): default = item elif isinstance(item, list): cases.extend(item) p[0] = ast.Switch(expr=p[3], cases=case...
def p_case_clause(self, p): """case_clause : CASE expr COLON source_elements""" p[0] = ast.Case(expr=p[2], elements=p[4])
def p_labelled_statement(self, p): """labelled_statement : identifier COLON statement""" p[0] = ast.Label(identifier=p[1], statement=p[3])
def p_try_statement_1(self, p): """try_statement : TRY block catch""" p[0] = ast.Try(statements=p[2], catch=p[3])
def p_try_statement_2(self, p): """try_statement : TRY block finally""" p[0] = ast.Try(statements=p[2], fin=p[3])