Friday, November 30, 2018

php - Match regex pattern that isn't within a bbcode tag

I am attempting to create a regex patten that will match words in a string that begin with @


Regex that solves this initial problem is '~(@\w+)~'


A second requirement of the code is that it must also ignore any matches that occur within [quote] and [/quote] tags


A couple of attempts that have failed are:


(?:[0-9]+|~(@\w+)~)(?![0-9a-z]*\[\/[a-z]+\])
/[quote[\s\]][\s\S]*?\/quote](*SKIP)(*F)|~(@\w+)~/i

Example: the following string should have an array output as displayed:


$results = [];
$string = "@friends @john [quote]@and @jane[/quote] @doe";
//run regex match
preg_match_all('regex', $string, $results);
//dump results
var_dump($results[1]);
//results: array consisting of:
[1]=>"@friends"
[2]=>"@john"
[3]=>"@doe

sql - Convert multiple rows into one with coma as separator

If I issue SELECT ID FROM TestAhmet I get this result:



1

3
5
2
4


but what I really need is one row with all the values separated by comma, like this:



1,2,3,4,5



How do I do this?



ps: I cant do this : Convert multiple rows into one with comma as separator

How to fix "Headers already sent" error in PHP




When running my script, I am getting several errors like this:





Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23




The lines mentioned in the error messages contain header() and setcookie() calls.



What could be the reason for this? And how to fix it?


Answer



No output before sending headers!



Functions that send/modify HTTP headers must be invoked before any output is made.

summary ⇊
Otherwise the call fails:




Warning: Cannot modify header information - headers already sent (output started at script:line)




Some functions modifying the HTTP header are:






Output can be:




  • Unintentional:









  • Intentional:




    • print, echo and other functions producing output


    • Raw sections prior code.




Why does it happen?



To understand why headers must be sent before output it's necessary
to look at a typical HTTP
response. PHP scripts mainly generate HTML content, but also pass a
set of HTTP/CGI headers to the webserver:




HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8

PHP page output page

Content

Some more output follows...


and



The page/output always follows the headers. PHP has to pass the
headers to the webserver first. It can only do that once.
After the double linebreak it can nevermore amend them.



When PHP receives the first output (print, echo, ) it will
flush all collected headers. Afterwards it can send all the output
it wants. But sending further HTTP headers is impossible then.



How can you find out where the premature output occured?




The header() warning contains all relevant information to
locate the problem cause:




Warning: Cannot modify header information - headers already sent by
(output started at /www/usr2345/htdocs/auth.php:52) in
/www/usr2345/htdocs/index.php on line 100





Here "line 100" refers to the script where the header() invocation failed.



The "output started at" note within the parenthesis is more significant.
It denominates the source of previous output. In this example it's auth.php
and line 52. That's where you had to look for premature output.



Typical causes:




  1. Print, echo




    Intentional output from print and echo statements will terminate
    the opportunity to send HTTP headers. The application flow must
    be restructured to avoid that. Use functions
    and templating schemes. Ensure header() calls occur before messages
    are written out.



    Functions that produce output include





    • print, echo, printf, vprintf

    • trigger_error, ob_flush, ob_end_flush, var_dump, print_r

    • readfile, passthru, flush, imagepng, imagejpeg




    among others and user-defined functions.


  2. Raw HTML areas



    Unparsed HTML sections in a .php file are direct output as well.
    Script conditions that will trigger a header() call must be noted

    before any raw blocks.




    // Too late for headers already.


    Use a templating scheme to separate processing from output logic.





    • Place form processing code atop scripts.

    • Use temporary string variables to defer messages.

    • The actual output logic and intermixed HTML output should follow last.


  3. Whitespace before for "script.php line 1" warnings



    If the warning refers to output in line 1, then it's mostly
    leading whitespace, text or HTML before the opening token.



     
    # There's a SINGLE space/newline before


    Similarly it can occur for appended scripts or script sections:



    ?>




    PHP actually eats up a single linebreak after close tags. But it won't
    compensate multiple newlines or tabs or spaces shifted into such gaps.


  4. UTF-8 BOM



    Linebreaks and spaces alone can be a problem. But there are also "invisible"
    character sequences which can cause this. Most famously the
    UTF-8 BOM (Byte-Order-Mark)
    which isn't displayed by most text editors. It's the byte sequence EF BB BF, which
    is optional and redundant for UTF-8 encoded documents. PHP however has to treat
    it as raw output. It may show up as the characters  in the output (if the client

    interprets the document as Latin-1) or similar "garbage".



    In particular graphical editors and Java based IDEs are oblivious to its
    presence. They don't visualize it (obliged by the Unicode standard).
    Most programmer and console editors however do:



    joes editor showing UTF-8 BOM placeholder, and MC editor a dot



    There it's easy to recognize the problem early on. Other editors may identify
    its presence in a file/settings menu (Notepad++ on Windows can identify and

    remedy the problem),
    Another option to inspect the BOMs presence is resorting to an hexeditor.
    On *nix systems hexdump is usually available,
    if not a graphical variant which simplifies auditing these and other issues:



    beav hexeditor showing utf-8 bom



    An easy fix is to set the text editor to save files as "UTF-8 (no BOM)"
    or similar such nomenclature. Often newcomers otherwise resort to creating new
    files and just copy&pasting the previous code back in.




    Correction utilities



    There are also automated tools to examine and rewrite text files
    (sed/awk or recode).
    For PHP specifically there's the phptags tag tidier.
    It rewrites close and open tags into long and short forms, but also easily
    fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:



    phptags  --whitespace  *.php



    It's sane to use on a whole include or project directory.


  5. Whitespace after ?>



    If the error source is mentioned as behind the
    closing ?>
    then this is where some whitespace or raw text got written out.
    The PHP end marker does not terminate script executation at this
    point. Any text/space characters after it will be written out as page content

    still.



    It's commonly advised, in particular to newcomers, that trailing ?> PHP
    close tags should be omitted. This eschews a small portion of these cases.
    (Quite commonly include()d scripts are the culprit.)


  6. Error source mentioned as "Unknown on line 0"



    It's typically a PHP extension or php.ini setting if no error source
    is concretized.





    • It's occasionally the gzip stream encoding setting
      or the ob_gzhandler.

    • But it could also be any doubly loaded extension= module
      generating an implicit PHP startup/warning message.


  7. Preceding error messages



    If another PHP statement or expression causes a warning message or
    notice being printeded out, that also counts as premature output.




    In this case you need to eschew the error,
    delay the statement execution, or suppress the message with e.g.
    isset() or @() -
    when either doesn't obstruct debugging later on.




No error message



If you have error_reporting or display_errors disabled per php.ini,

then no warning will show up. But ignoring errors won't make the problem go
away. Headers still can't be sent after premature output.



So when header("Location: ...") redirects silently fail it's very
advisable to probe for warnings. Reenable them with two simple commands
atop the invocation script:



error_reporting(E_ALL);
ini_set("display_errors", 1);



Or set_error_handler("var_dump"); if all else fails.



