Parses graph_ent and graph_ret events that were inserted by the Linux
kernel's function graph trace.
@constructor
964139
function KernelFuncParser(importer) {
    LinuxPerfParser.call(this, importer);

    importer.registerEventHandler('graph_ent',
        KernelFuncParser.prototype.traceKernelFuncEnterEvent.
            bind(this));
    importer.registerEventHandler('graph_ret',
        KernelFuncParser.prototype.traceKernelFuncReturnEvent.
            bind(this));

    this.model_ = importer.model_;
    this.ppids_ = {};
  }
1151975
function initVivaGraph(){
    g = Viva.Graph.graph();
    isPaused = false;

    divGraph = document.getElementById('divGraph');

    $('#divGraph').append("<div id='loadingText' class='hero-body has-text-centered'><h1 class='title'>Loading...</h1></div>");

    console.time("nodesFromMWG");
    graph.indexes(WORLD, TIME, function (indexNames) {
        var defer = graph.newCounter(indexNames.length);
        for (var i = 0; i < indexNames.length; ++i) {
            const indexName = indexNames[i];
            /*graph.getIndexNode(WORLD, TIME, indexName, function (node) {
             console.log(node.toString());
             });*/
            graph.findAll(WORLD, TIME, indexName, function (nodes) {
                // transform every mwg nodes and add them to a global array
                for (var j = 0; j < nodes.length; ++j){
                    addToGlobalNodes(nodes[j]);
                }
                defer.count();
            });
        }

        defer.then(function() {
            console.timeEnd("nodesFromMWG");
            console.time("nodesToVivagraph");
            // add only 'nbNodesToDisplay' nodes to the graph
            var nbNodesToDisplay = (gAllNodes.length > NB_NODES_TO_DISPLAY ? NB_NODES_TO_DISPLAY : gAllNodes.length);
            for (var i = 0; i < nbNodesToDisplay; ++i){
                addNodeToGraph(gAllNodes[i]);
            }
            for (var i = 0; i < gNodesWithRel.length; ++i){
                addRelToGraph(gNodesWithRel[i]);
            }
            gRootNodes = _.difference(gAllNodes, gChildrenNodes);
            createTree();
            var maxChildNodes = getMaxChildNodes();
            console.timeEnd("nodesToVivagraph");

            console.time("rendering+loading");
            graphics = Viva.Graph.View.webglGraphics();
            graphics
                .node(function(node){
                    return Viva.Graph.View.webglSquare(NODE_SIZE, colorsByNodeType[node.data._type]);
                })
                .link(function(link) {
                    return Viva.Graph.View.webglLine(colorsByLinkType[link.data]);
                });

            var events = Viva.Graph.webglInputEvents(graphics, g);

            events.mouseEnter(function (vivagraphNode) {
                /*var nodeUI = graphics.getNodeUI(vivagraphNode.id);
                 nodeUI.color = '0x00BFFFFF';
                 renderer.rerender();*/
            }).mouseLeave(function (vivagraphNode) {
                /* var nodeUI = graphics.getNodeUI(vivagraphNode.id);
                 nodeUI.color = hexColorToWebGLColor(colorsByNodeType[vivagraphNode.data._type]);
                 renderer.rerender();*/
            }).dblClick(function (vivagraphNode) {
                drawNodeContext(vivagraphNode.data._id, NB_HOPS);
            }).click(function (vivagraphNode) {
                highlightNodeWebGL(vivagraphNode.data);
                displayNameDOM(vivagraphNode.data);
                globalFunc.setNodeDetailOnClick(vivagraphNode.data);
            });

            //TODO : slow things really badly
            /*
             graphics.placeNode(function(ui, pos){
             var label = $('.nodeLabel');
             if (label.length){
             var nodePos = layout.getNodePosition(label.attr('id'));
             var domPos = {
             x: nodePos.x,
             y: nodePos.y
             };

             graphics.transformGraphToClientCoordinates(domPos);
             label.css({'left' : domPos.x, 'top' : domPos.y});

             //hide label if it goes out of the divGraph layout
             if (domPos.x < 0 || domPos.y < 0) {
             label.hide();
             } else {
             label.show();
             }
             }
             });
             */

            console.time("loading data in components");
            // Load the necessary stuff (nodes) in the react components
            globalFunc.addNodesInList();
            globalFunc.setTypesInList();
            globalFunc.loadRootNodesInTree();
            globalFunc.loadTree();
            console.timeEnd("loading data in components");

            var springLength = 200;
            var displayedChildNodes = Math.ceil(maxChildNodes / (gAllNodes.length / nbNodesToDisplay));
            var springLengthCoeff = (displayedChildNodes <= 250 ? 1 : displayedChildNodes / 250);
            layout = Viva.Graph.Layout.forceDirected(g, {
                springLength : springLength * springLengthCoeff,
                springCoeff : 0.0008,
                dragCoeff : 0.02
            });

            renderer = Viva.Graph.View.renderer(g, {
                graphics : graphics,
                layout: layout,
                container: divGraph,
                prerender: 50
            });

            $('#loadingText').hide();

            renderer.run();
            console.timeEnd("rendering+loading");

            console.time("table+events");
            createTableLayout();
            initJQueryEvents();
            console.timeEnd("table+events");

            console.timeEnd("all");
        });
    });


}
338016
function saxParser(elem, callbacks){
	if(typeof callbacks !== 'object')
		throw 'please provide callbacks!';

	//todo: support further events, options for trim & space normalisation
	
	function parse(node){
		var name = node.tagName.toLowerCase(),
		    attributeNodes = node.attributes;
		
		callbacks.onopentagname(name);
		
		for(var i = 0, j = attributeNodes.length; i < j; i++){
			callbacks.onattribute(attributeNodes[i].name+'', attributeNodes[i].value);
		}
		
		var childs = node.childNodes,
		    num = childs.length, nodeType;
		
		for(var i = 0; i < num; i++){
			nodeType = childs[i].nodeType;
			if(nodeType === 3 /*text*/)
				callbacks.ontext(childs[i].textContent);
			else if(nodeType === 1 /*element*/) parse(childs[i]);
			/*else if(nodeType === 8) //comment
				if(callbacks.oncomment) callbacks.oncomment(childs[i].toString());
			[...]
			*/
		}
		callbacks.onclosetag(name);
	}
	
	parse(elem);
}
1004369
function parse(c) {

  let ret = [];

  // replace windows line breaks with linux line breaks
  let c1 = c.replace(new RegExp('[\r][\n]', 'g'), '\n');

  // split string to line array
  let c2 = c1.split('\n');

  for (let i = 0; i < c2.length; i++) {

    //line object
    let lo = {};

    // line
    let l = c2[i];

    // trim line
    let l1 = l.trim();

    // set line number
    lo.num = i + 1;

    // set original line
    lo.content = l1;

    // check empty line
    if (l1 === '') {
      lo.isEmpty = true;
    } else {
      lo.isEmpty = false;

      // check line comment
      if (l1.startsWith('#')) {
        lo.isComment = true;
        lo.comment = lo.content.substring(1,lo.content.length).trim();
      } else {
        lo.isComment = false;

        // Check included comments
        lo = Object.assign(lo, checkComment(l1));

        // check key value
        lo = Object.assign(lo, checkKeyValue(lo.contentWithoutComment));

        // check block key
        lo = Object.assign(lo, checkBlockKey(lo));
        
    
      }
    }

    //console.log(lo);

    ret.push(lo);
  }

  checkBlockEndSum(ret);
  determineDepth(ret);

  return ret;
}
1113385
function visit(rootNodes, graph) {
    const result = {};
    const queue = rootNodes;
    rootNodes.forEach((node) => {
        result[node] = true;
    });
    while (queue.length > 0) {
        const el = queue.shift();
        const myEdges = graph[el] || [];
        myEdges.forEach((toNode) => {
            if (!result[toNode]) {
                result[toNode] = true;
                queue.push(toNode);
            }
        });
    }
    return result;
}
833130
def parse(self, data):
        
        graph = self._init_graph()
        if 'topology' not in data:
            raise ParserError('Parse error, "topology" key not found')
        elif 'mid' not in data:
            raise ParserError('Parse error, "mid" key not found')

        # determine version and revision
        if 'config' in data:
            version_info = data['config']['olsrdVersion'].replace(' ', '').split('-')
            self.version = version_info[1]
            # try to get only the git hash
            if 'hash_' in version_info[-1]:
                version_info[-1] = version_info[-1].split('hash_')[-1]
            self.revision = version_info[-1]

        # process alias list
        alias_dict = {}
        for node in data['mid']:
            local_addresses = [alias['ipAddress'] for alias in node['aliases']]
            alias_dict[node['ipAddress']] = local_addresses

        # loop over topology section and create networkx graph
        for link in data['topology']:
            try:
                source = link['lastHopIP']
                target = link['destinationIP']
                cost = link['tcEdgeCost']
                properties = {
                    'link_quality': link['linkQuality'],
                    'neighbor_link_quality': link['neighborLinkQuality']
                }
            except KeyError as e:
                raise ParserError('Parse error, "%s" key not found' % e)
            # add nodes with their local_addresses
            for node in [source, target]:
                if node not in alias_dict:
                    continue
                graph.add_node(node, local_addresses=alias_dict[node])
            # skip links with infinite cost
            if cost == float('inf'):
                continue
            # original olsrd cost (jsoninfo multiplies by 1024)
            cost = float(cost) / 1024.0
            # add link to Graph
            graph.add_edge(source, target, weight=cost, **properties)
        return graph
