text:
Q: what is the best way to parse big JSON file and insert into database using php? I have this huge JSON file.  Currently the way I am using it is:

*

*Read the entire contents into a string

*Do json_decode, get the array

*Loop through the array one record at a time and build my SQL insert statement

Problem is, the code is ugly.  Also, some of the objects in these arrays are themselves arrays, and not all records contain all values.  I have to use isset to check if a particular value is present, or use a default value etc.  Overall, it works correctly, but the code is ugly.  Is there any way I can write this better?

A: Hard to advice without looking at the code, but I'd like to remind you about the PHP + operator for arrays, which merges two arrays non-destructively.
$default_values = array('Name' => '', 'Email' => '', 'Meta' => '');
$data = array('Name' => 'John'); // Only name set
$fixed_data = $data + $default_values;

$fixed_data now looks like array('Name' => 'John', 'Email' => '', 'Meta' => ''); without a need for multiple isset() checks. (Might not be applicable to your case, hard to say without more info.)

A: If you dont want to write ugly code to generate sql queries consider using an ORM
Propel and doctrine are the ones i have personally used.
doctrine has a method to generate an object from an array and then simply call a save method on it.
have a look at this
http://www.doctrine-project.org/documentation/manual/1_0/en/working-with-models:arrays-and-objects:from-array

A: Beauty is in the eye of the beholder.
If the format of the JSON is beyond your control then there's not much you can do except shuffle the pieces around the board. Do the usual thing of making your functions as small and neat as possible instead of having one large block of code. Multiple function will be easier to read and more reusable.
I tend to call this process functional decomposition.
Of course you can also take an OO approach and build up some nice objects that save themselves to the database and build themselves from pieces of the JSON object but this is basically the same thing (except it makes OO purists sleep better at night).

A: Most databases (MySQL, sqlite etc.) prefer to work with the XML data format to import/export data.
You could convert your JSON object into XML, and then work with that.
I'm not surprised to see databases supporting JSON in the near future, but for now this is probably the best thing to do.

A: If you use a beautiful database abstraction like ADODb, then you will net need to build the insert query anymore.
This is the example of insert using ADODb:
$data['col1'] = 'value1';
$data['col2'] = 'value2';
$data['col3'] = 'value3';

$result = $adodb->AutoExecute($tablename, $data, 'INSERT');

Since the result of json_encode already an array, it fit perfectly. If the column definition in the database allow null, then the a missing column in $data will still be a valid insert.


text:
Q: Filter SQL with button I'm making a website that lets you submit information into a form and view it on a separate page. On that page, I want the user to be able to filter the data by language.
A button with a dropdown menu selects a language:
    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">
      Select a language
    </button>

Arabic

      ...
      ...

Spanish

This is the jQuery I have to do this:
          $(".selectlang").click( function() {
            var language = $(this).data('language'); //this gets the selected language from the dropdown. I want to use this var in the PHP to complete the query "SELECT * FROM slangdata WHERE language = ?"

            $.ajax({
              url:  "test.php",
              type: "post",
              data: language,
              success: function() {
                $("#fill").load("test.php");
              }
            });
          });

On the PHP side (test.php), I really have no idea where to start. I found this page that I think might be helpful (PHP: Filtering SQL query with select options) but I don't know how to begin to implement it.
This is what I have written so far — it's copied from another example which uses a function to sanitize the PHP and originally had a table, so I tried to convert it to work with my code but I really have no idea what I'm doing so it's just a mess.
<?php include 'database.php'; ?>