Speaking of redirect headers, you should often use an idiom like
this for final code paths:



exit(header("Location: /finished.html"));


Preferrably even a utility function, which prints a user message

in case of header() failures.



Output buffering as workaround



PHPs output buffering
is a workaround to alleviate this issue. It often works reliably, but shouldn't
substitute for proper application structuring and separating output from control
logic. Its actual purpose is minimizing chunked transfers to the webserver.





  1. The output_buffering=
    setting nevertheless can help.
    Configure it in the php.ini
    or via .htaccess
    or even .user.ini on
    modern FPM/FastCGI setups.
    Enabling it will allow PHP to buffer output instead of passing it to the webserver
    instantly. PHP thus can aggregate HTTP headers.


  2. It can likewise be engaged with a call to ob_start();
    atop the invocation script. Which however is less reliable for multiple reasons:





    • Even if starts the first script, whitespace or a
      BOM might get shuffled before, rendering it ineffective.


    • It can conceal whitespace for HTML output. But as soon as the application
      logic attempts to send binary content (a generated image for example),
      the buffered extraneous output becomes a problem. (Necessitating ob_clean()
      as furher workaround.)


    • The buffer is limited in size, and can easily overrun when left to defaults.
      And that's not a rare occurence either, difficult to track down
      when it happens.






Both approaches therefore may become unreliable - in particular when switching between
development setups and/or production servers. Which is why output buffering is
widely considered just a crutch / strictly a workaround.



See also the basic usage example
in the manual, and for more pros and cons:






But it worked on the other server!?



If you didn't get the headers warning before, then the output buffering
php.ini setting

has changed. It's likely unconfigured on the current/new server.



Checking with headers_sent()




You can always use headers_sent() to probe if
it's still possible to... send headers. Which is useful to conditionally print
an info or apply other fallback logic.



if (headers_sent()) {
die("Redirect failed. Please click on this link: ");
}
else{
exit(header("Location: /user.php"));
}



Useful fallback workarounds are:





Both approaches however make acceptable fallbacks when genuine HTTP header()
calls fail. Ideally you'd always combine this with a user-friendly message and
clickable link as last resort. (Which for instance is what the http_redirect()
PECL extension does.)



Why setcookie() and session_start() are also affected




Both setcookie() and session_start() need to send a Set-Cookie: HTTP header.
The same conditions therefore apply, and similar error messages will be generated
for premature output situations.



(Of course they're furthermore affected by disabled cookies in the browser,
or even proxy issues. The session functionality obviously also depends on free
disk space and other php.ini settings, etc.)



Further links





plot explanation - Why did Beth not run earlier?

A few days ago, I saw Falling Down (1993) for the second time or so.


(Spoiler ahead, if you managed not to see this movie yet)


During the movie, which in real time covers the best part of a day, William Foster, clearly in a violent mood, threatens to visit his ex wife, Elisabeth, to attend their little daughter Adele’s birthday party. He calls her a number of times. She is terrified of him and notifies the police until they get fed up with her and don't offer her any protection any more.


Beth stays at home, knowing that William is on his way. Isn't that strange? When she finally runs, William is already entering her house.


I understand that the plot needs suspense. But my question is, is it made plausible in the movie itself why she lingers so long?


(I randomly sampled the haystack of 346 reviews at IMDB, but no luck).


Answer


