Programs & Examples On #Parsing

Parsing refers to breaking an artifact into its constituent elements and capturing the relationship between those elements. This tag isn't for questions about the hosted service Parse.com (use [parse.com]) or parse errors in a particular programming language (use the appropriate language tag instead).

Python code to remove HTML tags from a string

There's a simple way to this in any C-like language. The style is not Pythonic but works with pure Python:

def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
            if c == '<' and not quote:
                tag = True
            elif c == '>' and not quote:
                tag = False
            elif (c == '"' or c == "'") and tag:
                quote = not quote
            elif not tag:
                out = out + c

    return out

The idea based in a simple finite-state machine and is detailed explained here: http://youtu.be/2tu9LTDujbw

You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s

PS - If you're interested in the class(about smart debugging with python) I give you a link: https://www.udacity.com/course/software-debugging--cs259. It's free!

Parse JSON String to JSON Object in C#.NET

Since you mentioned that you are using Newtonsoft.dll you can convert a JSON string to an object by using its facilities:

MyClass myClass = JsonConvert.DeserializeObject<MyClass>(your_json_string);

[Serializable]
public class MyClass
{
    public string myVar {get; set;}
    etc.
}

JSON Parse File Path

Loading local JSON file

Use something like this

$.getJSON("../../data/file.json", function(json) {
    console.log(json); // this will show the info in firebug console 
    alert(json);
});

Safely turning a JSON string into an object

If you're using jQuery, you can also use:

$.getJSON(url, function(data) { });

Then you can do things like

data.key1.something
data.key1.something_else

etc.

Malformed String ValueError ast.literal_eval() with String representation of Tuple

From the documentation for ast.literal_eval():

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Decimal isn't on the list of things allowed by ast.literal_eval().

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

How to convert string into float in JavaScript?

If you extend String object like this..

String.prototype.float = function() { 
  return parseFloat(this.replace(',', '.')); 
}

.. you can run it like this

"554,20".float()
> 554.20

works with dot as well

"554.20".float()
> 554.20

typeof "554,20".float()
> "number"

ParseError: not well-formed (invalid token) using cElementTree

What helped me with that error was Juan's answer - https://stackoverflow.com/a/20204635/4433222 But wasn't enough - after struggling I found out that an XML file needs to be saved with UTF-8 without BOM encoding.

The solution wasn't working for "normal" UTF-8.

Retrieving values from nested JSON Object

Maybe you're not using the latest version of a JSON for Java Library.

json-simple has not been updated for a long time, while JSON-Java was updated 2 month ago.

JSON-Java can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java

After switching the library, you can refer to my sample code down below:

public static void main(String[] args) {
    String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";

    JSONObject jsonObject = new JSONObject(JSON);
    JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
    Object level = getSth.get("2");

    System.out.println(level);
}

And as JSON-Java open-sourced, you can read the code and its document, they will guide you through.

Hope that it helps.

How do I create a comma delimited string from an ArrayList?

foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()

or

string.Concat(foo.ToArray().Select(a => a += ",").ToArray())

Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.

How do I parse JSON in Android?

I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:

try{
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet("http://example.json");

    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
    // In your production code handle any errors and catch the individual exceptions
    e.printStackTrace();
}

Once you have your JSONObject refer to the SDK for details on how to extract the data you require.

Correctly Parsing JSON in Swift 3

Swift has a powerful type inference. Lets get rid of "if let" or "guard let" boilerplate and force unwraps using functional approach:

  1. Here is our JSON. We can use optional JSON or usual. I'm using optional in our example:
let json: Dictionary<String, Any>? = ["current": ["temperature": 10]]
  1. Helper functions. We need to write them only once and then reuse with any dictionary:
/// Curry
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
    return { a in
        { f(a, $0) }
    }
}

/// Function that takes key and optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key, _ json: Dictionary<Key, Any>?) -> Value? {
    return json.flatMap {
        cast($0[key])
    }
}

/// Function that takes key and return function that takes optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key) -> (Dictionary<Key, Any>?) -> Value? {
    return curry(extract)(key)
}

/// Precedence group for our operator
precedencegroup RightApplyPrecedence {
    associativity: right
    higherThan: AssignmentPrecedence
    lowerThan: TernaryPrecedence
}

/// Apply. g § f § a === g(f(a))
infix operator § : RightApplyPrecedence
public func §<A, B>(_ f: (A) -> B, _ a: A) -> B {
    return f(a)
}

/// Wrapper around operator "as".
public func cast<A, B>(_ a: A) -> B? {
    return a as? B
}
  1. And here is our magic - extract the value:
let temperature = (extract("temperature") § extract("current") § json) ?? NSNotFound

Just one line of code and no force unwraps or manual type casting. This code works in playground, so you can copy and check it. Here is an implementation on GitHub.

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

Using C# regular expressions to remove HTML tags

The correct answer is don't do that, use the HTML Agility Pack.

Edited to add:

To shamelessly steal from the comment below by jesse, and to avoid being accused of inadequately answering the question after all this time, here's a simple, reliable snippet using the HTML Agility Pack that works with even most imperfectly formed, capricious bits of HTML:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(Properties.Resources.HtmlContents);
var text = doc.DocumentNode.SelectNodes("//body//text()").Select(node => node.InnerText);
StringBuilder output = new StringBuilder();
foreach (string line in text)
{
   output.AppendLine(line);
}
string textOnly = HttpUtility.HtmlDecode(output.ToString());

There are very few defensible cases for using a regular expression for parsing HTML, as HTML can't be parsed correctly without a context-awareness that's very painful to provide even in a nontraditional regex engine. You can get part way there with a RegEx, but you'll need to do manual verifications.

Html Agility Pack can provide you a robust solution that will reduce the need to manually fix up the aberrations that can result from naively treating HTML as a context-free grammar.

A regular expression may get you mostly what you want most of the time, but it will fail on very common cases. If you can find a better/faster parser than HTML Agility Pack, go for it, but please don't subject the world to more broken HTML hackery.

Extract data from XML Clob using SQL from Oracle Database

This should work

SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;

I have assumed the ** were just for highlighting?

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

How do you parse and process HTML/XML in PHP?

You could try using something like HTML Tidy to cleanup any "broken" HTML and convert the HTML to XHTML, which you can then parse with a XML parser.

How to strip all non-alphabetic characters from string in SQL Server?

Parameterized version of G Mastros' awesome answer:

CREATE FUNCTION [dbo].[fn_StripCharacters]
(
    @String NVARCHAR(MAX), 
    @MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @MatchExpression =  '%['+@MatchExpression+']%'

    WHILE PatIndex(@MatchExpression, @String) > 0
        SET @String = Stuff(@String, PatIndex(@MatchExpression, @String), 1, '')

    RETURN @String

END

Alphabetic only:

SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^a-z')

Numeric only:

SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^0-9')

Alphanumeric only:

SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^a-z0-9')

Non-alphanumeric:

SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', 'a-z0-9')

How to do an Integer.parseInt() for a decimal number?

Use,

String s="0.01";
int i= new Double(s).intValue();

How do I parse JSON with Objective-C?

NSString* path  = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"];

//????????????,????NSUTF8StringEncoding ????,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

//??????????
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];


for (int i=0; i<[allKeys count]; i++) {
    NSDictionary *arrayResult = [allKeys objectAtIndex:i];
    NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]);

}

file:

 [
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "MLMember",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  },
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "0.00",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  }
  ]

How to read XML using XPath in Java

Expanding on the excellent answer by @bluish and @Yishai, here is how you make the NodeLists and node attributes support iterators, i.e. the for(Node n: nodelist) interface.

Use it like:

NodeList nl = ...
for(Node n : XmlUtil.asList(nl))
{...}

and

Node n = ...
for(Node attr : XmlUtil.asList(n.getAttributes())
{...}

The code:

/**
 * Converts NodeList to an iterable construct.
 * From: https://stackoverflow.com/a/19591302/779521
 */
public final class XmlUtil {
    private XmlUtil() {}

    public static List<Node> asList(NodeList n) {
        return n.getLength() == 0 ? Collections.<Node>emptyList() : new NodeListWrapper(n);
    }

    static final class NodeListWrapper extends AbstractList<Node> implements RandomAccess {
        private final NodeList list;

        NodeListWrapper(NodeList l) {
            this.list = l;
        }

        public Node get(int index) {
            return this.list.item(index);
        }

        public int size() {
            return this.list.getLength();
        }
    }

    public static List<Node> asList(NamedNodeMap n) {
        return n.getLength() == 0 ? Collections.<Node>emptyList() : new NodeMapWrapper(n);
    }

    static final class NodeMapWrapper extends AbstractList<Node> implements RandomAccess {
        private final NamedNodeMap list;

        NodeMapWrapper(NamedNodeMap l) {
            this.list = l;
        }

        public Node get(int index) {
            return this.list.item(index);
        }

        public int size() {
            return this.list.getLength();
        }
    }
}

Read a XML (from a string) and get some fields - Problems reading XML

You should use LoadXml method, not Load:

xmlDoc.LoadXml(myXML); 

Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);

foreach (XmlNode childrenNode in nodes)
{
    HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
} 

How can I parse a String to BigDecimal?

Try the correct constructor http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)

You can directly instanciate the BigDecimal with the String ;)

Example:

BigDecimal bigDecimalValue= new BigDecimal("0.5");

JavaScriptSerializer.Deserialize - how to change field names

Json.NET will do what you want (disclaimer: I'm the author of the package). It supports reading DataContract/DataMember attributes as well as its own to change the property names. Also there is the StringEnumConverter class for serializing enum values as the name rather than the number.

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

This is the simplest way to get unix time:

use Time::Local;
timelocal($second,$minute,$hour,$day,$month-1,$year);

Note the reverse order of the arguments and that January is month 0. For many more options, see the DateTime module from CPAN.

As for parsing, see the Date::Parse module from CPAN. If you really need to get fancy with date parsing, the Date::Manip may be helpful, though its own documentation warns you away from it since it carries a lot of baggage (it knows things like common business holidays, for example) and other solutions are much faster.

If you happen to know something about the format of the date/times you'll be parsing then a simple regular expression may suffice but you're probably better off using an appropriate CPAN module. For example, if you know the dates will always be in YMDHMS order, use the CPAN module DateTime::Format::ISO8601.


For my own reference, if nothing else, below is a function I use for an application where I know the dates will always be in YMDHMS order with all or part of the "HMS" part optional. It accepts any delimiters (eg, "2009-02-15" or "2009.02.15"). It returns the corresponding unix time (seconds since 1970-01-01 00:00:00 GMT) or -1 if it couldn't parse it (which means you better be sure you'll never legitimately need to parse the date 1969-12-31 23:59:59). It also presumes two-digit years XX up to "69" refer to "20XX", otherwise "19XX" (eg, "50-02-15" means 2050-02-15 but "75-02-15" means 1975-02-15).

use Time::Local;

sub parsedate { 
  my($s) = @_;
  my($year, $month, $day, $hour, $minute, $second);

  if($s =~ m{^\s*(\d{1,4})\W*0*(\d{1,2})\W*0*(\d{1,2})\W*0*
                 (\d{0,2})\W*0*(\d{0,2})\W*0*(\d{0,2})}x) {
    $year = $1;  $month = $2;   $day = $3;
    $hour = $4;  $minute = $5;  $second = $6;
    $hour |= 0;  $minute |= 0;  $second |= 0;  # defaults.
    $year = ($year<100 ? ($year<70 ? 2000+$year : 1900+$year) : $year);
    return timelocal($second,$minute,$hour,$day,$month-1,$year);  
  }
  return -1;
}

How to read json file into java with simple JSON library

Hope this example helps too

I have done java coding in a similar way for the below json array example as follows :

following is the json data format : stored as "EMPJSONDATA.json"

[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},

{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},

{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}

{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]

public class Jsonminiproject {

public static void main(String[] args) {

      JSONParser parser = new JSONParser();

    try {
        JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
        for (Object o : a)
        {
            JSONObject employee = (JSONObject) o;

            Long no = (Long) employee.get("EMPNO");
            System.out.println("Employee Number : " + no);

            String st = (String) employee.get("EMP_NAME");
            System.out.println("Employee Name : " + st);

            String dob = (String) employee.get("DOB");
            System.out.println("Employee DOB : " + dob);

            String doj = (String) employee.get("DOJ");
            System.out.println("Employee DOJ : " + doj);

            String role = (String) employee.get("ROLE");
            System.out.println("Employee Role : " + role);

            System.out.println("\n");

        }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}

}

How to convert an XML file to nice pandas dataframe?

Here is another way of converting a xml to pandas data frame. For example i have parsing xml from a string but this logic holds good from reading file as well.

import pandas as pd
import xml.etree.ElementTree as ET

xml_str = '<?xml version="1.0" encoding="utf-8"?>\n<response>\n <head>\n  <code>\n   200\n  </code>\n </head>\n <body>\n  <data id="0" name="All Categories" t="2018052600" tg="1" type="category"/>\n  <data id="13" name="RealEstate.com.au [H]" t="2018052600" tg="1" type="publication"/>\n </body>\n</response>'

etree = ET.fromstring(xml_str)
dfcols = ['id', 'name']
df = pd.DataFrame(columns=dfcols)

for i in etree.iter(tag='data'):
    df = df.append(
        pd.Series([i.get('id'), i.get('name')], index=dfcols),
        ignore_index=True)

df.head()

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

Set DateTimePicker's Format property to custom and CustomFormat prperty to M/dd/yyyy.

Parsing huge logfiles in Node.js - read in line-by-line

node-byline uses streams, so i would prefer that one for your huge files.

for your date-conversions i would use moment.js.

for maximising your throughput you could think about using a software-cluster. there are some nice-modules which wrap the node-native cluster-module quite well. i like cluster-master from isaacs. e.g. you could create a cluster of x workers which all compute a file.

for benchmarking splits vs regexes use benchmark.js. i havent tested it until now. benchmark.js is available as a node-module

Parsing JSON Array within JSON Object

line 2 should be

for (int i = 0; i < jsonMainArr.size(); i++) {  // **line 2**

For line 3, I'm having to do

    JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());

How to reformat JSON in Notepad++?

Download and install this plugin JSToolNpp ,Then perform operations like this Plugins | JSTool | JSFormat. If you don’t want to install plugins, you can perform JSON beautification operations on JSON Formatter

How to parse/read a YAML file into a Python object?

If your YAML file looks like this:

# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

And you've installed PyYAML like this:

pip install PyYAML

And the Python code looks like this:

import yaml
with open('tree.yaml') as f:
    # use safe_load instead load
    dataMap = yaml.safe_load(f)

The variable dataMap now contains a dictionary with the tree data. If you print dataMap using PrettyPrint, you will get something like:

{
    'treeroot': {
        'branch1': {
            'branch1-1': {
                'name': 'Node 1-1'
            },
            'name': 'Node 1'
        },
        'branch2': {
            'branch2-1': {
                'name': 'Node 2-1'
            },
            'name': 'Node 2'
        }
    }
}

So, now we have seen how to get data into our Python program. Saving data is just as easy:

with open('newtree.yaml', "w") as f:
    yaml.dump(dataMap, f)

You have a dictionary, and now you have to convert it to a Python object:

class Struct:
    def __init__(self, **entries): 
        self.__dict__.update(entries)

Then you can use:

>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...

and follow "Convert Python dict to object".

For more information you can look at pyyaml.org and this.

What is Parse/parsing?

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.

String tenString = "10"

//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;

//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);

PDF Parsing Using Python - extracting formatted and plain texts

You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).

A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!

But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.

Parsing CSV / tab-delimited txt file with Python

If the file is large, you may not want to load it entirely into memory at once. This approach avoids that. (Of course, making a dict out of it could still take up some RAM, but it's guaranteed to be smaller than the original file.)

my_dict = {}
for i, line in enumerate(file):
    if (i - 8) % 7:
        continue
    k, v = line.split("\t")[:3:2]
    my_dict[k] = v

Edit: Not sure where I got extend from before. I meant update

Java HTML Parsing

If your HTML is well-formed, you can easily employ an XML parser to do the job for you... If you're only reading, SAX would be ideal.

How can I use the python HTMLParser library to extract data from a specific div tag?

This works perfectly:

print (soup.find('the tag').text)

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You define var scatterSeries = [];, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries)); which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.

Identify if a string is a number

If you want to know if a string is a number, you could always try parsing it:

var numberString = "123";
int number;

int.TryParse(numberString , out number);

Note that TryParse returns a bool, which you can use to check if your parsing succeeded.

How to parse a string to an int in C++?

This is a safer C way than atoi()

const char* str = "123";
int i;

if(sscanf(str, "%d", &i)  == EOF )
{
   /* error */
}

C++ with standard library stringstream: (thanks CMS )

int str2int (const string &str) {
  stringstream ss(str);
  int num;
  if((ss >> num).fail())
  { 
      //ERROR 
  }
  return num;
}

With boost library: (thanks jk)

#include <boost/lexical_cast.hpp>
#include <string>

try
{
    std::string str = "123";
    int number = boost::lexical_cast< int >( str );
}
catch( const boost::bad_lexical_cast & )
{
    // Error
}

Edit: Fixed the stringstream version so that it handles errors. (thanks to CMS's and jk's comment on original post)

Best XML Parser for PHP

Have a look at PHP's available XML extensions.

The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load the current node into memory. You define handlers for specific nodes which will get triggered when the Parser encounters it. That is faster and saves on memory. You pay for that with not being able to use XPath.

Personally, I find SimpleXml quite limiting (hence simple) in what it offers over DOM. You can switch between DOM and SimpleXml easily though, but I usually dont bother and go the DOM route directly. DOM is an implementation of the W3C DOM API, so you might be familiar with it from other languages, for instance JavaScript.

How to convert jsonString to JSONObject in Java

Codehaus Jackson - I have been this awesome API since 2012 for my RESTful webservice and JUnit tests. With their API, you can:

(1) Convert JSON String to Java bean

public static String beanToJSONString(Object myJavaBean) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.writeValueAsString(myJavaBean);
}

(2) Convert JSON String to JSON object (JsonNode)

public static JsonNode stringToJSONObject(String jsonString) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.readTree(jsonString);
}

//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";   
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());

(3) Convert Java bean to JSON String

    public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.readValue(JSONString, beanClass);
}