<?php
function sanitizeMySQL($conn, $var) {
    $var = strip_tags($var);
    $var = mysqli_real_escape_string($conn, $var);
    return $var;
}
if ( isset($_POST['language']) ) {
?>

<?php
    $language = sanitizeMySQL($conn, $_POST['language']);
    $query = "SELECT * FROM slangdata WHERE language = ?";
    // code runs only if the statement was prepared
    if ($stmt = mysqli_prepare($conn, $query)) {
        mysqli_stmt_bind_param($stmt, 's', $language);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $id, $language, $word, $pronunciation, $translation, $notes, $example, $nsfw);
        // handle the data we fetched with the SELECT statement ...
        while (mysqli_stmt_fetch($stmt)) {

                printf ("
", $nsfw);
                printf ("
%s", stripslashes($word));
                printf (" %s
", stripslashes($pronunciation));
                printf ("
%s
", stripslashes($translation));
                printf ("
%s
", stripslashes($notes));
                printf ("
%s
", stripslashes($example));
                printf ("

", $nsfw);
        } // end while-loop

        mysqli_stmt_close($stmt);
    }
    mysqli_close($conn);
} else {
?>

Error

<?php
}  // end of if-else isset
?>

(Alternatively, I have this code, which I think could replace the while loop I already have — not sure which is better):
        <?php while( $row = mysqli_fetch_assoc($run)) :  ?>

        <div class="<?php echo stripslashes($row['nsfw']); ?> entry <?php echo stripslashes($row['language']); ?>">

<?php echo stripslashes($row['word']); ?>  <?php echo stripslashes($row['pronunciation']); ?>

<?php echo stripslashes($row['translation']); ?>

<?php echo stripslashes($row['notes']); ?>

<?php echo stripslashes($row['example']); ?>

          <p class="<?php echo stripslashes($row['nsfw']); ?>">

         <?php endwhile;  ?>

Right now, when I pick a language it just comes back with error. I'm so sorry this is a really long post but I've been stuck on this for two days and really have no idea what to do. How can I write the PHP to make it do what I want?
Edit: deleted comments

A: On client side you can use like this

<select id="combo">
  <option value="english">English</option>
  <option value="arabic">Arabic</option>
</select>
<input id="button1" type="button" value="Click Me!" />

and jquery as like this
$(document).ready(function(){
  $('#button1').click(function(){
    $.post("somepage.php",
    {
        language: $('#combo :selected').text(),
    },
    function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });

  });
});

and in Server Side Code you can use this
<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $language = $_POST['language'];
    $sql = "SELECT * FROM slangdata WHERE language = '$language'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row or whatever you want to do
    }
?>

A: in your ajax, set language like this: data: { language: language } because the $_POST var need the key language.
in your test.php, just echo the content regarding the language and set it in your success function:
success: function(response) {
    $("#fill").html(response);
}

hope this helps (:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to disable Quick Find in Visual Studio 2012? I just upgraded to Visual Studio 2012 from 2010 and cannot stand the fact that Cntrl + F brings up the new Quick Find dialog in the upper right hand corner of the editor. I typically just dock the Find and Replace window and prefer to use that. Is there a way to disable Cntrl + F from bringing up the new Quick Find window and instead have it move focus to the Find and Replace window similar to how VS 2010 did it?

A: Instead of modifying the default keyboard shortcuts consider using
Ctrl+Shift+F for "Find in files"
Ctrl+Shift+H for "Replace in files"
Sometimes it's not always possible/advisable to change the default shortcuts. Like when working on another persons computer.

A: Yes there is. You can assign the keyboard shortcut ctrl+f to edit.findinfiles in tools>options>environment>keyboard. So far it works for me.


text:
Q: Attaching a debugger sometimes causes the app to crash I'm developing an Android application, and sometimes when attaching a debugger to the running app, after a while it causes it to crash. The stacktrace is below.  I should mention that I'm running the N preview in the phone.
A/art: art/runtime/runtime.cc:403] Runtime aborting...
A/art: art/runtime/runtime.cc:403] Aborting thread:
A/art: art/runtime/runtime.cc:403] "Jit thread pool worker thread 0" prio=5 tid=2 WaitingForDebuggerSend (still starting up)
A/art: art/runtime/runtime.cc:403]   | group="" sCount=0 dsCount=0 obj=0x0 self=0x6fc6479a00
A/art: art/runtime/runtime.cc:403]   | sysTid=18309 nice=9 cgrp=default sched=0/0 handle=0x6fcd607450
A/art: art/runtime/runtime.cc:403]   | state=R schedstat=( 4712207454 2665438173 3474 ) utm=390 stm=80 core=5 HZ=100
A/art: art/runtime/runtime.cc:403]   | stack=0x6fcd509000-0x6fcd50b000 stackSize=1021KB
A/art: art/runtime/runtime.cc:403]   | held mutexes= "abort lock"
A/art: art/runtime/runtime.cc:403]   native: #00 pc 0000000000479ebc  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+220)
A/art: art/runtime/runtime.cc:403]   native: #01 pc 0000000000479eb8  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+216)
A/art: art/runtime/runtime.cc:403]   native: #02 pc 000000000044e260  /system/lib64/libart.so (_ZNK3art6Thread9DumpStackERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEbP12BacktraceMap+480)
A/art: art/runtime/runtime.cc:403]   native: #03 pc 000000000043c33c  /system/lib64/libart.so (_ZNK3art10AbortState10DumpThreadERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEPNS_6ThreadE+56)
A/art: art/runtime/runtime.cc:403]   native: #04 pc 000000000043c1b8  /system/lib64/libart.so (_ZNK3art10AbortState4DumpERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEE+668)
A/art: art/runtime/runtime.cc:403]   native: #05 pc 000000000042fd34  /system/lib64/libart.so (_ZN3art7Runtime5AbortEv+144)
A/art: art/runtime/runtime.cc:403]   native: #06 pc 00000000000e4d78  /system/lib64/libart.so (_ZN3art10LogMessageD2Ev+1208)
A/art: art/runtime/runtime.cc:403]   native: #07 pc 00000000002f5f48  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState19SetWaitForJdwpTokenEm+1000)
A/art: art/runtime/runtime.cc:403]   native: #08 pc 00000000002f5468  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState24AcquireJdwpTokenForEventEm+124)
A/art: art/runtime/runtime.cc:403]   native: #09 pc 00000000002f4d20  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState29SendRequestAndPossiblySuspendEPNS0_9ExpandBufENS0_17JdwpSuspendPolicyEm+248)
A/art: art/runtime/runtime.cc:403]   native: #10 pc 00000000002f9d0c  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState16PostClassPrepareEPNS_6mirror5ClassE+1380)
A/art: art/runtime/runtime.cc:403]   native: #11 pc 0000000000123ba4  /system/lib64/libart.so (_ZN3art11ClassLinker11DefineClassEPNS_6ThreadEPKcmNS_6HandleINS_6mirror11ClassLoaderEEERKNS_7DexFileERKNS9_8ClassDefE+804)
A/art: art/runtime/runtime.cc:403]   native: #12 pc 00000000001236e4  /system/lib64/libart.so (_ZN3art11ClassLinker26FindClassInPathClassLoaderERNS_33ScopedObjectAccessAlreadyRunnableEPNS_6ThreadEPKcmNS_6HandleINS_6mirror11ClassLoaderEEEPPNS8_5ClassE+1484)
A/art: art/runtime/runtime.cc:403]   native: #13 pc 0000000000124674  /system/lib64/libart.so (_ZN3art11ClassLinker9FindClassEPNS_6ThreadEPKcNS_6HandleINS_6mirror11ClassLoaderEEE+944)
A/art: art/runtime/runtime.cc:403]   native: #14 pc 000000000010bfb4  /system/lib64/libart.so (_ZN3art11ClassLinker11ResolveTypeERKNS_7DexFileEtNS_6HandleINS_6mirror8DexCacheEEENS4_INS5_11ClassLoaderEEE+200)
A/art: art/runtime/runtime.cc:403]   native: #15 pc 00000000001911ac  /system/lib64/libart-compiler.so (_ZNK3art19HInstructionBuilder25IsOutermostCompilingClassEt+732)
A/art: art/runtime/runtime.cc:403]   native: #16 pc 000000000019091c  /system/lib64/libart-compiler.so (_ZN3art19HInstructionBuilder16BuildNewInstanceEtj+852)
A/art: art/runtime/runtime.cc:403]   native: #17 pc 000000000018ab78  /system/lib64/libart-compiler.so (_ZN3art19HInstructionBuilder21ProcessDexInstructionERKNS_11InstructionEj+3436)
A/art: art/runtime/runtime.cc:403]   native: #18 pc 0000000000189640  /system/lib64/libart-compiler.so (_ZN3art19HInstructionBuilder5BuildEv+1600)
A/art: art/runtime/runtime.cc:403]   native: #19 pc 00000000001626b8  /system/lib64/libart-compiler.so (_ZN3art13HGraphBuilder10BuildGraphEv+136)
A/art: art/runtime/runtime.cc:403]   native: #20 pc 00000000001c1248  /system/lib64/libart-compiler.so (_ZNK3art18OptimizingCompiler10TryCompileEPNS_14ArenaAllocatorEPNS_19CodeVectorAllocatorEPKNS_7DexFile8CodeItemEjNS_10InvokeTypeEtjP8_jobjectRKS5_NS_6HandleINS_6mirror8DexCacheEEEPNS_9ArtMethodEb+3280)
A/art: art/runtime/runtime.cc:403]   native: #21 pc 00000000001c36e4  /system/lib64/libart-compiler.so (_ZN3art18OptimizingCompiler10JitCompileEPNS_6ThreadEPNS_3jit12JitCodeCacheEPNS_9ArtMethodEb+472)
A/art: art/runtime/runtime.cc:403]   native: #22 pc 0000000000151bb8  /system/lib64/libart-compiler.so (_ZN3art3jit11JitCompiler13CompileMethodEPNS_6ThreadEPNS_9ArtMethodEb+284)
A/art: art/runtime/runtime.cc:403]   native: #23 pc 000000000030d0b8  /system/lib64/libart.so (_ZN3art3jit3Jit13CompileMethodEPNS_9ArtMethodEPNS_6ThreadEb+492)
A/art: art/runtime/runtime.cc:403]   native: #24 pc 000000000030efa4  /system/lib64/libart.so (_ZN3art3jit14JitCompileTask3RunEPNS_6ThreadE+656)
A/art: art/runtime/runtime.cc:403]   native: #25 pc 0000000000466dd4  /system/lib64/libart.so (_ZN3art16ThreadPoolWorker3RunEv+88)
A/art: art/runtime/runtime.cc:403]   native: #26 pc 000000000046671c  /system/lib64/libart.so (_ZN3art16ThreadPoolWorker8CallbackEPv+116)
A/art: art/runtime/runtime.cc:403]   native: #27 pc 000000000006863c  /system/lib64/libc.so (_ZL15__pthread_startPv+208)
A/art: art/runtime/runtime.cc:403]   native: #28 pc 000000000001d9fc  /system/lib64/libc.so (__start_thread+16)
A/art: art/runtime/runtime.cc:403]   (no managed stack frames)
A/art: art/runtime/runtime.cc:403] Dumping all threads without appropriate locks held: thread list lock mutator lock
A/art: art/runtime/runtime.cc:403] All threads:
A/art: art/runtime/runtime.cc:403] DALVIK THREADS (58):
A/art: art/runtime/runtime.cc:403] "Jit thread pool worker thread 0" prio=5 tid=2 Runnable (still starting up)
A/art: art/runtime/runtime.cc:403]   | group="" sCount=0 dsCount=0 obj=0x0 self=0x6fc6479a00
A/art: art/runtime/runtime.cc:403]   | sysTid=18309 nice=9 cgrp=default sched=0/0 handle=0x6fcd607450
A/art: art/runtime/runtime.cc:403]   | state=R schedstat=( 4767956307 2679954840 3643 ) utm=393 stm=83 core=4 HZ=100
A/art: art/runtime/runtime.cc:403]   | stack=0x6fcd509000-0x6fcd50b000 stackSize=1021KB
A/art: art/runtime/runtime.cc:403]   | held mutexes= "abort lock" "mutator lock"(shared held)
A/art: art/runtime/runtime.cc:403]   native: #00 pc 0000000000479ebc  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+220)
A/art: art/runtime/runtime.cc:403]   native: #01 pc 0000000000479eb8  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+216)
A/art: art/runtime/runtime.cc:403]   native: #02 pc 000000000044e260  /system/lib64/libart.so (_ZNK3art6Thread9DumpStackERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEbP12BacktraceMap+480)
A/art: art/runtime/runtime.cc:403]   native: #03 pc 0000000000465ba8  /system/lib64/libart.so (_ZN3art14DumpCheckpoint3RunEPNS_6ThreadE+832)
A/art: art/runtime/runtime.cc:403]   native: #04 pc 000000000045dd90  /system/lib64/libart.so (_ZN3art10ThreadList13RunCheckpointEPNS_7ClosureE+476)
A/art: art/runtime/runtime.cc:403]   native: #05 pc 000000000045d98c  /system/lib64/libart.so (_ZN3art10ThreadList4DumpERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEb+288)
A/art: art/runtime/runtime.cc:403]   native: #06 pc 000000000043c16c  /system/lib64/libart.so (_ZNK3art10AbortState4DumpERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEE+592)
A/art: art/runtime/runtime.cc:403]   native: #07 pc 000000000042fd34  /system/lib64/libart.so (_ZN3art7Runtime5AbortEv+144)
A/art: art/runtime/runtime.cc:403]   native: #08 pc 00000000000e4d78  /system/lib64/libart.so (_ZN3art10LogMessageD2Ev+1208)
A/art: art/runtime/runtime.cc:403]   native: #09 pc 00000000002f5f48  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState19SetWaitForJdwpTokenEm+1000)
A/art: art/runtime/runtime.cc:403]   native: #10 pc 00000000002f5468  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState24AcquireJdwpTokenForEventEm+124)
A/art: art/runtime/runtime.cc:403]   native: #11 pc 00000000002f4d20  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState29SendRequestAndPossiblySuspendEPNS0_9ExpandBufENS0_17JdwpSuspendPolicyEm+248)
A/art: art/runtime/runtime.cc:403]   native: #12 pc 00000000002f9d0c  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState16PostClassPrepareEPNS_6mirror5ClassE+1380)
A/art: art/runtime/runtime.cc:403]   native: #13 pc 0000000000123ba4  /system/lib64/libart.so (_ZN3art11ClassLinker11DefineClassEPNS_6ThreadEPKcmNS_6HandleINS_6mirror11ClassLoaderEEERKNS_7DexFileERKNS9_8ClassDefE+804)
A/art: art/runtime/runtime.cc:403]   native: #14 pc 00000000001236e4  /system/lib64/libart.so (_ZN3art11ClassLinker26FindClassInPathClassLoaderERNS_33ScopedObjectAccessAlreadyRunnableEPNS_6ThreadEPKcmNS_6HandleINS_6mirror11ClassLoaderEEEPPNS8_5ClassE+1484)
A/art: art/runtime/runtime.cc:403]   native: #15 pc 0000000000124674  /system/lib64/libart.so (_ZN3art11ClassLinker9FindClassEPNS_6ThreadEPKcNS_6HandleINS_6mirror11ClassLoaderEEE+944)
A/art: art/runtime/runtime.cc:403]   native: #16 pc 000000000010bfb4  /system/lib64/libart.so (_ZN3art11ClassLinker11ResolveTypeERKNS_7DexFileEtNS_6HandleINS_6mirror8DexCacheEEENS4_INS5_11ClassLoaderEEE+200)
A/art: art/runtime/runtime.cc:403]   native: #17 pc 00000000001911ac  /system/lib64/libart-compiler.so (_ZNK3art19HInstructionBuilder25IsOutermostCompilingClassEt+732)
A/art: art/runtime/runtime.cc:403]   native: #18 pc 000000000019091c  /system/lib64/libart-compiler.so (_ZN3art19HInstructionBuilder16BuildNewInstanceEtj+852)
A/art: art/runtime/runtime.cc:403]   native: #19 pc 000000000018ab78  /system/lib64/libart-compiler.so (_ZN3art19HInstructionBuilder21ProcessDexInstructionERKNS_11InstructionEj+3436)
A/art: art/runtime/runtime.cc:403]   native: #20 pc 0000000000189640  /system/lib64/libart-compiler.so (_ZN3art19HInstructionBuilder5BuildEv+1600)
A/art: art/runtime/runtime.cc:403]   native: #21 pc 00000000001626b8  /system/lib64/libart-compiler.so (_ZN3art13HGraphBuilder10BuildGraphEv+136)
A/art: art/runtime/runtime.cc:403]   native: #22 pc 00000000001c1248  /system/lib64/libart-compiler.so (_ZNK3art18OptimizingCompiler10TryCompileEPNS_14ArenaAllocatorEPNS_19CodeVectorAllocatorEPKNS_7DexFile8CodeItemEjNS_10InvokeTypeEtjP8_jobjectRKS5_NS_6HandleINS_6mirror8DexCacheEEEPNS_9ArtMethodEb+3280)
A/art: art/runtime/runtime.cc:403]   native: #23 pc 00000000001c36e4  /system/lib64/libart-compiler.so (_ZN3art18OptimizingCompiler10JitCompileEPNS_6ThreadEPNS_3jit12JitCodeCacheEPNS_9ArtMethodEb+472)
A/art: art/runtime/runtime.cc:403]   native: #24 pc 0000000000151bb8  /system/lib64/libart-compiler.so (_ZN3art3jit11JitCompiler13CompileMethodEPNS_6ThreadEPNS_9ArtMethodEb+284)
A/art: art/runtime/runtime.cc:403]   native: #25 pc 000000000030d0b8  /system/lib64/libart.so (_ZN3art3jit3Jit13CompileMethodEPNS_9ArtMethodEPNS_6ThreadEb+492)
A/art: art/runtime/runtime.cc:403]   native: #26 pc 000000000030efa4  /system/lib64/libart.so (_ZN3art3jit14JitCompileTask3RunEPNS_6ThreadE+656)
A/art: art/runtime/runtime.cc:403]   native: #27 pc 0000000000466dd4  /system/lib64/libart.so (_ZN3art16ThreadPoolWorker3RunEv+88)
A/art: art/runtime/runtime.cc:403]   native: #28 pc 000000000046671c  /system/lib64/libart.so (_ZN3art16ThreadPoolWorker8CallbackEPv+116)
A/art: art/runtime/runtime.cc:403]   native: #29 pc 000000000006863c  /system/lib64/libc.so (_ZL15__pthread_startPv+208)
A/art: art/runtime/runtime.cc:403]   native: #30 pc 000000000001d9fc  /system/lib64/libc.so (__start_thread+16)
A/art: art/runtime/runtime.cc:403]   (no managed stack frames)
A/art: art/runtime/runtime.cc:403]
A/art: art/runtime/runtime.cc:403] "main" prio=5 tid=1 Runnable
A/art: art/runtime/runtime.cc:403]   | group="" sCount=0 dsCount=0 obj=0x75942ad0 self=0x6fce095a00
A/art: art/runtime/runtime.cc:403]   | sysTid=18304 nice=0 cgrp=default sched=0/0 handle=0x6fd1e50a98
A/art: art/runtime/runtime.cc:403]   | state=R schedstat=( 12856552776 1693023464 11377 ) utm=1167 stm=117 core=5 HZ=100
A/art: art/runtime/runtime.cc:403]   | stack=0x7fe807c000-0x7fe807e000 stackSize=8MB
A/art: art/runtime/runtime.cc:403]   | held mutexes= "mutator lock"(shared held)
A/art: art/runtime/runtime.cc:403]   native: #00 pc 0000000000479ebc  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+220)
A/art: art/runtime/runtime.cc:403]   native: #01 pc 0000000000479eb8  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+216)
A/art: art/runtime/runtime.cc:403]   native: #02 pc 000000000044e260  /system/lib64/libart.so (_ZNK3art6Thread9DumpStackERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEbP12BacktraceMap+480)
A/art: art/runtime/runtime.cc:403]   native: #03 pc 0000000000465ba8  /system/lib64/libart.so (_ZN3art14DumpCheckpoint3RunEPNS_6ThreadE+832)
A/art: art/runtime/runtime.cc:403]   native: #04 pc 000000000044f1c4  /system/lib64/libart.so (_ZN3art6Thread21RunCheckpointFunctionEv+192)
A/art: art/runtime/runtime.cc:403]   native: #05 pc 0000000000548f6c  /system/lib64/libart.so (artTestSuspendFromCode+24)
A/art: art/runtime/runtime.cc:403]   native: #06 pc 00000000000dacd4  /system/lib64/libart.so (art_quick_test_suspend+68)
A/art: art/runtime/runtime.cc:403]   native: #07 pc 000000000010a518  /dev/ashmem/dalvik-jit-code-cache (deleted) (Java_android_view_View_applyBackgroundTint__+360)
A/art: art/runtime/runtime.cc:403]   at android.view.View.applyBackgroundTint(View.java:18322)
A/art: art/runtime/runtime.cc:403]   at android.view.View.setBackgroundDrawable(View.java:18197)
A/art: art/runtime/runtime.cc:403]   at android.view.View.setBackground(View.java:18120)
A/art: art/runtime/runtime.cc:403]   at android.view.View.<init>(View.java:4572)
A/art: art/runtime/runtime.cc:403]   at android.view.ViewGroup.<init>(ViewGroup.java:578)
A/art: art/runtime/runtime.cc:403]   at android.widget.FrameLayout.<init>(FrameLayout.java:92)
A/art: art/runtime/runtime.cc:403]   at android.widget.HorizontalScrollView.<init>(HorizontalScrollView.java:159)
A/art: art/runtime/runtime.cc:403]   at android.widget.HorizontalScrollView.<init>(HorizontalScrollView.java:154)
A/art: art/runtime/runtime.cc:403]   at android.widget.HorizontalScrollView.<init>(HorizontalScrollView.java:150)
A/art: art/runtime/runtime.cc:403]   at com.kushtrimchatlibrary.widgets.MyHorizontalScrollView.<init>(MyHorizontalScrollView.java:16)
A/art: art/runtime/runtime.cc:403]   at java.lang.reflect.Constructor.newInstance0!(Native method)
A/art: art/runtime/runtime.cc:403]   at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
A/art: art/runtime/runtime.cc:403]   at android.view.LayoutInflater.createView(LayoutInflater.java:645)
A/art: art/runtime/runtime.cc:403]   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
A/art: art/runtime/runtime.cc:403]   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
A/art: art/runtime/runtime.cc:403]   at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
A/art: art/runtime/runtime.cc:403]   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
A/art: art/runtime/runtime.cc:403]   at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
A/art: art/runtime/runtime.cc:403]   - locked <0x0acf94a9> (a java.lang.Object[])
A/art: art/runtime/runtime.cc:403]   at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
A/art: art/runtime/runtime.cc:403]   at com.kushtrimchatlibrary.chat.GroupCallAdapter.getView(GroupCallAdapter.java:110)
A/art: art/runtime/runtime.cc:403]   at android.widget.AbsListView.obtainView(AbsListView.java:2360)
A/art: art/runtime/runtime.cc:403]   at android.widget.ListView.measureHeightOfChildren(ListView.java:1326)
A/art: art/runtime/runtime.cc:403]   at android.widget.ListView.onMeasure(ListView.java:1233)
A/art: art/runtime/runtime.cc:403]   at android.view.View.measure(View.java:19730)
A/art: art/runtime/runtime.cc:403]   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
A/art: art/runtime/runtime.cc:403]   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
A/art: art/runtime/runtime.cc:403]   at android.view.View.measure(View.java:19730)
A/art: art/runtime/runtime.cc:403]   at android.widget.LinearLayout.measureVertical(LinearLayout.java:911)
A/art: art/runtime/runtime.cc:403]   at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
A/art: art/runtime/runtime.cc:403]   at android.view.View.measure(View.java:19730)
A/art: art/runtime/runtime.cc:403]   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
A/art: art/runtime/runtime.cc:403]   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
A/art: art/runtime/runtime.cc:403]   at android.view.View.measure(View.java:19730)
A/art: art/runtime/runtime.cc:403]   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
A/art: art/runtime/runtime.cc:403]   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
A/art: art/runtime/runtime.cc:403]   at android.view.View.measure(View.java:19730)
A/art: art/runtime/runtime.cc:403]   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
A/art: art/runtime/runtime.cc:403]   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
A/art: art/runtime/runtime.cc:403]   at android.view.View.measure(View.java:19730)
A/art: art/runtime/runtime.cc:403]   at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
A/art: art/runtime/runtime.cc:403]   at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358)
A/art: art/runtime/runtime.cc:403]   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607)
A/art: art/runtime/runtime.cc:403]   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
A/art: art/runtime/runtime.cc:403]   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
A/art: art/runtime/runtime.cc:403]   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
A/art: art/runtime/runtime.cc:403]   at android.view.Choreographer.doCallbacks(Choreographer.java:683)
A/art: art/runtime/runtime.cc:403]   at android.view.Choreographer.doFrame(Choreographer.java:619)
A/art: art/runtime/runtime.cc:403]   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
A/art: art/runtime/runtime.cc:403]   at android.os.Handler.handleCallback(Handler.java:751)
A/art: art/runtime/runtime.cc:403]   at android.os.Handler.dispatchMessage(Handler.java:95)
A/art: art/runtime/runtime.cc:403]   at android.os.Looper.loop(Looper.java:154)
A/art: art/runtime/runtime.cc:403]   at android.app.ActivityThread.main(ActivityThread.java:6077)
A/art: art/runtime/runtime.cc:403]   at java.lang.reflect.Method.invoke!(Native method)
A/art: art/runtime/runtime.cc:403]   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
A/art: art/runtime/runtime.cc:403]   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
A/art: art/runtime/runtime.cc:403]
A/art: art/runtime/runtime.cc:403] "Signal Catcher" prio=5 tid=3 WaitingInMainSignalCatcherLoop
A/art: art/runtime/runtime.cc:403]   | group="" sCount=1 dsCount=0 obj=0x32c050d0 self=0x6fc3b98000
A/art: art/runtime/runtime.cc:403]   | sysTid=18310 nice=0 cgrp=default sched=0/0 handle=0x6fcd506450
A/art: art/runtime/runtime.cc:403]   | state=S schedstat=( 703021 55260 1 ) utm=0 stm=0 core=1 HZ=100
A/art: art/runtime/runtime.cc:403]   | stack=0x6fcd40c000-0x6fcd40e000 stackSize=1005KB
A/art: art/runtime/runtime.cc:403]   | held mutexes=
A/art: art/runtime/runtime.cc:403]   kernel: __switch_to+0x8c/0x98
A/art: art/runtime/runtime.cc:403]   kernel: do_sigtimedwait+0xec/0x1dc
A/art: art/runtime/runtime.cc:403]   kernel: SyS_rt_sigtimedwait+0xd8/0x134
A/art: art/runtime/runtime.cc:403]   kernel: cpu_switch_to+0x48/0x4c
A/art: art/runtime/runtime.cc:403]   native: #00 pc 000000000006ac54  /system/lib64/libc.so (__rt_sigtimedwait+8)
A/art: art/runtime/runtime.cc:403]   native: #01 pc 0000000000024cc8  /system/lib64/libc.so (sigwait+64)
A/art: art/runtime/runtime.cc:403]   native: #02 pc 000000000044093c  /system/lib64/libart.so (_ZN3art9SignalSet4WaitEv+48)
A/art: art/runtime/runtime.cc:403]   native: #03 pc 00000000004403f8  /system/lib64/libart.so (_ZN3art13SignalCatcher13WaitForSignalEPNS_6ThreadERNS_9SignalSetE+232)
A/art: art/runtime/runtime.cc:403]   native: #04 pc 000000000043e98c  /system/lib64/libart.so (_ZN3art13SignalCatcher3RunEPv+400)
A/art: art/runtime/runtime.cc:403]   native: #05 pc 000000000006863c  /system/lib64/libc.so (_ZL15__pthread_startPv+208)
A/art: art/runtime/runtime.cc:403]   native: #06 pc 000000000001d9fc  /system/lib64/libc.so (__start_thread+16)
A/art: art/runtime/runtime.cc:403]   (no managed stack frames)
A/art: art/runtime/runtime.cc:403]
A/art: art/runtime/runtime.cc:403] "JDWP" prio=5 tid=4 WaitingInMainDebuggerLoop
A/art: art/runtime/runtime.cc:403]   | group="" sCount=1 dsCount=0 obj=0x32c05160 self=0x6fc6427e00
A/art: art/runtime/runtime.cc:403]   | sysTid=18311 nice=0 cgrp=default sched=0/0 handle=0x6fcd409450
A/art: art/runtime/runtime.cc:403]   | state=S schedstat=( 2373415436 183850832 3241 ) utm=218 stm=18 core=4 HZ=100
A/art: art/runtime/runtime.cc:403]   | stack=0x6fcd30f000-0x6fcd311000 stackSize=1005KB
A/art: art/runtime/runtime.cc:403]   | held mutexes=
A/art: art/runtime/runtime.cc:403]   kernel: __switch_to+0x8c/0x98