662719
function ParserContent () {
	// Parser reference
	var self = this
	// Current row
	var data = []

	// Define the parser rules
	var eol = ['\n','\r\n']
	var sep = options.separator || ','
	// Handlers are used instead of events
	atok
	    // Ignore comments
	    .ignore(true) // On rule match, do not do anything, skip the token
	        .addRule('#', eol, 'comment')
	    .ignore() // Turn the ignore property off
	    // Anything else is data
	    // Rule definition:
	    // first argument: always an exact match. To match anything, use ''
	    // next arguments: array of possible matches (first match wins)
	    .addRule('', { firstOf: [ sep ].concat(eol) }, function (token, idx) {
	        // token=the matched data
	        // idx=when using array of patterns, the index of the matched pattern
	        if (token === 'error') {
	            // Build the error message using positioning
	            var err = self.trackError(new Error('Dummy message'), token)
	            self.emit('error', err)
	            return
	        }
	        // Add the data
	        data.push(token)
	        // EOL reached, the parser emits the row
	        if (idx > 0) {
	            self.emit('data', data)
	            data = []
	        }
	    })
}
510239
function() {
      var logreader = new tr.e.importer.v8.LogReader(
          { 'timer-event' : {
            parsers: [null, parseInt, parseInt],
            processor: this.processTimerEvent_.bind(this)
          },
          'shared-library': {
            parsers: [null, parseInt, parseInt],
            processor: this.processSharedLibrary_.bind(this)
          },
          'timer-event-start' : {
            parsers: [null, parseInt],
            processor: this.processTimerEventStart_.bind(this)
          },
          'timer-event-end' : {
            parsers: [null, parseInt],
            processor: this.processTimerEventEnd_.bind(this)
          },
          'code-creation': {
            parsers: [null, parseInt, parseInt, parseInt, null],
            processor: this.processCodeCreateEvent_.bind(this)
          },
          'code-move': {
            parsers: [parseInt, parseInt],
            processor: this.processCodeMoveEvent_.bind(this)
          },
          'code-delete': {
            parsers: [parseInt],
            processor: this.processCodeDeleteEvent_.bind(this)
          },
          'tick': {
            parsers: [parseInt, parseInt, null, null, parseInt, 'var-args'],
            processor: this.processTickEvent_.bind(this)
          },
          'distortion': {
            parsers: [parseInt],
            processor: this.processDistortion_.bind(this)
          },
          'plot-range': {
            parsers: [parseInt, parseInt],
            processor: this.processPlotRange_.bind(this)
          },
          'v8-version': {
            parsers: [parseInt, parseInt, parseInt, parseInt, parseInt],
            processor: this.processV8Version_.bind(this)
          }
          });

      this.v8_timer_thread_ =
          this.model_.getOrCreateProcess(-32).getOrCreateThread(1);
      this.v8_timer_thread_.name = 'V8 Timers';
      this.v8_thread_ =
          this.model_.getOrCreateProcess(-32).getOrCreateThread(2);
      this.v8_thread_.name = 'V8';

      var lines = this.logData_.split('\n');
      for (var i = 0; i < lines.length; i++) {
        logreader.processLogLine(lines[i]);
      }

      // The processing of samples adds all the root stack frame to
      // this.root_stack_frame_. But, we don't want that stack frame in the real
      // model. So get rid of it.
      this.root_stack_frame_.removeAllChildren();

      function addSlices(slices, thread) {
        for (var i = 0; i < slices.length; i++) {
          var duration = slices[i].end - slices[i].start;
          var slice = new tr.model.Slice('v8', slices[i].name,
              ColorScheme.getColorIdForGeneralPurposeString(slices[i].name),
              slices[i].start, {}, duration);
          thread.sliceGroup.pushSlice(slice);
          addSlices(slices[i].children, thread);
        }
      }
      addSlices(this.v8_stack_timeline_, this.v8_thread_);
    }