REFS:

  1. Codehaus Jackson

  2. JsonNode API - How to use, navigate, parse and evaluate values from a JsonNode object

  3. Tutorial - Simple tutorial how to use Jackson to convert JSON string to JsonNode

How can I parse JSON with C#?

 using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(user)))
 {
    // Deserialization from JSON  
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UserListing))
    DataContractJsonSerializer(typeof(UserListing));
    UserListing response = (UserListing)deserializer.ReadObject(ms);

 }

 public class UserListing
 {
    public List<UserList> users { get; set; }      
 }

 public class UserList
 {
    public string FirstName { get; set; }       
    public string LastName { get; set; } 
 }

What is the best way to parse html in C#?

No 3rd party lib, WebBrowser class solution that can run on Console, and Asp.net

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;

class ParseHTML
{
    public ParseHTML() { }
    private string ReturnString;

    public string doParsing(string html)
    {
        Thread t = new Thread(TParseMain);
        t.ApartmentState = ApartmentState.STA;
        t.Start((object)html);
        t.Join();
        return ReturnString;
    }

    private void TParseMain(object html)
    {
        WebBrowser wbc = new WebBrowser();
        wbc.DocumentText = "feces of a dummy";        //;magic words        
        HtmlDocument doc = wbc.Document.OpenNew(true);
        doc.Write((string)html);
        this.ReturnString = doc.Body.InnerHtml + " do here something";
        return;
    }
}

usage:

string myhtml = "<HTML><BODY>This is a new HTML document.</BODY></HTML>";
Console.WriteLine("before:" + myhtml);
myhtml = (new ParseHTML()).doParsing(myhtml);
Console.WriteLine("after:" + myhtml);

How to avoid warning when introducing NAs by coercion

I have slightly modified the jangorecki function for the case where we may have a variety of values that cannot be converted to a number. In my function, a template search is performed and if the template is not found, FALSE is returned.! before gperl, it means that we need those vector elements that do not match the template. The rest is similar to the as.num function. Example:

as.num.pattern <- function(x, pattern){
  stopifnot(is.character(x))
  na = !grepl(pattern, x)
  x[na] = -Inf
  x = as.numeric(x)
  x[na] = NA_real_
  x
}

as.num.pattern(c('1', '2', '3.43', 'char1', 'test2', 'other3', '23/40', '23, 54 cm.'))

[1] 1.00 2.00 3.43   NA   NA   NA   NA   NA

XML parsing of a variable string in JavaScript

Marknote is a nice lightweight cross-browser JavaScript XML parser. It's object-oriented and it's got plenty of examples, plus the API is documented. It's fairly new, but it has worked nicely in one of my projects so far. One thing I like about it is that it will read XML directly from strings or URLs and you can also use it to convert the XML into JSON.

Here's an example of what you can do with Marknote:

var str = '<books>' +
          '  <book title="A Tale of Two Cities"/>' +
          '  <book title="1984"/>' +
          '</books>';

var parser = new marknote.Parser();
var doc = parser.parse(str);

var bookEls = doc.getRootElement().getChildElements();

for (var i=0; i<bookEls.length; i++) {
    var bookEl = bookEls[i];
    // alerts "Element name is 'book' and book title is '...'"
    alert("Element name is '" + bookEl.getName() + 
        "' and book title is '" + 
        bookEl.getAttributeValue("title") + "'"
    );
}

Which is the best library for XML parsing in java

Actually Java supports 4 methods to parse XML out of the box:

DOM Parser/Builder: The whole XML structure is loaded into memory and you can use the well known DOM methods to work with it. DOM also allows you to write to the document with Xslt transformations. Example:

public static void parse() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    File file = new File("test.xml");
    Document doc = builder.parse(file);
    // Do something with the document here.
}

SAX Parser: Solely to read a XML document. The Sax parser runs through the document and calls callback methods of the user. There are methods for start/end of a document, element and so on. They're defined in org.xml.sax.ContentHandler and there's an empty helper class DefaultHandler.

public static void parse() throws ParserConfigurationException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser saxParser = factory.newSAXParser();
    File file = new File("test.xml");
    saxParser.parse(file, new ElementHandler());    // specify handler
}

StAx Reader/Writer: This works with a datastream oriented interface. The program asks for the next element when it's ready just like a cursor/iterator. You can also create documents with it. Read document:

public static void parse() throws XMLStreamException, IOException {
    try (FileInputStream fis = new FileInputStream("test.xml")) {
        XMLInputFactory xmlInFact = XMLInputFactory.newInstance();
        XMLStreamReader reader = xmlInFact.createXMLStreamReader(fis);
        while(reader.hasNext()) {
            reader.next(); // do something here
        }
    }
}

Write document:

public static void parse() throws XMLStreamException, IOException {
    try (FileOutputStream fos = new FileOutputStream("test.xml")){
        XMLOutputFactory xmlOutFact = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = xmlOutFact.createXMLStreamWriter(fos);
        writer.writeStartDocument();
        writer.writeStartElement("test");
        // write stuff
        writer.writeEndElement();
    }
}

JAXB: The newest implementation to read XML documents: Is part of Java 6 in v2. This allows us to serialize java objects from a document. You read the document with a class that implements a interface to javax.xml.bind.Unmarshaller (you get a class for this from JAXBContext.newInstance). The context has to be initialized with the used classes, but you just have to specify the root classes and don't have to worry about static referenced classes. You use annotations to specify which classes should be elements (@XmlRootElement) and which fields are elements(@XmlElement) or attributes (@XmlAttribute, what a surprise!)

public static void parse() throws JAXBException, IOException {
    try (FileInputStream adrFile = new FileInputStream("test")) {
        JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
        Unmarshaller um = ctx.createUnmarshaller();
        RootElementClass rootElement = (RootElementClass) um.unmarshal(adrFile);
    }
}

Write document:

public static void parse(RootElementClass out) throws IOException, JAXBException {
    try (FileOutputStream adrFile = new FileOutputStream("test.xml")) {
        JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
        Marshaller ma = ctx.createMarshaller();
        ma.marshal(out, adrFile);
    }
}

Examples shamelessly copied from some old lecture slides ;-)

Edit: About "which API should I use?". Well it depends - not all APIs have the same capabilities as you see, but if you have control over the classes you use to map the XML document JAXB is my personal favorite, really elegant and simple solution (though I haven't used it for really large documents, it could get a bit complex). SAX is pretty easy to use too and just stay away from DOM if you don't have a really good reason to use it - old, clunky API in my opinion. I don't think there are any modern 3rd party libraries that feature anything especially useful that's missing from the STL and the standard libraries have the usual advantages of being extremely well tested, documented and stable.

Get value from a string after a special character

You can use .indexOf() and .substr() like this:

var val = $("input").val();
var myString = val.substr(val.indexOf("?") + 1)

You can test it out here. If you're sure of the format and there's only one question mark, you can just do this:

var myString = $("input").val().split("?").pop();

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

Parse JSON from HttpURLConnection object

Define the following function (not mine, not sure where I found it long ago):

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
return sb.toString();

}

Then:

String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
    {
        success = true;
        InputStream response = conn.getInputStream();
        jsonReply = convertStreamToString(response);

        // Do JSON handling here....
    }

Adding a parameter to the URL with JavaScript

Here's a vastly simplified version, making tradeoffs for legibility and fewer lines of code instead of micro-optimized performance (and we're talking about a few miliseconds difference, realistically... due to the nature of this (operating on the current document's location), this will most likely be ran once on a page).

/**
* Add a URL parameter (or changing it if it already exists)
* @param {search} string  this is typically document.location.search
* @param {key}    string  the key to set
* @param {val}    string  value 
*/
var addUrlParam = function(search, key, val){
  var newParam = key + '=' + val,
      params = '?' + newParam;

  // If the "search" string exists, then build params from it
  if (search) {
    // Try to replace an existance instance
    params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);

    // If nothing was replaced, then add the new param to the end
    if (params === search) {
      params += '&' + newParam;
    }
  }

  return params;
};

You would then use this like so:

document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');

How to check that a string is parseable to a double?

All answers are OK, depending on how academic you want to be. If you wish to follow the Java specifications accurately, use the following:

private static final Pattern DOUBLE_PATTERN = Pattern.compile(
    "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
    "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
    "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
    "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");

public static boolean isFloat(String s)
{
    return DOUBLE_PATTERN.matcher(s).matches();
}

This code is based on the JavaDocs at Double.

How to parse dates in multiple formats using SimpleDateFormat

Here is the complete example (with main method) which can be added as a utility class in your project. All the format mentioned in SimpleDateFormate API is supported in the below method.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;

public class DateUtility {

    public static Date parseDate(String inputDate) {

        Date outputDate = null;
        String[] possibleDateFormats =
              {
                    "yyyy.MM.dd G 'at' HH:mm:ss z",
                    "EEE, MMM d, ''yy",
                    "h:mm a",
                    "hh 'o''clock' a, zzzz",
                    "K:mm a, z",
                    "yyyyy.MMMMM.dd GGG hh:mm aaa",
                    "EEE, d MMM yyyy HH:mm:ss Z",
                    "yyMMddHHmmssZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
                    "YYYY-'W'ww-u",
                    "EEE, dd MMM yyyy HH:mm:ss z", 
                    "EEE, dd MMM yyyy HH:mm zzzz",
                    "yyyy-MM-dd'T'HH:mm:ssZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSzzzz", 
                    "yyyy-MM-dd'T'HH:mm:sszzzz",
                    "yyyy-MM-dd'T'HH:mm:ss z",
                    "yyyy-MM-dd'T'HH:mm:ssz", 
                    "yyyy-MM-dd'T'HH:mm:ss",
                    "yyyy-MM-dd'T'HHmmss.SSSz",
                    "yyyy-MM-dd",
                    "yyyyMMdd",
                    "dd/MM/yy",
                    "dd/MM/yyyy"
              };

        try {

            outputDate = DateUtils.parseDate(inputDate, possibleDateFormats);
            System.out.println("inputDate ==> " + inputDate + ", outputDate ==> " + outputDate);

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return outputDate;

    }

    public static String formatDate(Date date, String requiredDateFormat) {
        SimpleDateFormat df = new SimpleDateFormat(requiredDateFormat);
        String outputDateFormatted = df.format(date);
        return outputDateFormatted;
    }

    public static void main(String[] args) {

        DateUtility.parseDate("20181118");
        DateUtility.parseDate("2018-11-18");
        DateUtility.parseDate("18/11/18");
        DateUtility.parseDate("18/11/2018");
        DateUtility.parseDate("2018.11.18 AD at 12:08:56 PDT");
        System.out.println("");
        DateUtility.parseDate("Wed, Nov 18, '18");
        DateUtility.parseDate("12:08 PM");
        DateUtility.parseDate("12 o'clock PM, Pacific Daylight Time");
        DateUtility.parseDate("0:08 PM, PDT");
        DateUtility.parseDate("02018.Nov.18 AD 12:08 PM");
        System.out.println("");
        DateUtility.parseDate("Wed, 18 Nov 2018 12:08:56 -0700");
        DateUtility.parseDate("181118120856-0700");
        DateUtility.parseDate("2018-11-18T12:08:56.235-0700");
        DateUtility.parseDate("2018-11-18T12:08:56.235-07:00");
        DateUtility.parseDate("2018-W27-3");
    }

}

JSON response parsing in Javascript to get key/value pair

There are two ways to access properties of objects:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

var key = 'b';
obj[key] //bar

If you don't already have it as an object, you'll need to convert it.

For a more complex example, let's assume you have an array of objects that represent users:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

Another example: obj[2].key[3]["some key"]

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.


As Amadan noted, it might be worth also discussing how to loop over different structures.

To loop over an array, you can use a simple for loop:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

SQL: parse the first, middle and last name from a fullname field

I'm not sure about SQL server, but in postgres you could do something like this:

SELECT 
  SUBSTRING(fullname, '(\\w+)') as firstname,
  SUBSTRING(fullname, '\\w+\\s(\\w+)\\s\\w+') as middle,
  COALESCE(SUBSTRING(fullname, '\\w+\\s\\w+\\s(\\w+)'), SUBSTRING(fullname, '\\w+\\s(\\w+)')) as lastname
FROM 
public.person

The regex expressions could probably be a bit more concise; but you get the point. This does by the way not work for persons having two double names (in the Netherlands we have this a lot 'Jan van der Ploeg') so I'd be very careful with the results.

Read and parse a Json File in C#

For any of the JSON parse, use the website http://json2csharp.com/ (easiest way) to convert your JSON into C# class to deserialize your JSON into C# object.

 public class JSONClass
 {
        public string name { get; set; }
        public string url { get; set; }
        public bool visibility { get; set; }
        public string idField { get; set; }
        public bool defaultEvents { get; set; }
        public string type { get; set; }        
 }

Then use the JavaScriptSerializer (from System.Web.Script.Serialization), in case you don't want any third party DLL like newtonsoft.

using (StreamReader r = new StreamReader("jsonfile.json"))
{
   string json = r.ReadToEnd();
   JavaScriptSerializer jss = new JavaScriptSerializer();
   var Items = jss.Deserialize<JSONClass>(json);
}

Then you can get your object with Items.name or Items.Url etc.

How do I export html table data as .csv file?

For exporting html to csv try following this example. More details and examples are available at the author's website.

Create a html2csv.js file and put the following code in it.

jQuery.fn.table2CSV = function(options) {
    var options = jQuery.extend({
        separator: ',',
        header: [],
        delivery: 'popup' // popup, value
    },
    options);

    var csvData = [];
    var headerArr = [];
    var el = this;

    //header
    var numCols = options.header.length;
    var tmpRow = []; // construct header avalible array

    if (numCols > 0) {
        for (var i = 0; i < numCols; i++) {
            tmpRow[tmpRow.length] = formatData(options.header[i]);
        }
    } else {
        $(el).filter(':visible').find('th').each(function() {
            if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
        });
    }

    row2CSV(tmpRow);

    // actual data
    $(el).find('tr').each(function() {
        var tmpRow = [];
        $(this).filter(':visible').find('td').each(function() {
            if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
        });
        row2CSV(tmpRow);
    });
    if (options.delivery == 'popup') {
        var mydata = csvData.join('\n');
        return popup(mydata);
    } else {
        var mydata = csvData.join('\n');
        return mydata;
    }

    function row2CSV(tmpRow) {
        var tmp = tmpRow.join('') // to remove any blank rows
        // alert(tmp);
        if (tmpRow.length > 0 && tmp != '') {
            var mystr = tmpRow.join(options.separator);
            csvData[csvData.length] = mystr;
        }
    }
    function formatData(input) {
        // replace " with “
        var regexp = new RegExp(/["]/g);
        var output = input.replace(regexp, "“");
        //HTML
        var regexp = new RegExp(/\<[^\<]+\>/g);
        var output = output.replace(regexp, "");
        if (output == "") return '';
        return '"' + output + '"';
    }
    function popup(data) {
        var generator = window.open('', 'csv', 'height=400,width=600');
        generator.document.write('<html><head><title>CSV</title>');
        generator.document.write('</head><body >');
        generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
        generator.document.write(data);
        generator.document.write('</textArea>');
        generator.document.write('</body></html>');
        generator.document.close();
        return true;
    }
};

include the js files into the html page like this:

<script type="text/javascript" src="jquery-1.3.2.js" ></script>

<script type="text/javascript" src="html2CSV.js" ></script>

TABLE:

<table id="example1" border="1"  style="background-color:#FFFFCC" width="0%" cellpadding="3" cellspacing="3">

    <tr>

        <th>Title</th>

        <th>Name</th>

        <th>Phone</th>

    </tr>

    <tr>

        <td>Mr.</td>

        <td>John</td>

        <td>07868785831</td>

    </tr>

    <tr>

        <td>Miss</td>

        <td><i>Linda</i></td>

        <td>0141-2244-5566</td>

    </tr>

    <tr>

        <td>Master</td>

        <td>Jack</td>

        <td>0142-1212-1234</td>

    </tr>

    <tr>

        <td>Mr.</td>

        <td>Bush</td>

        <td>911-911-911</td>

    </tr>

</table>

EXPORT BUTTON:

<input value="Export as CSV 2" type="button" onclick="$('#example1').table2CSV({header:['prefix','Employee Name','Contact']})">

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

I catched the same error message today. The solution was to change the document from UTF-8 with BOM to UTF-8 without BOM

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

Parsing a pcap file in python

You might want to start with scapy.

Converting a number with comma as decimal point to float

Using str_replace() to remove the dots is not overkill.

$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));

// At this point, $number is a "natural" float.
print $number;

This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.

lexers vs parsers

When is lexing enough, when do you need EBNF?

EBNF really doesn't add much to the power of grammars. It's just a convenience / shortcut notation / "syntactic sugar" over the standard Chomsky's Normal Form (CNF) grammar rules. For example, the EBNF alternative:

S --> A | B

you can achieve in CNF by just listing each alternative production separately:

S --> A      // `S` can be `A`,
S --> B      // or it can be `B`.

The optional element from EBNF:

S --> X?

you can achieve in CNF by using a nullable production, that is, the one which can be replaced by an empty string (denoted by just empty production here; others use epsilon or lambda or crossed circle):

S --> B       // `S` can be `B`,
B --> X       // and `B` can be just `X`,
B -->         // or it can be empty.

A production in a form like the last one B above is called "erasure", because it can erase whatever it stands for in other productions (product an empty string instead of something else).

Zero-or-more repetiton from EBNF:

S --> A*

you can obtan by using recursive production, that is, one which embeds itself somewhere in it. It can be done in two ways. First one is left recursion (which usually should be avoided, because Top-Down Recursive Descent parsers cannot parse it):

S --> S A    // `S` is just itself ended with `A` (which can be done many times),
S -->        // or it can begin with empty-string, which stops the recursion.

Knowing that it generates just an empty string (ultimately) followed by zero or more As, the same string (but not the same language!) can be expressed using right-recursion:

S --> A S    // `S` can be `A` followed by itself (which can be done many times),
S -->        // or it can be just empty-string end, which stops the recursion.

And when it comes to + for one-or-more repetition from EBNF:

S --> A+

it can be done by factoring out one A and using * as before:

S --> A A*

which you can express in CNF as such (I use right recursion here; try to figure out the other one yourself as an exercise):

S --> A S   // `S` can be one `A` followed by `S` (which stands for more `A`s),
S --> A     // or it could be just one single `A`.

Knowing that, you can now probably recognize a grammar for a regular expression (that is, regular grammar) as one which can be expressed in a single EBNF production consisting only from terminal symbols. More generally, you can recognize regular grammars when you see productions similar to these:

A -->        // Empty (nullable) production (AKA erasure).
B --> x      // Single terminal symbol.
C --> y D    // Simple state change from `C` to `D` when seeing input `y`.
E --> F z    // Simple state change from `E` to `F` when seeing input `z`.
G --> G u    // Left recursion.
H --> v H    // Right recursion.

That is, using only empty strings, terminal symbols, simple non-terminals for substitutions and state changes, and using recursion only to achieve repetition (iteration, which is just linear recursion - the one which doesn't branch tree-like). Nothing more advanced above these, then you're sure it's a regular syntax and you can go with just lexer for that.

But when your syntax uses recursion in a non-trivial way, to produce tree-like, self-similar, nested structures, like the following one:

S --> a S b    // `S` can be itself "parenthesized" by `a` and `b` on both sides.
S -->          // or it could be (ultimately) empty, which ends recursion.

then you can easily see that this cannot be done with regular expression, because you cannot resolve it into one single EBNF production in any way; you'll end up with substituting for S indefinitely, which will always add another as and bs on both sides. Lexers (more specifically: Finite State Automata used by lexers) cannot count to arbitrary number (they are finite, remember?), so they don't know how many as were there to match them evenly with so many bs. Grammars like this are called context-free grammars (at the very least), and they require a parser.

Context-free grammars are well-known to parse, so they are widely used for describing programming languages' syntax. But there's more. Sometimes a more general grammar is needed -- when you have more things to count at the same time, independently. For example, when you want to describe a language where one can use round parentheses and square braces interleaved, but they have to be paired up correctly with each other (braces with braces, round with round). This kind of grammar is called context-sensitive. You can recognize it by that it has more than one symbol on the left (before the arrow). For example:

A R B --> A S B

You can think of these additional symbols on the left as a "context" for applying the rule. There could be some preconditions, postconditions etc. For example, the above rule will substitute R into S, but only when it's in between A and B, leaving those A and B themselves unchanged. This kind of syntax is really hard to parse, because it needs a full-blown Turing machine. It's a whole another story, so I'll end here.

PHP parse/syntax errors; and how to solve them

Unexpected 'endwhile' (T_ENDWHILE)

The syntax is using a colon - if there is no colon the above error will occur.

<?php while($query->fetch()): ?>
 ....
<?php endwhile; ?>

The alternative to this syntax is using curly brackets:

<?php while($query->fetch()) { ?>
  ....
<?php } ?>

http://php.net/manual/en/control-structures.while.php

How to extract multiple JSON objects from one file?

Added streaming support based on the answer of @dunes:

import re
from json import JSONDecoder, JSONDecodeError

NOT_WHITESPACE = re.compile(r"[^\s]")


def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
    buf = ""
    ex = None
    while True:
        block = file_obj.read(buf_size)
        if not block:
            break
        buf += block
        pos = 0
        while True:
            match = NOT_WHITESPACE.search(buf, pos)
            if not match:
                break
            pos = match.start()
            try:
                obj, pos = decoder.raw_decode(buf, pos)
            except JSONDecodeError as e:
                ex = e
                break
            else:
                ex = None
                yield obj
        buf = buf[pos:]
    if ex is not None:
        raise ex

preg_match(); - Unknown modifier '+'

You need to use delimiters with regexes in PHP. You can use the often used /, but PHP lets you use any matching characters, so @ and # are popular.

Further Reading.

If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote().

How to sum digits of an integer in java?

This should be working fine for any number of digits and it will return individual digit's sum

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("enter a string");
    String numbers = input.nextLine();  //String would be 55
    int sum = 0;
    for (char c : numbers.toCharArray()) {
        sum += c - '0';
    }
    System.out.println(sum); //the answer is 10
}

Safe String to BigDecimal conversion

The following sample code works well (locale need to be obtained dynamically)

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.Locale;

class TestBigDecimal {
    public static void main(String[] args) {

        String str = "0,00";
        Locale in_ID = new Locale("in","ID");
        //Locale in_ID = new Locale("en","US");

        DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance(in_ID);
        nf.setParseBigDecimal(true);

        BigDecimal bd = (BigDecimal)nf.parse(str, new ParsePosition(0));

        System.out.println("bd value : " + bd);
    }
}

What is the easiest way to parse an INI file in Java?

Using answer by @Aerospace, I realized that it is legitimate for INI files to have sections without any key-values. In this case, addition to the top-level map should happen before any key-values are found, ex (minimally updated for Java 8):

