Menu
  • HOME
  • TAGS

How to write an Scala parser for arithmetic operations including string?

scala,parsing,arithmetic-expressions

I think you should add it to the factor alternatives: def factor: Parser[Any] = ident | floatingPointNumber | "("~expr~")" ...

parsing into std::vector with Spirit Qi, getting segfaults or assert failures

c++,parsing,boost,boost-spirit,boost-spirit-qi

You reference the symbols variables. But they are locals so they don't exist once the constructor returns. This invokes Undefined Behaviour. Anything can happen. Make the symmbol tables members of the class. Also simplifying the dance around the skippers (see Boost spirit skipper issues). That link also answers your _"When...

Text File Reading and Structuring data

python,parsing

This should print out all your ID's. I think it should move you in the right direction. with open("textfile", 'r') as part_info: lineArray = part_info.readlines() for line in lineArray: if "I.D.:" in line: ID = line.split(':')[1] print ID.strip() ...

How to parse Selenium driver elements?

python,parsing,selenium,selenium-webdriver,web-scraping

find_elements_by_css_selector() would return you a list of WebElement instances. Each web element has a number of methods and attributes available. For example, to get a inner text of the element, use .text: for element in driver.find_elements_by_css_selector("div.flightbox"): print(element.text) You can also make a context-specific search to find other elements inside the...

parse complex xml with php [maybe 2 foreach loops]?

php,xml,parsing

Somehow using simplexml $str = '<Lineups date="2015-06-11"> <Game start_time="2015-06-11 09:10:00" number="901" revised="false"> <Team number="901" name="San Diego"> <Player name="Wil Myers" position="CF"/> <Player name="Will Venable" position="LF"/> <Player name="Matt Kemp" position="RF"/> <Player name="Yonder Alonso" position="1B"/> <Player name="Derek Norris" position="C"/> <Player name="Cory Spangenberg" position="2B"/> <Player name="Will Middlebrooks" position="3B"/>...

parsing JSON files in python to get specific values

python,json,parsing,data

Json.loads will also decode that dictionary. So to access cpu_count for example it would be json_data["Hosts"]["cpu_count"]. The json library will turn everything into a standard python data type (dict, list, int, str) or from those data type into a json readable format. You can also define a parser to parse...

Issues parsing a 1GB json file using JSON.NET

json,parsing,stream,json.net,large-object-heap

Thanks for all the help, I've managed to get it doing what I want which is de-serializing individual location objects. If the item is converted to a JObject it will read in the full object and de-serialize it, this can be looped to get the solution. This is the code...

How to translate parts of source program to library calls without writing a full parser?

c,parsing,translation

There's a lot of parsing wrapper generators out there, chief among these SWIG (which is awesome, and horrible at the same time). If you can't use SWIG or something like existing parsers: I'd completely avoid changing the original code -- the C functions must be externally visible, anyway, so it's...

how to parse this in android with json

java,android,json,parsing