Aside from what is said explicitly in the film (and it's been more than 10 years since I saw this one last), we never find out if William has ever threatened Elisabeth but failed to follow through - which might make her decision to stay until absolutely necessary easier for her.


Also, it's her daughter's birthday, which means that there will be a party, which means that there will be plenty of people over. This can help in some situations due to safety in numbers theory. Having people over for her daughter's birthday party might cause William to reconsider his threat, as he would have to deal with an unknown number of other people.


javascript - for loop in react



I got this function working to get some gym classes from a .json file.



    filtrarClase(dia, hora) {
let data = this.state.data
return data.filter(clase => {
if ((clase.dia === dia) && (clase.horaclase === hora)) {

return clase.actividad
} else {
return false
}
})
.map((clase,i) => {
return (
  • {clase.actividad}

    {clase.duracion}


    {clase.hoy} {clase.sala}




  • )
    })
    }


    it's ok, just passing it some "day and hour" will return right classes.
    But then I can't find a way to loop over this function... and only be able to do this ****





      {horas[0]}

      {this.filtrarClase(1, horas[0])}

      {this.filtrarClase(2, horas[0])}

      {this.filtrarClase(3, horas[0])}

      {this.filtrarClase(4, horas[0])}

      {this.filtrarClase(5, horas[0])}

      {this.filtrarClase(6, horas[0])}





    Over and over again... 17 times..



                

      {horas[1]}

      {this.filtrarClase(1, horas[16])}

      {this.filtrarClase(2, horas[16])}

      {this.filtrarClase(3, horas[16])}

      {this.filtrarClase(4, horas[16])}

      {this.filtrarClase(5, horas[16])}

      {this.filtrarClase(6, horas[16])}





    I'm sure you can point me on the right way with a "for" or "forEach", or hope so!
    I tried this:



        actualizarLista(dia){
    const horas = ['07:30','08:15','08:30','09:30','10:30','15:00','15:15','15:30','17:30','18:00','18:15','18:30','19:00','19:30','20:00','20:30','21:30']
    for (let i=0; i return
      {this.filtrarClase(dia, horas[i])}


    }

    }

    render() {
    let dias = [1,2,3,4,5,6]
    for (let i=0; i this.actualizarLista(i)
    }
    return (



    {dias}
    .........


    I tried a for loop but only returns 1 item, so I'm doing something wrong for sure. Thanks in advance.


    Answer



    Reason is, for loop is used to iterate the array it will never return anything, if you want to return something then use map.



    Write it like this:




    actualizarLista(dia){
    const horas = ['07:30','08:15','08:30','09:30','10:30','15:00','15:15','15:30','17:30','18:00','18:15','18:30','19:00','19:30','20:00','20:30','21:30']
    return horas.map((el, i) => {
    return
      {this.filtrarClase(dia, el)}

    })
    }

    render() {
    let dias = [1,2,3,4,5,6];

    let uiItems = dias.map(i => {
    return

    {this.actualizarLista(i)}

    })

    return (

    {uiItems}


    )
    }


    Suggestion: horas array is constant so i will suggest you to define it once outside of the class.


    How to [recursively] Zip a directory in PHP?



    Directory is something like:



    home/
    file1.html
    file2.html
    Another_Dir/
    file8.html

    Sub_Dir/
    file19.html


    I am using the same PHP Zip class used in PHPMyAdmin http://trac.seagullproject.org/browser/branches/0.6-bugfix/lib/other/Zip.php . I'm not sure how to zip a directory rather than just a file. Here's what I have so far:



    $aFiles = $this->da->getDirTree($target);
    /* $aFiles is something like, path => filetime
    Array
    (

    [home] =>
    [home/file1.html] => 1251280379
    [home/file2.html] => 1251280377
    etc...
    )

    */
    $zip = & new Zip();
    foreach( $aFiles as $fileLocation => $time ){
    $file = $target . "/" . $fileLocation;

    if ( is_file($file) ){
    $buffer = file_get_contents($file);
    $zip->addFile($buffer, $fileLocation);
    }
    }
    THEN_SOME_PHP_CLASS::toDownloadData($zip); // this bit works ok


    but when I try to unzip the corresponding downloaded zip file I get "operation not permitted"




    This error only happens when I try to unzip on my mac, when I unzip through the command line the file unzips ok. Do I need to send a specific content type on download, currently 'application/zip'


    Answer



    Here is a simple function that can compress any file or directory recursively, only needs the zip extension to be loaded.



    function Zip($source, $destination)
    {
    if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
    }


    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);


    foreach ($files as $file)
    {
    $file = str_replace('\\', '/', $file);

    // Ignore "." and ".." folders
    if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
    continue;

    $file = realpath($file);


    if (is_dir($file) === true)
    {
    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
    }
    else if (is_file($file) === true)
    {
    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
    }
    }

    }
    else if (is_file($source) === true)
    {
    $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
    }



    Call it like this:



    Zip('/folder/to/compress/', './compressed.zip');

    jvm - Why do the execution time of independent code blocks depend on execution order in Scala?




    I have a program written in Scala. I wanted to measure the execution time of different independent code blocks. When I did it in the obvious way (i.e. inserting System.nanoTime() before and after each block), I observed that the the execution time depends on the ordering of the blocks. The first some blocks always took more time than the others.



    I created a minimalistic example that reproduces this behaviour. All code blocks are the same and call hashCode() for an array of integers, for simplicity.




    package experiments

    import scala.util.Random

    /**
    * Measuring execution time of a code block
    *
    * Minimalistic example
    */

    object CodeBlockMeasurement {

    def main(args: Array[String]): Unit = {
    val numRecords = args(0).toInt
    // number of independent measurements
    val iterations = args(1).toInt

    // Changes results a little bit, but not too much
    // val records2 = Array.fill[Int](1)(0)
    // records2.foreach(x => {})


    for (_ <- 1 to iterations) {
    measure(numRecords)
    }
    }

    def measure(numRecords: Int): Unit = {
    // using a new array every time
    val records = Array.fill[Int](numRecords)(new Random().nextInt())
    // block of code to be measured

    def doSomething(): Unit = {
    records.foreach(k => k.hashCode())
    }
    // measure execution time of the code-block
    elapsedTime(doSomething(), "HashCodeExperiment")
    }

    def elapsedTime(block: => Unit, name: String): Unit = {
    val t0 = System.nanoTime()
    val result = block

    val t1 = System.nanoTime()
    // print out elapsed time in milliseconds
    println(s"$name took ${(t1 - t0).toDouble / 1000000} ms")
    }
    }


    After running the program with numRecords = 100000 and iterations = 10, my console looks like this:





    HashCodeExperiment took 14.630283 ms
    HashCodeExperiment took 7.125693 ms
    HashCodeExperiment took 0.368151 ms
    HashCodeExperiment took 0.431628 ms
    HashCodeExperiment took 0.086455 ms
    HashCodeExperiment took 0.056458 ms
    HashCodeExperiment took 0.055138 ms
    HashCodeExperiment took 0.062997 ms
    HashCodeExperiment took 0.063736 ms
    HashCodeExperiment took 0.056682 ms




    Can somebody explain why is that? Shouldn't all be the same? Which is the real execution time?



    Thanks a lot,
    Peter




    Environment parameters:
    OS: ubuntu 14.04 LTS (64 bit)
    IDE: IntelliJ IDEA 2016.1.1 (IU-145.597)
    Scala: 2.11.7




    Answer



    It's Java's JIT kicking in. Initially the plain bytecode is executed but after some time (1.5k/10k invocations by default for Oracle JVM, see -XX:CompileThreshold) the optimizations start processing the actual executed native code which usually results in quite drastic performance improvements.



    As Ivan mentions, then there's caching of intermediate bytecode/native code and various other technologies involved, one of the most significant ones being the Garbage Collector itself which cause even more variance to individual results. Depending how heavily the code allocates new objects this might absolutely trash performance whenever GC occurs, but that's a separate issue.



    To remove such outlier results when microbenchmarking it is recommendable that you benchmark multiple iterations of the action and discard the bottom and top 5..10% results and do the performance estimation based on remaining samples.


    php - Apache's default encoding is ISO-8859-1 but websites are UTF-8?



    I have to deal with encoding for the first time and I'm confused by how PHP, Apache, and browsers handle encodings. PHP and Apache use ISO-8859-1 by default, but most websites are UTF-8. At what point is ISO-8859-1 converted into UTF-8? Also, since PHP uses ISO-8859-1, how come it can read UTF-8 webpages?


    Answer



    Apache doesn't "use" any encoding by default, its job hardly has anything to do with understanding or converting text encodings. PHP doesn't "use" ISO-8859 by default, PHP's strings have no associated encoding.




    What is true is that many of PHP's core string functions assume ASCII or ISO-8859 encoding in their operations and are not equipped to deal with other encodings properly. However, and it's worth stating this again, PHP strings as a data type do not have any encoding per se, nothing is preventing you from having strings in any encoding you wish in PHP and PHP even offers functions to deal correctly with string manipulation in virtually any arbitrary encoding. So, as long as you do it correctly, nothing is preventing you from handling and outputting UTF-8 with PHP.



    Apache then does not care in the least what exactly you're sending to the client, it does not stand in anyone's way with regards to outputting text in any encoding (or binary data for that matter). The only thing it may do is add an HTTP header like this to the response:



    Content-Type: text/html; charset=iso-8859-1


    This header is only there to inform the client what content it receives. This header is not based in any way on the actual content you're sending, Apache neither cares nor checks nor converts anything. It just sets this header and that's all it does. You should configure Apache to set the correct charset value that corresponds to the encoding you're actually outputting from PHP, its default is simply iso-8859-1. Or you may set a Content-Type header yourself from PHP to prevent Apache from adding one. That's all.



    For more information, see What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text, Handling Unicode Front To Back In A Web App.



    Python unique list using set












    What I am trying to do is write a method that takes a list as an argument and uses a set to return a copy of the list where each element only occurs once, as well as having the elements in the new list occur in order of their first occurrence in the original list. I HAVE to use a set for this, however, I can't make it so that the output is in the right order while having a quick result.
    If I put something like this:



    def unique(a):

    return list(set(a))


    and passed a list with millions of elements, it would give me a result quickly, but it wouldn't be ordered.
    So what I have right now is this:




    def unique(a):
    b = set(a)
    c = {}
    d = []
    for i in b:
    c[a.index(i)] = i
    for i in c:
    d.append(c[i])
    return d



    This gives me the result I want, but not fast enough. If I pass a list with a million elements, I could be waiting for half an hour, whereas the one liner up there takes less than a second. How could I solve this problem?


    Answer



    >>> from collections import OrderedDict
    >>> items = [1, 2, 3, 'a', 2, 4, 'a']
    >>> OrderedDict.fromkeys(items).keys()
    [1, 2, 3, 'a', 4]

    Yii with PHP Storm Auto Complete and Class Recognition



    I've just started using the Yii Framework (A fantastic one at that!) and am using PHP Storm 5 with it.




    I have separated the testdrive file from the Yii framework and just changed the paths in the index.php file which all works but how do I now get code completion and the IDE to recognise all the yii system classes?



    I have googled and read heaps of stuff but it's all so confusing and not explained very well. Can anyone out there give me a few steps to follow?



    Thanks



    EDIT



    I figured it out, pretty easy. All you have to do is go File → Settings → Project settings → PHP → PHP Home → Add. and add the path to your framework folder in yii whereever it is.


    Answer




    I figured it out, pretty easy. All you have to do is go File → Settings → Project settings → PHP → PHP Home → Add. and add the path to your framework folder in yii whereever it is.


    validation - (Built-in) way in JavaScript to check if a string is a valid number



    I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function?


    Answer



    To check if a variable (including a string) is a number, check if it is not a number:




    This works regardless of whether the variable content is a string or number.



    isNaN(num)         // returns true if the variable does NOT contain a valid number


    Examples



    isNaN(123)         // false
    isNaN('123') // false

    isNaN('1e10000') // false (This translates to Infinity, which is a number)
    isNaN('foo') // true
    isNaN('10px') // true


    Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave:



    function isNumeric(num){
    return !isNaN(num)
    }



    To convert a string containing a number into a number:



    Only works if the string only contains numeric characters, else it returns NaN.



    +num               // returns the numeric value of the string, or NaN 
    // if the string isn't purely numeric characters



    Examples



    +'12'              // 12
    +'12.' // 12
    +'12..' // Nan
    +'.12' // 0.12
    +'..12' // Nan
    +'foo' // NaN
    +'12px' // NaN



    To convert a string loosely to a number



    Useful for converting '12px' to 12, for example:



    parseInt(num)      // extracts a numeric value from the 
    // start of the string, or NaN.


    Examples




    parseInt('12')     // 12
    parseInt('aaa') // NaN
    parseInt('12px') // 12
    parseInt('foo2') // NaN These last two may be different
    parseInt('12a5') // 12 from what you expected to see.


    Floats




    Bear in mind that, unlike +num, parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you're probably better off using another method instead):



    +'12.345'          // 12.345
    parseInt(12.345) // 12
    parseInt('12.345') // 12


    Empty strings



    Empty strings may be a little counter-intuitive. +num converts empty strings to zero, and isNaN() assumes the same:




    +''                // 0
    isNaN('') // false


    But parseInt() does not agree:



    parseInt('')       // NaN

    php - Regex match the double quote in BBCode attribute




    I have text stored in my forum database with some incompatible such as the following:



    Some text with [COLOR="red"]colored text[/COLOR] and [SIZE="7"]Big fonts[/SIZE] while "This double quote" is not matched


    What I want is a regex that match any double quotes " " with any string inside them while those double quotes are inside the square bracket [ ] of the bbcode.



    I need this to be able to fix those bbcodes by stripping the double quotes. The regex implementation is going to be using PHP.


    Answer



    You may be looking for something like this:




    $code= 'Some text with [COLOR="red"]colored text[/COLOR] and [SIZE="7"]Big fonts[/SIZE] while "This double quote" is not matched';

    preg_match_all('/\[.*?="(\w+)"\]/', $code, $matches, PREG_PATTERN_ORDER);
    for ($i = 0; $i < count($matches[1]); $i++) {
    echo $matches[1][$i]."\n";
    }


    DEMO:
    https://ideone.com/LEZHgx



    Thursday, November 29, 2018

    linux - When to wrap quotes around a shell variable?




    Could someone tell me whether or not I should wrap quotes around variables in a shell script?



    For example, is the following correct:



    xdg-open $URL 
    [ $? -eq 2 ]


    or




    xdg-open "$URL"
    [ "$?" -eq "2" ]


    And if so, why?


    Answer



    General rule: quote it if it can either be empty or contain spaces (or any whitespace really) or special characters (wildcards). Not quoting strings with spaces often leads to the shell breaking apart a single argument into many.



    $? doesn't need quotes since it's a numeric value. Whether $URL needs it depends on what you allow in there and whether you still want an argument if it's empty.




    I tend to always quote strings just out of habit since it's safer that way.


    java - How to call a SOAP web service on Android




    I am having a lot of trouble finding good information on how to call a standard SOAP/WSDL web service with Android. All I've been able to find are either very convoluted documents and references to "kSoap2" and then some bit about parsing it all manually with SAX. OK, that's fine, but it's 2008, so I figured there should be some good library for calling standard web services.




    The web service is just basically one created in NetBeans. I would like to have IDE support for generating the plumbing classes. I just need the easiest/most-elegant way to contact a WSDL based web service from an Android-based phone.


    Answer



    Android does not provide any sort of SOAP library. You can either write your own, or use something like kSOAP 2. As you note, others have been able to compile and use kSOAP2 in their own projects, but I haven't had to.



    Google has shown, to date, little interest in adding a SOAP library to Android. My suspicion for this is that they'd rather support the current trends in Web Services toward REST-based services, and using JSON as a data encapsulation format. Or, using XMPP for messaging. But that is just conjecture.



    XML-based web services are a slightly non-trivial task on Android at this time. Not knowing NetBeans, I can't speak to the tools available there, but I agree that a better library should be available. It is possible that the XmlPullParser will save you from using SAX, but I don't know much about that.


    android - How to display HTML in TextView?



    I have simple HTML:



    Title



    description here




    I want to display HTML styled text it in TextView. How to do this?


    Answer



    You need to use Html.fromHtml() to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.



    This is what you should do:



    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

    textView.setText(Html.fromHtml("

    Title


    Description here

    ", Html.FROM_HTML_MODE_COMPACT));
    } else {
    textView.setText(Html.fromHtml("

    Title


    Description here

    "));
    }

    Are table names in MySQL case sensitive?




    Are table names in MySQL case sensitive?



    On my Windows dev machine the code I have is able to query my tables which appear to be all lowercase. When I deploy to the test server in our datacenter the table names appear to start with an uppercase letter.



    The servers we use are all on Ubuntu.


    Answer



    In General:



    Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix.





    In MySQL, databases correspond to directories within the data
    directory. Each table within a database corresponds to at least one
    file within the database directory. Consequently, the case sensitivity of the
    underlying operating system plays a part in the case sensitivity of
    database and table names.




    One can configure how tables names are stored on the disk using the system variable lower_case_table_names. (in my.cnf configuration under [mysqld])




    Read the section: 10.2.2 Identifier Case Sensitivity for more information.


    How can I merge properties of two JavaScript objects dynamically?

    I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:



    var obj1 = { food: 'pizza', car: 'ford' }
    var obj2 = { animal: 'dog' }

    obj1.merge(obj2);

    //obj1 now has three properties: food, car, and animal



    Does anyone have a script for this or know of a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.

    javascript - How to run html file on localhost?



    I have a html file and i run it on localhost. But, this file includes mirror using webcam. Example, how can i run this html file on localhost? Webcam starting on this example when check to live checkbox. Thanx for your reply.



    Answer



    You can use python -m http.server. By default the local server will run on port 8000. If you would like to change this, simply add the port number python -m http.server 1234



    If you are using python 2 (instead of 3), the equivalent command is python -m SimpleHTTPServer


    java - How to pass an object from one activity to another on Android




    I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.



    The code for the customer class:



    public class Customer {

    private String firstName, lastName, Address;
    int Age;


    public Customer(String fname, String lname, int age, String address) {

    firstName = fname;
    lastName = lname;
    Age = age;
    Address = address;
    }

    public String printValues() {


    String data = null;

    data = "First Name :" + firstName + " Last Name :" + lastName
    + " Age : " + Age + " Address : " + Address;

    return data;
    }
    }



    I want to send its object from one Activity to another and then display the data on the other Activity.



    How can I achieve that?


    Answer



    One option could be letting your custom class implement the Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.



    Pseudocode:



    //To pass:
    intent.putExtra("MyClass", obj);


    // To retrieve object in second Activity
    getIntent().getSerializableExtra("MyClass");


    Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:



    class MainClass implements Serializable {

    public MainClass() {}


    public static class ChildClass implements Serializable {

    public ChildClass() {}
    }
    }

    android - how to make a method in asynctask

    Kindly guide me how to make all this into an asynctask method. I have to make this code in asynctask because it is giving a null value because of calling it in uithread. Kindly show me the correct way how to make this possible. I have seen many, many questions on stackoverflow but I am unable to make this work.



    I have seen following questions:



    How to fix android.os.NetworkOnMainThreadException?



    android.os.NetworkOnMainThreadException with android 4.2



    NetworkOnMainThreadException




    android.os.NetworkOnMainThreadException



    How to fix android.os.NetworkOnMainThreadException?



    My class is:



    public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONParser() {
    }
    public JSONObject makeHttpRequest(String url, String method, List params)
    { try
    {
    if(method == "POST")
    {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params));

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();
    }
    else if(method == "GET"){
    DefaultHttpClient httpClient = new DefaultHttpClient();
    String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString;
    HttpGet httpGet = new HttpGet(url);
    HttpResponse httpResponse = httpClient.execute(httpGet);
    HttpEntity httpEntity = httpResponse.getEntity();

    is = httpEntity.getContent();
    }
    }
    catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    catch (ClientProtocolException e) {
    e.printStackTrace();
    }
    catch (IOException e) {

    e.printStackTrace();
    }
    try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null)
    { sb.append(line + "\n");
    }
    is.close(); json = sb.toString();
    }

    catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString()); }
    try {
    jObj = new JSONObject(json);
    }
    catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    return jObj;
    }

    }

    php - Silex redirect from Twig template

    First, I know this is a horrible thing to do and should be done in controller logic only, but what I'm trying to do is create a custom redirect tag in Twig that fires a Silex redirect.



    I have a custom node that outputs the following into the doDisplay template:



    return $this->getEnvironment()->getExtension('silex')->getApp()->redirect('/', 301);


    Basically this gets the Twig environment and the extension I created which has a getApp method which returns the Silex $app variable, which contains the redirect method.




    But this only returns Array() to the screen. Any suggestions?

    php - Call to a member function on a non-object




    So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.



    class PageAtrributes 
    {
    private $db_connection;
    private $page_title;


    public function __construct($db_connection)
    {
    $this->db_connection = $db_connection;
    $this->page_title = '';
    }

    public function get_page_title()
    {
    return $this->page_title;
    }


    public function set_page_title($page_title)
    {
    $this->page_title = $page_title;
    }
    }


    Later on I call the set_page_title() function like so




    function page_properties($objPortal) {    
    $objPage->set_page_title($myrow['title']);
    }


    When I do I receive the error message:




    Call to a member function set_page_title() on a non-object





    So what am I missing?


    Answer



    It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable?



    As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:



    function page_properties(PageAtrributes $objPortal) {    
    ...
    $objPage->set_page_title($myrow['title']);

    }


    This function will only accept PageAtrributes for the first parameter.


    plot explanation - Where does the tunnel in the Wall come from?

    I just finished the first season of "Game of Thrones", where one of the main themes is 'The Wall', a huge ice wall that devides the realm (Westeros) from the dangerous and winterly North.


    From what I could gather this huge construct is not man-made. It was mentioned that it simply rose a few hundred years back from the ground. One of the characters says this when mentioning that they were no different than the wildlings, just happened to be on the right side of the wall.
    EDIT: found the quote on IMDB:



    Tyrion Lannister: But... I don't believe that giants and ghouls and white walkers are lurking beyond the Wall. I believe that the only difference between us and the wildlings is that when that Wall went up, our ancestors happened to live on the right side of it.



    Apparently the northern side of the Wall is extremely dangerous, hosting wildlings, dangerous animals and the mysterious "White Walkers". Therefore, the Night Watch has to constantly guard and protect the Wall from outside dangers.




    What I don't understand though is:
    Where does the long tunnel leading through the Wall come from?


    It is featured in the very first scene of the series, definitely looks man-made (it's shaped in a perfect bow form) and is covered by multiple massive gates.


    Did the people from Westeros cut the tunnel into the ice? It would've certainly taken years to do this.


    And if yes, what motivation could they possibly have? They probably knew before the wall came up that the north was dangerous. Why would they undertake such an effort to open a passage to this risky area?


    Apart from just being not of any worth to them, it also leaves a gaping hole in the otherwise perfect defensive structure that the Wall poses.


    Considering the risk they would certainly be better off to close the tunnel than to have a passage open and constantly send patrols out there. And even if they needed to go north of the Wall, they could simply let themselves from above, couldn't they?




    So is the tunnel man-made and with what motivation, or is it simply a story device?


    the wall


    Answer


    I have not yet gotten the chance to watch the series on TV but I have read the books and without any spoilers from beyond the first book here is the purpose for the tunnel in the wall.


    First of all the wall is over 900 ft high that has been built by both man and some magical help. IIRC the tunnel was cut into the wall to create that path to the other side specifically so that they could chop back the forest growth. By chopping back the forest they create a lane of perfect sight to see when someone is attempting to climb the Wall and attack Westeros.


    As for climbing down from the top of the wall to the northern side was not something they wished to do as it prevents a speedy return trip.


    Wednesday, November 28, 2018

    How to overload functions in javascript?

    There are multiple aspects to argument overloading in Javascript:



    1. Variable arguments - You can pass different sets of arguments (in both type and quantity) and the function will behave in a way that matches the arguments passed to it.


    2. Default arguments - You can define a default value for an argument if it is not passed.


    3. Named arguments - Argument order becomes irrelevant and you just name which arguments you want to pass to the function.



    Below is a section on each of these categories of argument handling.


    Variable Arguments


    Because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of myFunc() that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments.


    jQuery does this all the time. You can make some of the arguments optional or you can branch in your function depending upon what arguments are passed to it.


    In implementing these types of overloads, you have several different techniques you can use:



    1. You can check for the presence of any given argument by checking to see if the declared argument name value is undefined.

    2. You can check the total quantity or arguments with arguments.length.

    3. You can check the type of any given argument.

    4. For variable numbers of arguments, you can use the arguments pseudo-array to access any given argument with arguments[i].


    Here are some examples:


    Let's look at jQuery's obj.data() method. It supports four different forms of usage:


    obj.data("key");
    obj.data("key", value);
    obj.data();
    obj.data(object);

    Each one triggers a different behavior and, without using this dynamic form of overloading, would require four separate functions.


    Here's how one can discern between all these options in English and then I'll combine them all in code:


    // get the data element associated with a particular key value
    obj.data("key");

    If the first argument passed to .data() is a string and the second argument is undefined, then the caller must be using this form.




    // set the value associated with a particular key
    obj.data("key", value);

    If the second argument is not undefined, then set the value of a particular key.




    // get all keys/values
    obj.data();

    If no arguments are passed, then return all keys/values in a returned object.




    // set all keys/values from the passed in object
    obj.data(object);

    If the type of the first argument is a plain object, then set all keys/values from that object.




    Here's how you could combine all of those in one set of javascript logic:


     // method declaration for .data()
    data: function(key, value) {
    if (arguments.length === 0) {
    // .data()
    // no args passed, return all keys/values in an object
    } else if (typeof key === "string") {
    // first arg is a string, look at type of second arg
    if (typeof value !== "undefined") {
    // .data("key", value)
    // set the value for a particular key
    } else {
    // .data("key")
    // retrieve a value for a key
    }
    } else if (typeof key === "object") {
    // .data(object)
    // set all key/value pairs from this object
    } else {
    // unsupported arguments passed
    }
    },



    The key to this technique is to make sure that all forms of arguments you want to accept are uniquely identifiable and there is never any confusion about which form the caller is using. This generally requires ordering the arguments appropriately and making sure that there is enough uniqueness in the type and position of the arguments that you can always tell which form is being used.


    For example, if you have a function that takes three string arguments:


    obj.query("firstArg", "secondArg", "thirdArg");

    You can easily make the third argument optional and you can easily detect that condition, but you cannot make only the second argument optional because you can't tell which of these the caller means to be passing because there is no way to identify if the second argument is meant to be the second argument or the second argument was omitted so what's in the second argument's spot is actually the third argument:


    obj.query("firstArg", "secondArg");
    obj.query("firstArg", "thirdArg");

    Since all three arguments are the same type, you can't tell the difference between different arguments so you don't know what the caller intended. With this calling style, only the third argument can be optional. If you wanted to omit the second argument, it would have to be passed as null (or some other detectable value) instead and your code would detect that:


    obj.query("firstArg", null, "thirdArg");



    Here's a jQuery example of optional arguments. both arguments are optional and take on default values if not passed:


    clone: function( dataAndEvents, deepDataAndEvents ) {
    dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
    deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
    return this.map( function () {
    return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
    });
    },

    Here's a jQuery example where the argument can be missing or any one of three different types which gives you four different overloads:


    html: function( value ) {
    if ( value === undefined ) {
    return this[0] && this[0].nodeType === 1 ?
    this[0].innerHTML.replace(rinlinejQuery, "") :
    null;
    // See if we can take a shortcut and just use innerHTML
    } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
    (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
    !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
    value = value.replace(rxhtmlTag, "<$1>");
    try {
    for ( var i = 0, l = this.length; i < l; i++ ) {
    // Remove element nodes and prevent memory leaks
    if ( this[i].nodeType === 1 ) {
    jQuery.cleanData( this[i].getElementsByTagName("*") );
    this[i].innerHTML = value;
    }
    }
    // If using innerHTML throws an exception, use the fallback method
    } catch(e) {
    this.empty().append( value );
    }
    } else if ( jQuery.isFunction( value ) ) {
    this.each(function(i){
    var self = jQuery( this );
    self.html( value.call(this, i, self.html()) );
    });
    } else {
    this.empty().append( value );
    }
    return this;
    },



    Named Arguments


    Other languages (like Python) allow one to pass named arguments as a means of passing only some arguments and making the arguments independent of the order they are passed in. Javascript does not directly support the feature of named arguments. A design pattern that is commonly used in its place is to pass a map of properties/values. This can be done by passing an object with properties and values or in ES6 and above, you could actually pass a Map object itself.


    Here's a simple ES5 example:


    jQuery's $.ajax() accepts a form of usage where you just pass it a single parameter which is a regular Javascript object with properties and values. Which properties you pass it determine which arguments/options are being passed to the ajax call. Some may be required, many are optional. Since they are properties on an object, there is no specific order. In fact, there are more than 30 different properties that can be passed on that object, only one (the url) is required.


    Here's an example:


    $.ajax({url: "http://www.example.com/somepath", data: myArgs, dataType: "json"}).then(function(result) {
    // process result here
    });

    Inside of the $.ajax() implementation, it can then just interrogate which properties were passed on the incoming object and use those as named arguments. This can be done either with for (prop in obj) or by getting all the properties into an array with Object.keys(obj) and then iterating that array.


    This technique is used very commonly in Javascript when there are large numbers of arguments and/or many arguments are optional. Note: this puts an onus on the implementating function to make sure that a minimal valid set of arguments is present and to give the caller some debug feedback what is missing if insufficient arguments are passed (probably by throwing an exception with a helpful error message).


    In an ES6 environment, it is possible to use destructuring to create default properties/values for the above passed object. This is discussed in more detail in this reference article.


    Here's one example from that article:


    function selectEntries({ start=0, end=-1, step=1 } = {}) {
    ···
    };

    This creates default properties and values for the start, end and step properties on an object passed to the selectEntries() function.


    Default values for function arguments


    In ES6, Javascript adds built-in language support for default values for arguments.


    For example:


    function multiply(a, b = 1) {
    return a*b;
    }
    multiply(5); // 5

    Further description of the ways this can be used here on MDN.

    PHP variable does not update inside of the Javascript while loop

    I'm very new to web programming so I will try to explain my issue here! So basically I tried to get all the data from my query in PHP and push everything into an array in Javascript. The code below works for the first iteration, but it seems like after the first one, the rest just gets duplicated (it seems like the $i variable does not update?)
    Can someone explain to me why is that and how should I fix it? Thanks!




    ...
    $result = mysqli_query($con, $query);
    $num_rows = mysqli_num_rows($result);
    $i = 0;
    $history_array = array();

    if($num_rows > 0){
    while($row = mysqli_fetch_array($result)){
    array_push($history_array, $row);
    }
    }
    ?>


    sockets - Android Client Error - java.lang.IllegalStateException: Could not execute method of the activity



    I'm building a simple client-server system. I've built a Java server & an android client which runs on mine device (both connected to the same LAN).



    When I'm just trying to setup a connection (by clicking a button) the client fails with the error




    -"java.lang.IllegalStateException: Could not execute method of the activity"


    In other answers to close problem was said that it might be connected to AsyncTask, but I'm not sure.



    server code:



        import java.io.IOException;
    import java.net.ServerSocket;

    import java.net.Socket;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;

    public class Server {
    public static void startConnection(int portNum)
    {
    ServerSocket serverSocket=null;
    Socket clinetSocket=null;
    ObjectOutputStream serverOut=null;

    ObjectInputStream serverIn=null;
    String message=null;

    //create a socket
    try{
    serverSocket=new ServerSocket(portNum);
    }
    catch (IOException e) {
    e.printStackTrace();
    }

    System.out.println("Waiting for connection...");
    try{
    clinetSocket = serverSocket.accept();
    }
    catch (IOException e){
    e.printStackTrace();
    }

    System.out.println("connected to "+ clinetSocket.getInetAddress().getHostName());


    }


    Android client code :



        Main.java :

    package com.example.user_pc.myapplication;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;

    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import java.net.Socket;
    import java.io.IOException;
    import java.net.UnknownHostException;
    import java.net.SocketException;
    import android.util.Log;

    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;

    public class Main extends ActionBarActivity {

    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    text= (TextView) findViewById(R.id.textView1);
    text.setText("");
    }

    public void pushTheButton(View v)
    {
    Button button = (Button) findViewById(R.id.button);
    createSocket();

    }
    public void createSocket()
    {
    Socket sock = null;
    String dstIP = "192.168.2.103";//server ip
    int dstPort = 9632;


    try
    {

    sock = new Socket(dstIP, dstPort);
    }

    catch(SocketException ie)
    {
    Log.wtf("SocketException",ie);
    }

    catch(UnknownHostException ie)
    {

    Log.wtf("UnknownHostException",ie);
    }
    catch(IOException ie)
    {
    Log.wtf("IOException",ie);
    }

    }

    public static void main(String[] args)

    {
    int portNum=9632;
    startConnection(portNum);
    }

    ``}


    manifest.xml:





    package="com.example.user_pc.myapplication" >




    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"

    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    android:name=".Main"
    android:label="@string/app_name" >












    layout file:



        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Main"
    android:onClick="pushTheButton">

    android:layout_width="300dp"
    android:layout_height="100dp"
    android:text="Click to connect"

    android:id="@+id/button"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginTop="96dp"
    android:onClick="pushTheButton"
    />





    • Logcat



      01-19 16:28:02.425 10779-10779/com.example.user_pc.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
      java.lang.IllegalStateException: Could not execute method of the activity
      at android.view.View$1.onClick(View.java:3599)
      at android.view.View.performClick(View.java:4204)
      at android.view.View$PerformClick.run(View.java:17355)
      at android.os.Handler.handleCallback(Handler.java:725)
      at android.os.Handler.dispatchMessage(Handler.java:92)
      at android.os.Looper.loop(Looper.java:137)

      at android.app.ActivityThread.main(ActivityThread.java:5226)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:511)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
      at dalvik.system.NativeStart.main(Native Method)
      Caused by: java.lang.reflect.InvocationTargetException
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:511)
      at android.view.View$1.onClick(View.java:3594)

                  at android.view.View.performClick(View.java:4204)
                  at android.view.View$PerformClick.run(View.java:17355)
                  at android.os.Handler.handleCallback(Handler.java:725)
                  at android.os.Handler.dispatchMessage(Handler.java:92)
                  at android.os.Looper.loop(Looper.java:137)
                  at android.app.ActivityThread.main(ActivityThread.java:5226)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)

                  at dalvik.system.NativeStart.main(Native Method)
      Caused by: android.os.NetworkOnMainThreadException
      at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
      at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
      at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
      at libcore.io.IoBridge.connect(IoBridge.java:112)
      at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
      at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
      at java.net.Socket.startupSocket(Socket.java:566)
      at java.net.Socket.tryAllAddresses(Socket.java:127)

      at java.net.Socket.(Socket.java:177)
      at java.net.Socket.(Socket.java:149)
      at com.example.user_pc.myapplication.Main.createSocket(Main.java:50)
      at com.example.user_pc.myapplication.Main.pushTheButton(Main.java:35)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at android.view.View$1.onClick(View.java:3594)
                  at android.view.View.performClick(View.java:4204)
                  at android.view.View$PerformClick.run(View.java:17355)
                  at android.os.Handler.handleCallback(Handler.java:725)

                  at android.os.Handler.dispatchMessage(Handler.java:92)
                  at android.os.Looper.loop(Looper.java:137)
                  at android.app.ActivityThread.main(ActivityThread.java:5226)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
                  at dalvik.system.NativeStart.main(Native Method)



    Answer




    Exactly as I said. You are getting a NetworkOnMainThreadException. You need to do network I/O in a background thread. Your createSocket() method must start a new background thread to do this work. Or use an AsyncTask.


    Remove a Single Object from a Javascript Object




    How do I remove one item based on both the courseID and endDate from the following javascript object?



        window.MyCheckedCourses = [
    { courseID: '123', endDate: '6/7/2010' },
    { courseID: '123', endDate: '3/9/2003' },
    { courseID: '456', endDate: '3/9/2003' }
    ];


    Answer



    Iteration is a must. You have to use .splice() to remove corresponding item and break the for loop.



    var i, id = '123', date = '6/7/2010';
    for(var i = 0, il = MyCheckedCourses.length;i if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
    MyCheckedCourses.splice(i, 1);
    break;
    }

    }


    You can make a function and use it with parameters like this;



    function remove(id, date) {
    for(var i = 0, il = MyCheckedCourses.length;i if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
    MyCheckedCourses.splice(i, 1);
    break;

    }
    }
    }
    // Example usage:
    remove('123', '6/7/2010');


    Edit after Ian's comment:



    I assume that your collection have unique items. If not you have to iterate through all items and you have to do it backwards because if you remove an element from array it's index will change and iteration will not work correctly. So this function is a much more safer version;




    function remove(id, date) {
    for(var i = MyCheckedCourses.length - 1;i >= 0;i--) {
    if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
    MyCheckedCourses.splice(i, 1);
    }
    }
    }
    // Example usage:
    remove('123', '6/7/2010');


    javascript - React + Flux: Getting initial state into a store



    We have recently switched over to React + Flux from Angular to build a rather complex business application.




    Taking the approach of having one container component that passes all state as properties down the component tree isn't a practical way to develop the app for us as the app makes use of large page-like modals. Enough state does get passed down to the modals for them to load their data into their stores.



    The problem I have is I need to get some initial state (passed down as props) into the modal component's store. In this post the good guys over at Facebook say it's ok to use props for initial state when synchronization is not the goal.



    This is how I get the initial state into my store currently:



    var ABC = React.createClass({
    ...
    getInitialState: function() {

    return ABCStore.getInitialABCState(this.props.initialA);
    },
    ...

    var ABCStore = Reflux.createStore({
    ...
    init: function() {
    _state = {
    a: null,
    b: 'B init',

    c: 'C init'
    };
    },

    getInitialABCState: function(initialA) {
    _state.a = initialA;
    return _state;
    },

    getABCState: function() {

    return _state;
    }
    ...


    I am unsure what the best practice is to do this, or whether this is a Flux anti-pattern?


    Answer



    It feels wrong to me that you are using getInitialState() to change the state of your store. You should at least be doing that in componentWillMount.



    I would trigger an action in componentWillMount and have the store handler update the internal state of the store (this should always be the case in flux). Then your component's change handler for the store can consume whatever data that you are currently calling your "initial state"



    Checking if a key exists in a JavaScript object?



    How do I check if a particular key exists in a JavaScript object or array?




    If a key doesn't exist, and I try to access it, will it return false? Or throw an error?


    Answer



    Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?



    var obj = { key: undefined };
    obj["key"] !== undefined // false, but the key exists!


    You should instead use the in operator:




    "key" in obj // true, regardless of the actual value


    If you want to check if a key doesn't exist, remember to use parenthesis:



    !("key" in obj) // true if "key" doesn't exist in object
    !"key" in obj // ERROR! Equivalent to "false in obj"


    Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:




    obj.hasOwnProperty("key") // true


    For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark


    java - How can I pad an integer with zeros on the left?




    How do you left pad an int with zeros when converting to a String in java?



    I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).


    Answer



    Use java.lang.String.format(String,Object...) like this:



    String.format("%05d", yournumber);


    for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".




    The full formatting options are documented as part of java.util.Formatter.


    c - Skip variable declaration using goto?



    I am reading C Programming - A Modern Approach by K.N.King to learn the C programming language and it was noted that goto statements must not skip variable-length array declarations.



    But now the question is: Why are goto jumps allowed to skip fixed-length array declarations and ordinary declarations? And more precisely, what is the behavior of examples like these, according to the C99 standard? When I tested these cases it seemed like the declarations were actually not jumped over, but is that correct? Are the variables whose declarations might have been jumped over safe to use?



    1.




    goto later;
    int a = 4;
    later:
    printf("%d", a);


    2.



    goto later;

    int a;
    later:
    a = 4;
    printf("%d", a);


    3.



    goto later;
    int a[4];

    a[0] = 1;
    later:
    a[1] = 2;
    for(int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
    printf("%d\n", a[i]);

    Answer



    I'm in the mood for explaining this without gory memory-layout details (believe me, they get very gory when VLAs are used; see @Ulfalizer's answer for details).



    So, originally, in C89, it was mandatory to declare all variables at the start of a block, like this:




    {
    int a = 1;
    a++;
    /* ... */
    }


    This directly implies a very important thing: one block == one unchanging set of variable declarations.




    C99 changed this. In it, you can declare variables in any part of the block, but declaration statements are still different from regular statements.



    In fact, to understand this, you can imagine that all variable declarations are implicitly moved to the start of the block where they are declared and made unavailable for all statements that preceed them.



    That is simply because the one block == one set of declarations rule still holds.



    That is why you cannot "jump over a declaration". The declared variable would still exist.



    The problem is initialization. It doesn't get "moved" anywhere. So, technically, for your case, the following programs could be considered equivalent:




    goto later;
    int a = 100;
    later:
    printf("%d", a);


    and



    int a;
    goto later;

    a = 100;
    later:
    printf("%d", a);


    As you can see, the declaration is still there, what is being skipped is initialization.



    The reason this doesn't work with VLAs is that they're different. In short, it's because this is valid:



    int size = 7;

    int test[size];


    The declarations of VLAs will, unlike all other declarations, behave differently in different parts of the block where they are declared. In fact, a VLA might have entirely different memory layouts depending on where it is declared. You just can't "move" it outside of the place you just jumped over.



    You may ask, "all right, then why not make it so that the declaration would be unaffected by the goto"? Well, you'd still get cases like this:



    goto later;
    int size = 7;
    int test[size];

    later:


    What do you actually expect this to do?..



    So, prohibiting jumping over VLA declarations is there for a reason - it is the most logical decision for dealing with cases like the above by simply prohibiting them altogether.


    c++ - What does "vtable for *Class*" error means?




    Moments ago i was coding some stuff... Everything went smoothly until the compiler gave me this error:



    C:\Users\presgiovanni\workspace\verbaleesami\Debug/../persona.h:24: riferimento non definito a "vtable for Persona"
    main.o: nella funzione "ZN7PersonaD2Ev":
    C:\Users\presgiovanni\workspace\verbaleesami\Debug/../persona.h:25: riferimento non definito a "vtable for Persona"
    collect2.exe: error: ld returned 1 exit status


    (I'm sorry, but it's in italian, you know... It says "undefined reference to vtable for Persona")



    This is the code of the header file interested (the lines are indicated with ">>"):



    #ifndef PERSONA_H_
    #define PERSONA_H_


    #include
    using std::cout;
    using std::cin;
    using std::endl;
    using std::ostream;
    using std::istream;

    #include
    using std::string;

    class Persona{
    public:
    >> Persona(){;}
    >> virtual ~Persona() = default;
    virtual bool login(istream&);
    virtual ostream& print(ostream&);
    protected:
    string nome, cognome, nickname, password;
    };


    #endif /* PERSONA_H_ */


    Can someone explain me what happened (I'm working with Eclipse)? Thank you!


    Answer



    You failed to provide the definition of one of the member functions, specifically the one your compiler uses to chose the translation unit to store the vtable in.



    With gcc, that would be the first non-inline member function.



    Defining all member functions should solve the problem.


    java - ExecutorService workStealingPool and cancel method



    Can you think about any reason why this code doesn't work and always outputs "finished", but the second example works without any problems. I'm using latest JDK (8u45).




    public static class MyClass implements Runnable {

    @Override

    public void run() {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException ex) {
    System.out.println("Interrupted");
    return;
    }
    System.out.println("Finished");
    }


    public static void main(String[] args) {
    // spot the difference ->
    ExecutorService executorService = Executors.newWorkStealingPool(4);
    Future future = executorService.submit(new MyClass());
    Thread.sleep(100);
    future.cancel(true);
    }
    }



    And the following example works flawlessly:




    public static class MyClass implements Runnable {

    @Override
    public void run() {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException ex) {

    System.out.println("Interrupted");
    return;
    }
    System.out.println("Finished");
    }

    public static void main(String[] args) {
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future future = executorService.submit(new MyClass());
    Thread.sleep(100);

    future.cancel(true);
    }
    }


    EDIT: Added return and updated sleep times and another example.


    Answer



    It's simpler than I thought originally. The problem is that work-stealing-pool is internally using ForkJoinPool and ForkJoinTask doesn't support cancel(true) and therefore it's not possible to cancel task after the task is started.



    See javadoc documentation (http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html):




       mayInterruptIfRunning - this value has no effect in the default implementation 
    because interrupts are not used to control cancellation.

    plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

    In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...