..etc

A: So I was able to fix this on my project. I read here that it had something to do with breakpoints set on nested functions. For me to solve this issue, I had to go and view all my breakpoints (Shift + Command + F8), and remove all of the breakpoints I had set. I had a few disabled breakpoints, and I didn't bother to look and see where exactly the breakpoints where, but I removed all breakpoints (both enabled and disabled) and it fixed this problem. I don't know if this has anything to do with breakpoints on nested function. Others have said that by turning off instant run it solved the problem.
Hope this helps someone else!


text:
Q: PostgresSQL - analyzing cpe23Uri I got a table like this, columns are text.

cve
cpe23Uri

CVE-2019-0002
cpe:2.3:o:juniper:junos:15.1x53:d50:*:*:*:*:*:*

The fourth part(after the 3rd ":") is what I'm interested in - company name.
Is there a way that I can split/analyze the second column to find the top N companies with the most cve's?
I tried something with the "split_part" but I don't know how to do it for the whole table (second column).

A: split_part can indeed be used for this:
select cve,
       split_part(cpe23uri, ':', 4) as company_name
from the_table;

Online example


text:
Q: Boundendess of $f(x-y)/f(x)$ for $f(x)$ vanishing at $\infty$ Assume that $f(x)$ is a strictly positive, continuous and bounded function on $\mathbb R^d$ vanishing at infinity, and such that $f(x)\to 0$ as $|x|\to\infty$. Can we always tell that $f(x+y)/f(x)$ is bounded in $x$ when $|y|\leq 1$? If not, then what are the additional assumptions sufficient to tell that?

A: The answer in general is no. Consider $f(x)=e^{-x^2}$ on $\mathbb{R}$. Then
$$
\frac{f(x-1)}{f(x)}=e^{2x-1}
$$
is unbounded as $x\to\infty$. This happens because $f(x)$ decays at a very fast rate as $x\to\infty$.
A more complicated example is the following. Let $f\colon\mathbb{R}\to\mathbb{R}$ be such that $\lim_{|x|\to\infty}f(x)=0$ and $f(2\,k)=3^{-k}$, $f(2\,k+1)=2^{-k}$ for $k\in\mathbb{N}$. Then
$$
\frac{f(2\,k+1)}{f(2\,k)}=\Bigl(\frac32\Bigr)^k.
$$
A sufficient condition would be $f$ decreasing and
$$
|f(x)|\ge C\,e^{-c|x|}
$$
for some constants $C,c>0$.


