Copies the trace frame from 'graph' to this (self) graph.
        Also copies all the trace_frame-leaf assocs since we don't
        know which ones are needed until we know the issue that reaches it
177603
def _add_trace_frame(self, graph: TraceGraph, trace_frame: TraceFrame) -> None:
        
        trace_frame_id = trace_frame.id.local_id
        self.add_trace_frame(trace_frame)
        self._populate_shared_text(graph, trace_frame.filename_id)
        self._populate_shared_text(graph, trace_frame.caller_id)
        self._populate_shared_text(graph, trace_frame.callee_id)
        for (leaf_id, depth) in graph._trace_frame_leaf_assoc[trace_frame_id]:
            leaf = graph._shared_texts[leaf_id]
            if leaf_id not in self._shared_texts:
                self.add_shared_text(leaf)
            self.add_trace_frame_leaf_assoc(trace_frame, leaf, depth)
692939
private void visitFrameAfterOnMethodEntry() {
        if (!visitFramesAfterCallbacks)
            return;

        // The frame that is required after the trace guard must be
        // fully specified as 'this' is no longer an 'uninitialized this'
        if (isConstructor()) {
            List<Object> stackLocals = new ArrayList<Object>(argTypes.length + 1);
            stackLocals.add(classAdapter.getClassType().getInternalName());
            for (Type type : argTypes) {
                switch (type.getSort()) {
                    case Type.ARRAY:
                    case Type.OBJECT:
                        stackLocals.add(type.getInternalName());
                        break;
                    case Type.BOOLEAN:
                    case Type.CHAR:
                    case Type.BYTE:
                    case Type.SHORT:
                    case Type.INT:
                        stackLocals.add(INTEGER);
                        break;
                    case Type.LONG:
                        stackLocals.add(LONG);
                        break;
                    case Type.FLOAT:
                        stackLocals.add(FLOAT);
                        break;
                    case Type.DOUBLE:
                        stackLocals.add(DOUBLE);
                        break;
                }
            }
            visitFrame(F_FULL, stackLocals.size(), stackLocals.toArray(), 0, new Object[] {});
            visitInsn(NOP);
        } else {
            visitFrame(F_SAME, 0, null, 0, null);
            visitInsn(NOP);
        }
    }
1337973
def export_model(self):
        

        with self.graph.as_default():
            target_nodes = ','.join(self._process_graph())
            ckpt = tf.train.get_checkpoint_state(self.model_path)
            freeze_graph.freeze_graph(
                input_graph=self.model_path + '/raw_graph_def.pb',
                input_binary=True,
                input_checkpoint=ckpt.model_checkpoint_path,
                output_node_names=target_nodes,
                output_graph=(self.model_path + '/frozen_graph_def.pb'),
                clear_devices=True, initializer_nodes='', input_saver='',
                restore_op_name='save/restore_all',
                filename_tensor_name='save/Const:0')

        tf2bc.convert(self.model_path + '/frozen_graph_def.pb', self.model_path + '.nn')
        logger.info('Exported ' + self.model_path + '.nn file')
1070579
def _group_trace_frames(
        self, trace_frames: Iterable[TraceFrameQueryResult], limit: int
    ) -> Dict[Tuple[str, str], List[TraceFrameQueryResult]]:
        
        # pyre-fixme[9]: caller_buckets has type `DefaultDict[Tuple[str, str], List[T...
        caller_buckets: DefaultDict[
            Tuple[str, str], List[TraceFrameQueryResult]
        ] = defaultdict(list)
        for trace_frame in itertools.islice(trace_frames, limit):
            caller_buckets[(trace_frame.caller, trace_frame.caller_port)].append(
                trace_frame
            )
        return caller_buckets
106856
def to_graph(self):
        
        edges = set()
        for clause, target in self.edges_iter():
            for source, signature in clause:
                edges.add((source, target, signature))

        return Graph.from_tuples(edges)
1223972
function(kgraph) {
        if (kgraph) {
          zoomToFit(kgraph);
          // assign coordinates to nodes
          kgraph.children.forEach(function(n) {
            var d3node = nodes[parseInt(n.id)];
            copyProps(n, d3node);
            (n.ports || []).forEach(function(p, i) {
              copyProps(p, d3node.ports[i]);
            });
            (n.labels || []).forEach(function(l, i) {
              copyProps(l, d3node.labels[i]);
            });
          });
          // edges
          kgraph.edges.forEach(function(e) {
            var l = links[parseInt(e.id) - nodes.length];
            copyProps(e, l);
            copyProps(e.source, l.source);
  	        copyProps(e.target, l.target);
            // make sure the bendpoint array is valid
            l.bendPoints = e.bendPoints || [];
          });
        }
        function copyProps(src, tgt, copyKeys) {
          var keys = kgraphKeys;
          if (copyKeys) {
            keys = copyKeys.reduce(function (p, c) {p[c] = 1; return p;}, {});
          }
          for (var k in src) {
            if (keys[k]) {
              tgt[k] = src[k];
            }
          }
        }
        // invoke the 'finish' event
        dispatch.finish({graph: kgraph});
      }