442312
function parse(args) {
  const cliArgs = [];
  const nodeArgs = [];

  for (const arg of args) {
    if (NODE_FLAGS.test(arg)) {
      nodeArgs.push(arg);
    } else {
      cliArgs.push(arg);
    }
  }

  return {
    cliArgs,
    nodeArgs
  };
}
174163
def parse(self, data):
        
        # initialize graph and list of aggregated nodes
        graph = self._init_graph()
        server = self._server_common_name
        # add server (central node) to graph
        graph.add_node(server)
        # data may be empty
        if data is None:
            clients = []
            links = []
        else:
            clients = data.client_list.values()
            links = data.routing_table.values()
        # add clients in graph as nodes
        for client in clients:
            if client.common_name == 'UNDEF':
                continue
            client_properties = {
                'label': client.common_name,
                'real_address': str(client.real_address.host),
                'port': int(client.real_address.port),
                'connected_since': client.connected_since.strftime('%Y-%m-%dT%H:%M:%SZ'),
                'bytes_received': int(client.bytes_received),
                'bytes_sent': int(client.bytes_sent)
            }
            local_addresses = [
                str(route.virtual_address)
                for route in data.routing_table.values()
                if route.real_address == client.real_address
            ]
            if local_addresses:
                client_properties['local_addresses'] = local_addresses
            graph.add_node(str(client.real_address.host), **client_properties)
        # add links in routing table to graph
        for link in links:
            if link.common_name == 'UNDEF':
                continue
            graph.add_edge(server, str(link.real_address.host), weight=1)
        return graph