            Path location = ...;
            try (BufferedReader br = new BufferedReader(new FileReader(location.toFile()))) {
                String line;
                String section = null;
                while ((line = br.readLine()) != null) {
                    Matcher m = this.section.matcher(line);
                    if (m.matches()) {
                        section = m.group(1).trim();
                        entries.computeIfAbsent(section, k -> new HashMap<>());
                    } else if (section != null) {
                        m = keyValue.matcher(line);
                        if (m.matches()) {
                            String key = m.group(1).trim();
                            String value = m.group(2).trim();
                            entries.get(section).put(key, value);
                        }
                    }
                }
            } catch (IOException ex) {
                System.err.println("Failed to read and parse INI file '" + location + "', " + ex.getMessage());
                ex.printStackTrace(System.err);
            }

Import CSV file with mixed data types

Depending on the format of your file, importdata might work.

You can store Strings in a cell array. Type "doc cell" for more information.

Read .csv file in C

A complete example which leaves the fields as NULL-terminated strings in the original input buffer and provides access to them via an array of char pointers. The CSV processor has been confirmed to work with fields enclosed in "double quotes", ignoring any delimiter chars within them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// adjust BUFFER_SIZE to suit longest line 
#define BUFFER_SIZE 1024 * 1024
#define NUM_FIELDS 10
#define MAXERRS 5
#define RET_OK 0
#define RET_FAIL 1
#define FALSE 0
#define TRUE 1

// char* array will point to fields
char *pFields[NUM_FIELDS];
// field offsets into pFields array:
#define LP          0
#define IMIE        1
#define NAZWISKo    2
#define ULICA       3
#define NUMER       4
#define KOD         5
#define MIEJSCOw    6
#define TELEFON     7
#define EMAIL       8
#define DATA_UR     9

long loadFile(FILE *pFile, long *errcount);
static int  loadValues(char *line, long lineno);
static char delim;

long loadFile(FILE *pFile, long *errcount){

    char sInputBuf [BUFFER_SIZE];
    long lineno = 0L;

    if(pFile == NULL)
        return RET_FAIL;

    while (!feof(pFile)) {

        // load line into static buffer
        if(fgets(sInputBuf, BUFFER_SIZE-1, pFile)==NULL)
            break;

        // skip first line (headers)
        if(++lineno==1)
            continue;

        // jump over empty lines
        if(strlen(sInputBuf)==0)
            continue;
        // set pFields array pointers to null-terminated string fields in sInputBuf
        if(loadValues(sInputBuf,lineno)==RET_FAIL){
           (*errcount)++;
            if(*errcount > MAXERRS)
                break;
        } else {    
            // On return pFields array pointers point to loaded fields ready for load into DB or whatever
            // Fields can be accessed via pFields, e.g.
            printf("lp=%s, imie=%s, data_ur=%s\n", pFields[LP], pFields[IMIE], pFields[DATA_UR]);
        }
    }
    return lineno;
}


static int  loadValues(char *line, long lineno){
    if(line == NULL)
        return RET_FAIL;

    // chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.)
    // can be removed if sure fgets has removed both CR and LF from end of line
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1) == '\n')
        *(line + strlen(line)-1) = '\0';
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1 )== '\n')
        *(line + strlen(line)-1) = '\0';

    char *cptr = line;
    int fld = 0;
    int inquote = FALSE;
    char ch;

    pFields[fld]=cptr;
    while((ch=*cptr) != '\0' && fld < NUM_FIELDS){
        if(ch == '"') {
            if(! inquote)
                pFields[fld]=cptr+1;
            else {
                *cptr = '\0';               // zero out " and jump over it
            }
            inquote = ! inquote;
        } else if(ch == delim && ! inquote){
            *cptr = '\0';                   // end of field, null terminate it
            pFields[++fld]=cptr+1;
        }
        cptr++;
    }   
    if(fld > NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) exceeded on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;
    } else if (fld < NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) not reached on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;    
    }
    return RET_OK;
}

int main(int argc, char **argv)
{
   FILE *fp;
   long errcount = 0L;
   long lines = 0L;

   if(argc!=3){
       printf("Usage: %s csvfilepath delimiter\n", basename(argv[0]));
       return (RET_FAIL);
   }   
   if((delim=argv[2][0])=='\0'){
       fprintf(stderr,"delimiter must be specified\n");
       return (RET_FAIL);
   }
   fp = fopen(argv[1] , "r");
   if(fp == NULL) {
      fprintf(stderr,"Error opening file: %d\n",errno);
      return(RET_FAIL);
   }
   lines=loadFile(fp,&errcount);
   fclose(fp);
   printf("Processed %ld lines, encountered %ld error(s)\n", lines, errcount);
   if(errcount>0)
        return(RET_FAIL);
    return(RET_OK); 
}

Loop through all elements in XML using NodeList

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("file.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) nl.item(i);
            if (el.getNodeName().contains("staff")) {
                String name = el.getElementsByTagName("name").item(0).getTextContent();
                String phone = el.getElementsByTagName("phone").item(0).getTextContent();
                String email = el.getElementsByTagName("email").item(0).getTextContent();
                String area = el.getElementsByTagName("area").item(0).getTextContent();
                String city = el.getElementsByTagName("city").item(0).getTextContent();
            }
        }
    }

Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.

For each node under stuff (name, phone, email, area, city)

 el.getElementsByTagName("name").item(0).getTextContent(); 

el.getElementsByTagName("name") will extract the "name" nodes under stuff, .item(0) will get you the first node and .getTextContent() will get the text content inside.

Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:

public class Staff {
    private String name;
    private String phone;
    private String email;
    private String area;
    private String city;
...getters setters
}

Then using jackson:

    JsonNode root = new XmlMapper().readTree(xml.getBytes());
    ObjectMapper mapper = new ObjectMapper();
    root.forEach(node -> consume(node, mapper));



private void consume(JsonNode node, ObjectMapper mapper) {
    try {
        Staff staff = mapper.treeToValue(node, Staff.class);
        //TODO your job with staff
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

How to parse a query string into a NameValueCollection in .NET

I wanted to remove the dependency on System.Web so that I could parse the query string of a ClickOnce deployment, while having the prerequisites limited to the "Client-only Framework Subset".

I liked rp's answer. I added some additional logic.

public static NameValueCollection ParseQueryString(string s)
    {
        NameValueCollection nvc = new NameValueCollection();

        // remove anything other than query string from url
        if(s.Contains("?"))
        {
            s = s.Substring(s.IndexOf('?') + 1);
        }

        foreach (string vp in Regex.Split(s, "&"))
        {
            string[] singlePair = Regex.Split(vp, "=");
            if (singlePair.Length == 2)
            {
                nvc.Add(singlePair[0], singlePair[1]);
            }
            else
            {
                // only one key with no value specified in query string
                nvc.Add(singlePair[0], string.Empty);
            }
        }

        return nvc;
    }

PHP CSV string to array

Handy oneliner:

$csv = array_map('str_getcsv', file('data.csv'));

Parse query string in JavaScript

How about this?

function getQueryVar(varName){
    // Grab and unescape the query string - appending an '&' keeps the RegExp simple
    // for the sake of this example.
    var queryStr = unescape(window.location.search) + '&';

    // Dynamic replacement RegExp
    var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');

    // Apply RegExp to the query string
    var val = queryStr.replace(regex, "$1");

    // If the string is the same, we didn't find a match - return false
    return val == queryStr ? false : val;
}

..then just call it with:

alert('Var "dest" = ' + getQueryVar('dest'));

Cheers

Parsing a comma-delimited std::string

#include <sstream>
#include <vector>

const char *input = "1,1,1,1,2,1,1,1,0";

int main() {
    std::stringstream ss(input);
    std::vector<int> output;
    int i;
    while (ss >> i) {
        output.push_back(i);
        ss.ignore(1);
    }
}

Bad input (for instance consecutive separators) will mess this up, but you did say simple.

Get url parameters from a string in .NET

Here's another alternative if, for any reason, you can't or don't want to use HttpUtility.ParseQueryString().

This is built to be somewhat tolerant to "malformed" query strings, i.e. http://test/test.html?empty= becomes a parameter with an empty value. The caller can verify the parameters if needed.

public static class UriHelper
{
    public static Dictionary<string, string> DecodeQueryParameters(this Uri uri)
    {
        if (uri == null)
            throw new ArgumentNullException("uri");

        if (uri.Query.Length == 0)
            return new Dictionary<string, string>();

        return uri.Query.TrimStart('?')
                        .Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(parameter => parameter.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
                        .GroupBy(parts => parts[0],
                                 parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
                        .ToDictionary(grouping => grouping.Key,
                                      grouping => string.Join(",", grouping));
    }
}

Test

[TestClass]
public class UriHelperTest
{
    [TestMethod]
    public void DecodeQueryParameters()
    {
        DecodeQueryParametersTest("http://test/test.html", new Dictionary<string, string>());
        DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>());
        DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary<string, string> { { "key", "bla/blub.xml" } });
        DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } });
        DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary<string, string> { { "empty", "" } });
        DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary<string, string> { { "empty", "" } });
        DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary<string, string> { { "key", "1" } });
        DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } });
        DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary<string, string> { { "key", "value=what" } });
        DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22",
            new Dictionary<string, string>
            {
                { "q", "energy+edge" },
                { "rls", "com.microsoft:en-au" },
                { "ie", "UTF-8" },
                { "oe", "UTF-8" },
                { "startIndex", "" },
                { "startPage", "1%22" },
            });
        DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue", new Dictionary<string, string> { { "key", "value,anotherValue" } });
    }

    private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected)
    {
        Dictionary<string, string> parameters = new Uri(uri).DecodeQueryParameters();
        Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri);
        foreach (var key in expected.Keys)
        {
            Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri);
            Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri);
        }
    }
}

How to get everything after last slash in a URL?

url ='http://www.test.com/page/TEST2'.split('/')[4]
print url

Output: TEST2.

Parse HTML in Android

We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..

So Code goes like this

  private void getWebsite() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        final StringBuilder builder = new StringBuilder();

        try {
          Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
          String title = doc.title();
          Elements links = doc.select("a[href]");

          builder.append(title).append("\n");

          for (Element link : links) {
            builder.append("\n").append("Link : ").append(link.attr("href"))
            .append("\n").append("Text : ").append(link.text());
          }
        } catch (IOException e) {
          builder.append("Error : ").append(e.getMessage()).append("\n");
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText(builder.toString());
          }
        });
      }
    }).start();
  }

You just have to call the above function in onCreate Method of your MainActivity

I hope this one is also helpful for you guys.

Also read the original blog at Medium

How to parse JSON data with jQuery / JavaScript?

Setting dataType:'json' will parse JSON for you:

$.ajax({
  type: 'GET',
  url: 'http://example/functions.php',
  data: {get_param: 'value'},
  dataType: 'json',
  success: function (data) {
    var names = data
    $('#cand').html(data);
  }
});

Or else you can use parseJSON:

var parsedJson = $.parseJSON(jsonToBeParsed);

Then you can iterate the following:

var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';

...by using $().each:

var json = $.parseJSON(j);
$(json).each(function (i, val) {
  $.each(val, function (k, v) {
    console.log(k + " : " + v);
  });
}); 

JSFiddle

How to parse XML using vba

Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")

And the result line E1 will have your parsed value:

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365

Parsing Json rest api response in C#

Create a C# class that maps to your Json and use Newsoft JsonConvert to Deserialise it.

For example:

public Class MyResponse
{
    public Meta Meta { get; set; }
    public Response Response { get; set; }
}

How to read GET data from a URL using JavaScript?

Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.

The a code below works and is still useful in situations where URLSearchParams is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.


function parseURLParams(url) {
    var queryStart = url.indexOf("?") + 1,
        queryEnd   = url.indexOf("#") + 1 || url.length + 1,
        query = url.slice(queryStart, queryEnd - 1),
        pairs = query.replace(/\+/g, " ").split("&"),
        parms = {}, i, n, v, nv;

    if (query === url || query === "") return;

    for (i = 0; i < pairs.length; i++) {
        nv = pairs[i].split("=", 2);
        n = decodeURIComponent(nv[0]);
        v = decodeURIComponent(nv[1]);

        if (!parms.hasOwnProperty(n)) parms[n] = [];
        parms[n].push(nv.length === 2 ? v : null);
    }
    return parms;
}

Use as follows:

var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
    urlParams = parseURLParams(urlString);

which returns a an object like this:

{
  "a"  : ["a a"],     /* param values are always returned as arrays */
  "b b": ["b"],       /* param names can have special chars as well */
  "c"  : ["1", "2"]   /* an URL param can occur multiple times!     */
  "d"  : [null]       /* parameters without values are set to null  */ 
} 

So

parseURLParams("www.mints.com?name=something")

gives

{name: ["something"]}

EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.

In C#, how to check whether a string contains an integer?

Assuming you want to check that all characters in the string are digits, you could use the Enumerable.All Extension Method with the Char.IsDigit Method as follows:

bool allCharactersInStringAreDigits = myStringVariable.All(char.IsDigit);

How to use XMLReader in PHP?

For xml formatted with attributes...

data.xml:

<building_data>
<building address="some address" lat="28.902914" lng="-71.007235" />
<building address="some address" lat="48.892342" lng="-75.0423423" />
<building address="some address" lat="58.929753" lng="-79.1236987" />
</building_data>

php code:

$reader = new XMLReader();

if (!$reader->open("data.xml")) {
    die("Failed to open 'data.xml'");
}