632100
public static <V> void copyGraph(DirectedGraph<V, DefaultEdge> sourceGraph, DirectedGraph<V, DefaultEdge> targetGraph) {
        addAllVertices(targetGraph, sourceGraph.vertexSet());
        for (DefaultEdge edge : sourceGraph.edgeSet()) {
            targetGraph.addEdge(sourceGraph.getEdgeSource(edge), sourceGraph.getEdgeTarget(edge));
        }
    }
427823
def clone_subgraphs(self, g):
        if not isinstance(g, CGRContainer):
            raise InvalidData('only CGRContainer acceptable')

        r_group = []
        x_group = {}
        r_group_clones = []
        newcomponents = []

        ''' 
        '''
        components, lost_bonds, term_atoms = self.__split_graph(g)
        lost_map = {x: y for x, y in lost_bonds}
        ''' extract subgraphs and sort by group type (R or X)
        '''
        x_terminals = set(lost_map.values())
        r_terminals = set(lost_map)

        for i in components:
            x_terminal_atom = x_terminals.intersection(i)
            if x_terminal_atom:
                x_group[x_terminal_atom.pop()] = i
                continue

            r_terminal_atom = r_terminals.intersection(i)
            if r_terminal_atom:
                r_group.append([r_terminal_atom, i])
                continue

            newcomponents.append(i)
        ''' search similar R groups and patch.
        '''
        tmp = g
        for i in newcomponents:
            for k, j in r_group:
                gm = GraphMatcher(j, i, node_match=self.__node_match_products,
                                  edge_match=self.__edge_match_products)
                ''' search for similar R-groups started from bond breaks.
                '''
                mapping = next((x for x in gm.subgraph_isomorphisms_iter() if k.issubset(x) and
                                all(x[y] in term_atoms for y in k)), None)
                if mapping:
                    r_group_clones.append([k, mapping])
                    tmp = compose(tmp, self.__remap_group(j, tmp, mapping)[0])
                    break

        ''' add lose X groups to R groups
        '''
        for i, j in r_group_clones:
            for k in i:
                remappedgroup, mapping = self.__remap_group(x_group[lost_map[k]], tmp, {})
                tmp = CGRcore.union(tmp, remappedgroup)
                tmp.add_edge(j[k], mapping[lost_map[k]], s_bond=1, sp_bond=(1, None))

        if r_group_clones:
            tmp.meta.update(g.meta)
            return tmp

        return tmp.copy()
1141955
def copy(self, existing_inputs):
        """"""
        return PPOPolicyGraph(
            self.observation_space,
            self.action_space,
            self.config,
            existing_inputs=existing_inputs)
513642
public void attachToGraph(GraphContext graphContext)
    {
        for (IssueCategory issueCategory : this.issueCategories.values())
        {
            IssueCategoryModel model = graphContext.create(IssueCategoryModel.class);
            model.setCategoryID(issueCategory.getCategoryID());
            model.setName(issueCategory.getName());
            model.setDescription(issueCategory.getDescription());
            model.setOrigin(issueCategory.getOrigin());
            model.setPriority(issueCategory.getPriority());
        }
    }
265160
private SearchTree<VertexType> copySearchTree(SearchTree<VertexType> tree, Transpose<GraphType, EdgeType, VertexType> t) {
        // Copy this node
        SearchTree<VertexType> copy = new SearchTree<>(t.getOriginalGraphVertex(tree.getVertex()));

        // Copy children
        Iterator<SearchTree<VertexType>> i = tree.childIterator();
        while (i.hasNext()) {
            SearchTree<VertexType> child = i.next();
            copy.addChild(copySearchTree(child, t));
        }

        return copy;
    }
