Transfer causal edges that the source has to the target and yield the resulting hashes.
777730
def transfer_causal_edges(graph, source: BaseEntity, target: BaseEntity) -> Iterable[str]:
    """"""
    for _, v, data in graph.out_edges(source, data=True):
        if data[RELATION] not in CAUSAL_RELATIONS:
            continue

        yield graph.add_qualified_edge(
            target,
            v,
            relation=data[RELATION],
            evidence=data[EVIDENCE],
            citation=data[CITATION],
            annotations=data.get(ANNOTATIONS),
            subject_modifier=data.get(SUBJECT),
            object_modifier=data.get(OBJECT),
        )

    for u, _, data in graph.in_edges(source, data=True):
        if data[RELATION] not in CAUSAL_RELATIONS:
            continue

        yield graph.add_qualified_edge(
            u,
            target,
            relation=data[RELATION],
            evidence=data[EVIDENCE],
            citation=data[CITATION],
            annotations=data.get(ANNOTATIONS),
            subject_modifier=data.get(SUBJECT),
            object_modifier=data.get(OBJECT),
        )
1136926
def target_from_hash(hash)
      target = 0
      i = 0
      hash.each_byte do |byte|
        target += byte * (256**i)
        i += 1
      end
      target
    end
1332944
def add_edges(self, from_idx, to_idx, weight=1, symmetric=False, copy=False):
    ''''''
    raise NotImplementedError()
99222
def from_edges(edges):
        
        dag = DirectedGraph()
        for _u, _v in edges:
            dag.add_edge(_u, _v)
        return dag
249525
function nextend(target) { var sources
        sources = __slice.call(arguments, 1)
        sources.forEach(function(source) {
            keys(source).forEach(function(key) {
                target[key] = source[key] })})

        return target
    }
779480
def create_build_graph(self, target_roots, build_root=None):
    
    logger.debug('target_roots are: %r', target_roots)
    graph = LegacyBuildGraph.create(self.scheduler_session, self.build_file_aliases)
    logger.debug('build_graph is: %s', graph)
    # Ensure the entire generator is unrolled.
    for _ in graph.inject_roots_closure(target_roots):
      pass

    address_mapper = LegacyAddressMapper(self.scheduler_session, build_root or get_buildroot())
    logger.debug('address_mapper is: %s', address_mapper)
    return graph, address_mapper
684173
private byte[] generateDeterministicHash(
			StreamNode node,
			Hasher hasher,
			Map<Integer, byte[]> hashes,
			boolean isChainingEnabled,
			StreamGraph streamGraph) {

		// Include stream node to hash. We use the current size of the computed
		// hashes as the ID. We cannot use the node's ID, because it is
		// assigned from a static counter. This will result in two identical
		// programs having different hashes.
		generateNodeLocalHash(hasher, hashes.size());

		// Include chained nodes to hash
		for (StreamEdge outEdge : node.getOutEdges()) {
			if (isChainable(outEdge, isChainingEnabled, streamGraph)) {

				// Use the hash size again, because the nodes are chained to
				// this node. This does not add a hash for the chained nodes.
				generateNodeLocalHash(hasher, hashes.size());
			}
		}

		byte[] hash = hasher.hash().asBytes();

		// Make sure that all input nodes have their hash set before entering
		// this loop (calling this method).
		for (StreamEdge inEdge : node.getInEdges()) {
			byte[] otherHash = hashes.get(inEdge.getSourceId());

			// Sanity check
			if (otherHash == null) {
				throw new IllegalStateException("Missing hash for input node "
						+ streamGraph.getSourceVertex(inEdge) + ". Cannot generate hash for "
						+ node + ".");
			}

			for (int j = 0; j < hash.length; j++) {
				hash[j] = (byte) (hash[j] * 37 ^ otherHash[j]);
			}
		}

		if (LOG.isDebugEnabled()) {
			String udfClassName = "";
			if (node.getOperator() instanceof AbstractUdfStreamOperator) {
				udfClassName = ((AbstractUdfStreamOperator<?, ?>) node.getOperator())
						.getUserFunction().getClass().getName();
			}

			LOG.debug("Generated hash '" + byteToHexString(hash) + "' for node " +
					"'" + node.toString() + "' {id: " + node.getId() + ", " +
					"parallelism: " + node.getParallelism() + ", " +
					"user function: " + udfClassName + "}");
		}

		return hash;
	}