while($reader->read()) {
  if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'building') {
    $address = $reader->getAttribute('address');
    $latitude = $reader->getAttribute('lat');
    $longitude = $reader->getAttribute('lng');
}

$reader->close();

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

The file that I was using was saved through Powershell in UTF-8 format. I changed it to ANSI and it fixed the problem.

Creating a simple configuration file and parser in C++

I've searched config parsing libraries for my project recently and found these libraries:

How to parse a JSON string into JsonNode in Jackson?

Richard's answer is correct. Alternatively you can also create a MappingJsonFactory (in org.codehaus.jackson.map) which knows where to find ObjectMapper. The error you got was because the regular JsonFactory (from core package) has no dependency to ObjectMapper (which is in the mapper package).

But usually you just use ObjectMapper and do not worry about JsonParser or other low level components -- they will just be needed if you want to data-bind parts of stream, or do low-level handling.

How to parse data in JSON format?

Can use either json or ast python modules:

Using json :
=============

import json
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_data = json.loads(jsonStr)
print(f"json_data: {json_data}")
print(f"json_data['two']: {json_data['two']}")

Output:
json_data: {'one': '1', 'two': '2', 'three': '3'}
json_data['two']: 2




Using ast:
==========

import ast
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_dict = ast.literal_eval(jsonStr)
print(f"json_dict: {json_dict}")
print(f"json_dict['two']: {json_dict['two']}")

Output:
json_dict: {'one': '1', 'two': '2', 'three': '3'}
json_dict['two']: 2

How do I parse a string with a decimal point to a double?

It's difficult without specifying what decimal separator to look for, but if you do, this is what I'm using:

    public static double Parse(string str, char decimalSep)
    {
        string s = GetInvariantParseString(str, decimalSep);
        return double.Parse(s, System.Globalization.CultureInfo.InvariantCulture);
    }

    public static bool TryParse(string str, char decimalSep, out double result)
    {
        // NumberStyles.Float | NumberStyles.AllowThousands got from Reflector
        return double.TryParse(GetInvariantParseString(str, decimalSep), NumberStyles.Float | NumberStyles.AllowThousands, System.Globalization.CultureInfo.InvariantCulture, out result);
    }

    private static string GetInvariantParseString(string str, char decimalSep)
    {
        str = str.Replace(" ", "");

        if (decimalSep != '.')
            str = SwapChar(str, decimalSep, '.');

        return str;
    }
    public static string SwapChar(string value, char from, char to)
    {
        if (value == null)
            throw new ArgumentNullException("value");

        StringBuilder builder = new StringBuilder();

        foreach (var item in value)
        {
            char c = item;
            if (c == from)
                c = to;
            else if (c == to)
                c = from;

            builder.Append(c);
        }
        return builder.ToString();
    }

    private static void ParseTestErr(string p, char p_2)
    {
        double res;
        bool b = TryParse(p, p_2, out res);
        if (b)
            throw new Exception();
    }

    private static void ParseTest(double p, string p_2, char p_3)
    {
        double d = Parse(p_2, p_3);
        if (d != p)
            throw new Exception();
    }

    static void Main(string[] args)
    {
        ParseTest(100100100.100, "100.100.100,100", ',');
        ParseTest(100100100.100, "100,100,100.100", '.');
        ParseTest(100100100100, "100.100.100.100", ',');
        ParseTest(100100100100, "100,100,100,100", '.');
        ParseTestErr("100,100,100,100", ',');
        ParseTestErr("100.100.100.100", '.');
        ParseTest(100100100100, "100 100 100 100.0", '.');
        ParseTest(100100100.100, "100 100 100.100", '.');
        ParseTest(100100100.100, "100 100 100,100", ',');
        ParseTest(100100100100, "100 100 100,100", '.');
        ParseTest(1234567.89, "1.234.567,89", ',');    
        ParseTest(1234567.89, "1 234 567,89", ',');    
        ParseTest(1234567.89, "1 234 567.89",     '.');
        ParseTest(1234567.89, "1,234,567.89",    '.');
        ParseTest(1234567.89, "1234567,89",     ',');
        ParseTest(1234567.89, "1234567.89",  '.');
        ParseTest(123456789, "123456789", '.');
        ParseTest(123456789, "123456789", ',');
        ParseTest(123456789, "123.456.789", ',');
        ParseTest(1234567890, "1.234.567.890", ',');
    }

This should work with any culture. It correctly fails to parse strings that has more than one decimal separator, unlike implementations that replace instead of swap.

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

In case you need C++11 compatibility and cannot use boost, here is a boost-compatible drop-in with an example of usage:

#include <iostream>
#include <string>

static bool starts_with(const std::string str, const std::string prefix)
{
    return ((prefix.size() <= str.size()) && std::equal(prefix.begin(), prefix.end(), str.begin()));
}

int main(int argc, char* argv[])
{
    bool usage = false;
    unsigned int foos = 0; // default number of foos if no parameter was supplied

    if (argc > 1)
    {
        const std::string fParamPrefix = "-f="; // shorthand for foo
        const std::string fooParamPrefix = "--foo=";

        for (unsigned int i = 1; i < argc; ++i)
        {
            const std::string arg = argv[i];

            try
            {
                if ((arg == "-h") || (arg == "--help"))
                {
                    usage = true;
                } else if (starts_with(arg, fParamPrefix)) {
                    foos = std::stoul(arg.substr(fParamPrefix.size()));
                } else if (starts_with(arg, fooParamPrefix)) {
                    foos = std::stoul(arg.substr(fooParamPrefix.size()));
                }
            } catch (std::exception& e) {
                std::cerr << "Invalid parameter: " << argv[i] << std::endl << std::endl;
                usage = true;
            }
        }
    }

    if (usage)
    {
        std::cerr << "Usage: " << argv[0] << " [OPTION]..." << std::endl;
        std::cerr << "Example program for parameter parsing." << std::endl << std::endl;
        std::cerr << "  -f, --foo=N   use N foos (optional)" << std::endl;
        return 1;
    }

    std::cerr << "number of foos given: " << foos << std::endl;
}

How to parse a month name (string) to an integer for comparison in C#?

If you are using c# 3.0 (or above) you can use extenders

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

You have extra spaces after END; that cause the heredoc not terminated.

Extracting Path from OpenFileDialog path/filename

if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
    strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}

Regular expression to detect semi-colon terminated C++ for & while loops

I wouldn't even pay attention to the contents of the parens.

Just match any line that starts with for and ends with semi-colon:

^\t*for.+;$

Unless you've got for statements split over multiple lines, that will work fine?

How to parse JSON in Java

There are 2 main options...

  1. Object mapping. When you deserialize JSON data to a number of instances of:

    1.1. Some predefined classes, like Maps. In this case, you don't have to design your own POJO classes. Some libraries: org.json.simple https://www.mkyong.com/java/json-simple-example-read-and-write-json/

    1.2. Your own POJO classes. You have to design your own POJO classes to present JSON data, but this may be helpful if you are going to use them into your business logic as well. Some libraries: Gson, Jackson (see http://tutorials.jenkov.com/java-json/index.html)

The main backwards of the mapping is that it leads to intensive memory allocation (and GC pressure) and CPU utilization.

  1. Stream oriented parsing. For example, both Gson and Jackson support such lightweight parsing. Also, you can take a look at an example of custom, fast and GC-free parser https://github.com/anatolygudkov/green-jelly. Prefer this way in case you need to parse a lot of data and in latency sensitivity applications.

Parse JSON object with string and value only

My pseudocode example will be as follows:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;

Parse (split) a string in C++ using string delimiter (standard C++)

#include<iostream>
#include<algorithm>
using namespace std;

int split_count(string str,char delimit){
return count(str.begin(),str.end(),delimit);
}

void split(string str,char delimit,string res[]){
int a=0,i=0;
while(a<str.size()){
res[i]=str.substr(a,str.find(delimit));
a+=res[i].size()+1;
i++;
}
}

int main(){

string a="abc.xyz.mno.def";
int x=split_count(a,'.')+1;
string res[x];
split(a,'.',res);

for(int i=0;i<x;i++)
cout<<res[i]<<endl;
  return 0;
}

P.S: Works only if the lengths of the strings after splitting are equal

Parsing JSON in Java without knowing JSON format

Here is a sample I wrote shows how I parse a json and mess every number inside it:

public class JsonParser {

    public static Object parseAndMess(Object object) throws IOException {
        String json = JsonUtil.toJson(object);
        JsonNode jsonNode = parseAndMess(json);
        if(null != jsonNode)
            return JsonUtil.toObject(jsonNode, object.getClass());

        return null;
    }

    public static JsonNode parseAndMess(String json) throws IOException {
        JsonNode rootNode = parse(json);
        return mess(rootNode, new Random());
    }

    private static JsonNode parse(String json) throws IOException {
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        JsonNode rootNode = mapper.readTree(json);
        return rootNode;

    }

    private static JsonNode mess(JsonNode rootNode, Random rand) throws IOException {
        if (rootNode instanceof ObjectNode) {
            Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
            while (fieldsIterator.hasNext()) {
                Map.Entry<String, JsonNode> field = fieldsIterator.next();
                replaceObjectNode((ObjectNode) rootNode, field, rand);
            }
        } else if (rootNode instanceof ArrayNode) {
            ArrayNode arrayNode = ((ArrayNode) rootNode);
            replaceArrayNode(arrayNode, rand);
        }
        return rootNode;
    }

    private static void replaceObjectNode(ObjectNode rootNode, Map.Entry<String, JsonNode> field, Random rand)
            throws IOException {
        JsonNode childNode = field.getValue();
        if (childNode instanceof IntNode) {
            (rootNode).put(field.getKey(), rand.nextInt(1000));
        } else if (childNode instanceof LongNode) {
            (rootNode).put(field.getKey(), rand.nextInt(1000000));
        } else if (childNode instanceof FloatNode) {
            (rootNode).put(field.getKey(), format(rand.nextFloat()));
        } else if (childNode instanceof DoubleNode) {
            (rootNode).put(field.getKey(), format(rand.nextFloat()));
        } else {
            mess(childNode, rand);
        }
    }

    private static void replaceArrayNode(ArrayNode arrayNode, Random rand) throws IOException {
        int arrayLength = arrayNode.size();
        if(arrayLength == 0)
            return;
        if (arrayNode.get(0) instanceof IntNode) {
            for (int i = 0; i < arrayLength; i++) {
                arrayNode.set(i, new IntNode(rand.nextInt(10000)));
            }
        } else if (arrayNode.get(0) instanceof LongNode) {
            arrayNode.removeAll();
            for (int i = 0; i < arrayLength; i++) {
                arrayNode.add(rand.nextInt(1000000));
            }
        } else if (arrayNode.get(0) instanceof FloatNode) {
            arrayNode.removeAll();
            for (int i = 0; i < arrayLength; i++) {
                arrayNode.add(format(rand.nextFloat()));
            }
        } else if (arrayNode.get(0) instanceof DoubleNode) {
            arrayNode.removeAll();
            for (int i = 0; i < arrayLength; i++) {
                arrayNode.add(format(rand.nextFloat()));
            }
        } else {
            for (int i = 0; i < arrayLength; i++) {
                mess(arrayNode.get(i), rand);
            }
        }
    }

    public static void print(JsonNode rootNode) throws IOException {
        System.out.println(rootNode.toString());
    }

    private static double format(float a) {
        return Math.round(a * 10000.0) / 100.0;
    }
}

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

MySQL Cannot drop index needed in a foreign key constraint

In my case I dropped the foreign key and I still could not drop the index. That was because there was yet another table that had a foreign key to this table on the same fields. After I dropped the foreign key on the other table I could drop the indexes on this table.

HTTP 400 (bad request) for logical error, not malformed request syntax

It could be argued that having incorrect data in your request is a syntax error, even if your actual request at the HTTP level (request line, headers etc) is syntactically valid.

For example, if a Restful web service is documented as accepting POSTs with a custom XML Content Type of application/vnd.example.com.widget+xml, and you instead send some gibberish plain text or a binary file, it seems resasonable to treat that as a syntax error - your request body is not in the expected form.

I don't know of any official references to back this up though, as usual it seems to be down to interpreting RFC 2616.

Update: Note the revised wording in RFC 7231 §6.5.1:

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

seems to support this argument more than the now obsoleted RFC 2616 §10.4.1 which said just:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

Declaring and initializing a string array in VB.NET

I believe you need to specify "Option Infer On" for this to work.

Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.

Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.

Opinion incoming:

Also, you mention that you've got "Option Explicit Off". Please don't do this.

Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":

Dim X as Integer
Y = 3

This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.

How to start Activity in adapter?

callback from adapter to activity can be done using registering listener in form of interface: Make an interface:

      public MyInterface{
         public void  yourmethod(//incase needs parameters );
         }

In Adapter Let's Say MyAdapter:

    public MyAdapter extends BaseAdapter{
       private MyInterface listener;

    MyAdapter(Context context){
        try {
            this. listener = (( MyInterface ) context);
              } catch (ClassCastException e) {
               throw new ClassCastException("Activity must implement MyInterface");
          }

//do this where u need to fire listener l

          try {
                listener . yourmethod ();
            } catch (ClassCastException exception) {
               // do something
            }

      In Activity Implement your method:


         MyActivity extends AppCompatActivity implements MyInterface{

                yourmethod(){
                //do whatever you want
                     }
                     }

Extract month and year from a zoo::yearmon object

The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:

cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))

Check if string matches pattern

One-liner: re.match(r"pattern", string) # No need to compile

import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
...     print('Yes')
... 
Yes

You can evalute it as bool if needed

>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True

ssh_exchange_identification: Connection closed by remote host under Git bash

Hi I fix this on one vps service, restarting it, other way is if you have a console from your service o any other way to run a command in your remote machine the only command you must run is restart the ssh daemon and enjoy!! :P

/etc/init.d/ssh restart

Display all post meta keys and meta values of the same post ID in wordpress

As of Jan 2020 and WordPress v5.3.2, I confirm the following works fine.

It will include the field keys with their equivalent underscore keys as well, but I guess if you properly "enum" your keys in your code, that should be no problem:

$meta_values   = get_post_meta( get_the_ID() );
$example_field = meta_values['example_field_key'][0];

//OR if you do enum style 
//(emulation of a class with a list of *const* as enum does not exist in PHP per se)
$example_field = meta_values[PostTypeEnum::FIELD_EXAMPLE_KEY][0]; 

As the print_r(meta_values); gives:

Array
(
    [_edit_lock] => Array
        (
            [0] => 1579542560:1
        )

    [_edit_last] => Array
        (
            [0] => 1
        )

    [example_field] => Array
        (
            [0] => 13
        )
)

Hope that helps someone, go make a ruckus!

List of <p:ajax> events

As the list of possible events is not tied to p:ajax itself but to the component it is used with, you'll have to ask the component for which ajax events it supports.

There are multiple ways to determine the ajax events for a given component:

1) Ask the component in xhtml:

You can output the list directly in xhtml by binding that component to a request scoped variable and printing the eventNames property:

<p:autoComplete binding="#{ac}"></p:autoComplete>
<h:outputText value="#{ac.eventNames}" />

This outputs

[blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup,
 mousedown, mousemove, mouseout, mouseover, mouseup, select, itemSelect,
 itemUnselect, query, moreText, clear]

2) Ask the component in java code:

Figure out the component implementation class and invoke its' implementation of javax.faces.component.UIComponentBase.getEventNames() method:

import javax.faces.component.UIComponentBase;

public class SomeTest {

    public static void main(String[] args) {
        dumpEvents(new org.primefaces.component.inputtext.InputText());
        dumpEvents(new org.primefaces.component.autocomplete.AutoComplete());
        dumpEvents(new org.primefaces.component.datatable.DataTable());
    }

    private static void dumpEvents(UIComponentBase comp) {
        System.out.println(
                comp + ":\n\tdefaultEvent: " + comp.getDefaultEventName() + ";\n\tEvents: " + comp.getEventNames());
    }

}

This outputs:

org.primefaces.component.inputtext.InputText@239963d8:
    defaultEvent: valueChange;
    Events: [blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup, select]
org.primefaces.component.autocomplete.AutoComplete@72d818d1:
    defaultEvent: valueChange;
    Events: [blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup, select, itemSelect, itemUnselect, query, moreText, clear]
org.primefaces.component.datatable.DataTable@614ddd49:
    defaultEvent: null;
    Events: [rowUnselect, colReorder, tap, rowEditInit, toggleSelect, cellEditInit, sort, rowToggle, cellEdit, rowSelectRadio, filter, cellEditCancel, rowSelect, contextMenu, taphold, rowReorder, colResize, rowUnselectCheckbox, rowDblselect, rowEdit, page, rowEditCancel, virtualScroll, rowSelectCheckbox]

3) 'rtfm' ;-)

Best option is to look into the documentation of the particular component in use as hopefully provided by the component developers, not limited to PrimeFaces btw. (p:ajax can be attached to any component providing ajax behaviors).

The advantage over previous suggestions is that the documentation not only provides the event names, but also enhanced description of the event potentially enriched with an event type class that can be caught by a listener.

For example the org.primefaces.event.SelectEvent in case of

<p:ajax event="itemSelect" listener="#{anyBean.onItemSelect}"/>

and listener method signature public void onItemSelect(SelectEvent) provides additional event contextual data.

Where there is no explicit list of ajax events on a compoment in the PrimeFaces documentation, the list of on* javascript callbacks can be used as events by removing the 'on' and using the remainder as an event name. The other answers in this question provides help on these plain dom events too.

How to compare Boolean?

As long as checker is not null, you may use !checker as posted. This is possible since Java 5, because this Boolean variable will be autoboxed to the primivite boolean value.

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

Another way, is simply add the headers to your route:

router.get('/', function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // If needed
    res.setHeader('Access-Control-Allow-Credentials', true); // If needed

    res.send('cors problem fixed:)');
});

Could not load file or assembly for Oracle.DataAccess in .NET

please register your Oracle.DataAccess to GAC

raProvCfg.exe /action:gac /providerpath:C:\oracle\product\11.2.0\x32\ODP.NET\bin\4\Oracle.DataAccess.dll

OraProvCfg.exe /action:gac /providerpath:C:\oracle\product\11.2.0\x64\ODP.NET\bin\4\Oracle.DataAccess.dll

Display label text with line breaks in c#

You can also use <br/> where you want to break the text.