1236364
def copy(self):
        
        if self.debug: print("Coping....."+self.id)
        r = Runnable(self.id, self.component, self.parent)
        copies = dict()

        # Copy simulation time parameters
        r.time_step = self.time_step
        r.time_completed = self.time_completed
        r.time_total = self.time_total

        # Plasticity and state stack (?)
        r.plastic = self.plastic
        r.state_stack = Stack()
        
        # Copy variables (GG - Faster using the add_* methods?)
        for v in self.instance_variables:
            r.instance_variables.append(v)
            r.__dict__[v] = self.__dict__[v]
            r.__dict__[v + '_shadow'] = self.__dict__[v + '_shadow']
        
        for v in self.derived_variables:
            r.derived_variables.append(v)
            r.__dict__[v] = self.__dict__[v]
            r.__dict__[v + '_shadow'] = self.__dict__[v + '_shadow']
        
        # Copy array elements
        for child in self.array:
            child_copy = child.copy()
            child_copy.parent = r
            r.array.append(child_copy)
            copies[child.uid] = child_copy
            
        # Copy attachment def
        for att in self.attachments:
            atn = self.attachments[att]
            r.attachments[att] = atn
            r.__dict__[atn] = []

        # Copy children
        for uid in self.uchildren:
            child = self.uchildren[uid]
            child_copy = child.copy()
            child_copy.parent = r
            copies[child.uid] = child_copy
            
            r.add_child(child_copy.id, child_copy)

            # For typerefs
            try:
                idx = [k for k in self.__dict__ if self.__dict__[k] == child][0]
                r.__dict__[idx] = child_copy
            except:
                pass

            # For groups and attachments:
            try:
                idx = [k for k in self.__dict__ if child in self.__dict__[k]][0]
                if idx not in r.__dict__:
                    r.__dict__[idx] = []
                r.__dict__[idx].append(child_copy)

            except:
                pass
               
        # Copy event ports
        for port in self.event_in_ports:
            r.event_in_ports.append(port)
            r.event_in_counters[port] = 0

        for port in self.event_out_ports:
            r.event_out_ports.append(port)
            r.event_out_callbacks[port] = self.event_out_callbacks[port]
        
        for ec in r.component.structure.event_connections:
            if self.debug: print("--- Fixing event_connection: %s in %s"%(ec.toxml(), id(r)))
            
            source = r.parent.resolve_path(ec.from_)
            target = r.parent.resolve_path(ec.to)
            
            if ec.receiver:
                # Will throw error...
                receiver_template = self.build_runnable(ec.receiver, target)                                
                #receiver = copy.deepcopy(receiver_template)
                receiver = receiver_template.copy()
                receiver.id = "{0}__{1}__".format(component.id,
                                                  receiver_template.id)

                if ec.receiver_container:
                    target.add_attachment(receiver, ec.receiver_container)
                target.add_child(receiver_template.id, receiver)
                target = receiver
            else:
                source = r.resolve_path(ec.from_)
                target = r.resolve_path(ec.to)

            source_port = ec.source_port
            target_port = ec.target_port

            if not source_port:
                if len(source.event_out_ports) == 1:
                    source_port = source.event_out_ports[0]
                else:
                    raise SimBuildError(("No source event port "
                                         "uniquely identifiable"
                                         " in '{0}'").format(source.id))
            if not target_port:
                if len(target.event_in_ports) == 1:
                    target_port = target.event_in_ports[0]
                else:
                    raise SimBuildError(("No destination event port "
                                         "uniquely identifiable "
                                         "in '{0}'").format(target))
             
            if self.debug: print("register_event_out_callback\n   Source: %s, %s (port: %s) \n   -> %s, %s (port: %s)"%(source, id(source), source_port, target, id(target), target_port))
            source.register_event_out_callback(\
                source_port, lambda: target.inc_event_in(target_port))
            
        
            

        # Copy methods
        if getattr(self, "update_kinetic_scheme", None): r.update_kinetic_scheme = self.update_kinetic_scheme
        if getattr(self, "run_startup_event_handlers", None): r.run_startup_event_handlers = self.run_startup_event_handlers
        if getattr(self, "run_preprocessing_event_handlers", None): r.run_preprocessing_event_handlers = self.run_preprocessing_event_handlers
        if getattr(self, "run_postprocessing_event_handlers", None): r.run_postprocessing_event_handlers = self.run_postprocessing_event_handlers
        
        if getattr(self, "update_state_variables", None): r.update_state_variables = self.update_state_variables
        if getattr(self, "update_derived_variables", None): r.update_derived_variables = self.update_derived_variables
        #r.update_shadow_variables = self.update_shadow_variables
        if getattr(self, "update_derived_parameters", None): r.update_derived_parameters = self.update_derived_parameters

        for rn in self.regimes:
            r.add_regime(self.regimes[rn])
        r.current_regime = self.current_regime

        # Copy groups
        for gn in self.groups:
            g = self.__dict__[gn]
            for c in g:
                if c.uid in copies:
                    r.add_child_to_group(gn, copies[c.uid])
                else:
                    c2 = c.copy()
                    c2.parent = r
                    copies[c.uid] = c2
                    r.add_child_to_group(gn, c2)
                    

        # Copy remaining runnable references.
        for k in self.__dict__:
            if k == 'parent':
                continue
            c = self.__dict__[k]
            if isinstance(c, Runnable):
                if c.uid in copies:
                    r.__dict__[k] = copies[c.uid]
                else:
                    c2 = c.copy()
                    c2.parent = r
                    copies[c.uid] = c2
                    r.__dict__[k] = c2
           
        # Copy text fields
        for k in self.__dict__:          
            if not k in r.__dict__:
                c = self.__dict__[k]
                if self.debug: print("Adding remaining field: %s = %s"%(k,c))
                r.__dict__[k] = c
                
        if self.debug:
            print('########################################')
            keys = list(self.__dict__.keys())
            keys.sort()
            print(len(keys))
            for k in keys:
                print(k, self.__dict__[k])
            print('----------------------------------------')
            keys = list(r.__dict__.keys())
            keys.sort()
            print(len(keys))
            for k in keys:
                print(k, r.__dict__[k])
            print('########################################')
            print('')
            print('')
            print('')
            print('')
            
        if self.debug: print("Finished coping..."+self.id)
        
        return r