text:
Q: How to stop a function before it finishes in jquery? I have a program where when you click a button, a series of 5 lights and sounds play on a loop (basically, certain cells in the tables background colour change in order). I have another button "cancel" which cancels it. However, when you click cancel, it still finishes the current loop its on. Ideally I want it to stop mid loop and reset everything to how it is at the start (or at the end).
Here is my javaScript..
$(document).ready(function() {

var note1 = new Audio("audio/1.wav");
var note2 = new Audio("audio/2.wav");
var note3 = new Audio("audio/3.wav");
var note4 = new Audio("audio/4.wav");
var note5 = new Audio("audio/5.wav");

var isPlaying = false;
var speed = 500;
var buttonPressed = false;

var interval;

$("#button1").click(function(){
    if (!buttonPressed) {
        noteLoop();
        clearInterval(interval);
        interval = setInterval(noteLoop, 5000);
        $("#button1").text("MAKING CONTACT");
    };

$("#button2").click(function() {
    clearInterval(interval);
    $("#button1").text("CLICK TO MAKE CONTACT");
    buttonPressed = false;
    $.finish();
})

});

var noteLoop = function() {
    if (!isPlaying){
        playNotes();
        };
    }

var playNotes = function() {
        setTimeout(play1, speed);
        setTimeout(play2, speed * 2);
        setTimeout(play3, speed * 3);
        setTimeout(play4, speed * 4.6);
        setTimeout(play5, speed * 6.2);
        setTimeout(function(){
            resetNotes();
            isPlaying = false;
        }, speed * 9);
};

var play1 = function() {
    isPlaying = true;
    $("table tr:nth-child(2) td:nth-child(2)").addClass("yellow");
    $("table tr:nth-child(2) td:nth-child(2)").hide();
    $("table tr:nth-child(2) td:nth-child(2)").fadeIn('fast');
    note1.play();
};

var play2 = function() {
    $("table tr:nth-child(2) td:nth-child(2)").removeClass("yellow");
    $("table tr:nth-child(3) td:nth-child(3)").addClass("green");
    $("table tr:nth-child(3) td:nth-child(3)").hide();
    $("table tr:nth-child(3) td:nth-child(3)").fadeIn('fast');
    note2.play();
};

var play3 = function() {
    $("table tr:nth-child(3) td:nth-child(3)").removeClass("green");
    $("table tr:nth-child(3) td:nth-child(1)").addClass("blue");
    $("table tr:nth-child(3) td:nth-child(1)").hide();
    $("table tr:nth-child(3) td:nth-child(1)").fadeIn('fast');
    note3.play();
};

var play4 = function() {
    $("table tr:nth-child(3) td:nth-child(1)").removeClass("blue");
    $("table tr:nth-child(1) td:nth-child(4)").addClass("white");
    $("table tr:nth-child(1) td:nth-child(4)").hide();
    $("table tr:nth-child(1) td:nth-child(4)").fadeIn('fast');
    note4.play();
};

var play5 = function() {
    $("table tr:nth-child(1) td:nth-child(4)").removeClass("white");
    $("table tr:nth-child(4) td:nth-child(2)").addClass("orange");
    $("table tr:nth-child(4) td:nth-child(2)").hide();
    $("table tr:nth-child(4) td:nth-child(2)").fadeIn('fast');
    note5.play();
};

var resetNotes = function() {
    $("table tr:nth-child(4) td:nth-child(2)").removeClass("orange");
};

});
I'm also aware that I may have gone about this thing entirely the wrong way and what I want to do might not even be possible. I also wanted it to get faster and faster every time it looped but I couldn't figure out any way to make that possible :(
Thanks for any help.

A: According to your code excerpt, you could add event listener named "timeupdate"  to an audio element and check inside its handler for any cancellation requested if so restart your loop again .. below is an excerpt code  "I did not test :( but it just simplifies the idea for you"
<html>
<body>
  <audio id="myAudio"></audio>
  <button id="button1">Start</button>
  <button id="button2">Cancel</button>

  <script>
    var myAudio = document.getElementById("myAudio");
    //keep your notes in array
    var audios = ["audio/1.wav", "audio/2.wav", ...];
    var isCancelled = false;
    var currentTrack = null;

    myAudio.addEventListener("timeupdate", function(){
        if(isCancelled){
            //reset here .. do your stuff here according to current track
            myAudio.pause();
        }
    });

    function noteLoop(){
        for (i = 0;i<audios.length; i++){
            currentTrack = audios[i];
            play(audios[i]);
        }
    }

    function play(track){
        if(track){
            //do your stuff here according to track
            $("table tr:nth-child(2) td:nth-child(2)").addClass("yellow");
            $("table tr:nth-child(2) td:nth-child(2)").hide();
            $("table tr:nth-child(2) td:nth-child(2)").fadeIn('fast');
            myAudio.play();
        }
    }

    $("#button1").click(function(){
        isCancelled = false;
        noteLoop();
        $("#button1").text("MAKING CONTACT");
    });

    $("#button2").click(function() {
        isCancelled = true;
    });

  </script>

</body>
</html>


text:
Q: Update 2 Columns in PIG I want to update to columns when a particular condition satisfies.
For example:
We will first load data
A = load 'students.txt' as (name:chararray, age:int, gpa:float);

Now,
B = foreach A generate name, (age==18?1:age) as age, gpa;

Here whenever my condition for age is satisfied at the same instant I want to update one more column say is_adult and set it's value to true and this column in created dynamically(As you observe is_adult column is not there in original schema).
Your help will be highly appreciated.

A: A = LOAD 'students.txt' AS (name:chararray, age:int, gpa:float);
B = FOREACH A GENERATE
    name,
    (age==18?1:age) AS age,
    (age>=18?'true':'false') AS adult,
    gpa ;

The adult column would be updated with true or false based on the value of age. This is a pretty standard way of doing this. The new schema/alias obtained in the FOREACH loop can have more (or less) number of columns than the original alias.


text:
Q: Install package without internet: error in install.packages: no such file or directory I'm trying to install the readr package in R on a laptop without internet connection using the install.packages("C:/Users/MVC/Desktop/readr-master.zip", repos=NULL) command, but I keep getting the same error:
error in install.packages : cannot open file 'C:/Program Files/R/R-3.3.0/library/file27f07de57168
/readr-master/R/POSIXct.R': No such file or directory

Anybody who know why this is or how I can install the package without an internet connection?

A: This package is available as tar.gz or .zip file from cran
download it to your directory.
https://cran.r-project.org/web/packages/readr/index.html
and this should work. It worked for me
    install.packages("C:/Program Files/R/R-3.3.0/library/readr_0.2.2.zip",
    repos = NULL, type="source")

Please make sure that the path is correct.


text:
Q: How to retrive the MySQL server timezone and then do a convertion in php i have some timedate information of my users in my database. Also i have the timezone of all my users.
Any time a user logs in to my web, a mensage popup showing the last time he logs in. This datetime is stored on mysql database using the datetime format and the SERVER TIMEZONE (no the user datetime).
All this simple by:
mysql_query("UPDATE ".$this->tablename." SET last_login = NOW()
WHERE email = '".$_SESSION['email_of_user']."';");

What i want is to convert this stored datetime to my user timezone (stored in my database).

A: mysql function convert_tz
syntax

CONVERT_TZ(dt,from_tz,to_tz)

example
SELECT CONVERT_TZ('2004-01-01 12:00:00','SYSTEM','@user_timezone');

You have the user timezone stored into database,
then you can do a simple join when you want to display last time an user logs in

A: If I understand what you're looking to do, why not store everything as UTC, and then apply the timezone after the fact?


text:
Q: I'm implementing printf function in C/Linux Program:
 #ifndef PRINTF_H
 #define PRINTF_H
 #include "my_put_char.h"

 int my_printf(char *str, ...);

 #endif

This is my Header file for my function.
#include <stdio.h>
#include "my_put_char.h"

void my_put_char(char c)
{
     fwrite(&c, sizeof(char), 1, stdout);
}

This is my putchar implementation(my_put_char.c).
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "printf.h"

int my_printf(char *str, ...)
{
    if(str == NULL)
        return 0;

    int i;
    char a;

    va_list print;
    va_start(print,str);

    for(i = 0; str[i] ; i++)
    {
        if(str[i] == '%')
        {
            i++;
            switch(str[i])
            {
                case 'c':
                a = va_arg(print, char);
                my_put_char(a);
                break;
            }
        }
     }
     va_end(print);
     return 0;
}

At last, this is a part of my printf implementation.
I'm testing with %c to display a character.
When I do my_print("%c", 'd'); from main.c
it compiles and displays d.
But when I do my_print("%c", "hi"); , it still compiles and displays a number.
Question:
After(or before) writing a = va_arg(print, char); Is there a way to check whether my input is a different data type?
I'm trying to display an error if my input is a different data type.
I'm on this subject for 2 days and couldn't find any answer.
Thank you so much for your time!

A:
when I do my_print("%c", "hi"); , it still compiles and displays a number

You've got some undefined behavior, so be scared. Your my_printf would call va_arg with an argument of the bad type (expected char promoted to int, got char*).
To explain what is happening you should dive into implementation details (look into the assembler code, e.g. with gcc -Wall -fverbose-asm -O -S; study your processor, its instruction set architecture, its application binary interface and calling conventions). You don't want to do that, it could take years and is not reproducible.
Read absolutely Lattner's blog on UB, right now!
Then download C11 specification n1570....
You could also, with gcc, use some function attributes. Don't forget to compile with all warnings and debug info (gcc -Wall -Wextra -g)

after writing a = va_arg(print, char); Is there a way to check whether my input is a different data type?

No, not really and not always. But the format function attribute could help. And you could also spend months customizing GCC with your own plugin or some GCC MELT extension (that is not worth your time). Be aware of the Halting Problem and Rice's Theorem (each makes static source code program analysis so challenging). Look also into source analyzing tools like Frama-C.

I'm implementing printf function

BTW studying the source code of existing free software implementations of the C standard library (such as GNU glibc and musl-libc) could be inspirational; they are based upon syscalls(2).


text:
Q: Error in your SQL syntax 'WHERE c.name LIKE '%%'' I'm looking to produce the below table with search and pagination by joining 4 tables - categories, subcategories, childCategories and products.

The backend code to acheive the above is:
const [rows, fields] = await mysqlConnPool.promise().execute(
      `SELECT c.id, c.name, COUNT(DISTINCT(s.id)) AS subCategories,
      COUNT(DISTINCT(ch.id)) AS childCategories, COUNT(p.id) AS products
      FROM categories c
      LEFT JOIN subCategories s ON c.id = s.categoryId
      LEFT JOIN childCategories ch ON s.id = ch.subCategoryId
      LEFT JOIN products p ON ch.id = p.childCategoryId GROUP BY c.id
      ORDER BY c.id ASC LIMIT ${size} OFFSET ${page * size}`
    );

However, when I try to implement the search functionality, it throws a Mysql syntax error.
Please help to identify the error and point the correct syntax:
const [rows, fields] = await mysqlConnPool.promise().execute(
      `SELECT c.id, c.name, COUNT(DISTINCT(s.id)) AS subCategories,
      COUNT(DISTINCT(ch.id)) AS childCategories, COUNT(p.id) AS products
      FROM categories c
      LEFT JOIN subCategories s ON c.id = s.categoryId
      LEFT JOIN childCategories ch ON s.id = ch.subCategoryId
      LEFT JOIN products p ON ch.id = p.childCategoryId GROUP BY c.id
      ORDER BY c.id ASC LIMIT ${size} OFFSET ${page * size}
      WHERE c.name LIKE '%${search}%'`
    );

But it throws the following error:

A: Figured out the right syntax, posting if helpful to someone else:
const [rows, fields] = await mysqlConnPool.promise().execute(
      `SELECT c.id, c.name, COUNT(DISTINCT(s.id)) AS subCategories,
      COUNT(DISTINCT(ch.id)) AS childCategories, COUNT(p.id) AS products
      FROM categories c
      LEFT JOIN subCategories s ON c.id = s.categoryId
      LEFT JOIN childCategories ch ON s.id = ch.subCategoryId
      LEFT JOIN products p ON ch.id = p.childCategoryId
      WHERE c.name LIKE '%${search}%' GROUP BY c.id
      ORDER BY c.id ASC LIMIT ${size} OFFSET ${page * size}`
    );

WHERE clause needs to come before GROUP BY

A: Please use the below updated query.
const [rows, fields] = await mysqlConnPool.promise().execute(
      `SELECT c.id, c.name, COUNT(DISTINCT(s.id)) AS subCategories,
      COUNT(DISTINCT(ch.id)) AS childCategories, COUNT(p.id) AS products
      FROM categories c
      LEFT JOIN subCategories s ON c.id = s.categoryId
      LEFT JOIN childCategories ch ON s.id = ch.subCategoryId
      LEFT JOIN products p ON ch.id = p.childCategoryId
      WHERE c.name LIKE '%${search}%' GROUP BY c.id
      ORDER BY c.id ASC LIMIT ${size} OFFSET ${page * size}`


text:
Q: Obtain type parameters for generic methods in a stack trace I'm accessing the stack frame programatically and pulling out information about the stack which interests me. One such thing is the type parameter for a specific file, if it exists in the trace.
I'm not concerned about fast or maintainable solutions, this isn't going to be production code.
Here's a bit of the code if it helps for inspiration... this makes a collection of strings which are file names and line numbers where the assembly exists in a list defined in ProjectFiles. (Please forgive the conventions and styles, these are not my choice.)
var Frames = new StackTrace(true).GetFrames();
var FileNames = Frames
    .Where(Location => ProjectFiles.Any(File => File.Contains(Location.GetMethod().Module.Name)))
    .Select(
        Frame => string.Format("{0}:{1}", Frame.GetFileName() ?? string.Empty, Frame.GetFileLineNumber()))
    .Select(Location => Location.Substring(Location.LastIndexOf("\\", StringComparison.Ordinal) + 1))
    .Reverse();

Sample output:
Round Trip: SomeUI.cs:583 -> SomeRepository.cs:34, 002ms.


text:
Q: What is the most recent MSOffice that can be run under Wine/Playonlinux? I use msoffice 2013 in Windows, but I was not able to install it in Wine or Playonlinux, where instead I use msoffice 2007.
I wander if some user can confirm the most recent MSOffice that run under Wine/Playonlinux.
I am not asking how to install 2013 (although finding how to do that would be great) - but what is the latest that clearly works.

MSOffice version history at the date of this question:

After comments keep asking to let go MSO:
I am processing (translating) large documents that have been elaborated in new versions of MSo (eg 2013), and sometimes even mso-2007 isn't able to treat them properly, not to speak of LO, and I have to use latest versions of the program. - All the formatting has to remain completely unchanged when the sender re-opens his document that I return  translated  back to him (after I modify the text and save the document). -- But my work experience is much better in Linux than in Windows (desktop, internet browsing, other secondary tools that I need and have set up in Linux)  and that is why I am asking the question.

A: Since the new Wine 2.0 version got released, you can now theoretically run MS Office 2013 with it, according to the announcement on the official WineHQ website:

The Wine team is proud to announce that the stable release Wine 2.0
  is now available.
This release represents over a year of development effort and around
  6,600 individual changes. The main highlights are the support for
  Microsoft Office 2013, and the 64-bit support on macOS.

The new Wine is not yet provided through the official Ubuntu repos as far as I know though, so you have to install it from their official Wine PPA:
sudo add-apt-repository ppa:wine/wine-builds
sudo apt-get update
sudo apt-get install winehq-devel

More information about installing Wine 2.0 on Ubuntu may also be found here.
After that, you should be able to install MS Office 2013 on Wine.
Sources:

*

*OMG Ubuntu: "Wine 2.0 Released, Lets You Run Microsoft Office 2013 on Linux"

*WineHQ: Wine 2.0 Announcement

A: Office 2016, 16.0 - NO.

Office 2013, 15.0 - YES.
Answers  under this question seem to work.
I have installed it according to this answer, which was the most recent and is the most simple, as it only involves running a script in Playonlinux.

*

*Word seem to work decently, as well as Excel. Outlook starts (I never use it).

*Powerpoint has some bugs; from what I have seen, upon each startup one has to wait for a configuration progress to end and then select 'No' when asked to reboot Wine.

*OneNote doesn't work.

*Minimized windows are not seen in the task manager, panel or dock, but appear on the desktop as buttons/launchers which show window options when clicked. This may vary depending on the desktop environment, I have only tested in Plasma and Lxqt.

They are a bit annoying as  they stay on top of the normal Linux windows. This can be changed by altering the Wine configuration in POL to  allow the (Linux) window manager to control the windows.

In this way  the windows will then be accessible from task manager/panel as any other window, but this bug would stop you from resizing, moving or otherwise changing the windows' state once you have put them into the "un-maximized" state. So, avoid the un-maximize button.

-- and just use the minimize option or leave the windows maximized and switch them with Alt-Tab or from the panel or dock.
(I do not recommend enabling the other option of running the windows in a virtual desktop: minimized windows would in this case become totally inaccessible.)
UPDATE FOR 2013:
The above answer worked for me in 18.04, but not in 18.10. Instead I followed a combination of the other two answers there, that I have posted HERE.

Office 2010, 14.0 - YES
Before installation be sure you have winbind installed:
sudo apt install winbind

*

*In Playonlinux 4.2.10 it is listed under ' Install - Office'

Office 2007 - YES
More here.

A: Office 2016 (Word/Excel/Powerpoint) can run with POL and Wine 3.14 (latest 3.19 or 3.0 /3.4 did not work for me) on Ubuntu 18.04 with steps 1-5 post Kevin.
If you download the complete office 2016 IMG file, the installation includes your personal license and is already activated on start.


text:
Q: Error 404 Not found for @font-face files I am loading css using the following in <head> tag
<link rel="stylesheet" type="text/css" href="{{ asset('css/materialize.css') }}" media="screen" />

The page is not able to find the fonts used in the css file in the fonts directory mentioned under public folder. How am i supposed to load these for the css files ?
Image of Folder Struxture & Calling of font-face in the css file:

A: it seems you wrote "font", but it is "fonts" in directory structure.


text:
Q: Как избежать затирания табличных полей в документе? Доброго времени суток гуру битрикса! Помогите кто чем может.
Создаётся документ в сделке:
$entity_id = $Deal["ID"]; //id Сделки
$template = \Bitrix\DocumentGenerator\Template::loadById($template_id);
$template->setSourceType(\Bitrix\Crm\Integration\DocumentGenerator\DataProvider\Deal::class);
$document = \Bitrix\DocumentGenerator\Document::createByTemplate($template, $entity_id); ......

В нём есть табличные данные:
......
'ProductName' => ['VALUE' => 'Table.Item.Name'],
'ProductCost' => ['VALUE' => 'Table.Item.Cost'],
'ProductNds' => ['VALUE' => 'Table.Item.Nds'],
'ProductCount' => ['VALUE' => 'Table.Item.Count'],
'ProductPercent' => ['VALUE' => 'Table.Item.Percent'],
'ProductReward' => ['VALUE' => 'Table.Item.Reward'],
......

Всё замечательно создаётся и сохраняется где нужно, но! При правке документа в сделке через стандартный интерфейс, все табличные поля затираются.
Была попытка исключить их из формы редактирования через инъекцию кода в компонент:
**crm.document.view**

Поля из редактирования пропали, но по прежнему затираются.
Так же была попытка заново подсунуть табличные данные в событие:
\Bitrix\Main\EventManager::getInstance()->addEventHandler('documentgenerator', 'onUpdateDocument', function(\Bitrix\Main\Event $event)
///////////////////////////
$result = $document->getFile();
$res_data = $result->getData();

$res_data - рапортует что всё удачно добавилось, но!
Аналогично без результата, поля затираются.
Как можно этого избежать?

A: Ну собственно сам спросил сам и отвечу :-)
Используем событие \Bitrix\Main\EventManager::getInstance()->addEventHandler( "documentgenerator", "onBeforeProcessDocument", ["PreGenerationDocx", "onBeforeProcessDocument"]);
И в нём перезаписываем табличные данные.


text:
Q: Setting instance variables with ActiveScaffold I've recently added ActiveScaffold to an existing Rails project, and the problem I'm having is that the variable names that ActiveScaffold is using are not the same as the ones I already have. Rather than going through my entire application and changing all of the instance variable names, I'd like to be able to set the instance variables in the controller. The problem is that @record and @records cannot be called in before_filters, even if the before_filter is after the active_scaffold call.  Looking through the plugin, I see no obvious hook inside of the ActiveScaffold::Actions modules. I'm wondering:

*

*Is there such a hook?

*If not, how should I put one in?

A: the way to do this is to overwrite the do_show, do_create, do_list, etc... methods in the controller.


text:
Q: Update two tables using laravel Hi how can i update a values in two tables my code as shown as below cases:
public function subscriberprofileupdate($ids, Request $request) {
    $profile = Subscriberinfo::find($ids);
    $id = \Auth::user()->id;
    $user_id = \Auth::user()->user_id;
    $subscriber_id = \Auth::user()->subscriber_id;
    $inputteacher = $request->all();

    $profile->contact_person_firstname = $inputteacher['contact_person_firstname'];
    $profile->contact_person_lastname = $inputteacher['contact_person_lastname'];
    $profile->email = $inputteacher['email'];
    $profile->save();
    return Redirect('/subscriber/profile');
}

If i can update email in subscriber table means that it will also update on users table also by using the user_id.
How can i make it.

A: You can simply:
User::where('id',$user_id)->update(['email' => $inputteacher['email']]);

It will update the Users table email field where users.id is $user_id

A: The better way is to add a new column named user_id in your subscriber table  and you than you can fetch the data if you have given proper relation in your model.

A: When updating a belongsTo relationship, you may use the associate method.
For example:
$inputteacher = $request->all();
$userdetail = User::find(1);
$userdetail->firstname = $inputteacher['contact_person_firstname'];
$userdetail->lastname = $inputteacher['contact_person_lastname'];

$profile = Subscriberinfo::find($ids);
$profile->contact_person_firstname = $inputteacher['contact_person_firstname'];
$profile->contact_person_lastname = $inputteacher['contact_person_lastname'];
$userdetail->profiles()->save($profile);

//This will save not only a model, but also all of its relationships
$userdetail->push();


text:
Q: overlay is not working in IE6? Iam using the following code in my file for overlay image.This works fine in firefox but not in IE6.Can anyone please suggest a solution for this??
<div id="1" onclick="document.getElementById('div1').className = 'nodis';" CLASS="nodis" style="width:100%; background:url('/gifs/overlay.png');" align="center">

A: Png overlays aren't supported in IE6, and you'll have to make use of other hacks* instead.
Or, you could do what Microsoft has already done: drop support for IE6.
Microsoft are pushing out IE8 as a critical security update, so even Windows users that have pirated windows copies will get automatic upgrades from IE6. And large corporations aren't an issue anymore, since very few IT departments in the world want to have unsupported 3rd party software under their responsibility.
If you're still worried that many of your users use IE6, and you want to make sure they can see the page correctly, make use of an update script such as IE6update, which will tell your users that they need a browser update to show your page correctly.
*) Thanks to deceze for the link to various hacks.

A: I might have misunderstood your question, but here is a solution for PNG fix using javascript: PNGFix. If this is not what you need, please correct me and give me more detailed explanation or link to your site.


text:
Q: dotnet run --project  not taking project path as working directory When using the .NET commands to run my Console App that is being stored on a network drive it sees the Working Directory as where it is being called from instead of the project path..
dotnet run --project "\\network.drive\path\example\project"
I get the output as follows:
WORKING DIRECTORY: C:\Windows\system32
Current Environment: DEV
Current Root URL: <API_URL>
Current Excel File:

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: fileName
   at System.IO.FileInfo..ctor(String originalPath, String fullPath, String fileName, Boolean isNormalized)
   at System.IO.FileInfo..ctor(String fileName)
   at MyProject.Reader.ReadAgentData(Int32 sheetIndex) in \\network.drive\path\example\project\Reader.cs:line 68
   at MyProject.Program.Main(String[] args) in \\network.drive\path\example\project\Program.cs:line 119

The error is the Excel File variable being an empty string. Since the working directory is not the path of the project, but instead C:\Windows\system32 it cannot find the appsettings.json file that the information is pulled from.
Weirdly enough, using the command dotnet watch --project "\\network.drive\path\example\project" run causes the process to run correctly, it has the correct working directory and reads the appsettings.json file without issues, but then it obviously has to wait for a file change (the purpose of watch)..
How can I have my app recognize the Working Directory as the root of the project folder when using dotnet run --project?? (To be clear, I do NOT want to use watch unless I can have it end automatically)

A: Run dontet from the project's folder.
Because appsettings.json and ssh certificates are relative to the executiion folder.
Regardless of the System.Reflection.Assembly.GetExecutingAssembly().Location


text:
Q: Trigger method once every day I'm looking to trigger a method once every day. I've tried scheduling this with Timer and TimerTask, but my problem is that the program may be run several times a day, and somedays maybe none. How can I when the program first starts check if the method already has been run that day?
Thanks!

A: Use cron job with scheduling your selected method
For example  0 20 ***  this do every day clock when 20:00

A: Take a look into the Java Date Class. That way you can save the last time your program was run in a file and then once it is run again read the current date and see if the day changed.

A: I've used Quartz Scheduler in the past: https://quartz-scheduler.org/

A: If you are using spring, there are good abstractions to trigger a method:
@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {
}

I would suggest using a database to synchronize daily runs between multiple instances of your app:
@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
    Connection conn = ...
    String sql= "select lastrun from runs where method = 'doSomething' for update";
    PreparedStatement ps = conn.prepareStatement(sql,ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
        if(rs.getDate(1)/* is more than 23 hours ago*/){
            //do your work here....
            rs.updateDate(1, new Date());
            rs.updateRow();
        }
    } else{
        //todo
    }
    //todo: make sure rs, ps, and conn get closed...
}

Sources: http://blog.udby.com/archives/15 and http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support


text:
Q: Define sequence of axis labels I want to label certain tick marks with a regular sequence, and leave marks in between without labels.
My data ("coefs_PA") is like this
structure(list(year = c(1998, 1999, 2000, 2001, 2002, 2003,
2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014,
2015, 2016, 2017, 2018, 2019), estimate = c(0.111, 0.081, -0.106,
2.571, 0.606, -0.234, 0.325, 0.891, 0.062, 0.37, -0.041, 0.09,
0.436, 0.08, -0.973, 0.147, -0.116, 0.602, 0.385, 0.274, 0.118,
0.682), sd = c(0, 0.488, 0.411, 1.282, 0.473, 0.447, 0.427, 0.52,
0.477, 0.394, 0.384, 0.379, 0.404, 0.416, 0.43, 0.419, 0.464,
0.788, 0.456, 0.451, 0.427, 0.467)), row.names = c(NA, -22L), class = "data.frame")

and with the following code
library(Hmisc)

plot(coefs_PA$year, coefs_PA$estimate, xaxt='n', yaxt="n", xlab=NA, ylab=NA, pch=17,
     ylim = c(min(coefs_PA$estimate - coefs_PA$sd),
              max((coefs_PA$estimate + coefs_PA$sd))))

with(data = coefs_PA, expr = errbar(year, estimate, estimate+sd,
                                    estimate-sd, add = TRUE, cap = 0))

axis(2, las=2, at = c(-1:4, 1))
minor.tick(nx = 0, ny = 2, tick.ratio = 0.7)
axis(1, at=coefs_PA$fecha)
title(ylab=expression("Logit (P"[p]*")"), line=1.6, cex.lab=1)
mtext(side=3, line=0.2, "Year", font=2, cex=1.0)

I get the following figure

I want the values of the x-axis to be 2000, 2005, 2010, 2015 and the remaining tick marks to be blank. I have tried to get it with this
axis(1, at = coefs_fechas_PA$fecha,
     labels = c(rep("",2), "2000", rep("",4), "2005", rep("",4),
                "2010", rep("",4), "2015", rep("",4))))