How to print SQL statement in codeigniter model

use get_compiled_select() to retrieve query instead of replace it

base_url() function not working in codeigniter

Load url helper in controller

$this->load->helper('url');

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

Perform .join on value in array of objects

lets say the objects array is referenced by the variable users

If ES6 can be used then the easiest solution will be:

users.map(user => user.name).join(', ');

If not, and lodash can be used so :

 _.map(users, function(user) {
     return user.name;
 }).join(', ');

Array of arrays (Python/NumPy)

It seems strange that you would write arrays without commas (is that a MATLAB syntax?)

Have you tried going through NumPy's documentation on multi-dimensional arrays?

It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:

>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)

>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])

It has also been answered already...

From the documentation for MATLAB users:

You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:

mat("1 2 3; 4 5 6")

or

matrix("[1 2 3; 4 5 6]")

Please give it a try and tell me how it goes.

Python Variable Declaration

For scoping purpose, I use:

custom_object = None

Git removing upstream from local repository

git remote manpage is pretty straightforward:

Use

Older (backwards-compatible) syntax:
$ git remote rm upstream
Newer syntax for newer git versions: (* see below)
$ git remote remove upstream

Then do:    
$ git remote add upstream https://github.com/Foo/repos.git

or just update the URL directly:

$ git remote set-url upstream https://github.com/Foo/repos.git

or if you are comfortable with it, just update the .git/config directly - you can probably figure out what you need to change (left as exercise for the reader).

...
[remote "upstream"]
    fetch = +refs/heads/*:refs/remotes/upstream/*
    url = https://github.com/foo/repos.git
...

===

* Regarding 'git remote rm' vs 'git remote remove' - this changed around git 1.7.10.3 / 1.7.12 2 - see

https://code.google.com/p/git-core/source/detail?spec=svne17dba8fe15028425acd6a4ebebf1b8e9377d3c6&r=e17dba8fe15028425acd6a4ebebf1b8e9377d3c6

Log message

remote: prefer subcommand name 'remove' to 'rm'

All remote subcommands are spelled out words except 'rm'. 'rm', being a
popular UNIX command name, may mislead users that there are also 'ls' or
'mv'. Use 'remove' to fit with the rest of subcommands.

'rm' is still supported and used in the test suite. It's just not
widely advertised.

How to check if a string contains a specific text

You can use strpos() or stripos() to check if the string contain the given needle. It will return the position where it was found, otherwise will return FALSE.

Use the operators === or `!== to differ FALSE from 0 in PHP.

How to select all elements with a particular ID in jQuery?

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

The problem is you're telling Gson you have an object of your type. You don't. You have an array of objects of your type. You can't just try and cast the result like that and expect it to magically work ;)

The User guide for Gson Explains how to deal with this:

https://github.com/google/gson/blob/master/UserGuide.md

This will work:

ChannelSearchEnum[] enums = gson.fromJson(yourJson, ChannelSearchEnum[].class);

But this is better:

Type collectionType = new TypeToken<Collection<ChannelSearchEnum>>(){}.getType();
Collection<ChannelSearchEnum> enums = gson.fromJson(yourJson, collectionType);

Yarn: How to upgrade yarn version using terminal?

I had an outdated symlink that was preventing me from accessing the proper bin. I had also recently gone through a node upgrade which means a lot of my newer bins were available in a different folder with what i think was a lower priority

Here is what worked for me:

yarn -v 
> 1.15.2

which yarn
> /Users/lfender/.yarn/bin/yarn 

rm -rf /Users/lfender/.yarn/bin/yarn
npm uninstall --global yarn; npm install --global yarn

> + [email protected]
> added 1 package in 0.179s

which yarn
> /Users/lfender/.nvm/versions/node/v12.2.0/bin/yarn

yarn -v
> 1.16.0

If you are not using NVM, the location of your bin installs are likely to be unique to your system

From there, I've switched to doing yarn policies set-version as outlined here https://stackoverflow.com/a/55278430/1426788 to define my yarn version at the repo level

In log4j, does checking isDebugEnabled before logging improve performance?

Since many people are probably viewing this answer when searching for log4j2 and nearly all current answers do not consider log4j2 or recent changes in it, this should hopefully answer the question.

log4j2 supports Suppliers (currently their own implementation, but according to the documentation it is planned to use Java's Supplier interface in version 3.0). You can read a little bit more about this in the manual. This allows you to put expensive log message creation into a supplier which only creates the message if it is going to be logged:

LogManager.getLogger().debug(() -> createExpensiveLogMessage());

What is meant by the term "hook" in programming?

Oftentimes hooking refers to Win32 message hooking or the Linux/OSX equivalents, but more generically hooking is simply notifying another object/window/program/etc that you want to be notified when a specified action happens. For instance: Having all windows on the system notify you as they are about to close.

As a general rule, hooking is somewhat hazardous since doing it without understanding how it affects the system can lead to instability or at the very leas unexpected behaviour. It can also be VERY useful in certain circumstances, thought. For instance: FRAPS uses it to determine which windows it should show it's FPS counter on.

Get distance between two points in canvas

The distance between two coordinates x and y! x1 and y1 is the first point/position, x2 and y2 is the second point/position!

_x000D_
_x000D_
function diff (num1, num2) {_x000D_
  if (num1 > num2) {_x000D_
    return (num1 - num2);_x000D_
  } else {_x000D_
    return (num2 - num1);_x000D_
  }_x000D_
};_x000D_
_x000D_
function dist (x1, y1, x2, y2) {_x000D_
  var deltaX = diff(x1, x2);_x000D_
  var deltaY = diff(y1, y2);_x000D_
  var dist = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));_x000D_
  return (dist);_x000D_
};
_x000D_
_x000D_
_x000D_

Passing ArrayList from servlet to JSP

request.getAttribute("servletName") method will return Object that you need to cast to ArrayList

ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");

What's the best way to build a string of delimited items in Java?

You can try something like this:

StringBuilder sb = new StringBuilder();
if (condition) { sb.append("elementName").append(","); }
if (anotherCondition) { sb.append("anotherElementName").append(","); }
String parameterString = sb.toString();

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

How to count the number of columns in a table using SQL?

Maybe something like this:

SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'

this will count number of columns in a the table FOO

You can also just

select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';

where the owner is schema and note that Table Names are upper case

EPPlus - Read Excel Table

Below code will read excel data into a datatable, which is converted to list of datarows.

if (FileUpload1.HasFile)
{
    if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
    {
        Stream fs = FileUpload1.FileContent;
        ExcelPackage package = new ExcelPackage(fs);
        DataTable dt = new DataTable();
        dt= package.ToDataTable();
        List<DataRow> listOfRows = new List<DataRow>();
        listOfRows = dt.AsEnumerable().ToList();

    }
}
using OfficeOpenXml;
using System.Data;
using System.Linq;

 public static class ExcelPackageExtensions
    {
        public static DataTable ToDataTable(this ExcelPackage package)
        {
            ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
            DataTable table = new DataTable();
            foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
            {
                table.Columns.Add(firstRowCell.Text);
            }

            for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
            {
                var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
                var newRow = table.NewRow();
                foreach (var cell in row)
                {
                    newRow[cell.Start.Column - 1] = cell.Text;
                }
                table.Rows.Add(newRow);
            }
            return table;
        }

    }

How do I get the AM/PM value from a DateTime?

+ PC.GetHour(datetime) > 11 ? "pm" : "am"

For your example but there are better ways to format datetime.

Check element exists in array

EAFP vs. LBYL

I understand your dilemma, but Python is not PHP and coding style known as Easier to Ask for Forgiveness than for Permission (or EAFP in short) is a common coding style in Python.

See the source (from documentation):

EAFP - Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

So, basically, using try-catch statements here is not a last resort; it is a common practice.

"Arrays" in Python

PHP has associative and non-associative arrays, Python has lists, tuples and dictionaries. Lists are similar to non-associative PHP arrays, dictionaries are similar to associative PHP arrays.

If you want to check whether "key" exists in "array", you must first tell what type in Python it is, because they throw different errors when the "key" is not present:

>>> l = [1,2,3]
>>> l[4]

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    l[4]
IndexError: list index out of range
>>> d = {0: '1', 1: '2', 2: '3'}
>>> d[4]

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    d[4]
KeyError: 4

And if you use EAFP coding style, you should just catch these errors appropriately.

LBYL coding style - checking indexes' existence

If you insist on using LBYL approach, these are solutions for you:

  • for lists just check the length and if possible_index < len(your_list), then your_list[possible_index] exists, otherwise it doesn't:

    >>> your_list = [0, 1, 2, 3]
    >>> 1 < len(your_list) # index exist
    True
    >>> 4 < len(your_list) # index does not exist
    False
    
  • for dictionaries you can use in keyword and if possible_index in your_dict, then your_dict[possible_index] exists, otherwise it doesn't:

    >>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3}
    >>> 1 in your_dict # index exists
    True
    >>> 4 in your_dict # index does not exist
    False
    

Did it help?

Truncate a SQLite table if it exists?

After deleting I'm also using VACUUM command. So for full TRUNCATE equivalent I use this code:

DELETE FROM <table>;
UPDATE SQLITE_SEQUENCE SET seq = 0 WHERE name = '<table>';
VACUUM;

Deleting isn't working for me for reset Auto Increment

DELETE FROM "sqlite_sequence" WHERE "name"='<table>';

To read more about VACUUM you can go here: https://blogs.gnome.org/jnelson/2015/01/06/sqlite-vacuum-and-auto_vacuum/

No connection could be made because the target machine actively refused it (PHP / WAMP)

All I have to do in order to get rid of that error was to restart my wamp server.

C# adding a character in a string

You can use this:

string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;

for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
    alpha = alpha.Insert(i, "-");
}

Works perfectly with any string. As always, the size doesn't matter. ;)

How to add Certificate Authority file in CentOS 7

Your CA file must have been in a binary X.509 format instead of Base64 encoding; it needs to be a regular DER or PEM in order for it to be added successfully to the list of trusted CAs on your server.

To proceed, do place your CA file inside your /usr/share/pki/ca-trust-source/anchors/ directory, then run the command line below (you might need sudo privileges based on your settings);

# CentOS 7, Red Hat 7, Oracle Linux 7
update-ca-trust

Please note that all trust settings available in the /usr/share/pki/ca-trust-source/anchors/ directory are interpreted with a lower priority compared to the ones placed under the /etc/pki/ca-trust/source/anchors/ directory which may be in the extended BEGIN TRUSTED file format.

For Ubuntu and Debian systems, /usr/local/share/ca-certificates/ is the preferred directory for that purpose.

As such, you need to place your CA file within the /usr/local/share/ca-certificates/ directory, then update the of trusted CAs by running, with sudo privileges where required, the command line below;

update-ca-certificates

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

First of all thank you for all above answers. However, I use Intellij Idea for daily basis. So, I hope my answer will help others.

Run your favourite terminal or command line. Then check your java version by running command

java -version

Then in Intellij press

Ctrl+Alt+Shift+S

in the

Project Settings

tab under

Project SDK

choose appropriate java version. Lastly, rerun your code.

Python Matplotlib Y-Axis ticks on Right Side of Plot

Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:

import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()

It will show this:

enter image description here

GCC: array type has incomplete element type

The compiler needs to know the size of the second dimension in your two dimensional array. For example:

void print_graph(g_node graph_node[], double weight[][5], int nodes);

Populate dropdown select with array using jQuery

var qty = 5;
var option = '';
for (var i=1;i <= qty;i++){
   option += '<option value="'+ i + '">' + i + '</option>';
}
$('#items').append(option);

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

Disabling submit button until all fields have values

Check out this jsfiddle.

HTML

// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />

JavaScript

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup() which I think makes it more convenient for usability.

Visual Studio Code cannot detect installed git

open

C:\Users\nassim\AppData\Roaming\Code\User\settings.json

comment any git line there

// ...
// "git-graph.integratedTerminalShell": "E:\\Apps\\Git\\bin\\bash.exe",
// "git.path": ""
//...

and add git.exe to the OS path

Note for me fixing this git error also fixed the npm error too , since they are both defined in the path, if one fail , the remaining will fail as well

Disable button in WPF?

You could subscribe to the TextChanged event on the TextBox and if the text is empty set the Button to disabled. Or you could bind the Button.IsEnabled property to the TextBox.Text property and use a converter that returns true if there is any text and false otherwise.

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

How to pass ArrayList of Objects from one to another activity using Intent in android?

You must need to also implement Parcelable interface and must add writeToParcel method to your Questions class with Parcel argument in Constructor in addition to Serializable. otherwise app will crash.

How to randomly select an item from a list?

foo = ['a', 'b', 'c', 'd', 'e']
number_of_samples = 1

In python 2:

random_items = random.sample(population=foo, k=number_of_samples)

In python 3:

random_items = random.choices(population=foo, k=number_of_samples)

Brackets.io: Is there a way to auto indent / format <html>

The shortcut key is ctrl+] to indentation and ctrl +[ to unindent

AngularJS : ng-model binding not updating when changed with jQuery

You have to trigger the change event of the input element because ng-model listens to input events and the scope will be updated. However, the regular jQuery trigger didn't work for me. But here is what works like a charm

$("#myInput")[0].dispatchEvent(new Event("input", { bubbles: true })); //Works

Following didn't work

$("#myInput").trigger("change"); // Did't work for me

You can read more about creating and dispatching synthetic events.

Bootstrap 3 - 100% height of custom div inside column

The original question is about Bootstrap 3 and that supports IE8 and 9 so Flexbox would be the best option but it's not part of my answer due the lack of support, see http://caniuse.com/#feat=flexbox and toggle the IE box. Pretty bad, eh?

2 ways:

1. Display-table: You can muck around with turning the row into a display:table and the col- into display:table-cell. It works buuuut the limitations of tables are there, among those limitations are the push and pull and offsets won't work. Plus, I don't know where you're using this -- at what breakpoint. You should make the image full width and wrap it inside another container to put the padding on there. Also, you need to figure out the design on mobile, this is for 768px and up. When I use this, I redeclare the sizes and sometimes I stick importants on them because tables take on the width of the content inside them so having the widths declared again helps this. You will need to play around. I also use a script but you have to change the less files to use it or it won't work responsively.


DEMO: http://jsbin.com/EtUBujI/2

  .row.table-row > [class*="col-"].custom {
    background-color: lightgrey;
    text-align: center;
  }


@media (min-width: 768px) {
  
  img.img-fluid {width:100%;}

  .row.table-row {display:table;width:100%;margin:0 auto;}

  .row.table-row > [class*="col-"] {
    float:none;
    float:none;
    display:table-cell;
    vertical-align:top;
  }

  .row.table-row > .col-sm-11 {
    width: 91.66666666666666%;
  }
  .row.table-row > .col-sm-10 {
    width: 83.33333333333334%;
  }
  .row.table-row > .col-sm-9 {
    width: 75%;
  }
  .row.table-row > .col-sm-8 {
    width: 66.66666666666666%;
  }
  .row.table-row > .col-sm-7 {
    width: 58.333333333333336%;
  }
  .row.table-row > .col-sm-6 {
    width: 50%;
  }
  .col-sm-5 {
    width: 41.66666666666667%;
  }
  .col-sm-4 {
    width: 33.33333333333333%;
  }
  .row.table-row > .col-sm-3 {
    width: 25%;
  }
  .row.table-row > .col-sm-2 {
    width: 16.666666666666664%;
  }
  .row.table-row > .col-sm-1 {
    width: 8.333333333333332%;
  }


}

HTML

<div class="container">
    <div class="row table-row">
        <div class="col-sm-4 custom">
                100% height to make equal to ->
        </div>
        <div class="col-sm-8 image-col">
            <img src="http://placehold.it/600x400/B7AF90/FFFFFF&text=image+1" class="img-fluid">
        </div>
    </div>
</div>

2. Absolute bg div

DEMO: http://jsbin.com/aVEsUmig/2/edit

DEMO with content above and below: http://jsbin.com/aVEsUmig/3


.content {
        text-align: center;
        padding: 10px;
        background: #ccc;

}


@media (min-width:768px) { 
    .my-row {
        position: relative;
        height: 100%;
        border: 1px solid red;
        overflow: hidden;
    }
    .img-fluid {
        width: 100%
    }
    .row.my-row > [class*="col-"] {
        position: relative
    }
    .background {
        position: absolute;
        padding-top: 200%;
        left: 0;
        top: 0;
        width: 100%;
        background: #ccc;
    }
    .content {
        position: relative;
        z-index: 1;
        width: 100%;
        text-align: center;
        padding: 10px;
    }

}

HTML

<div class="container">
  
    <div class="row my-row">
      
        <div class="col-sm-6">
          
        <div class="content">
          This is inside a relative positioned z-index: 1 div
          </div>

         <div class="background"><!--empty bg-div--></div>
        </div>
      
        <div class="col-sm-6 image-col">
            <img src="http://placehold.it/200x400/777777/FFFFFF&text=image+1" class="img-fluid">
        </div>
      
    </div>
   
</div>
  

Understanding typedefs for function pointers in C

Use typedefs to define more complicated types i.e function pointers

I will take the example of defining a state-machine in C

    typedef  int (*action_handler_t)(void *ctx, void *data);

now we have defined a type called action_handler that takes two pointers and returns a int

define your state-machine

    typedef struct
    {
      state_t curr_state;   /* Enum for the Current state */
      event_t event;  /* Enum for the event */
      state_t next_state;   /* Enum for the next state */
      action_handler_t event_handler; /* Function-pointer to the action */

     }state_element;

The function pointer to the action looks like a simple type and typedef primarily serves this purpose.

All my event handlers now should adhere to the type defined by action_handler

    int handle_event_a(void *fsm_ctx, void *in_msg );

    int handle_event_b(void *fsm_ctx, void *in_msg );

References:

Expert C programming by Linden

Live video streaming using Java?

You can do this today in Java with the Red5 media server from Flash. If you want to also decode and encode video in Java, you can use the Xuggler project.

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

What's the use of ob_start() in php?

I prefer:

ob_start();
echo("Hello there!");
$output = ob_get_clean(); //Get current buffer contents and delete current output buffer

How do I run a docker instance from a DockerFile?

Straightforward and easy solution is:

docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67

3000 - can be any port