797171
function processFunction(funcNode) {
            const node = isEmbedded(funcNode) ? funcNode.parent : funcNode;

            if (!IIFEs && isIIFE(node)) {
                return;
            }
            let lineCount = 0;

            for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) {
                const line = lines[i];

                if (skipComments) {
                    if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) {
                        continue;
                    }
                }

                if (skipBlankLines) {
                    if (line.match(/^\s*$/u)) {
                        continue;
                    }
                }

                lineCount++;
            }

            if (lineCount > maxLines) {
                const name = astUtils.getFunctionNameWithKind(funcNode);

                context.report({
                    node,
                    messageId: "exceed",
                    data: { name, lineCount, maxLines }
                });
            }
        }
110865
function parse_children(lines, parent_node_names)
{
	// preprocess the lines (filter out comments, blank lines, etc)
	lines = filter_lines_for_parsing(lines)

	// return empty object if there are no lines to parse
	if (lines.length === 0)
	{
		return {}
	}

	// parse each child node's lines
	return split_lines_by_child_nodes(lines).map(function(lines)
	{
		// the first line is this child node's name (or names)
		const declaration_line = lines.shift()

		// check for excessive indentation of the first child style class
		if (declaration_line.tabs !== 0)
		{
			throw new Error(`Excessive indentation (${declaration_line.tabs} more "tabs" than needed) at line ${declaration_line.index}: "${declaration_line.original_line}"`)
		}

		// style class name declaration
		const declaration = declaration_line.line

		// child nodes' names
		const names = declaration.split(',').map(name => name.trim())

		// style class nesting validation
		validate_child_style_class_types(parent_node_names, names)

		// parse own CSS styles and recursively parse all child nodes
		const style_json = parse_style_class(lines, names)

		// generate style json for this child node (or child nodes)
		return names.map(function(node_declaration)
		{
			// parse this child node name
			const { name, is_a_modifier } = parse_node_name(node_declaration)

			// clone the style JSON object for this child node
			const json = extend({}, style_json)

			// set the modifier flag if it's the case
			if (is_a_modifier)
			{
				json._is_a_modifier = true
			}

			// this child node's style JSON object
			return { name, json }
		})
	})
	// convert an array of arrays to a flat array
	.reduce(function(array, child_array)
	{
		return array.concat(child_array);
	}, 
	[])
	// combine all the child nodes into a single JSON object
	.reduce(function(nodes, node)
	{
		// if style already exists for this child node, extend it
		if (nodes[node.name])
		{
			extend(nodes[node.name], node.json)
		}
		else
		{
			nodes[node.name] = node.json
		}
		
		return nodes
	}, 
	{})
}
1153717
function Graph(directed) {
  this.directed = (directed === undefined ? true : !!directed);
  this.adjList = Object.create(null);
  this.vertices = new HashSet();
}
662581
def _parse_line(self, line):
        
        # first isolate the timestamp and the event type
        try:
            self._line_parsed = self._line_parsed + 1

            m = RE_LINE_REG.match(line)
            if m is None:
                m = RE_LINE_EXT.match(line)
            if m is None:
                return False
            self.log.debug("Matching line found %s" % line)
            (tstamp, event_type, remainder) = m.groups()
            tstamp = int(tstamp)

            # skip passive checks reports by default for spamminess
            if event_type == 'PASSIVE SERVICE CHECK' and not self.passive_checks:
                return False
            # then retrieve the event format for each specific event type
            fields = EVENT_FIELDS.get(event_type, None)
            if fields is None:
                self.log.warning("Ignoring unknown nagios event for line: %s" % (line[:-1]))
                return False
            elif fields is False:
                # Ignore and skip
                self.log.debug("Ignoring Nagios event for line: %s" % (line[:-1]))
                return False

            # and parse the rest of the line
            parts = [p.strip() for p in remainder.split(';')]
            # Chop parts we don't recognize
            parts = parts[: len(fields._fields)]

            event = self.create_event(tstamp, event_type, self.hostname, fields._make(parts), tags=self.tags)

            self._event(event)
            self.log.debug("Nagios event: %s" % (event))

            return True
        except Exception:
            self.log.exception("Unable to create a nagios event from line: [%s]" % (line))
            return False