Okay, first of all the JSON string you've given is invalid. I've written my answer based on the correct version of the JSON string that you have provided { "head": { "link": [], "vars": ["city", "country"] }, "results": { "distinct": false, "ordered": true, "bindings": [ { "city": { "type": "uri",...

Getting error in JSON parsing with array in iOS

ios,json,parsing,nsjsonserialization

Your code here pcs.myProductCategory = [[MyProductCategory alloc] init]; pcs.myProductCategory = [item1 objectForKey:@"category"]; Is correctly creating your MyProductCategory instance, but then replacing it with a dictionary. You probably intended to write the second line as NSDictionary *category = [item1 objectForKey:@"category"]; And then use that in the next line to unpack the...

How to parse user search string for Postgresql query?

php,postgresql,parsing,full-text-search,logical-operators

Try this: $a=array('word1 +word2','word1+word2','word1 -word2',' word1-word2','word1 word2','word1 word2'); foreach ($a as &$v) { $v=preg_replace('/ +/','|', // last: change blanks to | preg_replace('/ *(?=[!&])/','', // delete blanks before ! or & strtr(trim($v),array('-'=>'&!','+'=>'&')) // turn + and - into & and !& )); } print_r($a); This will give: Array ( [0] =>...

How to reformat an int when parsing a csv (Java)

java,parsing,csv

As per your exception trace your integer contains double quotes. Exception in thread "main" java.lang.NumberFormatException: For input string: ""30" You can remove them using: yourString = yourString.replaceAll("\"", ""); Just in case there is an extra space, which i can't see but you have mentioned in your question. To remove trailing...

Problems in parsing

bash,parsing

You can pipe answer to tail, set tail params to get last line, and then use sed to extract value you need

How to parse table of numbers in C++

c++,parsing,table,numbers

Use std::istringstream. Here is an example: #include <sstream> #include <string> #include <fstream> #include <iostream> using namespace std; int main() { string line; istringstream strm; int num; ifstream ifs("YourData"); while (getline(ifs, line)) { istringstream strm(line); while ( strm >> num ) cout << num << " "; cout << "\n"; }...

Parse RSS with groovy

parsing,groovy,rss,xmlslurper

You can tell XmlSlurper and XmlParser to not try to handle namespaces in the constructor. I believe this does what you are after: 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml'.toURL().withReader { r -> new XmlSlurper(false, false).parse(r).channel.item.each { println it.title println it.description } } ...

pandas parse dates from csv

parsing,datetime,pandas

There are six columns, but only fix titles in the first line. This is why the parse_dates failed. you can skip the first line: df = pd.read_csv("tmp.csv", header=None, skiprows=1, parse_dates=[5]) ...

JSON parsing using .NET deserialize() with nested “list”

javascript,c#,json,parsing,serialization

One possibility is to deserialize into a dynamic object and convert from that to your strongly-typed object. Like so: var dict = new JavaScriptSerializer().Deserialize<dynamic>(responseText); The resulting dict object is a dictionary, with each property represented as a name-value pair in the dictionary. Nested objects, such as roster and its contained...

Grammar: Precedence of grammar alternatives

parsing,antlr,grammar,context-free-grammar

The answer depends primarily on the tool you are using, and what the semantics of that tool is. As written, this is not a context-free grammar in canonical form, and you'd need to produce that to get a theoretical answer, because only in that way can you clarify the intended...

How to Parse LaTex file

python,regex,parsing,python-3.x,latex

From what I get from the question you just want the definitions from the Latex file. You can use findall to directly get your definitions: A = re.findall(r'{definition}(.*?)\\end{definition}', raw.read()) Note the usage to .*? in order to tackle the greedy regex matching...

Reading JSON file from dropbox iOS

ios,json,parsing,dropbox

That's not a text file containing JSON; it's an RTF file containing JSON. That won't work with NSJSONSerialization: {\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural \f0\fs24 \cf0 \{\ "Version": 1.0,\ "ImageList": [\ "Nature.png",\ "Nature-1.png",\ "Ballon.png"\ ]\ \}}...

How to instantiate lexical.Scanner in a JavaTokenParsers class?

scala,parsing,lexical-scanner

The JavaTokenParsers does not implement the Scanners trait. So you would need to extends also from this trait (or a trait that extends it) in order to have access to this class. Unless your expr parser accepts the Reader as a parameter (not from its apply method), you'd need to...

printing invalid input from string in Java

java,string,parsing

your code inside if/else should be the other way around: if(str[i].indexOf(".")>0) { ///parse for double } else { //parse for int } ...

Algorithm to add implied parentheses in boolean expression

string,algorithm,parsing

It can be as simple as this (Python code ahead): def popnext(stream, token): if stream[0:len(token)] == list(token): del stream[0:len(token)] return True return False def parse_binary(stream, operator, nextfn): es = [nextfn(stream)] while popnext(stream, operator): es.append(nextfn(stream)) return '(' + ' {} '.format(operator).join(es) + ')' if len(es) > 1 else es[0] def parse_ors(stream):...

Stanford Parser - Factored model and PCFG

parsing,nlp,stanford-nlp,sentiment-analysis,text-analysis

This FAQ answer explains the difference in a long paragraph. Relevant parts are quoted below: Can you explain the different parsers? This answer is specific to English. It mostly applies to other languages although some components are missing in some languages. The file englishPCFG.ser.gz comprises just an unlexicalized PCFG grammar....

passing value down the pipe in Scala parser combinator

scala,parsing

You could use flatMap on the parser "bind-roaming-group" ~> name: def bindRg: Parser[Cmd] = ("bind-roaming-group" ~> name) flatMap (n => bindRgBody(n) <~ exit ^^ (b => new BindRoamingGroupCmd(n, b))) or def bindRg: Parser[Cmd] = ("bind-roaming-group" ~> name) >> (n => bindRgBody(n) <~ exit ^^ (new BindRoamingGroupCmd(n, _))) if you want...

Create XSD based on root element

java,xml,parsing,xsd

Using XSL 2.0 you can have multiple output documents and can define every file name, file content, etc. Default java support for XSL 2.0 is far from perfect, so I use the incredible Saxon (you can download saxon-he here, unzip it and add saxon9he.jar to your project). This is the...

How to parse output of external command in Julia?

parsing,julia-lang

Since readall returns a String, you want something that operates on a String, split fits the bill. Base.split(string, [chars]; limit=0, keep=true) Return an array of substrings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by "search"'s...

How to separate text from twitter streaming JSON responses and run analysis on text with python?

json,parsing,tweepy,sentiment-analysis,twitter-streaming-api

from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json # Variables that contains the user credentials to access Twitter API access_token = '' access_token_secret = '' consumer_key = '' consumer_secret = '' # This is a basic listener that just prints received tweets to stdout....

Need to parse live json file using Socket io

json,node.js,parsing,socket.io

i finally found something and with a little tweak and researching other answers i have finally made a working code First a brief review of what this code does watches your json file (in this case sports.json) if change detected then only reads the json file (in this case sports.json)...

How do we get text from a file (word-by-word) into a 2D array in PHP?

php,arrays,parsing,file-handling

This should work for you: Just read your file into an array with file() and explode() each line by a space with array_map(). $lines = array_map(function($v){ return explode(" ", $v); }, file("yourTextFile.txt", FILE_IGNORE_NEW_LINES |FILE_SKIP_EMPTY_LINES)); ...

XML file parsing - Get data from a child of a child

python,xml,parsing,python-3.x

For printing all display names , You should try - dnames = entry.findall(".//DisplayName") for x in dnames: print(x.text) For getting the specific display name under <Scalar> , you can do the below- name = entry.find('./Scalar/DisplayName').text print(name) ...

How to define a Regex in StandardTokenParsers to identify path?

regex,scala,parsing,lexical-analysis

In a double quoted string backslash is an escape character. If you mean to use the literal backslash in a double quotes string you must escape it, thus "\d" should be "\\d". Furthermore you do not need to escape the regex dot within a character class, since dot has no...

Parsing two different formats of dates in data frame

python,parsing,datetime,pandas,dataframes

Instead of using to_datetime(), first parse your strings with dateutil.parser.parse(): In [2]: from dateutil.parser import parse In [3]: dt1 = "Tue Nov 4 12:01:15 2014" In [4]: dt2 = "2014-11-04 13:15:13 +0000" In [5]: parse(dt1) Out[5]: datetime.datetime(2014, 11, 4, 12, 1, 15) In [6]: parse(dt2) Out[6]: datetime.datetime(2014, 11, 4, 13,...

Add new property based on a different objects property

arrays,regex,parsing,powershell

From the guess of it you just need one more calculated property on the end there for 'Pool'. You already have, and tested, the logic. Just need to implement it. $poolProperty = @{Label="Pool";Expression={ $lunID = $_.'LOGICAL UNIT NUMBER'; $pools | Where-Object{$_.LUNs -contains $lunID} | Select-Object -Expand 'Pool Name'} } $LUNSSummary...

Parsing html using Selenium - class name contains spaces

python,html,parsing,selenium,text

The p element has two classes: p0 and ng-binding. Try this selector: find_element_by_css_selector('p.p0.ng-binding') ...

Python - Deleting the first 2 lines of a string

python,string,file,parsing,lines

I don't know what your end character is, but what about something like postString = inputString.split("\n",2)[2]; The end character might need to be escaped, but that is what I would start with....

FParsec parses only first half

parsing,f#,dsl,fparsec

You're right, the line: let ptypedef = ptypedef1 <|> ptypedef2 is the problem. ptypedef1 is consuming some of the input so attempt needs to be used to backtrack when it fails so that ptypedef2 parses the text you're expecting it to, the fixed line would look like: let ptypedef =...

Converting a Distance string into a Number

javascript,parsing

If you are using the Google Maps Distance Matrix API, there is another field in the distance object called value that has a Number value. As documented in the API, the units is metres. But to answer your original question, I would remove all non-digit characters from the string using...

How can I split a string containing multiple js statements into an array of strings each string containing one statement?

javascript,parsing

A regular expression will be too simple to split the JavaScript code into statements. This could be made working though for simple things, but there's JavaScript strings, JavaScript regexes and comments which make this more complex. Additionally, JavaScript constructs are not necessarily ending with semicolons. Consider this: if (foo) {...

How to set up XPath query for HTML parsing?

python,xml,parsing,xpath,lxml

It is important to inspect the string returned by page.text and not just rely on the page source as returned by your Chrome browser. Web sites can return different content depending on the User-Agent, and moreover, GUI browsers such as your Chrome browser may change the content by executing JavaScript...

Regular Expression to remove everything but characters and numbers between Square brackets

java,regex,parsing

Translating my comments into an answer You can use this simple parsing in Java for your replacement: String s = "[a+b+c1 &$&$/[]]+(1+b&+c&)"; int d=0; StringBuilder sb = new StringBuilder(); for (char ch: s.toCharArray()) { if (ch == ']') d--; if (d==0 || Character.isAlphabetic(ch) || Character.isDigit(ch)) sb.append(ch); if (ch == '[')...

Parse.Cloud.httpRequest not returning response

parsing,parse.com,cloud-code

Parse.Cloud.httpRequest() is an asynchronous function call. It doesn't block the thread, so your code keeps running to status.success("Saved successfully."); before you get the result from httpRequest(). Parse.Cloud.httpRequest() returns a Promise now, so you can simply chain them together. Parse.Cloud.job("Loader", function(request, status) { var xmlreader = require('cloud/xmlreader.js'); var moment = require('cloud/moment.js');...

How to make xml to csv parsing/conversion faster?

c#,xml,parsing,csv

I'm seeing some things you could probably improve: You're calling .ToString() on joined a couple of times, when joined is already a string. You may be able to speed up your regex replace by compiling your regex first, outside of the loop. You're iterating over values multiple times, and each...

How to get a sub parameter of JSON

c#,json,parsing

You should actually already have all the link values with the first deserialization, no need for the second call to DeserializeObject: List<RootObject> obj = JsonConvert.DeserializeObject<List<RootObject>>(responseText); foreach (var item in obj) { //This is how you access the links: Console.WriteLine(item.Links.Self.href + " "); } ...

How do I load data from a txt file into variables in my C program?

c,arrays,parsing,file-io,struct

I won't be writing the code, but can try to help with the algotihm, in general. Open the file. Help : fopen() Check for successful opening. Hint: Return value. Read a line from the file. Check for the success. Help : fgets() and Return value. Based on data pattern ,...

Use DateTime format in a class but restrict time tokens

c#,parsing,datetime,formatting

DateTime d = new DateTime(2015, 6, 9); Console.WriteLine(d.ToString("dd MM yy")); // dd 06 15 Console.WriteLine(d.ToString("dd MMM yyyy HH mm tt")); // dd Jun 2015 HH mm tt var regex = new Regex("[yY]+|[M]+"); Console.WriteLine(regex.Replace("dd MM yy", m => d.ToString(m.Value))); Console.WriteLine(regex.Replace("dd MMM yyyy HH mm tt", m => d.ToString(m.Value))); output 09 06...

Parsing Json into a dynamic c# object with a dynamic key

c#,json,parsing,google-calendar

You can access it via a string indexer: var myObj = JsonConvert.DeserializeObject<dynamic>(jsonString); Console.WriteLine(myObj.calendars["[email protected]"]); ...

Parsing CSV in Python 101

python,parsing,csv

I'm ignoring the CSV stuff and concentrating just on your list misunderstanding. When you split the row of text, it becomes a list of strings. That is, rows becomes: ["day1, sunny","day2, rain"]. The for statement, applied to a list, iterates through the elements of that list. So, on the first...

JSON parsing not working javascript [closed]

javascript,json,parsing,sanity-check

You have an extra : symbol in your json variable. Try: var json = [{"OID":"1b383180186940dc0cc2a781fcf013ce", "NUMBER":"029348203984","SETTINGS":"Default","LATEST":"09-06-2015"}]; var obj=json[0]; console.log(obj['OID']); console.log(obj['NUMBER']); Edit: For next time, I recommend declaring your objects (and contents of arrays, and really anything that can get over 80 characters), in a more readable format. It will help...

Generic csv parser in java

java,parsing,csv

I suggest not to write a generic parser and use Apache Commons CSV. As you don't know the order of the columns, use CSVFormat as described in its documentation: Referencing columns safely If your source contains a header record, you can simplify your code and safely reference columns, by using...

find common string in two text files using batch script

string,parsing,batch-file,search,replace

Not sure about the requirements, but, maybe awk "{print $1}" 2.txt | findstr /g:/ /l /b 1.txt Without awk cmd /q /c"(for /f "usebackq" %%a in ("2.txt") do echo(%%a)" | findstr /g:/ /l /b 1.txt Only awk awk "{a[$1]=!a[$1]} !a[$1]" 2.txt 1.txt ...

Jsoup Login aspx Digikey

java,parsing,post,login,jsoup

You can log in with this code: try { String urlLogin = "https://www.digikey.it/classic/RegisteredUser/Login.aspx?ReturnUrl=%2fclassic%2fregistereduser%2fmydigikey.aspx%3fsite%3dit%26lang%3dit&site=it&lang=it"; Connection.Response response = Jsoup.connect(urlLogin) .method(Connection.Method.GET) .execute(); Document loginPage = response.parse(); Element eventValidation = loginPage.select("input[name=__EVENTVALIDATION]").first(); Element viewState = loginPage.select("input[name=__VIEWSTATE]").first(); response =...

String parsing with batch scripting

windows,string,parsing,batch-file,xml-parsing

This should work: @ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION FOR /F "tokens=*" %%a in (pictures.xml) DO ( SET b=%%a SET b=!b:"=+! FOR /F "delims=+ tokens=2" %%c in ("!b!") DO ( ECHO %%c ) ) This will output only something.jpg. Here the expülanation: First we split the file into lines. Now we want...

Android - Saving Objects to List of Object

android,parsing

It seems to me that static UserName and UserMessage in your Chat class are the cause of your problem. Change them to public String UserName; //from public static String UserName; public String UserMessage; //from public static String UserMessage; and also change this part in your adapter: holder.UserName.setText(chat.UserName); // from Chat.UserName...

PHP: How to update values of variables in a string? (inline variable parsing updates)

php,string,parsing

Use sprintf to specify where the arguments need to appear in the string and pass $id_a and $id_b as parameters. E.g. $id_a=1; $id_b = 2; $format = "The id %d is related to id %d\n"; echo sprintf($format, $id_a, $id_b); // operations go in here that calculate new values for $id_...

get element by id and get element by Value xpath in php

php,xml,parsing,domxpath,xpathquery

Using //*[@id='$previous_tag_id' and @value='$previous_tag_value'] should've worked, see the demo in eval.in : $xml = <<<XML <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ew-language id="en"> <global> <phrase id="actiondeleted" value="Deleted"> <child_phrase_1 id="1234" value="numbers"> <child id="test_id" value="test_value"/> <child id="test_id" value="test_value_2"/> </child_phrase_1> </phrase> </global> </ew-language> XML; $doc = new DOMDocument;...

DateTime.Parse ignoring my IFormatProvider?

c#,.net,parsing,datetime

If you follow through the reference source you'll see that DateTimeFormatInfo is extracted from your CultureInfo by simply referencing CultureInfo.DateTimeFormat. There is a Calendar property on DateTimeFormatInfo, which is what is used in parsing. These two are normally the same (i.e. reference equal), the fact you Clone your CultureInfo results...

How to extract derivation rules from a bracketed parse tree?

java,parsing,recursion,nlp,pseudocode

I wrote this for python. I believe you can read it as a pseudocode. I will edit the post for Java later . I added the Java implementation later. import re # grammar repository grammar_repo = [] s = "( S ( NP-SBJ ( PRP I ) ) ( [email protected]

jquery get elements by class name

html,arrays,parsing,getelementsbyclassname

You can do it like this way: $('.x:eq(0)').text('changed text'); or: $('.x').eq(1).text('bbb'); both works well sorry for my before answer.....

Removing line breaks from XML data before converting to CSV

c#,xml,wpf,parsing,csv

Try children.Add(Regex.Replace(child.InnerText, "\\s+", " ")); This shouldn't depend on any specific newline character and will also get rid of the four spaces in between every line. \s is the regex for any whitespace and + means one or more occurrences....

Find element by class name

python,parsing,selenium,selenium-webdriver,css-selectors

Just let selenium know you don't want the element having ng-hide class with the help of not negation pseudo class: p.p1.transfer strong.ng-binding:not(.ng-hide) ...

Fetch url-data attribute using simple html dom

php,html,arrays,parsing,dom

include("simple_html_dom.php"); $html=' <div id="base" url-data="http://www.domaine.com/page?user=username"></div> <div id="base" url-data="http://www.domaine.info/page?user=username"></div> <div id="base" url-data="http://www.domaine.org/page?user=username"></div> <div id="base" url-data="http://www.domaine.net/page?user=username"></div> <div id="base" url-data="http://www.domaine.biz/page?user=username"></div> <div id="base"...

how to use Query.limit and Query.skip?

ios,swift,uitableview,parsing,tableview

You don't want to change the limit, you just want to download the next 5 so the limit still 5 during all the interactions, the only number you should alter is the number of rows to skip, however this will require adjustments in the if condition as now you want...

Extracting strings from HTML with Python wont work with regex or BeautifulSoup

python,regex,parsing,beautifulsoup,python-requests

In order to match the string with a literal backlash, you need to double-escape it in a raw string, e.g.: re.search(r'@CAD_DTA\\">(.+?)@[email protected]@CAD_LBL',result.text) ^ ^ In order to get the index of the found match, you can use start([group]) of re.MatchObject IDEONE demo: import re obj = re.search(r'@CAD_DTA\\">(.+?)@[email protected]@CAD_LBL', 'Some text [email protected]_DTA\\">I WANT...

Parse text from a .txt file using csv module

python,python-2.7,parsing,csv

How about using Regular Expression def get_info(string_to_search): res_dict = {} import re find_type = re.compile("Type:[\s]*[\w]*") res = find_type.search(string_to_search) res_dict["Type"] = res.group(0).split(":")[1].strip() find_Status = re.compile("Status:[\s]*[\w]*") res = find_Status.search(string_to_search) res_dict["Status"] = res.group(0).split(":")[1].strip() find_date = re.compile("Date:[\s]*[/0-9]*") res = find_date.search(string_to_search) res_dict["Date"] = res.group(0).split(":")[1].strip() res_dict["description"] =...

JSON parse will not execute with JavaScript

javascript,json,list,parsing

Since data is an object, you can access the games array using data.listApp.games and iterate over it using $.each(), then inside the loop callback you will the game object as second param and you can access its properties using member operator function jsonParser(data) { $.each(data.listApp.games, function (i, game) { var...

How to get xml attribute and values using JAXB

xml,parsing,jaxb

I suppose you have your class MessageMapping.java which has in turn a list (or one? dunno) of message of type Message.java. Message.java in turn will be structured with a list of Field of type Field.java. The classes will be as follow: @XmlAccessorType(XmlAccessType.FIELD) public class Field { @XmlAttribute private String tag;...

PHP - Parse Facebook Post JSON

php,json,parsing,facebook-graph-api

echo prints Array() because you are casting an array to a string. To print the array in a human-readable format use print_r($obj); then, to print the id for the first place for example, use echo $obj['data'][0]['place']['id']; or loop through all the places and print each id use foreach ($obj['data'] as...

Jackson CSV missing columns

java,parsing,csv,jackson

You can throw an exception yourself when you build the output LinkedList inside the while loop: while(it.hasNext()) { Person line = it.next(); //call a method which checks that all values have been set if (thatMethodReturnsTrue){ output.push(line); } else{ throw SomeException(); } } ...

parse string of array in php

php,arrays,string,parsing

Try this <? $prices['holiday:waterpark']['person:1_person'] = 100; $str = "prices\['holiday:waterpark'\]\['person:1_person'\]"; $str = stripslashes($str); // be careful with passing $str from untrusted source // make necessary variable filtering before! echo eval('return $' . $str . ';'); ...

Get youtube title from videoid in PHP using API v3

php,parsing,youtube,youtube-api,youtube-data-api

Something along these lines will get you the information related to a specific video using the PHP client library: <?php require_once 'Google/autoload.php'; require_once 'Google/Client.php'; require_once 'Google/Service/YouTube.php'; $client = new Google_Client(); $client->setDeveloperKey('{YOUR-API-KEY}'); $youtube = new Google_Service_YouTube($client); $videoResponse = $youtube->videos->listVideos('snippet', array( 'id' => '{YOUR-VIDEO-ID}' )); $title = $videoResponse['items'][0]['snippet']['title']; ?> <!doctype...

Whats the simplest way when writing & reading a 2D-boolean-Array to a CSV File?

java,arrays,parsing,csv

Use uniVocity-parsers to write/read your booleans. public static void main(String ... args){ CsvWriterSettings writerSettings = new CsvWriterSettings(); ObjectRowWriterProcessor writerProcessor = new ObjectRowWriterProcessor(); // handles rows of objects and conversions to String. writerProcessor.convertAll(Conversions.toBoolean("T", "F")); // will write "T" and "F" instead of "true" and "false" writerSettings.setRowWriterProcessor(writerProcessor); CsvWriter writer = new CsvWriter(writerSettings);...

How to hide API keys in GitHub for iOS (SWIFT) projects?

ios,swift,api,parsing,apple-watch

You can use a .plist file where you store all your important keys. It is very important to put this file into your .gitignore file. In your case, you need to set your keys.plist file like this: And use it inside your AppDelegate as follows: var keys: NSDictionary? if let...

Parse “div” which have no name or id , only class atrribute , with htmlClener in android

android,parsing,htmlcleaner

Switch to Jsoup, It's really awesome! In my opinion you should use jsoup. It is Java HTML parser. Its feature is listed below. Ability to fetch web pages from network Very simple and straightforward API CSS selector to tagert HTML element(s). For example you want to get a DIV elements...

How to write a Scala parser for paths?

scala,parsing,path

You regex looks like it has typos. Try with something like this: scala> val regex = """^/hfds://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+)$)""".r regex: scala.util.matching.Regex = ^/hfds://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+)$) Some sample path: scala> val path = """/hfds://111.222.33.444:5555/path1/path2/filename1.jpg""" path: String = /hfds://111.222.33.444:5555/path1/path2/filename1.jpg Then do the matching: scala> val regex(numbers,afterColon,fullPath,filename) = path numbers: String = 111.222.33.444 afterColon: String = 5555...

Node.js - Browserify: Error on parsing tar file

javascript,node.js,parsing,tar,browserify

The problem here (and its solution) are tucked away in the http-browserify documentation. First, you need to understand a few things about browserify: The browser environment is not the same as the node.js environment Browserify does its best to provide node.js APIs that don't exist in the browser when the...

Python parse string with regex for constitute a dictionary

python,regex,parsing

You can use re.findall() to find the key value pairs: >>> import re >>> groups = re.findall(r'(\w+)="(.*?)"', s) >>> line = dict(groups) >>> >>> from pprint import pprint >>> pprint(line) {'action': 'xxxx', 'dstip': 'xxxx', 'dstport': 'xxxx', 'fwrule': 'xxxx', 'id': 'xxxx', 'length': 'xxxx', 'name': 'xxxx aaaa', 'outitf': 'xxxx', 'prec': 'xxxx', 'proto':...

shift/reduce and reduce/reduce errors in F# using fsyacc and fslex

parsing,f#,dsl,lexer,fsyacc

First, your Expression non-terminal has two identical productions: Expression: | IDENTIFIER ASSIGN Expression { ScalarAssignmentExpression($1, $3) } | IDENTIFIER ASSIGN Expression { ArrayAssignmentExpression($1, $3) } So there is absolutely no way for the parser to distinguish between them, and thus know which action to take. I suppose you can tell...

So I'm tring to get a date as a string at the command line and convert it into milliseconds but it keeps adding five hours. Any ideas why?

java,parsing,date,simpledateformat

I'm going to guess you're in the Eastern time zone and are confusing EDT with GMT.

Exception Value: list indices must be integers, not str

python,json,parsing

The results key gives a list of objects: >>> from pprint import pprint >>> import json >>>...

what's wrong with my php syntax? [closed]

php,html,arrays,parsing

You are missing comma "," after first index of main array and a semicolon at the end of main array. Here how your code should look like: $varProduct = array ( array("Title" , 10213 , 100, 0,0,1,1,0, "/womens/tops/s/2.png", "/womens/tops/s/2.jpg", "/womens/tops/s/2.jpg", 50 ), array("Title" , 10213 , 100, 0,0,1,1,0, "/womens/tops/s/2.png", "/womens/tops/s/2.jpg",...

Parse JSON on PHP and extract the particular value(s)

php,mysql,json,parsing,logic

<? $json = '{ "user_name": "USER", "selected_date": "2015-06-08", "selected_project": "Project1", "tasks": [ { "task_name": "task-1", "work_hours": [ { "Monday": " 3" }, { "Tuesday": " 0" }, { "Wednesday": " 2.5" }, { "Thursday": " 2" }, { "Friday": " 0" }, { "Saturday": " 0" }, { "Sunday":...

Faster bash writing to file

bash,parsing,read-write

The bash loop only slows it down (especially the part where you invoke an external program (cut) once per iteration). You can do all of it in one cut: cut -c 1-8 file_one.xt ...

Selenium - get all children divs but not grandchildren

python,html,parsing,selenium,selenium-webdriver

Here is a way to find the direct div children of the div with class name "main_div": driver.find_elements_by_xpath('//div[@class="main_div"]/div') The key here is the use of a single slash which would make the search inside the "main_div" non-recursive finding only direct div children. Or, with a CSS selector: driver.find_elements_by_css_selector("div.main_div > div")...

ElementTree errors, html files will not parse using Python/Sublime

python,html,parsing,sublimetext2

You are trying to parse HTML with an XML parser, and valid HTML is not always valid XML. You would be better off using the HTML parsing library in the lxml package. import xml.etree.ElementTree as ET # ... tree = ET.parse(HTML_PATH + '/' + file) would be changed to import...

How to merge two different paths in a XML file?

python,xml,parsing,xml-parsing,lxml

So there wasn't too much detail to go on here, but this at least give the correct output: from lxml import etree root = etree.fromstring(xml) replace_set = {} for node in root.iter("Node"): if 'NodeRef' in [c.tag for c in node]: # This is a <Node> type with child element <NodeRef>....

Parsing XML in PHP with SimpleXML

php,xml,parsing

You can try below code for SimpleXML <?php $xml ='<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <SubmitLeadResponse xmlns="https://test.com/"> <SubmitLeadResult> <Result>C</Result> <RedirectURL>https://testred.com</RedirectURL> <ApplicantID>123</ApplicantID>...

save parsed JSON as obj

javascript,jquery,json,parsing

Presumably your service is returning application/json. Therefore data already contains the json. tgmIndex = data; Then... "Tough Guys" is what you should be indexing. Not "ToughGuys" Your example JSON is wrong in your question. If I go to http://webspace.ocad.ca/~wk12ml/test.json I see: {"Tough Guys":[ {"name":"Ivan", "position":"Executive"}, {"name":"Little Johnny", "position":"Intern"}, {"name":"Beige Cathy",...

Parsing with MPC library in C returns only first number

c,parsing,rpn

The bnf you are using is the problem : Look at your example (2 2 +) and your entry rule: rpn : '(' <exp> ')' | <number>; 1 - rpn left part is not matched by input : 2 != ( 2 - then number is matched 3 - end...

Python import XML intro SQLITE (xmltodict)

python,xml,sqlite,parsing,xmltodict

The ? can only be used for values, not for column names. This INSERT INTO stocks ? VALUES '?' is not valid. You must use INSERT INTO stocks (columnname) VALUES (?) Note the missing quotes around the ?. In code: c.execute("INSERT INTO stocks ({}) VALUES (?)".format(column["@name"]), column["#text"]) ...

Custom Converter for Retrofit

android,json,parsing,gson,retrofit

I would do something like that: public class StringList extends ArrayList<String> { // Empty on purpose. The class is here only to be recognized by Gson } public class CitationMain { @SerializedName("field_name_here") StringList values; // Your other fields } Then when creating the RestAdapter: public class StringListDeserializer implements JsonDeserializer<StringList> {...

fatal error: Array index out of range with Parse.com

ios,xcode,swift,parsing,uisearchcontroller

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var query: PFQuery = PFQuery(className: "NewsNow") if self.dataForSearchController == nil { return objects?.count ?? 0 } else { return dataForSearchController?.count ?? 0 } } ...

Lazy parsing with Stanford CoreNLP to get sentiment only of specific sentences

java,performance,parsing,stanford-nlp,sentiment-analysis

If you're looking to speed up constituency parsing, the single best improvement is to use the new shift-reduce constituency parser. It is orders of magnitude faster than the default PCFG parser. Answers to your later questions: Why is CoreNLP parsing not lazy? This is certainly possible, but not something that...

Parsing android resources from xml

java,android,xml,parsing,xml-parsing

Try this: Resources resources = getResources(); XmlResourceParser xmlParser = resources.getXml(R.xml.programlist); ... int resourceId = xmlParser.getAttributeResourceValue(null, "color", 0); pi.color = (resorceId == 0) ? SOME_DEFAULT_COLOR : resources.getColor(resourceId); pi.pref = xmlParser.getAttributeResourceValue(null, "prefLayoutId", 0); getAttributeResourceValue will return a referenced resource id, stored in corresponding value....

No module named ijson [closed]

python,json,parsing,tweets

ijson is an external package that is not included with the regular python libraries. You need to install ijson yourself first. Look into using something like pip which is a package manager for python. Once installed you can install ijson through the terminal like this: pip install ijson ...

Golang - using/iterating through JSON parsed map

json,parsing,go

In Go, unmarshaling works only if a struct has exported fields, ie. fields that begin with a capital letter. Change your first structure to: type fileData struct{ Tn string Size int } See http://play.golang.org/p/qO3U7ZNrNs for a fixed example. Moreover, if you intend to marshal this struct back to JSON, you'll...