but it didn´t work.
Any hint will be more than welcome.

A: Set
years <- do.call(seq, as.list(range(coefs_PA$year)))
years5 <- seq(2000, 2020, by = 5)
# or, more dynamically
years5 <- years[ years %% 5 == 0 ]

plot(coefs_PA$year, coefs_PA$estimate, xaxt='n', yaxt="n", xlab=NA, ylab=NA, pch=17,
     ylim=c(min(coefs_PA$estimate - coefs_PA$sd), max((coefs_PA$estimate + coefs_PA$sd))))

axis(1, years, labels = ifelse(years %in% years5, years, years[NA]))

(And then all of your other plot components ... omitted for brevity.)
Note: If we instead do ifelse(.., years, ""), then the desired years may not show because the empty strings are still causing potential overlap and/or problems with the labels. We can use ifelse(.., years, NA), and that's perhaps more intuitive, but programmatically speaking I chose years[NA] for a couple of reasons:

*

*ifelse-replacements (dplyr::if_else and data.table::fifelse come to mind) generally complain when the class of objects in the yes= and no= arguments are different. Did you know that there are at least six types of NA, all different classes?

*I could have hard-coded NA_integer_ since years is an integer vector, but I didn't want to assume that ... perhaps you'll have numeric instead (and therefore should be using NA_real_). It's perhaps a little more declarative that I want the same NA as the class of years, so years[NA] gives me that. (Perhaps my programming OCD is showing.)