a3e628814c68 - hash result given by success build command

NOTE: you should be within directory that contains Dockerfile.

Is it possible to use raw SQL within a Spring Repository

YES, You can do this on bellow ways:

1. By CrudRepository (Projection)

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons.

Suppose your entity is like this :

    import javax.persistence.*;
    import java.math.BigDecimal;

    @Entity
    @Table(name = "USER_INFO_TEST")
    public class UserInfoTest {
        private int id;
        private String name;
        private String rollNo;

        public UserInfoTest() {
        }

        public UserInfoTest(int id, String name) {
        this.id = id;
        this.name = name;
        }

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "ID", nullable = false, precision = 0)
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Basic
        @Column(name = "name", nullable = true)
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Basic
        @Column(name = "roll_no", nullable = true)
        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

Now your Projection class is like bellow. It can those fields that you needed.

public interface IUserProjection {
     int getId();
     String getName();
     String getRollNo();
}

And Your Data Access Object(Dao) is like bellow :

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.ArrayList;

public interface UserInfoTestDao extends CrudRepository<UserInfoTest,Integer> {
    @Query(value = "select id,name,roll_no from USER_INFO_TEST where rollNo = ?1", nativeQuery = true)
    ArrayList<IUserProjection> findUserUsingRollNo(String rollNo);
}

Now ArrayList<IUserProjection> findUserUsingRollNo(String rollNo) will give you the list of user.

2. Using EntityManager

Suppose your query is "select id,name from users where roll_no = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

Your Response class is like:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where roll_no = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

Here is the Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

get EntityManager from this way:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Note:

query.getSingleResult() return a object array. You have to maintain the column position and data type with query column position.

select id,name from users where roll_no = 1001 

query return a array and it's [0] --> id and [1] -> name.

More info visit this thread and this Thread

Thanks :)

change image opacity using javascript

You can use CSS to set the opacity, and than use javascript to apply the styles to a certain element in the DOM.

.opClass {
    opacity:0.4;
    filter:alpha(opacity=40); /* For IE8 and earlier */
}

Than use (for example) jQuery to change the style:

$('#element_id').addClass('opClass');

Or with plain javascript, like this:

document.getElementById("element_id").className = "opClass";

How can I check if the current date/time is past a set date/time?

There's also the DateTime class which implements a function for comparison operators.

// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');

if ( $dtA > $dtB ) {
  echo 'dtA > dtB';
}
else {
  echo 'dtA <= dtB';
}

How can I simulate a click to an anchor tag?

None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):

var clicker = null;
$('a').click(function(e){ 
    clicker=$(this); // capture the clicked dom object
    /* ... do something ... */
    e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.

Openssl is not recognized as an internal or external command

This is worked for me successfully.

"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary | "C:\cygwin\bin\openssl.exe" base64

Be careful with below path :

  • "C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe"
  • "D:\keystore\SocialListing" or it can be like this "C:\Users\Shaon.android\debug.keystore"
  • "C:\cygwin\bin\openssl.exe" or can be like this C:\Users\openssl\bin\openssl.exe

If command successfully work then you will see this command :

Enter keystore password : typeyourpassword

Encryptedhashkey**

How to set image on QPushButton?

This is old but it is still useful, Fully tested with QT5.3.

Be carreful, example concerning the ressources path :

In my case I created a ressources directory named "Ressources" in the source directory project.

The folder "ressources" contain pictures and icons.Then I added a prefix "Images" in Qt So the pixmap path become:

QPixmap pixmap(":/images/Ressources/icone_pdf.png");

JF

How to set RelativeLayout layout params in code not in xml?

I hope the below code will help. It will create an EditText and a Log In button. Both placed relatively. All done in MainActivity.java.

package com.example.atul.allison;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;
import android.widget.EditText;
import android.content.res.Resources;
import android.util.TypedValue;     
    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Layout
            RelativeLayout atulsLayout = new RelativeLayout(this);
            atulsLayout.setBackgroundColor(Color.GREEN);

            //Button
            Button redButton = new Button(this);
            redButton.setText("Log In");
            redButton.setBackgroundColor(Color.RED);

            //Username input
            EditText username =  new EditText(this);

            redButton.setId(1);
            username.setId(2);

            RelativeLayout.LayoutParams buttonDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            RelativeLayout.LayoutParams usernameDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            //give rules to position widgets
            usernameDetails.addRule(RelativeLayout.ABOVE,redButton.getId());
            usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            usernameDetails.setMargins(0,0,0,50);

            buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);

            Resources r = getResources();
            int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,r.getDisplayMetrics());
            username.setWidth(px);

            //Add widget to layout(button is now a child of layout)
            atulsLayout.addView(redButton,buttonDetails);
            atulsLayout.addView(username,usernameDetails);

            //Set these activities content/display to this view
            setContentView(atulsLayout);
        }
    }

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

use NPOI to read and write excel..it's free and open source

for exapmle

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

//.....

private void button1_Click(object sender, EventArgs e)
{
    HSSFWorkbook hssfwb;
    using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
    {
        hssfwb= new HSSFWorkbook(file);
    }

    ISheet sheet = hssfwb.GetSheet("Arkusz1");
    for (int row = 0; row <= sheet.LastRowNum; row++)
    {
        if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
        {
            MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));
        }
    }
}  

see this Stackoverflow question

For loop in multidimensional javascript array

A bit too late, but this solution is nice and neat

const arr = [[1,2,3],[4,5,6],[7,8,9,10]]
for (let i of arr) {
  for (let j of i) {
    console.log(j) //Should log numbers from 1 to 10
  }
}

Or in your case:

const arr = [[1,2,3],[4,5,6],[7,8,9]]
for (let [d1, d2, d3] of arr) {
  console.log(`${d1}, ${d2}, ${d3}`) //Should return numbers from 1 to 9
}

Note: for ... of loop is standardised in ES6, so only use this if you have an ES5 Javascript Complier (such as Babel)

Another note: There are alternatives, but they have some subtle differences and behaviours, such as forEach(), for...in, for...of and traditional for(). It depends on your case to decide which one to use. (ES6 also has .map(), .filter(), .find(), .reduce())

How to find if an array contains a string

Using the code from my answer to a very similar question:

Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range

Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"

For Each cell In Selection
  If IsInArray(cell.Value, MainFram) Then
    Row(cell.Row).Style = "Accent1"
  End If
Next cell

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

hash keys / values as array

var myHash = {"apples": 3, "oranges": 4, "bananas": 42}
vals=(function(e){a=[];for (var i in e) a.push(e[i]); return a;})(myHash).join(',')
keys=(function(e){a=[];for (var i in e) a.push(  i ); return a;})(myHash).join(',')
console.log(vals,keys)

basically

array=(function(e){a=[];for (var i in e) a.push(e[i]); return a;})(HASHHERE)

CSS 100% height with padding/margin

I learned how to do these sort of things reading "PRO HTML and CSS Design Patterns". The display:block is the default display value for the div, but I like to make it explicit. The container has to be the right type; position attribute is fixed, relative, or absolute.

_x000D_
_x000D_
.stretchedToMargin {_x000D_
  display: block;_x000D_
  position:absolute;_x000D_
  height:auto;_x000D_
  bottom:0;_x000D_
  top:0;_x000D_
  left:0;_x000D_
  right:0;_x000D_
  margin-top:20px;_x000D_
  margin-bottom:20px;_x000D_
  margin-right:80px;_x000D_
  margin-left:80px;_x000D_
  background-color: green;_x000D_
}
_x000D_
<div class="stretchedToMargin">_x000D_
  Hello, world_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle by Nooshu's comment

Get the current first responder without using a private API

With a category on UIResponder, it is possible to legally ask the UIApplication object to tell you who the first responder is.

See this:

Is there any way of asking an iOS view which of its children has first responder status?

HTML/CSS--Creating a banner/header

Remove the z-index value.

I would also recommend this approach.

HTML:

<header class="main-header" role="banner">
  <img src="mybannerimage.gif" alt="Banner Image"/>
</header>

CSS:

.main-header {
  text-align: center;
}

This will center your image with out stretching it out. You can adjust the padding as needed to give it some space around your image. Since this is at the top of your page you don't need to force it there with position absolute unless you want your other elements to go underneath it. In that case you'd probably want position:fixed; anyway.

How to set a variable to current date and date-1 in linux?

You can also use the shorter format

From the man page:

%F     full date; same as %Y-%m-%d

Example:

#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)

SQL Server tables: what is the difference between @, # and ##?

CREATE TABLE #t

Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.

CREATE TABLE ##t

Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.

How do I run all Python unit tests in a directory?

This is an old question, but what worked for me now (in 2019) is:

python -m unittest *_test.py

All my test files are in the same folder as the source files and they end with _test.

Call to undefined function curl_init().?

If you're on Windows:

Go to your php.ini file and remove the ; mark from the beginning of the following line:

;extension=php_curl.dll

After you have saved the file you must restart your HTTP server software (e.g. Apache) before this can take effect.


For Ubuntu 13.0 and above, simply use the debundled package. In a terminal type the following to install it and do not forgot to restart server.

sudo apt-get install php-curl

Or if you're using the old PHP5

sudo apt-get install php5-curl

or

sudo apt-get install php5.6-curl

Then restart apache to activate the package with

sudo service apache2 restart

Embedding JavaScript engine into .NET

I know I'm opening up an old thread but I've done a lot of work on smnet (spidermonkey-dotnet). In the recent years. It's main development focus has been seamless embedding of .net objects into the spidermonkey engine. It supports a wide variety of conversions from js values to .net objects. Some of those including delegates and events.

Just saying it might be worth checking into now that there's some steady development on it :). I do keep the SVN repo up to date with bug fixes and new features. The source and project solution files are configured to successfully build on download. If there are any problems using it, feel free to open a discussion.

I do understand the desire to have a managed javascript solution, but of all the managed javascript's I've used they're all very lacking in some key features that help make them both robust and easy to work with. I myself am waiting on IronJS to mature a little. While I wait, I have fun playing with spidermonkey-dotnet =)

spidermonkey-dotnet project and download page

Edit: created documentation wiki page this afternoon.

react native get TextInput value

constructor(props) {
        super(props);

        this.state ={
            commentMsg: ''         
        }
    }

 onPress = () => {
          alert("Hi " +this.state.commentMsg)
      }

 <View style={styles.sendCommentContainer}>

     <TextInput
        style={styles.textInput}
        multiline={true}
        onChangeText={(text) => this.setState({commentMsg: text})}
        placeholder ='Comment'/>

       <Button onPress={this.onPress} 
           title="OK!"
           color="#841584"
        />

  </TouchableOpacity>

</View>

Create instance of generic type whose constructor requires a parameter?

As Jon pointed out this is life for constraining a non-parameterless constructor. However a different solution is to use a factory pattern. This is easily constrainable

interface IFruitFactory<T> where T : BaseFruit {
  T Create(int weight);
}

public void AddFruit<T>( IFruitFactory<T> factory ) where T: BaseFruit {    
  BaseFruit fruit = factory.Create(weight); /*new Apple(150);*/    
  fruit.Enlist(fruitManager);
}

Yet another option is to use a functional approach. Pass in a factory method.

public void AddFruit<T>(Func<int,T> factoryDel) where T : BaseFruit { 
  BaseFruit fruit = factoryDel(weight); /* new Apple(150); */
  fruit.Enlist(fruitManager);
}

Using regular expressions to do mass replace in Notepad++ and Vim

In vim

:%s/<option value='.\{1,}' >//

or

:%s/<option value='.\+' >//

In vim regular expressions you have to escape the one-or-more symbol, capturing parentheses, the bounded number curly braces and some others.

See :help /magic to see which special characters need to be escaped (and how to change that).

How to SUM two fields within an SQL query

SUM is an aggregate function. It will calculate the total for each group. + is used for calculating two or more columns in a row.

Consider this example,

ID  VALUE1  VALUE2
===================
1   1       2
1   2       2
2   3       4
2   4       5

 

SELECT  ID, SUM(VALUE1), SUM(VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1), SUM(VALUE2)
1   3           4
2   7           9

 

SELECT  ID, VALUE1 + VALUE2
FROM    TableName

will result

ID, VALUE1 + VALUE2
1   3
1   4
2   7
2   9

 

SELECT  ID, SUM(VALUE1 + VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1 + VALUE2)
1   7
2   16

How to prevent caching of my Javascript file?

You can append a queryString to your src and change it only when you will release an updated version:

<script src="test.js?v=1"></script>

In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)

Convert Json Array to normal Java list

You can use a String[] instead of an ArrayList<String>:

Hope it helps!

   private String[] getStringArray(JSONArray jsonArray) throws JSONException {
            if (jsonArray != null) {
                String[] stringsArray = new String[jsonArray.length()];
                for (int i = 0; i < jsonArray.length(); i++) {
                    stringsArray[i] = jsonArray.getString(i);
                }
                return stringsArray;
            } else
                return null;
        }

Android: Pass data(extras) to a fragment

There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment

private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;


public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    fragment.init(music);
    return fragment;
}

public void init(List<Music> music){
    this.listMusic = music;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState)
{

    View view = inflater.inflate(R.layout.musiclistview, container, false);
    listMusic = (ListView) view.findViewById(R.id.musicListView);
    listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));

    return view;
}
}

In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.

Python copy files to a new directory and rename if file name already exists

Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.

movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
    for filename in files:
        # I use absolute path, case you want to move several dirs.
        old_name = os.path.join( os.path.abspath(root), filename )

        # Separate base from extension
        base, extension = os.path.splitext(filename)

        # Initial new name
        new_name = os.path.join(basedir, base, filename)

        # If folder basedir/base does not exist... You don't want to create it?
        if not os.path.exists(os.path.join(basedir, base)):
            print os.path.join(basedir,base), "not found" 
            continue    # Next filename
        elif not os.path.exists(new_name):  # folder exists, file does not
            shutil.copy(old_name, new_name)
        else:  # folder exists, file exists as well
            ii = 1
            while True:
                new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
                if not os.path.exists(new_name):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                   break 
                ii += 1

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

Add a header to your request to set content type to application/json

curl -H 'Content-Type: application/json' -s -XPOST http://your.domain.com/ -d YOUR_JSON_BODY

this way spring knows how to parse the content.

Python Dictionary contains List as Value - How to update?

An accessed dictionary value (a list in this case) is the original value, separate from the dictionary which is used to access it. You would increment the values in the list the same way whether it's in a dictionary or not:

l = dictionary.get('C1')
for i in range(len(l)):
    l[i] += 10

Scanner vs. BufferedReader

In currently latest JDK6 release/build (b27), the Scanner has a smaller buffer (1024 chars) as opposed to the BufferedReader (8192 chars), but it's more than sufficient.

As to the choice, use the Scanner if you want to parse the file, use the BufferedReader if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.

  • Parsing = interpreting the given input as tokens (parts). It's able to give back you specific parts directly as int, string, decimal, etc. See also all those nextXxx() methods in Scanner class.
  • Reading = dumb streaming. It keeps giving back you all characters, which you in turn have to manually inspect if you'd like to match or compose something useful. But if you don't need to do that anyway, then reading is sufficient.

How can I know when an EditText loses focus?

Its Working Properly

EditText et_mobile= (EditText) findViewById(R.id.edittxt);

et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {          
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            // code to execute when EditText loses focus
            if (et_mobile.getText().toString().trim().length() == 0) {
                CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
            }
        }
    }
});



public static void showAlert(String message, Activity context) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message).setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    try {
        builder.show();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

How to monitor network calls made from iOS Simulator

Wireshark it

Select your interface

enter image description here

Add filter start the capture

enter image description here


Testing

Click on any action or button that would trigger a GET/POST/PUT/DELETE request

You will see it on listed in the wireshark

enter image description here

If you want to know more details about one specific packet, just select it and Follow > HTTP Stream.

enter image description here

hope this help others !!

How can I copy the output of a command directly into my clipboard?

I am using Parcellite and xsel to copy last commit message from git to my clipboard manager (for some reason xclip does not work):

$ git log -1 --pretty=%B | xsel -i -b

How to access site through IP address when website is on a shared host?

Include the port number with the IP address.

For example:

http://19.18.20.101:5566

where 5566 is the port number.

ES6 Class Multiple inheritance

Here's an awesome/really crappy way of extending multiple classes. I'm utilizing a couple functions that Babel put into my transpiled code. The function creates a new class that inherits class1, and class1 inherits class2, and so on. It has its issues, but a fun idea.

var _typeof = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? function (obj) {
  return typeof obj
} : function (obj) {
  return obj && typeof Symbol === 'function' && obj.constructor === Symbol ? 'symbol' : typeof obj
}

function _inherits (subClass, superClass) {
  if (typeof superClass !== 'function' && superClass !== null) {
    throw new TypeError('Super expression must either be null or a function, not ' + (
      typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)))
  }
  subClass.prototype = Object.create(
    superClass && superClass.prototype,
    {
      constructor: {
        value: subClass,
        enumerable: false,
        writable: true,
        configurable: true
      }
    })
  if (superClass) {
    Object.setPrototypeOf
    ? Object.setPrototypeOf(subClass, superClass)
    : subClass.__proto__ = superClass.__proto__  // eslint-disable-line no-proto
  }
}

function _m (...classes) {
  let NewSuperClass = function () {}
  let c1 = NewSuperClass
  for (let c of classes) {
    _inherits(c1, c)
    c1 = c
  }
  return NewSuperClass
}

import React from 'react'

/**
 * Adds `this.log()` to your component.
 * Log message will be prefixed with the name of the component and the time of the message.
 */
export default class LoggingComponent extends React.Component {
  log (...msgs) {
    if (__DEBUG__) {
      console.log(`[${(new Date()).toLocaleTimeString()}] [${this.constructor.name}]`, ...msgs)
    }
  }
}

export class MyBaseComponent extends _m(LoggingComponent, StupidComponent) {}

Fit Image into PictureBox

I have routine in VB ..

but you should have 2 pictureboxes .. 1 for frame .. 1 for the image .. and it make keep the picture's size ratio

Assumed picFrame is the image frame and picImg is the image