530233
def graph(self, ig):
        

        res = copy.copy(self)
        res._edges = ig
        res._nodes = None
        return res
1145500
def _next_trace_frames(
        self,
        session: Session,
        trace_frame: TraceFrameQueryResult,
        visited_ids: Set[int],
        backwards: bool = False,
    ) -> List[TraceFrameQueryResult]:
        
        query = (
            session.query(
                TraceFrame.id,
                TraceFrame.caller_id,
                CallerText.contents.label("caller"),
                TraceFrame.caller_port,
                TraceFrame.callee_id,
                CalleeText.contents.label("callee"),
                TraceFrame.callee_port,
                TraceFrame.callee_location,
                TraceFrame.kind,
                FilenameText.contents.label("filename"),
                TraceFrameLeafAssoc.trace_length,
            )
            .filter(TraceFrame.run_id == self.current_run_id)
            .filter(TraceFrame.kind == trace_frame.kind)
            .join(CallerText, CallerText.id == TraceFrame.caller_id)
            .join(CalleeText, CalleeText.id == TraceFrame.callee_id)
            .join(FilenameText, FilenameText.id == TraceFrame.filename_id)
            .filter(
                TraceFrame.caller_id != TraceFrame.callee_id
            )  # skip recursive calls for now
        )
        if backwards:
            query = query.filter(TraceFrame.callee_id == trace_frame.caller_id).filter(
                TraceFrame.callee_port == trace_frame.caller_port
            )
        else:
            query = query.filter(TraceFrame.caller_id == trace_frame.callee_id).filter(
                TraceFrame.caller_port == trace_frame.callee_port
            )

        results = (
            query.join(
                TraceFrameLeafAssoc, TraceFrameLeafAssoc.trace_frame_id == TraceFrame.id
            )
            .group_by(TraceFrame.id)
            .order_by(TraceFrameLeafAssoc.trace_length, TraceFrame.callee_location)
        )
        filter_leaves = (
            self.sources if trace_frame.kind == TraceKind.POSTCONDITION else self.sinks
        )

        filtered_results = []
        for frame in results:
            if int(frame.id) not in visited_ids and filter_leaves.intersection(
                set(
                    self._get_leaves_trace_frame(
                        session,
                        int(frame.id),
                        self._trace_kind_to_shared_text_kind(frame.kind),
                    )
                )
            ):
                filtered_results.append(frame)

        return filtered_results
854917
def dump(self):
        
        result = collections.deque()

        for node_name in self.graph.nodes_geometry:
            transform, geometry_name = self.graph[node_name]

            current = self.geometry[geometry_name].copy()
            current.apply_transform(transform)
            result.append(current)
        return np.array(result)
359371
def copy(self):
        
        copied = TransformForest()
        copied.base_frame = copy.deepcopy(self.base_frame)
        copied.transforms = copy.deepcopy(self.transforms)

        return copied