A: You could achieve that by specifying that you want only every fifth data label to be shown using scale_x_date(breaks = my.data$date[seq(1, length(my.data$date), by = 5)]) in ggplot, as explained by Eric Watt on How to show every second R ggplot2 x-axis label value?


text:
Q: Error converting varchar to numeric in SQL subtract query I have this query
select SUM(quantity) from Sales join Document on Sales.IdDocument = Document.IdDocument where (IdTipoDocumento = 'vco' or IdTipoDocumento = 'vcr') and IdArticulo = '01-00321' and IdListaEmpresa = 1000129
-
(select SUM(quantity) from Sales join Document on Sales.IdDocument = Document.IdDocument where IdTipoDocumento = 'dco'  and IdArticulo = '01-00321' and IdListaEmpresa = 1000129)

If I run each line separately, each query works fine (the first gives 419 as a result, the second 380) but if I try to run the whole thing to get the result (419-380) it tells me "Error converting data type varchar to numeric."
They're both supposed to already be numeric (the quantity field is of integer type anyways) so I don't know why the error comes out...

A: Method 1:
SELECT
(select SUM(quantity) from Sales join Document on Sales.IdDocument = Document.IdDocument
where (IdTipoDocumento = 'vco' or IdTipoDocumento = 'vcr') and IdArticulo = '01-00321' and
IdListaEmpresa = 1000129)

-
(select SUM(quantity) from Sales join Document on Sales.IdDocument = Document.IdDocument
where IdTipoDocumento = 'dco'  and IdArticulo = '01-00321' and IdListaEmpresa = 1000129)

Method 2:
SELECT SUM(SQ)
FROM (
SELECT CASE WHEN (IdTipoDocumento = 'vco' or IdTipoDocumento = 'vcr') THEN SUM(Quantity)
WHEN IdTipoDocumento = 'dco' THEN -1*SUM(Quantity)
END AS SQ
FROM  Sales join Document on Sales.IdDocument = Document.IdDocument
where (IdTipoDocumento IN ('vco', 'vcr','dco')) and IdArticulo = '01-00321' and
IdListaEmpresa = '1000129'
GROUP BY IdTipoDocumento) AS T1

Method 3:
SELECT SUM(CASE WHEN IdTipoDocumento IN ('vco', 'vcr') THEN Quantity ELSE -1*Quantity END)
AS SQ
FROM  Sales join Document on Sales.IdDocument = Document.IdDocument
where (IdTipoDocumento IN ('vco', 'vcr','dco')) and IdArticulo = '01-00321' and
IdListaEmpresa = 1000129

Method 3a:
   SELECT IdListaEmpresa,
         SUM(CASE WHEN IdTipoDocumento IN ('vco', 'vcr')
                  THEN Quantity
                  ELSE -1*Quantity END) AS SQ
   FROM  Sales join Document on Sales.IdDocument = Document.IdDocument
   WHERE (IdTipoDocumento IN ('vco', 'vcr','dco'))
       AND IdArticulo = '01-00321'
       AND IdListaEmpresa IN (1000129, 1000130, 1,2,3,4,5)
   GROUP BY IdListaEmpresa


text:
Q: Nativescript - native emulator error when run android --emulator I receive the following error when I run android --emulator on my cmd;

Cannot run your app in the native emulator. Increase the timeout of the operation with the --timeout option or try to restart your adb server with 'adb kill-server' command. Alternatively, run the Android Virtual Device manager and increase the allocated RAM for the virtual device.

I've opened it with administrator rights and ran all the tutorials on the website.
I'm now stuck at this point and haven't been able to find the solution.
I've also tried tns run android --emulator --timeout -0 and waited for an hour without result.
What can i do to get the emulator running?

A: I had the same problem, I solved by opening avd manager and try starting the virtual device(emulator) you created. If the emulator doesnt launches, you will get an error in the console.
For me I had to install the intel HAXM, for launching the emulator

A:
You just need to open your Android Virtual Device Manager and download
  the latest emulator. Then run your application again.It will work.

A: tns run android

Runs the Emulator and then run the app on it.
Sometimes both process can't happen at once, admin access in Linux can be such case.
try starting the Emulator first then the app.
emulator -avd avd_name [ {-option [value]} … ]

for example:
sudo $ANDROID_HOME/emulator/emulator -avd test -netdelay none -netspeed full

'sudo' is important for Linux users.
then use this to start the app.
tns run android


text:
Q: Strange error in iAd I've added iAd to my application, and while testing it in my simulator/device I receive some error from bannerView:didFailToReceiveAdWithError:, here are the error listed:
MyTest[11915:907] [iAd] Error di=3: The operation couldn't be completed. Inventario annunci non disponibile
MyTestApp[11877:907] [iAd] Error di=4: The operation couldn't be completed. L'applicazione presenta un errore di configurazione rete di iAd
2013-01-15 02:31:26.620 MyTestApp[11877:907] [iAd] Error di=5: The operation couldn't be completed. Il banner è visibile ma non ha contenuto
After some time (30-40sec) the banner correctly show in the device.. I am missing something?
Thanks

A: Apple documentation says: "While you are developing your application, iAd Network sends test advertisements to your application. To assist you in validating your implementation, the iAd Network occasionally returns errors to test your error handling code."
Also in my app iad return a mix of correct banner,error 3,error 5...
I think that this problem will disapper after the release of the app when iAd will change from "iAd Network serves test ads" to "iAd Network serves live ads if you signed the iAd Network Agreement and enabled advertising for your application"


text:
Q: Python: How to ignore an exception and proceed? I have a try...except block in my code and When an exception is throw. I really just want to continue with the code because in that case, everything is still able to run just fine. The problem is if you leave the except: block empty or with a #do nothing, it gives you a syntax error. I can't use continue because its not in a loop. Is there a keyword i can use that tells the code to just keep going?

A: except Exception:
    pass

Python docs for the pass statement

A: Generic answer
The standard "nop" in Python is the pass statement:
try:
    do_something()
except Exception:
    pass

Using except Exception instead of a bare except avoid catching exceptions like SystemExit, KeyboardInterrupt etc.
Python 2
Because of the last thrown exception being remembered in Python 2, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of pass:
try:
    do_something()
except Exception:
    sys.exc_clear()

This clears the last thrown exception.
Python 3
In Python 3, the variable that holds the exception instance gets deleted on exiting the except block. Even if the variable held a value previously, after entering and exiting the except block it becomes undefined again.

A: There's a new way to do this coming in Python 3.4:
from contextlib import suppress

with suppress(Exception):
  # your code

Here's the commit that added it: http://hg.python.org/cpython/rev/406b47c64480
And here's the author, Raymond Hettinger, talking about this and all sorts of other Python hotness (relevant bit at 43:30): http://www.youtube.com/watch?v=OSGv2VnC0go
If you wanted to emulate the bare except keyword and also ignore things like KeyboardInterrupt—though you usually don't—you could use with suppress(BaseException).
Edit: Looks like ignored was renamed to suppress before the 3.4 release.

A: Try this:
try:
    blah()
except:
    pass