Sub InsertPicture(ByVal oImg As Image)
    Dim oFoto As Image
    Dim x, y As Integer

    oFoto = oImg
    picImg.Visible = False
    picImg.Width = picFrame.Width - 2
    picImg.Height = picFrame.Height - 2
    picImg.Location = New Point(1, 1)
    SetPicture(picPreview, oFoto)
    x = (picImg.Width - picFrame.Width) / 2
    y = (picImg.Height - picFrame.Height) / 2
    picImg.Location = New Point(x, y)
    picImg.Visible = True

End Sub

I'm sure you can make it as C# ....

Choosing the best concurrency list in Java

Any Java collection can be made to be Thread-safe like so:

List newList = Collections.synchronizedList(oldList);

Or to create a brand new thread-safe list:

List newList = Collections.synchronizedList(new ArrayList());

http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)

Advantages of SQL Server 2008 over SQL Server 2005?

Someone with more reputation can copy this into the main answer:

  • Change Tracking. Allows you to get info on what changes happened to which rows since a specific version.
  • Change Data Capture. Allows all changes to be captured and queried. (Enterprise)

Typescript: How to extend two classes?

I found an up-to-date & unparalleled solution: https://www.npmjs.com/package/ts-mixer

You are welcome :)

importing jar libraries into android-studio

I see so many complicated answer.

All this confused me while I was adding my Aquery jar file in the new version of Android Studio.

This is what I did :

Copy pasted the jar file in the libs folder which is visible under Project view.

And in the build.gradle file just added this line : compile files('libs/android-query.jar')

PS : Once downloading the jar file please change its name. I changed the name to android-query.jar

git: Switch branch and ignore any changes without committing

Close terminal, delete the folder where your project is, then clone again your project and voilá.

What's is the difference between include and extend in use case diagram?

Diagram Elements

  • Actors: Also referred to as Roles. Name and stereotype of an actor can be changed in its Properties tab.

  • Inheritance: Refinement relations between actors. This relation can carry a name and a stereotype.

  • Use cases: These can have Extension Points.

  • Extension Points: This defines a location where an extension can be added.

  • Associations: Between roles and use cases. It is useful to give associations speaking names.

  • Dependencies: Between use cases. Dependencies often have a stereotype to better define the role of the dependency. To select a stereotype, select the dependency from the diagram or the Navigation pane, then change the stereotype in the Properties tab. There are two special kinds of dependencies: <<extend>> and <<include>>, for which Poseidon offers own buttons (see below).

  • Extend relationship: A uni-directional relationship between two use cases. An extend relationship between use case B and use case A means that the behavior of B can be included in A.

  • Include relationship: A uni-directional relationship between two use cases. Such a relationship between use cases A and B means, that the behavior of B is always included in A.

  • System border: The system border is actually not implemented as model element in Poseidon for UML. You can simply draw a rectangle, send it to the background and use it as system border by putting all corresponding use cases inside the rectangle.

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

Since others have covered the differences, I'll hit the uses.

TIFF is usually used by scanners. It makes huge files and is not really used in applications.

BMP is uncompressed and also makes huge files. It is also not really used in applications.

GIF used to be all over the web but has fallen out of favor since it only supports a limited number of colors and is patented.

JPG/JPEG is mainly used for anything that is photo quality, though not for text. The lossy compression used tends to mar sharp lines.

PNG isn't as small as JPEG but is lossless so it's good for images with sharp lines. It's in common use on the web now.

Personally, I usually use PNG everywhere I can. It's a good compromise between JPG and GIF.

Adding text to ImageView in Android

To add a text to your ImageView you can do this:

<RelativeLayout> // Only works inside a RelativeLayout
    <ImageView
        android:id="@+id/myImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/myImageSouce" />

    <TextView
        android:id="@+id/myImageViewText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/myImageView"
        android:layout_alignTop="@+id/myImageView"
        android:layout_alignRight="@+id/myImageView"
        android:layout_alignBottom="@+id/myImageView"
        android:layout_margin="1dp"
        android:gravity="center"
        android:text="Hello"
        android:textColor="#000000" />
 </RelativeLayout>

Base64 encoding and decoding in client-side Javascript

Short and fast Base64 JavaScript Decode Function without Failsafe:

function decode_base64 (s)
{
    var e = {}, i, k, v = [], r = '', w = String.fromCharCode;
    var n = [[65, 91], [97, 123], [48, 58], [43, 44], [47, 48]];

    for (z in n)
    {
        for (i = n[z][0]; i < n[z][1]; i++)
        {
            v.push(w(i));
        }
    }
    for (i = 0; i < 64; i++)
    {
        e[v[i]] = i;
    }

    for (i = 0; i < s.length; i+=72)
    {
        var b = 0, c, x, l = 0, o = s.substring(i, i+72);
        for (x = 0; x < o.length; x++)
        {
            c = e[o.charAt(x)];
            b = (b << 6) + c;
            l += 6;
            while (l >= 8)
            {
                r += w((b >>> (l -= 8)) % 256);
            }
         }
    }
    return r;
}

How to resume Fragment from BackStack if exists

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {

    @Override
    public void onBackStackChanged() {

        if(getFragmentManager().getBackStackEntryCount()==0) {
            onResume();
        }    
    }
});

Batch Renaming of Files in a Directory

Try: http://www.mattweber.org/2007/03/04/python-script-renamepy/

I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.

This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.

The program's source code is also available.

How to add hours to current date in SQL Server?

SELECT GETDATE() + (hours / 24.00000000000000000)

Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

OK, I've worked out what's going on. Leonidas is right, it's not just the hash that gets encrypted (in the case of the Cipher class method), it's the ID of the hash algorithm concatenated with the digest:

  DigestInfo ::= SEQUENCE {
      digestAlgorithm AlgorithmIdentifier,
      digest OCTET STRING
  }

Which is why the encryption by the Cipher and Signature are different.

How can I trim leading and trailing white space?

A simple function to remove leading and trailing whitespace:

trim <- function( x ) {
  gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)
}

Usage:

> text = "   foo bar  baz 3 "
> trim(text)
[1] "foo bar  baz 3"

Writing a string to a cell in excel

replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"

jQuery DataTable overflow and text-wrapping issues

Using the classes "responsive nowrap" on the table element should do the trick.

Gradle version 2.2 is required. Current version is 2.10

Use ./gradlew instead of gradle to resolve this issue.

How to properly ignore exceptions

How to properly ignore Exceptions?

There are several ways of doing this.

However, the choice of example has a simple solution that does not cover the general case.

Specific to the example:

Instead of

try:
    shutil.rmtree(path)
except:
    pass

Do this:

shutil.rmtree(path, ignore_errors=True)

This is an argument specific to shutil.rmtree. You can see the help on it by doing the following, and you'll see it can also allow for functionality on errors as well.

>>> import shutil
>>> help(shutil.rmtree)

Since this only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

General approach

Since the above only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

New in Python 3.4:

You can import the suppress context manager:

from contextlib import suppress

But only suppress the most specific exception:

with suppress(FileNotFoundError):
    shutil.rmtree(path)

You will silently ignore a FileNotFoundError:

>>> with suppress(FileNotFoundError):
...     shutil.rmtree('bajkjbkdlsjfljsf')
... 
>>> 

From the docs:

As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.

Note that suppress and FileNotFoundError are only available in Python 3.

If you want your code to work in Python 2 as well, see the next section:

Python 2 & 3:

When you just want to do a try/except without handling the exception, how do you do it in Python?

Is the following the right way to do it?

try :
    shutil.rmtree ( path )
except :
    pass

For Python 2 compatible code, pass is the correct way to have a statement that's a no-op. But when you do a bare except:, that's the same as doing except BaseException: which includes GeneratorExit, KeyboardInterrupt, and SystemExit, and in general, you don't want to catch those things.

In fact, you should be as specific in naming the exception as you can.

Here's part of the Python (2) exception hierarchy, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
... and so on

You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory.

We can get that specific error number from the errno library, and reraise if we don't have that:

import errno

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno == errno.ENOENT: # no such file or directory
        pass
    else: # we had an OSError we didn't expect, so reraise it
        raise 

Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly pass with code in the exception handling:

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno != errno.ENOENT: # no such file or directory
        raise 

binning data in python with scipy/numpy

It's probably faster and easier to use numpy.digitize():

import numpy
data = numpy.random.random(100)
bins = numpy.linspace(0, 1, 10)
digitized = numpy.digitize(data, bins)
bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]

An alternative to this is to use numpy.histogram():

bin_means = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])

Try for yourself which one is faster... :)

RabbitMQ / AMQP: single queue, multiple consumers for same message?

The send pattern is a one-to-one relationship. If you want to "send" to more than one receiver you should be using the pub/sub pattern. See http://www.rabbitmq.com/tutorials/tutorial-three-python.html for more details.

Java: how to represent graphs?

I'd recommend graphviz highly when you get to the point where you want to render your graphs.

And its companions: take a look at Laszlo Szathmary's GraphViz class, along with notugly.xls.

Removing index column in pandas when reading a csv

One thing that i do is df=df.reset_index() then df=df.drop(['index'],axis=1)

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

How to replace a set of tokens in a Java String?

You can use template library for complex template replacement.

FreeMarker is a very good choice.

http://freemarker.sourceforge.net/

But for simple task, there is a simple utility class can help you.

org.apache.commons.lang3.text.StrSubstitutor

It is very powerful, customizable, and easy to use.

This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods.

Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.

For example, if you want to substitute system environment variable into a template string, here is the code:

public class SysEnvSubstitutor {
    public static final String replace(final String source) {
        StrSubstitutor strSubstitutor = new StrSubstitutor(
                new StrLookup<Object>() {
                    @Override
                    public String lookup(final String key) {
                        return System.getenv(key);
                    }
                });
        return strSubstitutor.replace(source);
    }
}

How to define the css :hover state in a jQuery selector?

Well, you can't add styling using pseudo selectors like :hover, :after, :nth-child, or anything like that using jQuery.

If you want to add a CSS rule like that you have to create a <style> element and add that :hover rule to it just like you would in CSS. Then you would have to add that <style> element to the page.

Using the .hover function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:

$('head').append('<style>.myclass:hover div {background-color : red;}</style>')

If you want to read more on adding CSS with javascript you can check out one of David Walsh's Blog posts.

Why I get 'list' object has no attribute 'items'?

result_list = [int(v) for k,v in qs[0].items()]

qs is a list, qs[0] is the dict which you want!

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

Do you recommend using semicolons after every statement in JavaScript?

Yes, you should use semicolons after every statement in JavaScript.

How to get the day name from a selected date?

What about if we use String.Format here

_x000D_
_x000D_
DateTime today = DateTime.Today;_x000D_
String.Format("{0:dd-MM}, {1:dddd}", today, today) //In dd-MM format_x000D_
String.Format("{0:MM-dd}, {1:dddd}", today, today) //In MM-dd format
_x000D_
_x000D_
_x000D_

How to default to other directory instead of home directory

I use ConEmu (strongly recommended on Windows) where I have a task for starting Git Bash like

enter image description here

Note the button "Startup dir..." in the bottom. It adds a -new_console:d:<path> to the startup command of the Git Bash. Make it point to wherever you like

How to convert datetime format to date format in crystal report using C#?

In selection formula try this

Date(Year({datetimefield}), Month({datetimefield}), Day({datetimefield}))

How to center images on a web page for all screen sizes

In your specific case, you can set the containing a element to be:

a {
    display: block;
    text-align: center;
}

JS Bin demo.

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

How to recursively find the latest modified file in a directory?

Shows the latest file with human readable timestamp:

find . -type f -printf '%TY-%Tm-%Td %TH:%TM: %Tz %p\n'| sort -n | tail -n1

Result looks like this:

2015-10-06 11:30: +0200 ./foo/bar.txt

To show more files, replace -n1 with a higher number

What is an Endpoint?

Endpoint, in the OpenID authentication lingo, is the URL to which you send (POST) the authentication request.

Excerpts from Google authentication API

To get the Google OpenID endpoint, perform discovery by sending either a GET or HEAD HTTP request to https://www.google.com/accounts/o8/id. When using a GET, we recommend setting the Accept header to "application/xrds+xml". Google returns an XRDS document containing an OpenID provider endpoint URL.The endpoint address is annotated as:

<Service priority="0">
<Type>http://specs.openid.net/auth/2.0/server</Type> 
<URI>{Google's login endpoint URI}</URI> 
</Service>

Once you've acquired the Google endpoint, you can send authentication requests to it, specifying the appropriate parameters (available at the linked page). You connect to the endpoint by sending a request to the URL or by making an HTTP POST request.

Warning: push.default is unset; its implicit value is changing in Git 2.0

I realize this is an old post but as I just ran into the same issue and had trouble finding the answer I thought I'd add a bit.

So @hammar's answer is correct. Using push.default simple is, in a way, like configuring tracking on your branches so you don't need to specify remotes and branches when pushing and pulling. The matching option will push all branches to their corresponding counterparts on the default remote (which is the first one that was set up unless you've configured your repo otherwise).

One thing I hope others find useful in the future is that I was running Git 1.8 on OS X Mountain Lion and never saw this error. Upgrading to Mavericks is what suddenly made it show up (running git --version will show git version 1.8.3.4 (Apple Git-47) which I'd never seen until the update to the OS.

What is AF_INET, and why do I need it?

You need arguments like AF_UNIX or AF_INET to specify which type of socket addressing you would be using to implement IPC socket communication. AF stands for Address Family.

As in BSD standard Socket (adopted in Python socket module) addresses are represented as follows:

  1. A single string is used for the AF_UNIX/AF_LOCAL address family. This option is used for IPC on local machines where no IP address is required.

  2. A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer. Used to communicate between processes over the Internet.

AF_UNIX , AF_INET6 , AF_NETLINK , AF_TIPC , AF_CAN , AF_BLUETOOTH , AF_PACKET , AF_RDS are other option which could be used instead of AF_INET.

This thread about the differences between AF_INET and PF_INET might also be useful.

Find by key deep in a nested array

Just use recursive function.
See example below:

_x000D_
_x000D_
const data = [
  {
    title: 'some title',
    channel_id: '123we',
    options: [
      {
        channel_id: 'abc',
        image: 'http://asdasd.com/all-inclusive-block-img.jpg',
        title: 'All-Inclusive',
        options: [
          {
            channel_id: 'dsa2',
            title: 'Some Recommends',
            options: [
              {
                image: 'http://www.asdasd.com',
                title: 'Sandals',
                id: '1',
                content: {},
              }
            ]
          }
        ]
      }
    ]
  }
]

function _find(collection, key, value) {
  for (const o of collection) {
    for (const [k, v] of Object.entries(o)) {
      if (k === key && v === value) {
        return o
      }
      if (Array.isArray(v)) {
        const _o = _find(v, key, value)
        if (_o) {
          return _o
        }
      }
    }
  }
}

console.log(_find(data, 'channel_id', 'dsa2'))
_x000D_
_x000D_
_x000D_

python NameError: global name '__file__' is not defined

change your codes as follows! it works for me. `

os.path.dirname(os.path.abspath("__file__"))

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

Where will log4net create this log file?

it will create the file in the root directory of your project/solution.

You can specify a location of choice in the web.config of your app as follows:

   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:/ServiceLogs/Olympus.Core.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value=".yyyyMMdd.log" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
      <maxSizeRollBackups value="-1" />
      <countDirection value="1" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
      </layout>
    </appender>

the file tag specifies the location.

How to collapse blocks of code in Eclipse?

Here you go!

  1. Right Click on + button appeared on numbering strip on left most side --> Folding --> Expand All
  2. Right Click on + button appeared on numbering strip on left most side --> Folding --> Collapse All

This way you can expand and collapse all the methods on the file.

Plus Buttons on numbering strip

Context Menu:

Context Menu

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

How to find index of STRING array in Java from a given value?

Testable mockable interafce

public interface IArrayUtility<T> {

    int find(T[] list, T item);

}

implementation

public class ArrayUtility<T> implements IArrayUtility<T> {

    @Override
    public int find(T[] array, T search) {
        if(array == null || array.length == 0 || search == null) {
            return -1;
        }

        int position = 0;

        for(T item : array) {

            if(item.equals(search)) {
                return position;
            } else {
                ++position;
            }
        }

        return -1;
    }

}

Test

@Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
    // Arrange
    String search = "bus";
    String[] array = {"car", search, "motorbike"};

    // Act
    int position = arrayUtility.find(array, search);

    // Assert
    Assert.assertEquals(position, 1);
}

HTML.HiddenFor value set

You can do this way

@Html.HiddenFor(model=>model.title, new {ng_init = string.Format("model.title='{0}'", Model.title) })

mean() warning: argument is not numeric or logical: returning NA

From R 3.0.0 onwards mean(<data.frame>) is defunct (and passing a data.frame to mean will give the error you state)

A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".

In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following

lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)

Install numpy on python3.3 - Install pip for python3

I'm on Ubuntu 15.04. This seemed to work:

$ sudo pip3 install numpy

On RHEL this worked:

$ sudo python3 -m pip install numpy

How to connect to remote Oracle DB with PL/SQL Developer?

I would recommend creating a TNSNAMES.ORA file. From your Oracle Client install directory, navigate to NETWORK\ADMIN. You may already have a file called TNSNAMES.ORA, if so edit it, else create it using your favorite text editor.

Next, simply add an entry like this:

MYDB =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521))
    (CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED))
  )

You can change MYDB to whatever you like, this is the identifier that applications will will use to find the database using the info from TNSNAMES.

Finally, login with MYDB as your database in PL/SQL Developer. It should automatically find the connection string in the TNSNAMES.ORA.

If that does not work, hit Help->About then click the icon with an "i" in it in the upper-lefthand corner. The fourth tab is the "TNS Names" tab, check it to confirm that it is loading the proper TNSNAMES.ORA file. If it is not, you may have multiple Oracle installations on your computer, and you will need to find the one that is in use.

How to execute a remote command over ssh with arguments?

This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH

# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`


ssh \
    -o StrictHostKeyChecking=no \
    -i ~/.ssh/id_rsa \
    [email protected] \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!

EOF

How to construct a std::string from a std::vector<char>?

Well, the best way is to use the following constructor:

template<class InputIterator> string (InputIterator begin, InputIterator end);

which would lead to something like:

std::vector<char> v;
std::string str(v.begin(), v.end());

How can I determine whether a 2D Point is within a Polygon?

C# version of nirg's answer is here: I'll just share the code. It may save someone some time.

public static bool IsPointInPolygon(IList<Point> polygon, Point testPoint) {
            bool result = false;
            int j = polygon.Count() - 1;
            for (int i = 0; i < polygon.Count(); i++) {
                if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y) {
                    if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < testPoint.X) {
                        result = !result;
                    }
                }
                j = i;
            }
            return result;
        }

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

How to compare two NSDates: Which is more recent?

Use this simple function for date comparison

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{

BOOL isTokonValid;

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
    isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
    isTokonValid = NO;
} else {
    isTokonValid = NO;
    NSLog(@"dates are the same");
}

return isTokonValid;}