912301
function addParagraph()
    {
        $style = "";
        $numArgs = func_num_args();
        $argArray = func_get_args();

        if ( $numArgs > 1 )
        {
            // Check for style definition
            if ( !is_array( $argArray[0] ) )
            {
                $style = $argArray[0];
                $argArray = array_slice( $argArray, 1, count( $argArray ) -1 );
            }
        }

        if ( $numArgs > 0 and is_array( $argArray[0] ) )
        {
            $paragraphArray = array();

            foreach ( $argArray as $paragraphElement )
            {
                switch ( $paragraphElement[0] )
                {
                    case self::TEXT:
                    {
                        $tagContent = $paragraphElement[1];

                        $tagContent = str_replace( "&", "&amp;", $tagContent );
                        $tagContent = str_replace( ">", "&gt;", $tagContent );
                        $tagContent = str_replace( "<", "&lt;", $tagContent );
                        $tagContent = str_replace( "'", "&apos;", $tagContent );
                        $tagContent = str_replace( '"', "&quot;", $tagContent );

                        $paragraphArray[] = array( 'Type' => 'text', "Content" => $tagContent );
                    } break;

                    case self::STYLE_START:
                    {
                        if ( $paragraphElement[1] == "bold" )
                            $paragraphArray[] = array( 'Type' => 'bold_start' );
                        if ( $paragraphElement[1] == "italic" )
                            $paragraphArray[] = array( 'Type' => 'italic_start' );

                        if ( substr( $paragraphElement[1], 0, 18 ) == "eZCustominline_20_" )
                            $paragraphArray[] = array( 'Type' => 'custom_inline_start', 'Name' => $paragraphElement[1] );

                    } break;

                    case self::STYLE_STOP:
                    {
                        $paragraphArray[] = array( 'Type' => 'style_stop' );
                    } break;

                    case self::LINK:
                    {
                        $paragraphArray[] = array( 'Type' => 'link',
                                                   "Content" => $content = $paragraphElement[2],
                                                   "HREF" => $paragraphElement[1] );
                    } break;

                    case self::LINE:
                    {
                        $paragraphArray[] = array( 'Type' => 'line',
                                                   "Content" => '');
                    }break;

                    default:
                    {
                        eZDebug::writeError( "Unknown paragraph element." );
                    } break;
                }
            }
        }
        else if ( $numArgs > 0 )
        {
            // Alex 2008-06-03 - Added isset()
            $paragraphArray = array( array( 'Type' => 'text', "Content" => isset( $argArray[0] ) ? $argArray[0] : '' ) );
        }
        else
        {
            $paragraphArray = array( array( 'Type' => 'text', "Content" => '' ) );
        }

        $elementArray = array( 'Type' => 'paragraph',
                               'Style' => $style,
                               'Content' => $paragraphArray );
        $this->addElement( $elementArray );
    }
508787
function objToGraph(obj, containerName) {
    if (!containerName) containerName = 'definitions';
    let graph = [];

    for (let p in obj[containerName]) {
        let entry = {};
        entry._id = '#/'+containerName+'/'+p;
        entry.links = [];
        graph.push(entry);
    }

    recurse(obj,{identityDetection:true},function(obj,key,state){
        if (isRef(obj,key)) {
            let ptr = obj[key].replace('/$ref','');
            let spath = state.path.replace('/$ref','');
            let target = graph.find(function(e){
                return e._id === ptr;
            });
            if (target) {
                target.links.push(ptr);
            }
            else {
                target = {};
                target._id = ptr;
                target.links = [];
                target.links.push(ptr);
                graph.push(target);
            }
            let source = graph.find(function(e){
                return e._id === spath;
            });
            if (source) {
                //source.links.push(spath);
            }
            else {
                source = {};
                source._id = spath
                source.links = [];
                graph.push(source);
            }
        }
    });

    return graph;
}
893303
@Override
	public GraphRequest<JsonNode> graph(String object, Param... params) {
		return this.graph(object, JsonNode.class, params);
	}