text:
Q: using paste with read.csv inside a function I want to create a function that uses read.csv() with paste().  The following code works in general
df <- read.csv(paste("/file name", 2010, ".CSV", sep = ""), header = TRUE)

but when I place it inside a function like so
myfunction <- function(date){df <- read.csv(
                             paste("/file name", date, ".CSV", sep = ""),
                             header = TRUE)
                            }

The command myfunction(2010) fails to produce output and does not result in any errors or warnings.  What am I doing wrong?

A: You need to use <<- instead of <-
myfunction <- function(date){df <<- read.csv(
                             paste("/file name", date, ".CSV", sep = ""),
                             header = TRUE)
                            }

or you write:
myfunction <- function(date){read.csv(
                             paste("/file name", date, ".CSV", sep = ""),
                             header = TRUE)
                            }
df <- myfunction(2000)

A: You could always use sprintf
myfunction <- function(date){
  df <- read.csv(sprintf('/filename%s.csv',date))
  return(df)
}
csv <- myfunction(date)

and if you have lots of dates
ListDates <- as.list(dates)
ListOfCsvs <- lapply(ListDates,myfunction)

EDIT: I didnt make it clear that your issue was solved by return(df) inside myfunction()

A: Return the dataframe from your function
myfunction <- function(date){
   df <- read.csv(paste("/file name", date, ".CSV", sep = ""),header = TRUE)
   return(df)
}

and assign it
df <- myfunction(2010)

In R, the last line in the function is automatically returned anyway, so this should also work.
myfunction <- function(date){
   read.csv(paste("/file name", date, ".CSV", sep = ""),header = TRUE)
}


text:
Q: Selected row GridView won't extract data I have a GridView which I am filling with data from my database. The data displays perfectly. My problem is that I want to be able to click on a row and then display the information that is in that row elsewhere (eventually I'll have a splitscreen to format the selected data nicely). The selection works, because it highlights the current row. However, I cannot figure out how to display that data elsewhere. For now, I'm trying to display the content of a single cell in a label called testLabel. I've tried many different methods, and the testLabel never updates when I click a new row. Can anybody see what is going wrong here?
C#
protected void DefaultGrid_SelectedIndexChanged(Object sender, EventArgs e)
{
    GridViewRow row = DefaultGrid.SelectedRow;
    testLabel.Text = row.Cells[2].Text;
}

ASPX

    <title></title>

    <form id="form1" runat="server">
    <asp:ScriptManager ID = "ScriptManager" runat="server" />

            <asp:Label runat="server" id = "orderByLabel" Text = "Order By: " />

            <asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
                <asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
                <asp:ListItem Value="lName">Last Name</asp:ListItem>
                <asp:ListItem Value="state">State</asp:ListItem>
                <asp:ListItem Value="zip">Zip Code</asp:ListItem>
                <asp:ListItem Value="cwaSource">Source</asp:ListItem>
                <asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
            </asp:DropDownList>

            <asp:Label runat="server" ID="searchLabel" Text="Search For: " />
            <asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
            <asp:Button ID="searchButton" runat="server" Text="Search" />

    <asp:UpdatePanel ID = "up" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID = "orderByList"
        EventName="SelectedIndexChanged" />
         <asp:AsyncPostBackTrigger ControlId="searchButton" EventName="Click" />
    </Triggers>

    <ContentTemplate>
        <asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "fName"
        onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
        autogenerateselectbutton = "true"
        selectedindex="0">
        <SelectedRowStyle BackColor="Azure"
        forecolor="Black"
        font-bold="true" />
        <Columns>
            <asp:ButtonField CommandName="Select" Visible="false" />
        </Columns>
        </asp:GridView>
        </ContentTemplate>
        </asp:UpdatePanel>

        <asp:Label runat="server" ID="testLabel" Text="test" />

    </form>

A: You have provided own select button and also set property http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogenerateselectbutton.aspx to true. You must choose only one of those.
Edit: Ah, see it now. Label 'testLabel' is outside updatepanel. Move it to ContentTemplate.

A: Have you tried placing testLabel inside another UpdatePanel and force an update on it after you change the label's text?

A: By the looks of it, it should be working. Here are a few pointers:

*

*When accessing row.Cells[2].Text, keep in mind the index is Zero based (first cell is indexed 0).

*You have a fixed column that is invisible. Although not showing, that column should count in your column indexing numbers.

*Place a breakpoint inside DefaultGrid_SelectedIndexChanged. When it gets there, fool around with the possibilities by watching variables and calling methods. That should help you a lot.

A: I doubt your DefaultGrid_SelectedIndexChanged ever get called. Check this: http://forums.asp.net/t/1448445.aspx
Quote:

you need a buttonfield or a postback control such as a button, linkbutton,imagebutton with the commandName="Select" for the selectedIndexChanged event handler to trigger.


text:
Q: Keyboard Extension: Is it possible to inherit features and UI from the stock iOS keyboard? Custom Keyboard Extensions are a powerful new tool in iOS 8 that allow you to implement keyboard features that the stock iOS 8 keyboard will never have.
However, the stock iOS keyboard is already very good. It has had years of development as the only iOS keyboard, and thus has many (costly to implement) features that people expect from their keyboard.
I would be interested in implementing several small keyboard features, but would also want to keep the main UI and features of the normal iOS 8 keyboard.
For example, rather than suggesting a list of words in the new Auto-Complete area, a keyboard extension could suggest a list of Emoji.

Keymoji have created this keyboard, but seem to have manually copied the look of the iOS keyboard rather than inherit from it. There are many small differences when typing on their keyboard. This creates an uncanny valley-like experience, typing on a keyboard that is very similar to, but not quite, the stock iOS keyboard.
It would be ideal to only implement a keyboard listener, emoji lookup, and custom UI limited to the Auto-Complete area. Other features and UI would be handled by the stock keyboard.
Or are you also on the hook for (re-)implementing auto-complete, capitalization, resizing tap targets, UI for individual keys, and the many other features that people expect from a keyboard?
Do Custom Keyboard Extensions get any of these features "for free"?

A: The entire internal implementation of the system keyboard is currently private API and is not available to developers. Some functionality cannot be replicated completely, as the system keyboard is hosted in the user app process, while keyboard extensions are spun up in a helper process. The view hierarchy of keyboard extensions is rendered off process, and drawn on the user app using XPC.
Despite any limitations on keyboard extensions, many of the default features could be offered to users, such as views, predictive typing API and so on. This would help achieving consistency between switching keyboards, for example.
Make sure to open a bug report with Apple, letting them know the current shortcomings of their solution, and what you think would benefit developers. Post the bug report number (radar) here, so other developers can duplicate the bug report, and let Apple prioritize it accordingly.


text:
Q: How do you create modeled coverage of obstruction based data? I was wondering how it is possible to create a map of modeled coverage a CBRS radio provides in the real world with no auxiliary hardware? For reference this image is the modeled coverage a baicells 430h provides in the real world.

I'm thinking it works similar to echolocation where you can effectively hear what's around you. But is a CBRS radio with some mathematic proof or formula enough to calculate the coverage to such accuracy? Or do you need information from another source to accurately map the coverage? Thanks


text:
Q: Active Directory Search not returning all users I have code to populate a user id dropdown list within a VB.net application. Some user names are not being returned. I'm getting more than 1000 returned so it does not appear to be the 1000 limit. If I add (sAMAccountName=Kry*) to the search filter, then the user (whose name starts with kry) that was not appearing does get returned. Any help on this would be greatly appreciated. Thanks!
Private Sub PopSecurityUser()
    cboUser.Items.Clear()

    Dim SearchRoot As DirectoryEntry = ActiveDirectory.Forest.GetCurrentForest.RootDomain.GetDirectoryEntry '< More portable. Discover domain root DirectoryEntry rather than hard coding a Global Catalog.
    Dim AdObj As System.DirectoryServices.SearchResult

    Dim Searcher As New DirectorySearcher(SearchRoot)

    With Searcher
        .PropertiesToLoad.Add("sAMAccountName")
        .SearchScope = SearchScope.Subtree
        .Filter = "(&(!objectClass=contact)(objectCategory=person)(objectClass=user))"  '< Exclude contacts because they don't have a sAMAccountName property.
        .ReferralChasing = ReferralChasingOption.All    '< Causes lookups to follow LDAP referrals if the object doesn't exist on the queried domain controller.
    End With

    For Each AdObj In Searcher.FindAll
        If Not IsNumeric(AdObj.Properties("sAMAccountName")(0).ToString.Substring(0, 1)) Then
            cboUser.Items.Add(AdObj.Properties("sAMAccountName")(0))
        End If
    Next

    cboUser.Sorted = True
End Sub

A: The DirectorySearcher.SizeLimit property is set to 1,000 by default. I found another StackOverflow question regarding this exact situation and apparently there are two workarounds. The StackOverflow answer that I am referring to is here: https://stackoverflow.com/a/3488957/1920035


text:
Q: get the ID of a selected value in the drop down list I have an Album table with an Id_album attribute. and a songs table with Id_song attribute and Id_album as foreign key attribute. In the aspx page I have a drop down list of the album names to be selected to get its Id and use that Id in the songs table to add new songs ofthat album *depending on Id)
what I have done so far returns for me Id_album 1 whenever an album name is selected from the drop down list. In other words, the songs are all added to album of Id=1.what is going wrong??
this is the aspx page:
public partial class newSongs : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        MusicStoreBL bl = new MusicStoreBL();
        var data = bl.GetAlbums();
         //GetAlbums is a function that returns the Id_album, AlbumName
        albums.DataSource = data;
        //albums is the HTML dropdownlist
        albums.DataTextField = "AlbumName";
        albums.DataValueField = "Id_Album";
        albums.DataBind();
    }

    protected void save_Click(object sender, EventArgs e)
    {
        Song song = new Song();
        //Song is a get/set model

        song.Id_album = int.Parse(albums.SelectedValue);

        song.SongName = songName.Text;
        song.SongAuthor = author.Text;
        song.MusicArtist = songArtist.Text;
        song.Genre = genre.Text;

        MusicStoreBL bl = new MusicStoreBL();
        bl.CreateNewSong(song);
        Response.Redirect("albumSelection.aspx");
    }
}

A: You should place your data binding code in the Page Load event handler inside the following if statement:
if(!Page.IsPostBack)
{
    MusicStoreBL bl = new MusicStoreBL();
    var data = bl.GetAlbums();
    //GetAlbums is a function that returns the Id_album, AlbumName
    albums.DataSource = data;
    //albums is the HTML dropdownlist
    albums.DataTextField = "AlbumName";
    albums.DataValueField = "Id_Album";
    albums.DataBind();
}

This way you fetch your data only once and then you bind them to the corresponding drop down list control. Otherwise, each time you trigger a postback, like selecting an element from your drop down list control or clicking on a button and so on, your data bind code in the Page_Load runs from the start.
So why you get all the time the Id=1?
The reason why you get every time as an Id the 1 is the fact that every time you click the save the code in the Page_Load runs. The data bind happens and the first item of the drop down list is the selected one.


text:
Q: Physics Vector Collision Momentum Question A $2 \ kg$ particle is initially moving in the $x$ direction at $10 \ m/s$ and so has momentum $m*|v| = 20 \ kgm/s$, with components $p_{1x} = -20 kgm/s$, $p_{1y} = p_{1z} = 0$. It hits a second particle initially moving in the $y$ direction with a momentum of $5 kgm/s$. Thus $p_{2x} = p_{2z} = 0$, and $p_{2y} = 5 kgm/s$. The two particles' total momentum is ?
So apparently total momentum is not just adding $20 \ kgm/s$ and $5 \ kgm/s$. What am I not seeing here?

A: This is classical mechanics. You can use vector addition.
$$
p = p_1 + p_2 = (-20, 0, 0)^\top \text{Ns} + (0, 5, 0)^\top \text{Ns}= (-20, 5, 0)^\top \text{Ns}
$$