1172091
def _inject_synthetic_target(self, vt, sources):
    
    target = vt.target

    # NB: For stability, the injected target exposes the stable-symlinked `vt.results_dir`,
    # rather than the hash-named `vt.current_results_dir`.
    synthetic_target_dir = self.synthetic_target_dir(target, vt.results_dir)
    synthetic_target_type = self.synthetic_target_type(target)
    synthetic_extra_dependencies = self.synthetic_target_extra_dependencies(target, synthetic_target_dir)

    copied_attributes = {}
    for attribute in self._copy_target_attributes:
      copied_attributes[attribute] = getattr(target, attribute)

    if self._supports_exports(synthetic_target_type):
      extra_exports = self.synthetic_target_extra_exports(target, synthetic_target_dir)

      extra_exports_not_in_extra_dependencies = set(extra_exports).difference(
        set(synthetic_extra_dependencies))
      if len(extra_exports_not_in_extra_dependencies) > 0:
        raise self.MismatchedExtraExports(
          'Extra synthetic exports included targets not in the extra dependencies: {}. Affected target: {}'
            .format(extra_exports_not_in_extra_dependencies, target))

      extra_export_specs = {e.address.spec for e in extra_exports}
      original_export_specs = self._original_export_specs(target)
      union = set(original_export_specs).union(extra_export_specs)

      copied_attributes['exports'] = sorted(union)

    synthetic_target = self.context.add_new_target(
      address=self._get_synthetic_address(target, synthetic_target_dir),
      target_type=synthetic_target_type,
      dependencies=synthetic_extra_dependencies,
      sources=sources,
      derived_from=target,
      **copied_attributes
    )

    build_graph = self.context.build_graph
    # NB(pl): This bypasses the convenience function (Target.inject_dependency) in order
    # to improve performance.  Note that we can walk the transitive dependee subgraph once
    # for transitive invalidation rather than walking a smaller subgraph for every single
    # dependency injected.
    for dependent_address in build_graph.dependents_of(target.address):
      build_graph.inject_dependency(
        dependent=dependent_address,
        dependency=synthetic_target.address,
      )
    # NB(pl): See the above comment.  The same note applies.
    for concrete_dependency_address in build_graph.dependencies_of(target.address):
      build_graph.inject_dependency(
        dependent=synthetic_target.address,
        dependency=concrete_dependency_address,
      )

    if target in self.context.target_roots:
      self.context.target_roots.append(synthetic_target)

    return synthetic_target
1021885
def _preprocess_edges_for_pydot(edges_with_data):
    """'"""
    for (source, target, attrs) in edges_with_data:
        if 'label' in attrs:
            yield (quote_for_pydot(source), quote_for_pydot(target),
                   {'label': quote_for_pydot(attrs['label'])})
        else:
            yield (quote_for_pydot(source), quote_for_pydot(target), {})
892241
private void setChaining(Map<Integer, byte[]> hashes, List<Map<Integer, byte[]>> legacyHashes, Map<Integer, List<Tuple2<byte[], byte[]>>> chainedOperatorHashes) {
		for (Integer sourceNodeId : streamGraph.getSourceIDs()) {
			createChain(sourceNodeId, sourceNodeId, hashes, legacyHashes, 0, chainedOperatorHashes);
		}
	}
973262
def def_forward(mappings, *names)
      if mappings.instance_of? Hash
        mappings.each do |method_name, target|
          define_singleton_method method_name do |*args, &block|
            self.config = config.public_send(target, *args, &block)
          end
        end
      else
        def_forward([mappings, *names].map{|name| {name => name}}.inject(:merge))
      end
    end