1233920
private void initHelperGraph() {

        int[] backPropOrder = origGraph.topologicalSortOrder().clone();
        ArrayUtils.reverse(backPropOrder);

        Set<String> allFrozen = new HashSet<>();
        if (applyFrozen) {
            Collections.addAll(allFrozen, frozenOutputAt);
        }
        for (int i = 0; i < backPropOrder.length; i++) {
            org.deeplearning4j.nn.graph.vertex.GraphVertex gv = origGraph.getVertices()[backPropOrder[i]];
            if (applyFrozen && allFrozen.contains(gv.getVertexName())) {
                if (gv.hasLayer()) {
                    //Need to freeze this layer
                    org.deeplearning4j.nn.api.Layer l = gv.getLayer();
                    gv.setLayerAsFrozen();

                    //We also need to place the layer in the CompGraph Layer[] (replacing the old one)
                    //This could no doubt be done more efficiently
                    org.deeplearning4j.nn.api.Layer[] layers = origGraph.getLayers();
                    for (int j = 0; j < layers.length; j++) {
                        if (layers[j] == l) {
                            layers[j] = gv.getLayer(); //Place the new frozen layer to replace the original layer
                            break;
                        }
                    }
                }

                //Also: mark any inputs as to be frozen also
                VertexIndices[] inputs = gv.getInputVertices();
                if (inputs != null && inputs.length > 0) {
                    for (int j = 0; j < inputs.length; j++) {
                        int inputVertexIdx = inputs[j].getVertexIndex();
                        String alsoFreeze = origGraph.getVertices()[inputVertexIdx].getVertexName();
                        allFrozen.add(alsoFreeze);
                    }
                }
            } else {
                if (gv.hasLayer()) {
                    if (gv.getLayer() instanceof FrozenLayer) {
                        allFrozen.add(gv.getVertexName());
                        //also need to add parents to list of allFrozen
                        VertexIndices[] inputs = gv.getInputVertices();
                        if (inputs != null && inputs.length > 0) {
                            for (int j = 0; j < inputs.length; j++) {
                                int inputVertexIdx = inputs[j].getVertexIndex();
                                String alsoFrozen = origGraph.getVertices()[inputVertexIdx].getVertexName();
                                allFrozen.add(alsoFrozen);
                            }
                        }
                    }
                }
            }
        }
        for (int i = 0; i < backPropOrder.length; i++) {
            org.deeplearning4j.nn.graph.vertex.GraphVertex gv = origGraph.getVertices()[backPropOrder[i]];
            String gvName = gv.getVertexName();
            //is it an unfrozen vertex that has an input vertex that is frozen?
            if (!allFrozen.contains(gvName) && !gv.isInputVertex()) {
                VertexIndices[] inputs = gv.getInputVertices();
                for (int j = 0; j < inputs.length; j++) {
                    int inputVertexIdx = inputs[j].getVertexIndex();
                    String inputVertex = origGraph.getVertices()[inputVertexIdx].getVertexName();
                    if (allFrozen.contains(inputVertex)) {
                        frozenInputVertices.add(inputVertex);
                    }
                }
            }
        }

        TransferLearning.GraphBuilder builder = new TransferLearning.GraphBuilder(origGraph);
        for (String toRemove : allFrozen) {
            if (frozenInputVertices.contains(toRemove)) {
                builder.removeVertexKeepConnections(toRemove);
            } else {
                builder.removeVertexAndConnections(toRemove);
            }
        }

        Set<String> frozenInputVerticesSorted = new HashSet<>();
        frozenInputVerticesSorted.addAll(origGraph.getConfiguration().getNetworkInputs());
        frozenInputVerticesSorted.removeAll(allFrozen);
        //remove input vertices - just to add back in a predictable order
        for (String existingInput : frozenInputVerticesSorted) {
            builder.removeVertexKeepConnections(existingInput);
        }
        frozenInputVerticesSorted.addAll(frozenInputVertices);
        //Sort all inputs to the computation graph - in order to have a predictable order
        graphInputs = new ArrayList(frozenInputVerticesSorted);
        Collections.sort(graphInputs);
        for (String asInput : frozenInputVerticesSorted) {
            //add back in the right order
            builder.addInputs(asInput);
        }
        unFrozenSubsetGraph = builder.build();
        copyOrigParamsToSubsetGraph();
        //unFrozenSubsetGraph.setListeners(origGraph.getListeners());

        if (frozenInputVertices.isEmpty()) {
            throw new IllegalArgumentException("No frozen layers found");
        }

    }