text:
Q: Why is the second derivative of the probability distribution function in this case not valid probability density function? I am asked to find the covariance of $X$ and $Z=min(X,Y)$, where $X$ has exponential distribution $\epsilon(2)$, $Y$ has exponential distribution $\epsilon(3)$ and $X$ and $Y$ are independent. I am trying to find $E(XZ)$. To do this I calculate $$F_{X,Z} (x,z) = p \{X \leq x, Z \leq z \} = p\{X \leq x  \} = 1 - e^{-2x}$$, in case $x \leq z$ and  $$F_{X,Z} (x,z) = p\{ X \leq z\} + p\{z<X\leq x, Z \leq z \} = (1 - e^{-2z}) + (1 - e^{-2x} - 1 + e^{-2z})(1 - e^{-3z}) = 1 - e^{-2x} - e^{-5z}
 +e^{-2x -3z}$$, otherwise.
So density function is $F_{X,Z}$ derivated with respect to $x$ and $z$:
$$f_{X,Z}(x,z) = 6e^{-3z-2x}$$ when $x > z$, and $0$ otherwise.
But when I integrate this:
$$\int_{0}^{+\infty} \int_{0}^{x} 6 e^{-3z-2x} dzdx = \frac{3}{5}$$
I don't get 1. Why ?

A: There is no joint density of $(X,Z)$ (with respect to Lebesgue measure) because $$P(X=Z)=P(X=\min(X,Y))=P(X<Y)>0$$
And we know that Lebesgue measure (or area) of the set $\{(x,z):x=z\}$ is $0$.
In other words, $(X,Z)$ is not absolutely continuous. Joint distribution function of $(X,Z)$ exists of course, but you don't get a density function by differentiating the distribution function.
Now using an indicator function $I$, one can write
$$Z=\min(X,Y)=XI_{X<Y}+YI_{X>Y}$$
Therefore,
$$E(XZ)=E(X^2I_{X<Y})+E(XYI_{X>Y})$$
So, if $f_{X,Y}$ is the joint density of $(X,Y)$, both expectations above can be found using this theorem:
$$E(X^2I_{X<Y})=\iint_{x<y} x^2 f_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y$$
$$E(XYI_{X>Y})=\iint_{x>y} xy \,f_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y$$

A: $(X,Z)$ is not jointly continuously distributed, so one cannot obtain its density by pointwise differentiation of its CDF. The actual source of the error is that $F$ is not even differentiable at a point $(x,x)$ with $x>0$. You can see this by looking at the directional derivatives, e.g. comparing the unnormalized directional derivative in the directions $(1,0),(0,1)$ and $(1,1)$. The first two should add up to the third if $F$ were differentiable, but they don't.


text:
Q: Installing jboss jsf 3.3 tools (no others) for Eclipse 3.7 breaks my block comment shortcut ctrl+shift+L in the jsf 2 xhtml file It worked before I installed the JBoss tools, but if I uninstall the jboss tools it's still broke.  It's driving me crazy.
In addition to that, Eclipse doesn't throw warning or error messages when I enter undefined tags in my xhtml files.  It flags undefined html tags like , but it's ok with .  This is not Jboss related.

A: How about doing this : Windows->Preferences->General->Keys , and change the "Ctrl + Shift + C" for toggle comments into "Ctrl + Shift + L" ? (for an easier finding of the shortcut you can order the table of shortcuts by Bindings Column...)


text:
Q: Вернуть md5 к исходному значению на С Подскажите какой-нибудь декриптор или что-нибудь в этом роде на Си для md5.
Нужно сделать так, чтобы шифровка md5 превращалась в то, что было до шифрования. Возможно ли такое в принципе, и если нет, то почему?

A: Обратное действие в md5 не возможно.
Получить оригинал можно только методом перебора, то есть брутом или по словарю.
Перебирать варианты, md5 хеш каждого нужно сравнить с имеющимся хешом md5. Тот который будет равен вашему хешу, возможно будет ваш оригинал! (возможно! но не факт!).
А на сайтах про которые вы говорите имеются словари с готовым оригиналом и готовым мд5, они просто проверяют есть ли в их словарях такие хеши, и смотрят к ним записанные ранее оригиналы строк. Но опять таки тоже не факт что это ваш хэш.

A: MD5 - это не "шифрование", это хэш-функция. Основное требование к криптографическим хэш-функциям - необратимость.
Если бы хэши были обратимы, то архиваторы и прочие алгоритмы сжатия стали бы не нужны. Например, я посчитал хэш от терабайтного файла. Получил 79a2520f22b9e1526ff93176029603b8. Вы считаете что можно эту строчку расшифровать обратно в тот же терабайт информации?
Максимум, что можно сделать для MD5 - найти коллизию (второй прообраз) - строчку, для которой MD5 выдаст такое же значение. Это можно сделать или по готовым словарям (если есть подозрение что строчка - это пароль вида 12345), или с использованием радужных таблиц.
Но никакой гарантии что вы получите при этом именно оригинальную строку нет. Точнее, вы с некоторой вероятностью получите оригинальную строку, если она была короткой. Но вы точно получите неоригинальную строку, а просто коллизию, если оригинал был достаточно длинным.
Если поиска коллизии для вас достаточно - поищите готовую опен-сорс реализацию  работы с радужными таблицами, например MD5Rainbow.


text:
Q: Why does my for loop return only one result The value of the search is supposed to append  to the nyt api and the for loop is supposed to list all the links. I'm only getting one result for some reason but when looked through console I see that there 100s of links.
function myFunction(){
var citySearch = $("#city").val();

var NYTurl = "https://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + citySearch +
"$sort=newest&api-key=xxxxxxxxxxxxxxxxxxxxxxxx"

jQuery.getJSON(NYTurl, function (data){
    var headlines = $("#headlines")
    var contentUrl = data.response.docs
    for(var i = 0; i < contentUrl.length; i++ ){
        contentUrlLoop = contentUrl[i];
        headlines.html('Link' );
    }
    console.log(data)
})

return false;

}

A: headlines.html( assigns the passed HTML string to headlines's inner HTML. So, on each iteration, you're overwriting whatever headlines had previously. Use append instead if you want to insert an  for every item in the response:
headlines.append('Link' );

Or, rather than making hundreds of DOM changes, you might consider coming up with a single HTML string and then appending it:
jQuery.getJSON(NYTurl, function(data) {
  var headlines = $("#headlines");
  var contentUrl = data.response.docs;
  var htmlStr = contentUrl.reduce(
    (a, { web_url }) => a + 'Link',
    ''
  );
  headlines.html('Link');
});

(perhaps enclose them in divs as well so that each link is on a new line, or make the as block, so that the HTML is readable)


text:
Q: Use prepared statements in PHP to insert into/display from multiple MySQL tables with foreign key I have two tables: movies and directors. The directors attribute in the movie entity is multi-valued, which is why I created the directors table with movieId as a foreign key that references the id column of the movies table.
Now, if I want to insert movies into my movies table, how do I add all the information for the movies into the movies table, as well as the name of the directors into the directors table at the same time, possibly using transactions? Also, how do I display the information from the movies table with their corresponding directors from the directors table in a HTML5 table using a while loop? I am using PHP with prepared statements.
This is what I have so far, but it's not complete:
mysqli_autocommit($connect, FALSE);
$stmtMov = $connect->prepare("SELECT id, title, plot, rating, releaseDate, language, duration, country, posterUrl, trailerUrl, imdbUrl FROM movies");
$stmtMov->execute();
$resultMov = $stmtMov->get_result();
$rowMov = $resultMov->fetch_assoc();
$movieId = $rowMov['id'];
$stmtDir = $connect->prepare("SELECT movieId, name FROM directors WHERE movieId = ?")
$stmtDir->bind_param("?", $movieId);
$stmtDir->execute();
$resultDir = $stmtDir->get_result();
$rowDir = $resultDir->fetch_assoc();

Any help would be very much appreciated.

A: Since you haven't added anything about insert, I'll consider only your select part.
The $rowMov will likely result in a rowset, which is nothing more than an array, which each row will have an ID value. What you should do is iterate with your rowset and generate, for every value, a query for directors entity and get the data you want. Something like:
foreach ($rowMov as $movie) {
    $stmt = $connection->prepare("SELECT .... FROM directors WHERE id_movie = ?");
    $stmt->bindParam("?", $movie["ID"]);
    // $execution, binding results, etc.
}

With that done, you'll have an array with directors and an array with movies. If you want to simplify things on your view (considering you're using a MVC pattern), I would associate both arrays, looking for relations of directors["ID_MOVIE"] and  movies["ID"], finally creating an array with both informations like and object.

A: You've asked two questions,

*

*How do I insert into two tables at the same time, and

*How do I display from two tables

But before I go into that, a bit of database review is in order. I would think that each movie would have one director, while each director might have many movies.  I suppose the possibility for co-directors exists, too.
So for the first case, each movie must have a director:
movies
------
movie_id
director_id
title
plot, etc...

In this case, you could simply put the director's name in the movie database, but in order to list movies by director you would have to search by the actual name (and mis-spelling would make things complicated). And directors and movies are two different things, so it's better to have separate tables.
In the second case, you need a join table to have a many-to-many relationship.
movies        director_movie     directors
-------       --------------     --------
movie_id       movie_id          director_id
title          director_id       name

So to answer your questions,
How do you insert into two tables at the same time?
You don't. First insert into whichever table stands on its own-- in the first case, directors.  Then you get the last_insert_id from that table (or if the director already exists, search for the director_id). If last_insert_id is squirrely, you may have to search for what you just inserted to get the id.
Then, you take that id value and insert it into the dependent table movies along with the rest of that table's fields.
For the many-to-many case, you would do it in similar steps: 1) insert into movies 2) get the movie_id 3) insert into  direcotors 4) get the director_id 5) insert ids into director_movie
How do I display the results
If there is only one director per movie, it's a simple sql query:
SELECT movies.*, directors.name FROM movies, directors where movies.director_id=directors.director_id AND movies.movie_id=?"
If you have multiple directors per movie, you'll have to loop through results:
SELECT * FROM movies WHERE movie_id=?
then make another query to list the directors
SELECT d.* from directors AS d,director_movie AS dm WHERE dm.director_id=d.director_id AND dm.movie_id=?


text:
Q: Preserve 'randomness' in parallel programs I've always drawn random numbers like,
srand(time(NULL))                      // seed with current time
...
double rnum = 1.0*rand()/RAND_MAX;     // convert to [0.0,1.0]

And I've never had any issues. I'm currently running parallel code with up to hundreds of cores, and they seem to have the same 'random' series of numbers, presumably because they're all starting at the same time (or very similar times).
What's a good way to randomize between processors?
I can access each processor's ID, so I was thinking about using something like,
srand(time(NULL)*(pG->my_id+1))        // +1 incase my_id == 0

But I don't know exactly how seeding works - so I was a little worried about an integer multiplier (especially a factor of 2?) not being 'random enough' (note: I have no specific criteria for sufficiently random).

A: All pseudo-random number generators yield sequences of values that eventually cycle.  One abstract viewpoint is that the seed is equivalent to an entry point into the cycle.  Any two different seeds represent different entry points, and should be fine as long as the cycle length is sufficiently long that the subsequences don't overlap.  You'd do about as well to pick 10 sequential seed values for 10 processors as to do anything extremely fancy.  For instance, here are 10 values apiece from seeding Ruby's Mersenne twister with 0, 1, and 2.  As you can see, they appear to have nothing to do with each other even though the seeds were picked sequentially.
seed = 0:
0.5488135039273248
0.7151893663724195
0.6027633760716439
0.5448831829968969
0.4236547993389047
0.6458941130666561
0.4375872112626925
0.8917730007820798
0.9636627605010293
0.3834415188257777
seed = 1: 0.417022004702574
0.7203244934421581
0.00011437481734488664
0.30233257263183977
0.14675589081711304
0.0923385947687978
0.1862602113776709
0.34556072704304774
0.39676747423066994
0.538816734003357
seed = 2: 0.43599490214200376
0.025926231827891333
0.5496624778787091
0.4353223926182769
0.42036780208748903
0.3303348210038741
0.2046486340378425
0.6192709663506637
0.29965467367452314
0.26682727510286663