Getting or changing CSS class property with Javascript using DOM style

If you are looking for sending color data from backend

def color():
    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
    return color

How to declare and add items to an array in Python?

Just for sake of completion, you can also do this:

array = []
array += [valueToBeInserted]

If it's a list of strings, this will also work:

array += 'string'

Font-awesome, input type 'submit'

Also possible like this

<button type="submit" class="icon-search icon-large"></button>

Disabling Chrome cache for website development

Until the bug is fixed you could use Clear Cache Chrome plugin and you can also set a keyboard shortcut for it.

After installing it, right click and go to options:

enter image description here

Check Automatically reload active tab after clearing data:

enter image description here

Select Everything for Time Period:

enter image description here

And then you can go to Menu => Tools => Extensions:

enter image description here

Click on keyboard shortcuts at the bottom:

enter image description here

And set your keyboard shortcut, for example Ctrl + Shift +R:

enter image description here

How do you remove Subversion control for a folder?

On Linux, this will work:

  find . -iname ".svn" -print0 | xargs -0 rm -r

Get path to execution directory of Windows Forms application

Check this out:

Imports System.IO
Imports System.Management

Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
        Process.Start(TextBox1.Text)
    End Sub
End Class

Creating an Arraylist of Objects

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

What is the difference between $routeProvider and $stateProvider?

Both do the same work as they are used for routing purposes in SPA(Single Page Application).

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on the page that you wanted to render based on some conditions, $routeProvider fails. (to achieve that, we need to use directives like ng-include, ng-switch, ng-if, ng-show, which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part of the view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views in a template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manage nested state & views.

Pros

  • You can have multiple ui-view on single page
  • Various views can be nested in each other and maintained by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Another way you could do relative routing is by using only @ to change ui-view="some". This will replace the ui-view rather than checking if it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

Google Chrome: This setting is enforced by your administrator

In my case, the setting was HKEY_CURRENT_USER\Software\Policies\Google\Chrome

I deleted Chrome and everything is fine now.

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

Another solution is to set the window type to a system dialog:

dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

This requires the SYSTEM_ALERT_WINDOW permission:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

As the docs say:

Very few applications should use this permission; these windows are intended for system-level interaction with the user.

This is a solution you should only use if you require a dialog that's not attached to an activity.

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

There's actually a way to do this without javascript.

If you set an <input>'s required selector to true, you can check if there's text in it with the CSS :valid tag.

References:

MDN Docs
CSS Tricks

_x000D_
_x000D_
input {
  background: red;
}

input:valid {
  background: lightgreen;
}
_x000D_
<input type="text" required>
_x000D_
_x000D_
_x000D_

Counting the occurrences / frequency of array elements

Using Lodash

_x000D_
_x000D_
const values = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const frequency = _.map(_.groupBy(values), val => ({ value: val[0], frequency: val.length }));
console.log(frequency);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

How to move a marker in Google Maps API

<style>
    #frame{
        position: fixed;
        top: 5%;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        width: 98%;
        height: 92%;
        display: none;
        z-index: 1000;
    }
    #map{
        position: fixed;
        display: inline-block;
        width: 99%;
        height: 93%;
        display: none;
        z-index: 1000;
    }

    #loading{
        position: fixed;
        top: 50%;
        left: 50%;
        opacity: 1!important;
        margin-top: -100px;
        margin-left: -150px;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        max-width: 66%;
        display: none;
        color: #000;

    }
    #mytitle{
        color: #FFF;
        background-image: linear-gradient(to bottom,#d67631,#d67631);
        //  border-color: rgba(47, 164, 35, 1);
        width: 100%;
        cursor: move;
    }
    #closex{ 
        display: block;
        float:right;
        position:relative;
        top:-10px;
        right: -10px;
        height: 20px;
        cursor: pointer;
    }
    .pointer{
        cursor: pointer !important;
    }

</style> 
<div id="loading">
    <i class="fa fa-circle-o-notch fa-spin fa-2x"></i>
    Loading...
</div>
<div id="frame">
    <div id="headerx"></div>
    <div id="map" >    
    </div>
</div>


<?php
$url = Yii::app()->baseUrl . '/reports/reports/transponderdetails';
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

<script>
    function clode() {
        $('#frame').hide();
        $('#frame').html();
    }
    function track(id) {
        $('#loading').show();
        $('#loading').parent().css("opacity", '0.7');


        $.ajax({
            type: "POST",
            url: '<?php echo $url; ?>',
            data: {'id': id},
            success: function(data) {
                $('#frame').show();
                $('#headerx').html(data);
                $('#loading').parents().css("opacity", '1');
                $('#loading').hide();
                var thelat = parseFloat($('#lat').text());
                var long = parseFloat($('#long').text());
                $('#map').show();
                var lat = thelat;
                var lng = long;
                var orlat=thelat;
                var orlong=long;
                //Intialize the Path Array
                var path = new google.maps.MVCArray();
                var service = new google.maps.DirectionsService();


                var myLatLng = new google.maps.LatLng(lat, lng), myOptions = {zoom: 4, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP};
                var map = new google.maps.Map(document.getElementById('map'), myOptions);
                var poly = new google.maps.Polyline({map: map, strokeColor: '#4986E7'});
                var marker = new google.maps.Marker({position: myLatLng, map: map});

                function initialize() {
                    marker.setMap(map);
                    movepointer(map, marker);
                    var drawingManager = new google.maps.drawing.DrawingManager();
                    drawingManager.setMap(map);
                }

                function movepointer(map, marker) {
                    marker.setPosition(new google.maps.LatLng(lat, lng));
                    map.panTo(new google.maps.LatLng(lat, lng));

                    var src = myLatLng;//start point
                    var des = myLatLng;// should be the destination
                    path.push(src);
                    poly.setPath(path);
                    service.route({
                        origin: src,
                        destination: des,
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    }, function(result, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                path.push(result.routes[0].overview_path[i]);
                            }
                        }
                    });

                }
                ;

                // function()
                setInterval(function() {
                    lat = Math.random() + orlat;
                    lng = Math.random() + orlong;
                    console.log(lat + "-" + lng);
                    myLatLng = new google.maps.LatLng(lat, lng);
                    movepointer(map, marker);

                }, 1000);



            },
            error: function() {
                $('#frame').html('Sorry, no details found');
            },
        });
        return false;
    }
    $(function() {
        $("#frame").draggable();
    });

</script>

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I asked a similar question, but where possible I try to copy the names already in the .NET framework, and I look for ideas in the Java and Android frameworks.

It seems Helper, Manager, and Util are the unavoidable nouns you attach for coordinating classes that contain no state and are generally procedural and static. An alternative is Coordinator.

You could get particularly purple prosey with the names and go for things like Minder, Overseer, Supervisor, Administrator, and Master, but as I said I prefer keeping it like the framework names you're used to.


Some other common suffixes (if that is the correct term) you also find in the .NET framework are:

  • Builder
  • Writer
  • Reader
  • Handler
  • Container

Android - how do I investigate an ANR?

Consider using the ANR-Watchdog library to accurately track and capture ANR stack traces in a high level of detail. You can then send them to your crash reporting library. I recommend using setReportMainThreadOnly() in this scenario. You can either make the app throw a non-fatal exception of the freeze point, or make the app force quit when the ANR happens.

Note that the standard ANR reports sent to your Google Play Developer console are often not accurate enough to pinpoint the exact problem. That's why a third-party library is needed.

Angular File Upload

Try this

Install

npm install primeng --save

Import

import {FileUploadModule} from 'primeng/primeng';

Html

<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
    accept="image/*" auto="auto"></p-fileUpload>

Disable browser 'Save Password' functionality

One way I know is to use (for instance) JavaScript to copy the value out of the password field before submitting the form.

The main problem with this is that the solution is tied to JavaScript.

Then again, if it can be tied to JavaScript you might as well hash the password on the client-side before sending a request to the server.

Fast way of finding lines in one file that are not in another?

$ join -v 1 -t '' file1 file2
line2
line3

The -t makes sure that it compares the whole line, if you had a space in some of the lines.

How to determine the version of Gradle?

You can also add the following line to your build script:

println "Running gradle version: $gradle.gradleVersion"

or (it won't be printed with -q switch)

logger.lifecycle "Running gradle version: $gradle.gradleVersion"

How to turn a string formula into a "real" formula

UPDATE This used to work (in 2007, I believe), but does not in Excel 2013.

EXCEL 2013:

This isn't quite the same, but if it's possible to put 0.4 in one cell (B1, say), and the text value A1 in another cell (C1, say), in cell D1, you can use =B1*INDIRECT(C1), which results in the calculation of 0.4 * A1's value.

So, if A1 = 10, you'd get 0.4*10 = 4 in cell D1. I'll update again if I can find a better 2013 solution, and sorry the Microsoft destroyed the original functionality of INDIRECT!

EXCEL 2007 version:

For a non-VBA solution, use the INDIRECT formula. It takes a string as an argument and converts it to a cell reference.

For example, =0.4*INDIRECT("A1") will return the value of 0.4 * the value that's in cell A1 of that worksheet.

If cell A1 was, say, 10, then =0.4*INDIRECT("A1") would return 4.

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

Display Python datetime without time

You can usee the following code: week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]

Best way to Bulk Insert from a C# DataTable

If using SQL Server, SqlBulkCopy.WriteToServer(DataTable)

Or also with SQL Server, you can write it to a .csv and use BULK INSERT

If using MySQL, you could write it to a .csv and use LOAD DATA INFILE

If using Oracle, you can use the array binding feature of ODP.NET

If SQLite:

How can I check the size of a file in a Windows batch script?

Important to note is the INT32 limit of Batch: 'Invalid number. Numbers are limited to 32-bits of precision.'

Try the following statements:

IF 2147483647 GTR 2147483646 echo A is greater than B (will be TRUE)
IF 2147483648 GTR 2147483647 echo A is greater than B (will be FALSE!)

Any number greater than the max INT32 value will BREAK THE SCRIPT! Seeing as filesize is measured in bytes, the scripts will support a maximum filesize of about 255.9999997615814 MB !

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

This works for to present any view controller ,if you have navigation controller available. self.navigationController?.present(MyViewController, animated: true, completion: nil) Also , I can able to present alerts and mail controller also.

jQuery Combobox/select autocomplete?

Have a look at the following example of the jQueryUI Autocomplete, as it is keeping a select around and I think that is what you are looking for. Hope this helps.

http://jqueryui.com/demos/autocomplete/#combobox

ReferenceError: $ is not defined

jQuery is a JavaScript library, The purpose of jQuery is to make code much easier to use JavaScript.

The jQuery syntax is tailor-made for selecting, A $ sign to define/access jQuery.

Its in declaration sequence must be on top then any other script included which uses jQuery

Correct position to jQuery declaration :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    console.log('hi from jQuery!');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
_x000D_
_x000D_
_x000D_

Above example will work perfectly because jQuery library is initialized before any other library which is using jQuery functions, including $

But if you apply it somewhere else, jQuery functions will not initialize in browser DOM and it will not able to identify any code related to jQuery, and its code starts with $ sign, so you will receive $ is not a function error.

Incorrect position for jQuery declaration:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    console.log('hi from jQuery!');_x000D_
});
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Above code will not work because, jQuery is not declared on the top of any library which uses jQuery ready function.

How to Get JSON Array Within JSON Object?

  Gson gson = new Gson();
                Type listType = new TypeToken<List<Data>>() {}.getType();
                List<Data>     cartProductList = gson.fromJson(response.body().get("data"), listType);
                Toast.makeText(getContext(), ""+cartProductList.get(0).getCity(), Toast.LENGTH_SHORT).show();

How to split a file into equal parts, without breaking individual lines?

I made a bash script, that given a number of parts as input, split a file

#!/bin/sh

parts_total="$2";
input="$1";

parts=$((parts_total))
for i in $(seq 0 $((parts_total-2))); do
  lines=$(wc -l "$input" | cut -f 1 -d" ")
  #n is rounded, 1.3 to 2, 1.6 to 2, 1 to 1
  n=$(awk  -v lines=$lines -v parts=$parts 'BEGIN { 
    n = lines/parts;
    rounded = sprintf("%.0f", n);
    if(n>rounded){
      print rounded + 1;
    }else{
      print rounded;
    }
  }');
  head -$n "$input" > split${i}
  tail -$((lines-n)) "$input" > .tmp${i}
  input=".tmp${i}"
  parts=$((parts-1));
done
mv .tmp$((parts_total-2)) split$((parts_total-1))
rm .tmp*

I used head and tail commands, and store in tmp files, for split the files

#10 means 10 parts
sh mysplitXparts.sh input_file 10

or with awk, where 0.1 is 10% => 10 parts, or 0.334 is 3 parts

awk -v size=$(wc -l < input) -v perc=0.1 '{
  nfile = int(NR/(size*perc)); 
  if(nfile >= 1/perc){
    nfile--;
  } 
  print > "split_"nfile
}' input

Get a list of distinct values in List

mcilist = (from mci in mcilist select mci).Distinct().ToList();

Show red border for all invalid fields after submitting form angularjs

I have created a working CodePen example to demonstrate how you might accomplish your goals.

I added ng-click to the <form> and removed the logic from your button:

<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />

Here's the updated template:

<section ng-app="app" ng-controller="MainCtrl">
  <form class="well" name="addRelation" data-ng-click="save(model)">
    <label>First Name</label>
    <input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
    <label>Last Name</label>
    <input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
    <label>Email</label>
    <input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
    <input class="btn" type="submit" value="SAVE" />  
  </form>
</section>

and controller code:

app.controller('MainCtrl', function($scope) {  
  $scope.save = function(model) {
    $scope.addRelation.submitted = true;

    if($scope.addRelation.$valid) {
      // submit to db
      console.log(model); 
    } else {
      console.log('Errors in form data');
    }
  };
});

I hope this helps.

Reload .profile in bash shell script (in unix)?

Try this:

cd 
source .bash_profile

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Step 1. Install "Apache_OpenOffice_4.1.2" in your system Step 2. Download "unoconv" library from github or any where else.

-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory

-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder

-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf

-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.

If pdf not created than last step is Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop

Create sample .php file and put below code and run on wamp or xampp server

$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);

This code working for me in windows-8 operating system

How to add button inside input

This can be achieved using inline-block JS fiddle here

<html>
<body class="body">
    <div class="form">
        <form class="email-form">
            <input type="text" class="input">
            <a href="#" class="button">Button</a>
        </form>
    </div>
</body>
</html>


<style>
* {
    box-sizing: border-box;
}

.body {
    font-family: Arial, sans-serif;
    font-size: 14px;
    line-height: 20px;
    color: #333;
}

.form {
    display: block;
    margin: 0 0 15px;
}

.email-form {
    display: block;
    margin-top: 20px;
    margin-left: 20px;
}

.button {
    height: 40px;
    display: inline-block;
    padding: 9px 15px;
    background-color: grey;
    color: white;
    border: 0;
    line-height: inherit;
    text-decoration: none;
    cursor: pointer;
}

.input {
    display: inline-block;
    width: 200px;
    height: 40px;
    margin-bottom: 0px;
    padding: 9px 12px;
    color: #333333;
    vertical-align: middle;
    background-color: #ffffff;
    border: 1px solid #cccccc;
    margin: 0;
    line-height: 1.42857143;
}
</style>

How to delete empty folders using windows command prompt?

This is a hybird of the above. It removes ALL files older than X days and removes any empty folders for the given path. To use simply set the days, folderpath and drive

@echo off
SETLOCAL
set days=30
set folderpath=E:\TEST\
set drive=E:

::Delete files
forfiles -p %folderpath% -s -d -%days% -c "cmd /c del /q @path "

::Delete folders
cd %folderpath%
%drive%
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"`

How to sum all column values in multi-dimensional array?

Use this snippet:

$key = 'gozhi';
$sum = array_sum(array_column($array,$key));

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

rails bundle clean

If you are using RVM you can install your gems into gemsets. That way when you want to perform a full cleanup you can simply remove the gemset, which in turn removes all the gems installed in it. Your other option is to simply uninstall your unused gems and re-run your bundle install command.

Since bundler is meant to be a project-per-project gem versioning tool it does not provide a bundle clean command. Doing so would mean the possibility of removing gems associated with other projects as well, which would not be desirable. That means that bundler is probably the wrong tool to use to manage your gem directory. My personal recommendation would be to use RVM gemsets to sandbox your gems in certain projects or ruby versions.

Sass calculate percent minus px

IF you know the width of the container, you could do like this:

#container
  width: #{200}px
  #element
    width: #{(0.25 * 200) - 5}px

I'm aware that in many cases #container could have a relative width. Then this wouldn't work.

Quickest way to convert XML to JSON in Java

I have uploaded the project you can directly open in eclipse and run that's all https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA

Thank You

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you are using CORS middleware and you want to send withCredential boolean true, you can configure CORS like this:

var cors = require('cors');    
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

How to grep for contents after pattern?

grep -Po 'potato:\s\K.*' file

-P to use Perl regular expression

-o to output only the match

\s to match the space after potato:

\K to omit the match

.* to match rest of the string(s)

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

Declare found as "volatile". This should tell the compiler to NOT optimize it out.

volatile int found = 0;

Cannot set property 'innerHTML' of null

Add jquery into < head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

Use $document.ready() : the code can be in < head> or in a separate file like main.js

1) using js in same file (add this in the < head>):

<script>
$( document ).ready(function() {
function what(){
    document.getElementById('hello').innerHTML = 'hi';
};
});
</script>

2) using some other file like main.js (add this in the < head>):

<script type="text/javascript" src="/path/to/main.js" charset="utf-8"></script>

and add the code in main.js file :)

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.