48608
def _backward_slice_indirect(self, cfgnode, sim_successors, current_function_addr):
        
        # TODO: make this a real indirect jump resolver under the new paradigm

        irsb = sim_successors.artifacts['irsb']  # shorthand

        l.debug("Resolving indirect jump at IRSB %s", irsb)

        # Let's slice backwards from the end of this exit
        next_tmp = irsb.next.tmp
        stmt_id = [i for i, s in enumerate(irsb.statements)
                   if isinstance(s, pyvex.IRStmt.WrTmp) and s.tmp == next_tmp][0]

        cdg = self.project.analyses.CDG(cfg=self, fail_fast=self._fail_fast)
        ddg = self.project.analyses.DDG(cfg=self, start=current_function_addr, call_depth=0, fail_fast=self._fail_fast)

        bc = self.project.analyses.BackwardSlice(self,
                                                 cdg,
                                                 ddg,
                                                 targets=[(cfgnode, stmt_id)],
                                                 same_function=True,
                                                 fail_fast=self._fail_fast)
        taint_graph = bc.taint_graph
        # Find the correct taint
        next_nodes = [cl for cl in taint_graph.nodes() if cl.block_addr == sim_successors.addr]

        if not next_nodes:
            l.error('The target exit is not included in the slice. Something is wrong')
            return []

        next_node = next_nodes[0]

        # Get the weakly-connected subgraph that contains `next_node`
        all_subgraphs = networkx.weakly_connected_component_subgraphs(taint_graph)
        starts = set()
        for subgraph in all_subgraphs:
            if next_node in subgraph:
                # Make sure there is no symbolic read...
                # FIXME: This is an over-approximation. We should try to limit the starts more
                nodes = [n for n in subgraph.nodes() if subgraph.in_degree(n) == 0]
                for n in nodes:
                    starts.add(n.block_addr)

        # Execute the slice
        successing_addresses = set()
        annotated_cfg = bc.annotated_cfg()
        for start in starts:
            l.debug('Start symbolic execution at 0x%x on program slice.', start)
            # Get the state from our CFG
            node = self.get_any_node(start)
            if node is None:
                # Well, we have to live with an empty state
                base_state = self.project.factory.blank_state(addr=start)
            else:
                base_state = node.input_state.copy()
                base_state.set_mode('symbolic')
                base_state.ip = start

                # Clear all initial taints (register values, memory values, etc.)
                initial_nodes = [n for n in bc.taint_graph.nodes() if bc.taint_graph.in_degree(n) == 0]
                for cl in initial_nodes:
                    # Iterate in all actions of this node, and pick corresponding actions
                    cfg_nodes = self.get_all_nodes(cl.block_addr)
                    for n in cfg_nodes:
                        if not n.final_states:
                            continue
                        actions = [ac for ac in n.final_states[0].history.recent_actions
                                   # Normally it's enough to only use the first final state
                                   if ac.bbl_addr == cl.block_addr and
                                   ac.stmt_idx == cl.stmt_idx
                                   ]
                        for ac in actions:
                            if not hasattr(ac, 'action'):
                                continue
                            if ac.action == 'read':
                                if ac.type == 'mem':
                                    unconstrained_value = base_state.solver.Unconstrained('unconstrained',
                                                                                      ac.size.ast * 8)
                                    base_state.memory.store(ac.addr,
                                                            unconstrained_value,
                                                            endness=self.project.arch.memory_endness)
                                elif ac.type == 'reg':
                                    unconstrained_value = base_state.solver.Unconstrained('unconstrained',
                                                                                      ac.size.ast * 8)
                                    base_state.registers.store(ac.offset,
                                                               unconstrained_value,
                                                               endness=self.project.arch.register_endness)

                # Clear the constraints!
                base_state.release_plugin('solver')

            # For speed concerns, we are limiting the timeout for z3 solver to 5 seconds
            base_state.solver._solver.timeout = 5000

            sc = self.project.factory.simulation_manager(base_state)
            sc.use_technique(Slicecutor(annotated_cfg))
            sc.use_technique(LoopSeer(bound=1))
            sc.run()

            if sc.cut or sc.deadended:
                all_deadended_states = sc.cut + sc.deadended
                for s in all_deadended_states:
                    if s.addr == sim_successors.addr:
                        # We want to get its successors
                        succs = s.step()
                        for succ in succs.flat_successors:
                            successing_addresses.add(succ.addr)

            else:
                l.debug("Cannot determine the exit. You need some better ways to recover the exits :-(")

        l.debug('Resolution is done, and we have %d new successors.', len(successing_addresses))

        return list(successing_addresses)
1188571
def _copy_sources(self, target, results_dir):
    
    buildroot = get_buildroot()
    source_relative_to = target.address.spec_path
    for source in target.sources_relative_to_buildroot():
      dest = os.path.join(results_dir, os.path.relpath(source, source_relative_to))
      safe_mkdir(os.path.dirname(dest))
      shutil.copyfile(os.path.join(buildroot, source), dest)
576934
def get_edges_by_hashes(self, edge_hashes: List[str]) -> List[Edge]:
        """"""
        return self.session.query(Edge).filter(Edge.sha512.in_(edge_hashes)).all()
1051533
def _assemble_regulate_amount(self, stmt):
        """"""
        activates = isinstance(stmt, IncreaseAmount)
        relation = get_causal_edge(stmt, activates)
        self._add_nodes_edges(stmt.subj, stmt.obj, relation, stmt.evidence)
1154052
def get_upstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):
    
    return get_subgraph_by_edge_filter(graph, build_upstream_edge_predicate(nbunch))
1020629
def output_files(self):
        """"""
        for dep in self.subgraph.successors(self.address):
            dep_rule = self.subgraph.node[dep]['target_obj']
            for out_file in dep_rule.output_files:
                yield out_file