text:
Q: Removing enclosed intervals in an array of intervals in PHP I have such an array of intervals sorted by the lower bound ($a[$i] <= $a[$i+1] for every $i), key l is lower bound and , key h is upper bound and I'd like to remove all rows with intervals that are enclosed by larger intervals.
$a[0] = array('l' => 123, 'h'=>241);
$a[1] = array('l' => 250, 'h'=>360);
$a[2] = array('l' => 280, 'h'=>285);
$a[3] = array('l' => 310, 'h'=>310);
$a[4] = array('l' => 390, 'h'=>400);

So the result I'd like to get is
$a[0] = array('l' => 123, 'h'=>241);
$a[1] = array('l' => 250, 'h'=>360);
$a[2] = array('l' => 390, 'h'=>400);

This is what I attempted
function dup($a){
  $c = count($a)-1;
  for ($i = $c; $i > 0; $i --){
    while ($a[$i]['h'] <= $a[$i-1]['h']){
        unset($a[$i]);
    }
  }
$a = array_values($a);
}

A: The first answer which comes in mind was given with different variations by other contributors : for each interval, loop on each interval looking for a larger and enclosing interval. It's simple to understand and to write, and it works for sure.
This is basically n2 order, which means for n intervals we'll do n*n loop turns. There can be some tricks to optimize it :

*

*break'ing when we find an enclosing interval in the nested loop, as in user3137702's answer, because it's useless to continue if we find at least one enclosing interval

*avoiding looping on the same interval in the nested loop because we know an interval cant be strictly enclosed in itself (not significant)

*avoiding looping on already excluded intervals in the nested loop (can have a significant impact)

*looping on intervals (global loop) in ascending width = (h - l) order, because smaller intervals have more chance to be enclosed in others and the earliest we eliminate intervals, the more the next loop turns are effective (can be significant too in my opinion)

*searching for enclosing intervals (nested loop) in descending width order, because larger intervals have more chance to be enclosing other intervals (I think it can have a significant impact too)

*probably many other things that do not come to mind at the moment

Let me say now that :

*

*optimization does not matter much if we have only few intervals to compute from time to time, and currently accepted user3137702's answer does the trick

*to develop the suitable algorithm, it is necessary anyway to study the characteristics of the data that we have to deal with : in the case before us, how is the distribution of intervals ? Are there many enclosed intervals ? This can help to choose from the above list, the most useful tricks.

For educational purposes, I wondered if we could develop a different algorithm avoiding a n*n order which running time is necessarily very quickly deteriorated gradually as you increase the number of intervals to compute.
"Virtual rule" algorithm
I imagined this algorithm I called the "virtual rule".

*

*place starting and ending points of the intervals on a virtual rule

*run through the points along the rule in ascending order

*during the run, register open or not intervals

*when an interval starts and ends while another was opened before and is still open, we can say it is enclosed

*so when an interval ends, check if it was opened after one of the other currently open intervals and if it is strictly closed before this interval. If yes, it is enclosed !

I do not pretend this is the best solution. But we can assume this is faster than the basic method because, despite many tests to do during the loop, this is n order.
Code example
I wrote comments to make it as clear as possible.
<?php
    function removeEnclosedIntervals_VirtualRule($a, $debug = false)
    {
        $rule = array();

        // place one point on a virtual rule for each low or up bound, refering to the interval's index in $a
        // virtual rule has 2 levels because there can be more than one point for a value
        foreach($a as $i => $interval)
        {
            $rule[$interval['l']][] = array('l', $i);
            $rule[$interval['h']][] = array('h', $i);
        }

        // used in the foreach loop
        $open = array();
        $enclosed = array();

        // loop through the points on the ordered virtual rule
        ksort($rule);
        foreach($rule as $points)
        {
            // Will register open intervals
            // When an interval starts and ends while another was opened before and is still open, it is enclosed

            // starts
            foreach($points as $point)
                if($point[0] == 'l')
                    $open[$point[1]] = $point[1]; // register it as open

            // ends
            foreach($points as $point)
            {
                if($point[0] == 'h')
                {
                    unset($open[$point[1]]); // UNregister it as open

                    // was it opened after a still open interval ?
                    foreach($open as $i)
                    {
                        if($a[$i]['l'] < $a[$point[1]]['l'])
                        {
                            // it is enclosed.

                            // is it *strictly* enclosed ?
                            if($a[$i]['h'] > $a[$point[1]]['h'])
                            {
                                // so this interval is strictly enclosed
                                $enclosed[$point[1]] = $point[1];

                                if($debug)
                                    echo debugPhrase(
                                        $point[1], //           $iEnclosed
                                        $a[$point[1]]['l'], //  $lEnclosed
                                        $a[$point[1]]['h'], //  $hEnclosed

                                        $i, //                  $iLarger
                                        $a[$i]['l'], //         $lLarger
                                        $a[$i]['h'] //          $hLarger
                                    );

                                break;
                            }
                        }
                    }
                }
            }
        }

        // obviously
        foreach($enclosed as $i)
            unset($a[$i]);

        return $a;
    }
?>

Benchmarking against basic method

*

*It runs tests on randomly generated intervals

*basic method works without a doubt. Comparing results from the two methods allows me to predent the "VirtualRule" method works because as far as I tested, it returned the same results
// * include removeEnclosingIntervals_VirtualRule function *

// arbitrary range for intervals start and end
// Note that it could be interesting to do benchmarking with different MIN and MAX values !
define('MIN', 0);
define('MAX', 500);

// Benchmarking params
define('TEST_MAX_NUMBER', 100000);
define('TEST_BY_STEPS_OF', 100);

// from http://php.net/manual/en/function.microtime.php
// used later for benchmarking purpose
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

function debugPhrase($iEnclosed, $lEnclosed, $hEnclosed, $iLarger, $lLarger, $hLarger)
{
    return '('.$iEnclosed.')['.$lEnclosed.' ; '.$hEnclosed.'] is strictly enclosed at least in ('.$iLarger.')['.$lLarger.' ; '.$hLarger.']'.PHP_EOL;
}

// 2 foreach loops solution (based on user3137702's *damn good* work ;) and currently accepted answer)
function removeEnclosedIntervals_Basic($a, $debug = false)
{
    foreach ($a as $i => $valA)
    {
        $found = false;

        foreach ($a as $j => $valB)
        {
            if (($valA['l'] > $valB['l']) && ($valA['h'] < $valB['h']))
            {
                $found = true;

                if($debug)
                    echo debugPhrase(
                        $i, //                  $iEnclosed
                        $a[$i]['l'], //         $lEnclosed
                        $a[$i]['h'], //         $hEnclosed

                        $j, //                  $iLarger
                        $a[$j]['l'], //         $lLarger
                        $a[$j]['h'] //          $hLarger
                    );

                break;
            }
        }

        if (!$found)
        {
            $out[$i] = $valA;
        }
    }

    return $out;
}

// runs a benchmark with $number intervals
function runTest($number)
{
    // Generating a random set of intervals with values between MIN and MAX
    $randomSet = array();
    for($i=0; $i<$number; $i++)
        // avoiding self-closing intervals
        $randomSet[] = array(
            'l' => ($l = mt_rand(MIN, MAX-2)),
            'h' => mt_rand($l+1, MAX)
        );

    /* running the two methods and comparing results and execution time */

    // Basic method
    $start = microtime_float();
    $Basic_result = removeEnclosedIntervals_Basic($randomSet);
    $end = microtime_float();
    $Basic_time = $end - $start;

    // VirtualRule
    $start = microtime_float();
    $VirtualRule_result = removeEnclosedIntervals_VirtualRule($randomSet);
    $end = microtime_float();
    $VirtualRule_time = $end - $start;

    // Basic method works for sure.
    // If results are the same, comparing execution time. If not, sh*t happened !
    if(md5(var_export($VirtualRule_result, true)) == md5(var_export($VirtualRule_result, true)))
        echo $number.';'.$Basic_time.';'.$VirtualRule_time.PHP_EOL;
    else
    {
        echo '/;/;/;Work harder, results are not the same ! Cant say anything !'.PHP_EOL;
        stop;
    }
}

// CSV header
echo 'Number of intervals;Basic method exec time (s);VirtualRule method exec time (s)'.PHP_EOL;

for($n=TEST_BY_STEPS_OF; $n<TEST_MAX_NUMBER; $n+=TEST_BY_STEPS_OF)
{
    runTest($n);
    flush();
}

Results (for me)

*

*As I thought, clearly different performances are obtained.

*I ran the tests on a Core i7 computer with PHP5 and on a (old) AMD Quad Core computer with PHP7. There are clear differences in performance between the two versions on my systems ! which in principle can be explained by the difference in PHP versions because the computer that is running PHP5 is much more powerful...

A: A simplistic approach, maybe not exactly what you want, but should at least point you in the right direction.  I can refine it if needed, just a bit busy and didn't want to leave the question unanswered..
$out = [];

foreach ($a as $valA)
{
  $found = false;

  foreach ($a as $valB)
  {
    if (($valA['l'] > $valB['l']) && ($valA['h'] < $valB['h']))
    {
      $found = true;
      break;
    }
  }

  if (!$found)
  {
    $out[] = $valA;
  }
}

This is entirely untested, but should end up with only the unique (large) ranges in $out.  Overlaps as I mentioned in my comment are unhandled.

A: The problem was missing break in the while cycle
function dup($a){
  $c = count($a)-1;
  for ($i = $c; $i > 0; $i --){
     while ($a[$i]['h'] <= $a[$i-1]['h']){
      unset($a[$i]);
      break; //here
     }
  }
  $a = array_values($a);
}

A: Here is the code
function sort_by_low($item1,$item2){
    if($item1['l'] == $item2['l'])
        return 0;
    return ($item1['l']>$item2['l'])? -1:1;
}

usort($a,'sort_by_low');

for($i=0; $i<count($a); $i++){
  for($j=$i+1; $j<count($a);$j++){
     if($a[$i][l]<=$a[$j]['l'] && $a[$i][h]>=$a[$j]['h']){
        unset($a[$j]);
     }
  }
}

$a=array_values($a);

A: Here is the working code (Tested)
$result = array();
usort($a, function ($item1, $item2) {
    if ($item1['l'] == $item2['l']) return 0;
    return $item1['l'] < $item2['l'] ? -1 : 1;
});

foreach ($a as $element) {
    $exists = false;
    foreach ($result as $r) {
        if (($r['l'] < $element['l'] && $r['h'] > $element['h'])) {
            $exists = true;
            break;
        }
    }
    if (!$exists) {
        $result[] = $element;
    }
}

$result will contain the desired result


text:
Q: How to get autocomplete `super` on PyCharm I'm searching for an autocomplete to super function.
Usually the super is something like:
super(MyClass, self).my_func(*func_args, *func_kwargs)

It there a shortcut/macro to have it auto completed?
Many thanks!

A: Press ctrl+j to list available macros and start typing super to select autocompleteon:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure Cognitive Search - No results using wildcards on content with DOT I'm using Azure Cognitive Search to build a rich search experience inside a web application, however I'm facing the following issue: a field of the index will contains codes like "Z.A.01.12", "A.A.44.11" and so on...I'm trying to use the wildcards * as suffix in order to search all the results that starts with the value Z.A (just an example).
"Z.A.01.12" -> Z.A* => No results found.
"Z.A.01.12" -> Z.A.* => No results found.
"Z.A.01.12" -> Z\.A* => No results found.

I have tried different analyzer (standard lucene, en.microsoft, whitespace and keyword), but also when I see that exists only one token produced (for example with whitespace) with the entire content, when I query the service using wildlcard I receive "No results found".
I have already set queryType=full and searchMode=any. Furthermore I also tried to escape the . with "", but the results is always empty. Is there anything I can do to manage these cases?


text:
Q: How to add App Session data in IBM MobileFirst Analytics Console? I'm building a Cordova App and docs mention that regarding analytics: "In Cordova applications, no setup is required and initialization is built-in."
documentation
The problem is that after testing the App the Analytics Console doesn't show any App Session, although I can create custom metrics with this snippet:
 var event = {viewLoad: 'Hello'};
 WL.Analytics.log(event, 'Hello World');
 WL.Analytics.send();

How can I create session data in the Analytics Console?

A: MobileFirst 8.0 works a little differently than the previous versions of MobileFirst. Like DoraC said we changed app sessions to be recorded when the app goes from background to foreground.
You can read more about the Analytics API and Life cycle events here: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/analytics/analytics-api/
Make sure you area calling WL.Analytics.send() sometime after bringing the app back to the foreground.


text:
Q: Google Sheets - Query Multiple Columns With Custom Labels I am trying to create a simple query in my Google Sheet that will allow me to label the two columns it is outputting and sort the results based off of another column. However as soon as I add the Order By or the second Label command it throws and error. Here is my formula. Thanks for any help.
=query(A1:H,"SELECT H, SUM(G) WHERE H > '' AND G > 0 GROUP BY H ORDER BY A LABEL SUM(G) 'Sub Total', LABEL H 'Group Description'",0)

A: Try this. You can hide the query return of column A if you need to. Also note the label syntax.
=query(A2:H,"SELECT A,H, sum(G) where H is not null and G>0 group by A,H order by A asc label sum(G) 'Sub Total', H 'Group Description',A 'Col A'",1)

Here is my test spreadsheet:https://docs.google.com/spreadsheets/d/1U6OFD_bxkNu27WMFPYHcxps1SA3oH9m3jMTEdb-fiQY/edit?usp=sharing

A: You have multiple problems in the query. First, remove the second occurence of LABEL. Secondly the order of columns H and G in the data table (and the query string) should be reversed. The aggregator (coulmn on which you group by) should be on the left.


text:
Q: How to invoke a function on parent thread in .NET? I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on a new thread in order to avoid blocking the caller. But once the method finishes it should execute some code on the main thread. In a WinForms application I could have used the System.Windows.Forms.Control.Invoke method but this is not my case. So how can I achieve this in C#?

A: There's no way to explicitly make code run on a specific thread, (except for the thread that was used to create UI Controls - this is an exception) but if you simply want to call code other than the code when a thread completes, You use delegates.
First declare a delegate with the signature of the method you want to run on the new thread...
public delegate bool CheckPrimeDelegate(long n);

Then in your code, create an instance of the delegate, call it using BeginInvoke (passing any parameters it needs) and PASS a callback function delegate (OnChkPrimeDone)
class MyClassApp
{
   static void Main()
   {
      CheckPrimeDelegate ckPrimDel = new CheckPrimeDelegate(Prime.Check);

      // Initiate the operation
      ckPrimDel.BeginInvoke(4501232117, new AsyncCallback(OnChkPrimeDone), null);

      // go do something else . . . .
   }

   static void OnChkPrimeDone( IAsyncResult iAr)
   {
        AsyncResult ar = iAr as AsynchResult;
         CheckPrimeDelegate ckPrimDel = ar.AsyncDelegate as CheckPrimeDelegate;
         bool isPrime = ckPrimDel.EndInvoke(ar);
         Console.WriteLine(" Number is " + (isPrime? "prime ": "not prime");
   }
}

When it is done, it will call the callback function (OnChkPrimeDone)
If you explicitly need to run this callback function on the thread that was used to create the COM Active-X object, then check the .Net Managed Code wrapper variable that holds a reference to this object... If it has a method called InvokeRequired(), then, in your callback function, test the boolean return value of this method.
If it has InvokeRequired() method and it returns true, then the active-X object will also expose a "BeginInvoke()" Method.  Then, Create ANOTHER Delegate, populated with the same function, and call BeginInvoke
on the Active-X Object, passing it this new delegate... It will then run on the same thread as was used to create teh Active-X Object
If (MyActiveXObject.InvokeRequired())
     MyActiveXObject.BeginInvoke(...);

A: You can invoke a function on a specific thread by using a System.Windows.Threading.Dispatcher object (from the WindowsBase assembly).
For example:
public class ClassCreatedBySomeThread
{
    Dispatcher dispatcher = Dispatcher.CurrentDispatcher;

    public void SafelyCallMeFromAnyThread(Action a)
    {
       dispatcher.Invoke(a);
    }
}

A: A thread cannot just execute stuff on another thread. The closest you can get is to put a delegate on a queue for the other thread to execute, but that assumes that the other thread is cooperating about this.
In a WinForms application, the main loop looks for such queued messages on each loop iteration.
If you just need to communicate the finishing of the worker thread, you can use e.g. a flag variabe. If the main thread should be able to wait for job termination, use a semaphore or condition variable (monitor).

A: Here's my exact scenario: I have a .NET class library exposed as a COM object (using regasm.exe). The COM object contains a method that runs an external application (using Process.Start). The COM object is used in Internet Explorer. So my web page runs the external application and I need to find a way to pass the ExitCode to the web page.
At first I didn't start the external application on a new thread and just waited for the user to close the application and then my function returned the ExitCode to the caller. But while the application was running IE was not responsive. So I decided to start the application in a new thread but now I can no longer return the ExitCode.
The COM object is created with: new ActiveXObject instruction and unfortunately javascript doesn't support event sinking so I can't write an event in C# that's triggered when the application exits.

A: I found a simple solution to the problem :
My COM object is declared like this:
public class Runner
{
    public void Run(string executable, object processExitHandler)
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            var p = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = executable
                }
            };
            p.Start();
            while (!p.HasExited)
            {
                Thread.Sleep(100);
            }

            state
                .GetType()
                .InvokeMember(
                    "call",
                    BindingFlags.InvokeMethod,
                    null,
                    state,
                    new object[] { null, p.ExitCode }
                );
        }, processExitHandler);
    }
}

And in my HTML page I use it like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>ActiveXRunner</title>

    Run notepad and show exit code when finished

A: If a thread has to be able to execute some bit of code (usually in the form of a delegate) posted to it by another thread, it will have to basically be waiting for those instructions. What else is your main thread doing? It's not that hard to build an equivalent of the event loop (basically you'd have a producer/consumer queue of delegates) but you need to be aware that you can't just interrupt the main thread and say "do this now".
Why does this have to execute on the main thread?


text:
Q: Can't connect to VMs via ssh from Windows 11 PC after it's hard stop I've had an issue with my laptop network adapter (suddenly lost all connection to WIFI and Bluetooth and under the Device Manager, the Intel(R) Wi-Fi 6 AX201 160MHz there was and exclamation mark and device couldn't be started properly). I've done hard power off with pressing power button for 5-10 sec) and restart. Since then I am no able to connect via ssh.
I've a couple of Linux virtual machines on Virtual Box, trying to connect with powershell/cmd (I'm on win 11) to one with a password auth (like I previously did):
OpenSSH_for_Windows_9.1p1, LibreSSL 3.6.1
debug3: Failed to open file:C:/Users/eugen/.ssh/config error:2
debug3: Failed to open file:C:/ProgramData/ssh/ssh_config error:2
debug2: resolve_canonicalize: hostname 192.168.56.102 is address
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts' -> 'C:\\Users\\eugen/.ssh/known_hosts'
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts2' -> 'C:\\Users\\eugen/.ssh/known_hosts2'
debug3: ssh_connect_direct: entering
debug1: Connecting to 192.168.56.102 [192.168.56.102] port 22.
debug3: finish_connect - ERROR: async io completed with error: 10060, io:0344E950
debug1: connect to address 192.168.56.102 port 22: Connection timed out
ssh: connect to host 192.168.56.102 port 22: Connection timed out

And also via MobaXterm:
OpenSSH_9.0p1, OpenSSL 1.1.1q  5 Jul 2022
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 9: Deprecated option "useroaming"
debug2: resolve_canonicalize: hostname 192.168.56.102 is address
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts' -> '/home/EVIL/.ssh/known_hosts'
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts2' -> '/home/EVIL/.ssh/known_hosts2'
debug3: ssh_connect_direct: entering
debug1: Connecting to 192.168.56.102 [192.168.56.102] port 22.
debug3: set_sock_tos: set socket 4 IP_TOS 0x48
debug1: connect to address 192.168.56.102 port 22: Connection timed out
ssh: connect to host 192.168.56.102 port 22: Connection timed out

Also failed to connect to another Linux VM with a ssh-key (like I previously did):
PS C:\Users\eugen> ssh -vvv -i 'C:\Users\eugen\.ssh\id_rsa-uvm' serveru@192.168.56.101
OpenSSH_for_Windows_9.1p1, LibreSSL 3.6.1
debug3: Failed to open file:C:/Users/eugen/.ssh/config error:2
debug3: Failed to open file:C:/ProgramData/ssh/ssh_config error:2
debug2: resolve_canonicalize: hostname 192.168.56.101 is address
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts' -> 'C:\\Users\\eugen/.ssh/known_hosts'
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts2' -> 'C:\\Users\\eugen/.ssh/known_hosts2'
debug3: ssh_connect_direct: entering
debug1: Connecting to 192.168.56.101 [192.168.56.101] port 22.
debug3: finish_connect - ERROR: async io completed with error: 10060, io:03673B30
debug1: connect to address 192.168.56.101 port 22: Connection timed out
ssh: connect to host 192.168.56.101 port 22: Connection timed out

And now I got the exact same issue on another Win 11 Pro Laptop with Hyper-V VM (it's also happened after it's hard stop with holding power button for a while)
I tried to reinstall OpenSSH and restart it's services on Windows.
However, I'm able to establish ssh connection with my localhost (with OpenSSH server installed) and other fully external servers with no problem, so it seems ssh is working, but not with my "host-only" network VM's
`PS C:\Users\eugen> ssh -vvv localhost
OpenSSH_for_Windows_9.1p1, LibreSSL 3.6.1
debug3: Failed to open file:C:/Users/eugen/.ssh/config error:2
debug3: Failed to open file:C:/ProgramData/ssh/ssh_config error:2
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts' -> 'C:\\Users\\eugen/.ssh/known_hosts'
debug3: expanded UserKnownHostsFile '~/.ssh/known_hosts2' -> 'C:\\Users\\eugen/.ssh/known_hosts2'
debug2: resolving "localhost" port 22
debug3: resolve_host: lookup localhost:22
debug3: ssh_connect_direct: entering
debug1: Connecting to localhost [::1] port 22.
debug1: Connection established.`

    ssh ip172-19-0-26-cfu1id63tccg00bkr4l0@direct.labs.play-with-docker.com
The authenticity of host 'direct.labs.play-with-docker.com (40.76.55.146)' can't be established.
RSA key fingerprint is SHA256:vCbhEjmYQhtNzuuuh7TmGAPfe9T+JdGnGaVquQJUphY.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'direct.labs.play-with-docker.com' (RSA) to the list of known hosts.
Connecting to 52.188.144.191:8022
###############################################################
#                          WARNING!!!!                        #
# This is a sandbox environment. Using personal credentials   #
# is HIGHLY! discouraged. Any consequences of doing so are    #
# completely the user's responsibilites.                      #
#                                                             #
# The PWD team.                                               #
###############################################################
[node1] (local) root@192.168.0.18 ~

UPDATE: It's working after creating a new network and assigning a new IP addresses to both VM's in Network tool (at least in Virtual Box)


text:
Q: sigabrt on filteredArrayUsingPredicate I'm a noob and trying to convert an example from a book into an app I can use.
The sample app is a modified version of the contacts application and it works.
I've done some further modification, and the search no longer works.  It sigabrts on the following line
self.filteredAnswercards = [flattenedArray
                            filteredArrayUsingPredicate:predicate];

I'm stumped.
my head is bloody from beating it against my keyboard.
ANY help is massively appreciated.
Thanks.

A: My suggestion was to wrap the line that crashes inside a @try/@catch block and, inside the catch, log the exception and the result of the exception's callStackSymbols method.
For the record, part of the problem with the 4.x versions of Xcode is that they are much worse than 3.x versions at telling you where an exception is coming from.  For this reason, getting familiar with tricks that make a program or the debugger tell you what you need to know is very important.

A: Very hard to say without seeing more code.  Sigabort generally means an exception has been thrown.  You can put a break point in objc_exception_throwto get a back trace which should help highlight the cause.
If you get NO new info with the above, others have said that a full reboot of the computer can help... but I have not had a situation where I could verify this.
---- edit based on comments -----
It sounds like filteredAnswercards is nil, that will definitely cause a Sigabort.  Allocate that array properly and you should be good to go.

A: I would guess that predicate is nil.  Where did you assign it? Or did you never assign it?


text:
Q: Illegal array key This function
function convert($size) {
  $unit = array(
    'B',
    'KByte',
    'MByte',
    'GByte',
  );
  return round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}

works but PHPStorm says

 Illegal array key type on line 54

that means $unit[$i].
What's wrong with this function?

A: floor returns a float, not an integer. (Counter-intuitive, but true.) Floats are illegal keys in PHP arrays.
The code works fine, because floats are implicitly cast to integers when used as keys in an array, but I imagine that is why you are getting the notification in PHPStorm.


text:
Q: Can we create windows service from Java? Can we create windows service from Java? I want some (possibly non-Java) application to run as a service and I want to configure that from within my Java program.
Also: can we pass parameters to services? Also, please help me with deleting any existing service and restarting it on crash.
this question is not same as running java program from service its the other way round i want to create service using a java program, on server side

A: You need to install your software, right? Then advancedInstaller does this.

A: got an idea to export a registry from some already exiting hand made registry and launch it on client machine... can be given a thought :)


text:
Q: Yii2 ignore first database result is there any way to ignore the first result record in Yii2 at a query? I have a list of numbers that represents a client. For designing purposes i had to query the first record separatly but now i have it duplicated. My questin is how can I query in Yii2 to ignore the first result?
Regards,
Gábor
The second find is the query where i need to ignore the first result:
public function actionGeneratePage() {
public function actionGeneratePage() {
    $behivott = Sorszam::find()->with('ablak')
        ->orderBy(['behivas_datum' => SORT_DESC])
        ->limit(1)
        ->all();
    $sorszamok = Sorszam::find()->with('ablak')
        ->orderBy(['behivas_datum' => SORT_DESC])
        ->limit(4)
        ->all();
    $reklam = Reklam::find()->all();

    return $this->render('generatePage', [
        'sorszamok' => $sorszamok,
        'reklam'    => $reklam,
        'behivott'  => $behivott,
    ]);
}

A: You use offset() to skip the first record:
$sorszamok = Sorszam::find()->with('ablak')
    ->orderBy(['behivas_datum' => SORT_DESC])
    ->limit(4)
    ->offset(1)
    ->all();

Also you can use a single query to get both $behivott and $sorszamok with array_shift:
$sorszamok = Sorszam::find()->with('ablak')
    ->orderBy(['behivas_datum' => SORT_DESC])
    ->limit(5)
    ->all();

$behivott = array_shift($sorszamok);


text:
Q: How can I check if a xls file is editable file or not, using phpexcel? I have this input file bootstrap:

This input file only accept xls file, when I send the xls file, first I need check in php if the file is only read or not and return a specific number, because I need accept only editable files.
Example what I need:
I send a xls file, in php I check if is a editable file , if is editable file , continue with the next step, and if is not a editable file, return 3.
This is a only read file:

I work with phpexcel and when I send a only read file , I have the next error:

This is my code in php:
<?php

require "dao/daoExcel.php";
require "vendor/autoload.php";

class ControllerExcel {

    private $aDatosExcel;

    public function setDataExcel($dataexcel) {

        $estado = true;

        if($this->moverArchivo($dataexcel)==false){
            $estado = false;
        }

        if($estado == true && $this->validaHeaders($dataexcel)==false){
            $estado = false;
            return 2;
        }

        if($estado == true){
            return $this->setInsertExcel($dataexcel);
        }

    }

    public function moverArchivo($dataexcel) {

        $fileName = $_FILES["archivo"]["name"];
        $fileTmpLoc = $_FILES["archivo"]["tmp_name"];
        $aHeader = new DaoExcel();
        $excelUrl = $aHeader->getHeaderExel($dataexcel);

        $pathAndName = $excelUrl[17]['par_valor'].$fileName;

        $moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
        if ($moveResult == true) {
           return true;
        }else{
           return false;
        }

    }

    public function validaHeaders($dataexcel){

        $inputFileType = 'Excel5';
        $aHeader = new DaoExcel();
        $excelHead = $aHeader->getHeaderExel($dataexcel);
        $inputFileName = $excelHead[17]['par_valor'].$_FILES["archivo"]["name"];
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);

        $h1 = $objPHPExcel->getActiveSheet()->getCell('A1')->getValue();
        $h2 = $objPHPExcel->getActiveSheet()->getCell('B1')->getValue();
        $h3 = $objPHPExcel->getActiveSheet()->getCell('C1')->getValue();
        $h4 = $objPHPExcel->getActiveSheet()->getCell('D1')->getValue();
        $h5 = $objPHPExcel->getActiveSheet()->getCell('E1')->getValue();

        $header = $h1."###".$h2."###".$h3."###".$h4."###".$h5;

        if($excelHead[16]['par_valor'] == $header){
            return true;
        }else{
            return false;
        }

    }

    public function setInsertExcel($dataexcel){

        $inputFileType = 'Excel5';
        $aHeader = new DaoExcel();
        $excelHead = $aHeader->getHeaderExel($dataexcel);
        $inputFileName = $excelHead[17]['par_valor'].$_FILES["archivo"]["name"];
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
        $contRows = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();

        for($i=2;$i<=$contRows;$i++){
            $h1 = $objPHPExcel->getActiveSheet()->getCell('A'.$i)->getValue();
            $h2 = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getValue();
            $h3 = $objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue();
            $h4 = $objPHPExcel->getActiveSheet()->getCell('D'.$i)->getValue();
            $h5 = $objPHPExcel->getActiveSheet()->getCell('E'.$i)->getValue();
            $aDatos['ac_no']=$h1;
            $aDatos['custom_no']=$h2;
            $aDatos['nombre']=$h3;
            $aDatos['marc']=$h4;
            $aDatos['estado']=$h5;
            $aDatos['fecha_registro']=$this->setFecha();
            $aDatos['rco_oculto']=0;
            $this->aDatosExcel[]=$aDatos;
        }
        return $aHeader->insertDatosExcel($this->aDatosExcel);
    }

    private function setFecha(){

        date_default_timezone_set("America/Santiago");
        $now = time();
        putenv("TZ=America/Santiago");
        $fecha=date("Y-m-d H:i:s",$now);
        $date=date("Y/m/d H:i:s", strtotime($fecha));
        return $date;

    }

}

?>

So I see that by default,phpexcel only accept editable files , but how can I check by my self if a xls file is only read or not with phpexcel ,  and return a message?
Sorry by my english.

A: echo $objPHPExcel->getSecurity()->isSecurityEnabled() ? 'some security is enabled' : 'no security is enabled';

source


text:
Q: sqlite read back after write I have a rather baffling situation. I write to a database in an IntentService:
App.database.beginTransaction();
try {
  for (Data item : data) {
    ContentValues values = item.getValues();
    if (App.database.insertWithOnConflict(TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_IGNORE) < 1)
      App.database.updateWithOnConflict(TABLE_NAME, values, "id=?", new String[] { item.id }, SQLiteDatabase.CONFLICT_REPLACE);
  }
  App.database.setTransactionSuccessful();
}
catch (Exception e) {
  Log.i(TAG, e.toString());
}
finally {
  App.database.endTransaction();
}

with properly applied transaction calls. There are no exceptions and no rollback during the write operation. If I check the database by reading it back after this write, I get the full row count number all right: the database is populated.
Log.i(TAG, "count " + Data.getCount()); // returns correct row count
ResultReceiver receiver = intent.getParcelableExtra("receiver");
receiver.send(RESULT_INITIALIZED, null);

As soon as the writing finishes, the IntentService notifies my activity using a ResultReceiver that the writing operation took place.
private class MyResultReceiver extends ResultReceiver {

@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
  Log.i(TAG, "count " + Data.getCount()); // returns zero
}

But, if I check my database row count again in the receiver, I get a zero, the database is empty. Data.getCount() simply opens a new cursor and gets the count:
public static int getCount() throws SQLiteException {
  Cursor cursor = App.database.query(TABLE_NAME, null, null, null, null, null, null);
  int count = cursor.getCount();
  cursor.close();
  return count;
}

I'm aware of the limitations of simultaneous reads and writes (and also the WAL mode) but I don't want them to overlap. I'd simply like to be able to populate the database in the service and act upon it in the original activity. What am I doing wrong?

A: This was a nasty one, after all. A deleteDatabase() in a different part in the app startup sequence that must have been somewhat asynchronous (its source code doesn't reveal that but still). So, the database was cleared before the write and the read operations, after all. Took quite some time to track it down...


text:
Q: Homotopy of two paths whose composition is nullhomotopic Let $f, g$ be two paths in a space such that their concatenation $f * g$ is nullhomotopic. Prove that $f$ is homotopic to $g$ rel $\{0,1\}$.

A: As Rasmus points out, once you state the result correctly, it's easy -assuming you've already proved some elementary properties of homotopy.
Namely, let $f,g$ be two loops with $f(0) = g(0) = f(1)= g(1) = x_0$ and such that $g^{-1}*f \sim 1$, where $1$ is the constant path at $x_0$.
Then $f\sim 1* f \sim (g*g^{-1})*f \sim g* (g^{-1}*f) \sim g*1  \sim g$.
Exercise. Which "elementary properties of homotopy" have we used and where?


text:
Q: Select with subquery avoid running more than once? I have a query like this
Select
     Col_A
    ,Col_B
    ,Col_C
    ,CASE
        WHEN (SELECT ...{a very complicated query}...) IS NOT NULL THEN 1
        ELSE 0
     END CASE AS Col_D
FROM
    MyTable

The subquery that produces Col_D returns an integer when it is not null.
I need to show the BIT that Col_D is, but I also need to show the INT that it returns. Normally, I would just rewrite the subquery and call it Col_E, but given it's complexity, I don't really want to run it twice. Ideally, I would have:
Select
     Col_A
    ,Col_B
    ,Col_C
    ,(SELECT ...{a very complicated query}...) AS Col_E
    ,CASE
        WHEN Col_E IS NOT NULL THEN 1
        ELSE 0
     END CASE AS Col_D
FROM
    MyTable

Do I have any options? (MS SQL 2008)
EDIT:
Sorry - I should have mentioned that the complicated query includes a where clause based on my columns i.e.
SELECT ...{a very complicated query}... WHERE X = Col_A AND Y = Col_B

A: So if the results of your query are only a single value or null, you could use:
Select
     Col_A
    ,Col_B
    ,Col_C
    ,CASE
        WHEN t.whatevercol IS NOT NULL THEN 1
        ELSE 0
     END CASE AS Col_D,
    t.whatevercol
FROM
    MyTable, (SELECT ...{a very complicated query}...) t

Do be careful as this could result in a cartesian product though if there are potential multiple returns.  If there are fields you can join on, that might be a better approach (and since you're checking for NULL, you may need an OUTER JOIN).

A: You can nest the query that returns Col_E in another SELECT, and add Col_D on top of it, like this:
SELECT
     Col_A
    ,Col_B
    ,Col_C
    ,Col_E
    , CASE
        WHEN Col_E IS NOT NULL THEN 1
        ELSE 0
     END CASE AS Col_D
FROM (
    Select
         Col_A
        ,Col_B
        ,Col_C
        ,(SELECT ...{a very complicated query}...) AS Col_E
    FROM
        MyTable
) X

This way you would not need to copy the query, because its result would be available to the outer SELECT.


text:
Q: C : printf with only string format as argument int main()
    {

       printf("Hello World!");
       printf("%s");//printing Hello World again why?

    }

This code prints "Hello World!" twice. Why is it happening like this?

A: printf("%s") causes undefined behaviour.
Once you have that line in your program, your entire program becomes undefined and could do or not do anything.
Most likely, by complete luck, your stack still contains pointer to the literal string from the previous call so the function still is able to execute correctly.


text:
Q: QT C++ Reading Custom File Structures How would I read and store the data of a line of text in a text file for example that went like:
Bob 13 14 21
In other words how would I set a string variable equal to Bob, and then two integer variables for 13 and 14 if that was the line from a text file. I would really appreciate any input.

A: There are two paradigms for this:  1) let the object read its members; 2) have a function read the members.
With the first paradigm, you overload the stream extraction operator>> to input each field in the object.  This should be recursive for non-POD members in the class.
Templates can be used to overload operator>> for reading types.
You could also search and read about "serialization".


text:
Q: Need a powershell script to use a parameter to manipulate/read in fields from another csv file I have and existing PowerShell script (not written by me!) which is designed to use a passed-in parameter (SCOM Alert ID) to then set additional information in the alert, e.g. $alert.CustomField1 = $alert.PrincipleName etc etc.
I am looking to add functionality to this script to be able to add additional 'custom' information which is stored in a separate text/CSV file.  The text/CSV file has header line
ServerName,ServiceOwner,Application Tier

so a row in the file would be
MYSERVER.CONTOSO.COM,Joe Bloggs, Tier 1

There will be one unique row for each server in our environment (over 600 rows).
So what I need to do is using the passed-in alert ID. I can use $alert.PrincipleName to find the corresponding row in the text file and pull in the additional details stored in field 2 and 3, i.e. ServiceOwner and ApplicationTier.
This logic holds for the majority of alerts but IF server name is a specific value (e.g. MYSTSERVER.CONTOSO.COM) then instead of using $alert.PrincipleName to match servername in text file, I need to match on another alert property $alert.MonitoringObjectDisplayName. However, the server name in this field is part of a larger string in the format, e.g. User Services Watcher for Pool [MYTARGETSERVER.CONTOSO.COM] - so I need to extract the severname from between the square brackets  of the string to then perform the match with the text file.
Hopefully I have explained what I'm trying to do clearly - if not I'm happy to provide further clarification and can also post up the existing PS Script I'm trying to modify if thats any help.

A: You can react to the server name like this:
$csv = Import-Csv 'C:\path\to\your.csv'
...
if ( $alert.PrincipalName -eq 'MYSTSERVER.CONTOSO.COM' ) {
  if ( $alert.MonitoringObjectDisplayName -match '.*\[(.*?)\]' ) {
    $targetserver = $matches[1]
  }
} else {
  $targetserver = $alert.PrincipalName
}

$newdata = $csv | ? { $_.ServerName -eq $targetserver } `
                | select ServiceOwner, 'Application Tier'
...
$alert.CustomField2 = $newdata.ServiceOwner
$alert.CustomField3 = $newdata.'Application Tier'
...


text:
Q: Floating Information About Words it's possible to make a latex pdf , such that when the mouse points some word in the pdf, appears a floating information about it, like when we put the mouse over "Disco Local (D:)" and appears that information about the free space in the disk.
It's not necessarily for me use Latex, but there is a way to do it???

Thanks.


text:
Q: Как в JBoss AS увеличить heap space? После нескольких часов работы наблюдаю в логах вот такой message:
2012-12-28 09:01:33,732 ERROR [STDERR] 2012-12-28 09:01:33,728 [ERROR] org.springframework.integration.message.MessageHandlingException: method 'public void my_package.MyClass.myMethod(java.io.File)' threw an Exception.
        at org.springframework.integration.handler.MessageMappingMethodInvoker.invokeMethod(MessageMappingMethodInvoker.java:113)
        at org.springframework.integration.handler.ServiceActivatingHandler.handleRequestMessage(ServiceActivatingHandler.java:49)
        at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:91)
        at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:59)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:103)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:90)
        at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:43)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:116)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:94)
        at org.springframework.integration.channel.MessageChannelTemplate.doSend(MessageChannelTemplate.java:224)
        at org.springframework.integration.channel.MessageChannelTemplate.send(MessageChannelTemplate.java:181)
        at org.springframework.integration.router.AbstractMessageRouter.handleMessageInternal(AbstractMessageRouter.java:114)
        at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:59)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:103)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:90)
        at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:43)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:116)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:94)
        at org.springframework.integration.channel.MessageChannelTemplate.doSend(MessageChannelTemplate.java:224)
        at org.springframework.integration.channel.MessageChannelTemplate.send(MessageChannelTemplate.java:181)
        at org.springframework.integration.router.AbstractMessageRouter.handleMessageInternal(AbstractMessageRouter.java:114)
        at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:59)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:103)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:90)
        at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:43)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:116)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:94)
        at org.springframework.integration.channel.MessageChannelTemplate.doSend(MessageChannelTemplate.java:224)
        at org.springframework.integration.channel.MessageChannelTemplate.send(MessageChannelTemplate.java:181)
        at org.springframework.integration.endpoint.SourcePollingChannelAdapter.doPoll(SourcePollingChannelAdapter.java:78)
        at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.innerPoll(AbstractPollingEndpoint.java:232)
        at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.poll(AbstractPollingEndpoint.java:216)
        at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:209)
        at org.springframework.integration.scheduling.SimpleTaskScheduler$ErrorHandlingRunnableWrapper.run(SimpleTaskScheduler.java:307)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
        at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
        at org.springframework.integration.scheduling.SimpleTaskScheduler$TriggeredTask.run(SimpleTaskScheduler.java:256)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.OutOfMemoryError: Java heap space
 at org.springframework.integration.handler.LoggingHandler.handleMessageInternal(LoggingHandler.java:83)

Вопрос, как увеличить heap space?
A: Чтобы понять какую из опций нужно "подкрутить" я рекомендую хорошую статью на Хабре: Какие бывают типы OutOfMemoryError или из каких частей состоит память java процесса
Т.о. для устранения Java heap space нужно тюнить -Xms и -Xmx
Далее рождается следующий вопрос: как это сделать в JBoss? Зависит от того как вы его запускаете. Например, если скриптом, например, так:
/opt/jboss-as/bin/standalone.sh

То варианта (как минимум) два:

*

*указать необходимые опции в командной строке: JAVA_OPTS='-Xmx512m' /opt/jboss-as/bin/standalone.sh

*установить JAVA_OPTS в конфигурационном файле (/opt/jboss-as/bin/standalone.conf в моём случае)

P.S. А Spring тут не причем.


text:
Q: Find strings from a list starting with strings in another list I have two list listOne & listTwo
e.g.
listOne could contain 'about', 'day', 'school'
listTwo could contain 'a','c','da','z'
I want to find out all the elements in listOne which start with characters from elements in listTwo. The output with above example is 'about' and 'day'
I try to implement it with following code:
for elem1 in listTwo:
    for elem2 in listOne:
        if elem2.startswith(elem1):
            result.append(elem2)

but I feel it nested too much. Is there a more elegant way to achieve it in Python?

A: The way that you're doing it is fine.  It's easy to read/understand, etc.
However, if you really want, you can probably condense it down using itertools.product:
from itertools import product
result = [elem2 for elem1, elem2 in product(listTwo, listOne) if elem2.startswith(elem1)]

A: You can pass a tuple to str.startswith method.
From the doc:

str.startswith(prefix[, start[, end]]): Return True if string starts
  with the prefix, otherwise return False. prefix can also be a tuple of
  prefixes to look for. With optional start, test string beginning at
  that position. With optional end, stop comparing string at that
  position.

But this is supported in Python 2.5+
tuple_listTwo = tuple(listTwo)

[ele for ele in listOne if ele.startswith(tuple_listTwo)]

Output:

['day', 'about']


text:
Q: How to use WinDbg to debug a driver I'm following this article https://msdn.microsoft.com/en-us/library/windows/hardware/mt269367(v=vs.85).aspx and I've gotten to the step where you run the command to start WinDbg.
WinDbg –k net:port=50000,key=1.2.3.4
However, when WinDbg restarts it is stuck on "Waiting to reconnect..." and it shows "Debugee not connected" at the bottom. I've tried unplugging the Ethernet cable multiple times as well as restarting the target multiple times. I can also ping the host computer from the target. Oddly, I can't ping the target from the host.
The host machine is running Windows 7 and the target machine is Windows 8.

A: So I turned off the firewall on the host and it started to work.


text:
Q: Connection timeout to streams.canonical.com when installing juju The .cloud-install/commands.log file shows this error:
Attempt 5 to download tools from https://streams.canonical.com/juju/tools/agent/1.25.3/juju-1.25.3-trusty-amd64.tgz...
curl: (7) Failed to connect to streams.canonical.com port 443: Connection timed out

It attempts to download the tar file five times and then fails.
This is where the node stops and nothing happens here after.
The complete log file is available at: http://paste.ubuntu.com/15390451/

A: Solved it!!!!
Seems like for JUJU bootstrap to work IP forwarding needs to be enabled on MAAS server.
Refer: https://github.com/Ubuntu-Solutions-Engineering/openstack-installer/issues/901


text:
Q: Continuity of the argument of a complex number. The argument of the complex number $x-i$ (real $x$) can be found using angle($x$,-1) in Wolfram Alpha. I asked WA if angle($x$,-1) is a continuous at $x=0$ it replied YES and drew a graph showing a discontinuity at zero. Yet when asked to find the left/right limits of angle($x-i$) at zero it returns $-\pi$ and $\pi$ (as does my ti-nspire CAS). Can anyone throw some light on this discrepancy in WA ?

A: The complex number $x-i\in{\mathbb C}$, where $x\in{\mathbb R}$, can be viewed as a vector emanating at $i$and having its tip at $x$. The signed angle from the negative $y$-axis to this vector   is $=\arctan x$, and goes from $-{\pi\over2}$ to ${\pi\over2}$ as $x$ goes from $-\infty$ to $\infty$ It follows that the argument of this vector with respect to the positive $x$-direction is given by
$${\rm Arg}(x-i)=\arctan x-{\pi\over2}\qquad(-\infty<x<\infty)\ ,$$
and is continuous on all of ${\mathbb R}$. I cannot help you with the idiosyncrasies of WA.

A: A single-valued function is continuous at a point ONLY if the negative and positive limits and the function output at that point all agree: No ifs, no buts!!
WA throws up many whacky answers, in fact, there is a whole (big) section devoted to WA on this site.
Ask yourself this buddy, if online-WA is so good why is it free but they ask you to sign up for a premium version. WA is based on MATHEMATICA which costs hundreds of green-backs(there ain't no such thing as a free lunch). If you want better solutions buy MATHEMATICA; online WA is there to draw you in so you buy the premium version or go the full hog with MATHEMATICA.


text:
Q: Magento cart can only take one item (1 quantity per product) I'm working on a page with Magento!
When I try to Add to my Card a product with quantity more than 1, it comes to my Card with quantity 1...
How can this problem be solved???

A: Take a look at my answer at https://magento.stackexchange.com/questions/38523/magento-cart-can-only-take-one-item-1-quantity-per-product
There are 2 qty input field on your page that been submitted see debug below.
You need to remove one of them


text:
Q: Expectation of the "truncated" partial sum of random variables Suppose $X_i, i = 1,2,..., N$ are i.i.d. nonnegative random variables. Given any constant $C > 0$, can I prove the following?
$\mathbb{E}[\sum_{n=1}^N(C - \sum_{k=1}^nX_i)^+] - \sum_{n=1}^N(C - \sum_{k=1}^n\mathbb{E}[X_i])^+$ is $\mathcal{O}(\sqrt{N})$, where $(a)^+ = \max\{a, 0\}$.

A: $$\mathbb{E}[\sum_{n=1}^N(C - \sum_{k=1}^nX_i)^+] - \sum_{n=1}^N(C - \sum_{k=1}^n\mathbb{E}[X_i])^+ = \sum_{n=1}^N\mathbb{E}(C - \sum_{k=1}^nX_i)^+] - \sum_{n=1}^N(C - \sum_{k=1}^n\mathbb{E}[X_i])^+ = \sum_{n=1}^N[\mathbb{E}(C - \sum_{k=1}^nX_i)^+ - (C - \sum_{k=1}^n\mathbb{E}[X_i])^+]$$
To prove that it is $O(\sqrt{N})$ it is sufficient to prove, that $\mathbb{E}(C - \sum_{k=1}^nX_i)^+ - (C - \sum_{k=1}^n\mathbb{E}[X_i])^+$ is $O(\frac{1}{\sqrt{n}})$. Moreover, it is sufficient to prove that for $\mathbb{E}(C - \sum_{k=1}^nX_i)^+$ as $(C - \sum_{k=1}^n\mathbb{E}[X_i])^+ = 0$ for large $n$.
$\mathbb{E}\sqrt{n}(C - \sum_{k=1}^nX_i)^+ \leq C\sqrt{n}P(\sum_{k=1}^nX_i < C) \leq C\sqrt{n}P(|\sum_{k=1}^nX_i - nEX_1| > |C - n EX_1|) \leq C\sqrt{n}\frac{nDX_1}{|C - nEX_1|^2}$
by Chebyshev inequality.
And that value is indeed bounded.


text:
Q: ESLint - Angular2 Anotations I use ESLint and gulp-eslint. Is there a way to activate linter rules for Angular2 anotations?
@Component( {
  selector: 'example',
  styleUrls: ['app.css'],
  templateUrl: 'app.html', //Linter should warn cause the semicolon
})
//Linter should warn in case of a blank line between componente and class

export class App {

}

A: You could use eslint-plugin-angular to get Angular-specific rules for ESLint. From there, if you want specific rules that don't yet exist, you could see about adding them to the plugin.
plugins:
    - angular

rules:
    # Whichever rules you like

globals:
    angular: true

settings:
    angular: 2


text:
Q: What is the target of legacy directory I am confused about the locations that I can write on Android devices of all Android version
I can't understand the target of /storage/emulated/legacy I checked it and found that I can write on it, What the difference between it and /storage/emulated/0

A: i read this has relation with the  version  JellyBeanant 4.2 the new Multi-user functionality.
storage/emulated/legacy:  this directory always pointing to the directory to the currently logged-in user.
storage/emulated/0:  is for device owners.
And probably you have the same files because just have 1 account in the device and is the same the user and the owner.
This link hace more information about legacy and 0


text:
Q: Value not getting pass from variable in string in PLSQL I have a For loop in plsql and a procedure.
Inside the procedure I have IF block :
 IF c.payer='GCC' and  c.dataset='SAME' then
EMPID:=REGEXP_SUBSTR(c.hitablename,'[^_]+',1,4);
vbquery:='
Insert /*parallel(unk_codes)*/ into unk_codes(act_nbr, hitablename, groupid, payer)
select /* parallel(a,4) */ distinct '''||EMPID||'0100'' as  unknown_codes,'''||c.hitablename||''' as hitablename,
REGEXP_SUBSTR('''||c.hitablename||''',''[^_]+'',1,4) as groupid,'''||c.payer||''' as payer  from HI0777777.'||c.hitablename||' a
where '''||EMPID||'0100'' in  (select NVL(b.ACC_NUM,''NOT'') from group_abc b where
'''||EMPID||'0100'' = b.ACC_NUM
        AND
REGEXP_SUBSTR('''||c.hitablename||''',''[^_]+'',1,4)=b.group_id)';
BEGIN
EXECUTE IMMEDIATE vbquery;
EXCEPTION WHEN OTHERS THEN
Dbms_Output.put_line('GCC SAME block'||SQLERRM||vbquery||c.ai_table);
END;
END IF;

I want to pass EMPID inside the vbquery string but I am getting ORA-00936: missing expression error.
I tried to debugged and see what is the problem and I found EMPID value not getting replaced inside vbquery.
My vbquery is being printed as:
 ORA-00936: missing expression
Insert /*parallel(unk_codes)*/ into unk_codes(act_nbr, hitablename, groupid, payer)
select /* parallel(a,4) */ distinct  unknown_codes,'HI_SAME_GCC_MPD' as hitablename,
REGEXP_SUBSTR('HI_SAME_GCC_MPD','[^_]+',1,4) as groupid,'GCC' as payer  from HI0777777.HI_SAME_GCC_MPD a
where not exists (select 1 from group_abc b where b.acc_num= and
REGEXP_SUBSTR('HI_SAME_GCC_MPD','[^_]+',1,4)=b.group_id)

My EMPID may be 'ABCD'.
So my expected output was:
  Insert /*parallel(unk_codes)*/ into unk_codes(act_nbr, hitablename, groupid, payer)
    select /* parallel(a,4) */ distinct  'ABCD0100' unknown_codes,'HI_SAME_GCC_MPD' as hitablename,
    REGEXP_SUBSTR('HI_SAME_GCC_MPD','[^_]+',1,4) as groupid,'GCC' as payer  from HI0777777.HI_SAME_GCC_MPD a
    where not exists (select 1 from group_abc b where b.acc_num='ABCD0100' and
    REGEXP_SUBSTR('HI_SAME_GCC_MPD','[^_]+',1,4)=b.group_id)

Why is that EMPID value not getting passed in string?

A: I think you're looking in a wrong place in code. In the plsql-example I see the following part in the query you're trying to build
... where '''||EMPID||'0100'' in  (select NVL(b.ACC_NUM,''NOT'') from group_abc b where...

but in the debug result of your query there is a part which is completely different and shouldn't be there at all
... where not exists (select 1 from group_abc b where b.acc_num= and ...

I'm pretty sure there is another branch in the "if" or something similar to that

A: You didn't say what values are involved so I tried to guess; also, I don't have your tables so I skipped a loop and used local variables instead.
It seems that either

*

*c.hitablename doesn't look as you think it does, or

*REGEXP_SUBSTR (which is used to set EMPID's value) doesn't work as you think it does as it returns an empty string, not e.g. ABCD (as you expected)

Because, if hitablename is something like in my example (X_Y_Z_ABCD), then the final insert statement looks OK:

SQL> set serveroutput on
SQL> DECLARE
  2     c_hitablename  VARCHAR2 (20) := 'X_Y_Z_ABCD';   --> this isn't what you think it is ...
  3     c_payer        VARCHAR2 (20) := 'xxxx';
  4     EMPID          VARCHAR2 (20);
  5     vbquery        VARCHAR2 (1000);
  6  BEGIN
  7     EMPID :=                                        --> ... or this doesn't do what you think it does
  8        REGEXP_SUBSTR (c_hitablename,
  9                       '[^_]+',
 10                       1,
 11                       4);
 12     vbquery :=
 13           '
 14  Insert /*parallel(unk_codes)*/ into unk_codes(act_nbr, hitablename, groupid, payer)
 15  select /* parallel(a,4) */ distinct '''
 16        || EMPID
 17        || '0100'' as  unknown_codes,'''
 18        || c_hitablename
 19        || ''' as hitablename,
 20  REGEXP_SUBSTR('''
 21        || c_hitablename
 22        || ''',''[^_]+'',1,4) as groupid,'''
 23        || c_payer
 24        || ''' as payer  from HI0777777.'
 25        || c_hitablename
 26        || ' a
 27  where '''
 28        || EMPID
 29        || '0100'' in  (select NVL(b.ACC_NUM,''NOT'') from group_abc b where
 30  '''
 31        || EMPID
 32        || '0100'' = b.ACC_NUM
 33          AND
 34  REGEXP_SUBSTR('''
 35        || c_hitablename
 36        || ''',''[^_]+'',1,4)=b.group_id)';
 37
 38     DBMS_OUTPUT.put_line (vbquery);
 39  END;
 40  /

Insert /*parallel(unk_codes)*/ into unk_codes(act_nbr, hitablename, groupid,
payer)
select /* parallel(a,4) */ distinct 'ABCD0100' as
unknown_codes,'X_Y_Z_ABCD' as
hitablename,
REGEXP_SUBSTR('X_Y_Z_ABCD','[^_]+',1,4) as groupid,'xxxx' as payer
from HI0777777.X_Y_Z_ABCD a
where 'ABCD0100' in  (select NVL(b.ACC_NUM,'NOT')
from group_abc b where
'ABCD0100' = b.ACC_NUM

AND
REGEXP_SUBSTR('X_Y_Z_ABCD','[^_]+',1,4)=b.group_id)

PL/SQL procedure successfully completed.

SQL>

Formatted:
INSERT                                                 /*parallel(unk_codes)*/
       INTO unk_codes (act_nbr,
                       hitablename,
                       groupid,
                       payer)
   SELECT                                                  /* parallel(a,4) */
          DISTINCT 'ABCD0100' AS unknown_codes,
                   'X_Y_Z_ABCD' AS hitablename,
                   REGEXP_SUBSTR ('X_Y_Z_ABCD',
                                  '[^_]+',
                                  1,
                                  4) AS groupid,
                   'xxxx' AS payer
     FROM HI0777777.X_Y_Z_ABCD a
    WHERE 'ABCD0100' IN (SELECT NVL (b.ACC_NUM, 'NOT')
                           FROM group_abc b
                          WHERE     'ABCD0100' = b.ACC_NUM
                                AND REGEXP_SUBSTR ('X_Y_Z_ABCD',
                                                   '[^_]+',
                                                   1,
                                                   4) = b.GROUP_ID)

Finally: what do you think those /*parallel(unk_codes)*/ thingies do? I bet you thought query will run faster if you executed it with that hint, didn't you? Bad news for you - what you put in here is just a comment, not a hint. Oracle suggests us (developers) not to use hints if we don't know what they do and how to properly use them. You, apparently, don't as you made the same mistake twice (so it wasn't a typo). Therefore, you can remove those comments out of your code (or use a hint if you really want to, but then use proper syntax).


text:
Q: angularjs add years to max datetime-local via controller I'm wondering if anybody had this issue:
In an input datetime-local I want to set the min and the max values in relation with today.
Everything is fine for today (min):
var nowDate = Date.now();
$scope.spectacle.nowDate = $filter('date')(nowDate, 'yyyy-MM-ddTHH:mm');

But I really don't understand how to add 10 years from now to my max attribute.  I tried a lot of things found on websites but nothing is working out.
Note that it's not critical that we see the real day 10 years from now (leap years calculation...) because I just want a big range for my validation.
EDIT: On a side note: is it the best practice to use the type="datetime-local" for datepicking?  If not, what would constitue the "best and most reliable" way to do that kind of thing in angular (choose a date with min max validation and a time (hour/minute))?
Thanks for any help.

A: You're just looking for the JavaScript version of adding 10 years to the current date?
var date = new Date();
// Tue Sep 23 2014 17:12:55 GMT-0400 (Eastern Daylight Time)
date.setYear(date.getFullYear()+10)
// Mon Sep 23 2024 17:12:55 GMT-0400 (Eastern Daylight Time)


text:
Q: how to get string array from response in nsurlconnction (of wcf web srvice)? I created wcf soap service, which contains one method and it returns string array...
I call that service in ios(in xcode objective c) application, but it returns the response as xml.
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><IMethodNameResponse xmlns="http://tempuri.org/">

how can i get string array from response result ?

A: You have several options here.
First one is to parse that XML with NSXMLParser. You need to know XML structure and create object for each XML document. This object must implement NSXMLParserDelegate protocol.
Another one is to use XPath to get exactly what you want from XML document. Here is XPath example. This doesn't require any third-party libraries to include in your project but if you OK with third-party, you could check this library and tutorial XML Tutorial for iOS.
And the last option is WCF itself. You could try to switch to JSON in WCF.


text:
Q: How does ChunkMessageChannelItemWriter collect replies in spring batch remote chunking? I am trying to implement remote chunking in spring batch using spring integration and amqp (rabbitmq).
I am not able to understand how does ChunkMessageChannelItemWriter collect replies in remote chunking test below
https://github.com/spring-projects/spring-batch/blob/master/spring-batch-integration/src/test/resources/org/springframework/batch/integration/chunk/RemoteChunkStepIntegrationTests-context.xml
How does it work ? Does it send one message, wait for its reply, receives its reply and Then again second message, wait for second message reply and receives second message reply and so on ?
Or it sends all messages asynchronously and wait for replies and then receives replies as they arrives on reply channel ?
If we refer to remote chunking documentation here
http://docs.spring.io/spring-batch/reference/html/springBatchIntegration.html#asynchronous-processors
it uses inbound and outbound adapters. If ChunkMessageChannelItemWriter receives replies why do we need adapters ? and at slave side why adapters and service activator both are used?
Can anybody please help me to understand how it works as its difficult to understand from documentation.

A: That is just a test case - everything runs locally - look at the JMS test case for a more real-world example. The channel item writer sends all the chunks to JMS using an outbound channel adapter.
The remote side (jms listener container) receives the chunks, processes them and sends the replies to the replies queue.
Each time the writer is called to write a chunk, it checks for replies and suspends, if necessary, if the throttle limit is exceeded.
When all chunks are written, in afterStep(), it waits for the rest of the results.
This all works the same with the local test case because the chunk handler writes the replies to a queue channel.


text:
Q: List listObject = new ArrayList()? So many time I have seen that instantiation of Arraylist is done in the manner "
List<Object> listObject = new ArrayList<Object>();

So I am wondered that what is the significance of instantiation of Arraylist in this way? What happens if we instantiate ArrayList() like
ArrayList<Object> listObject = new ArrayList<Object>();

A: List is an interface , ArrayList class is a specific implementation of that interface.
List<Object> listObject = new ArrayList<Object>();

With this you can change the List implementation in future. List listObject can invoke all the methods declared in the List interface. In future , if you don't want the ArrayList implementation of the List, and change it with say a LinkedList , you can do that :
List<Object> listObject = new LinkedList<Object>();

You will not have to alter the code which uses listObject , if you had declared the listObject as List interface type, and not worry about it breaking the rest of the code because you might have used something specific to ArrayListwith this declaration:
ArrayList<Object> listObject = new ArrayList<Object>();

This is called Programming to an interface, not to an implementation.

A: This is because of the fact that its always a good practice to write code to interface and not implementation. So when you do List<Object> listObject = new ArrayList<Object>(); you always have the liberty to change ArrayList to LinkedList and elsewhere in the code will need no change. So programming to interface (List) here gives you the liberty/power to change the underlying implementation without affecting other places in code. I will suggest you to read this small note to have more clarity.

A: Most of answers refer to the mantra of "coding to the interface". Although, it is a sound advice, it might lead to some problems. Specifically, in case of List the user of object listObject would not know anything about the efficiency of the underlying data structure. For example, if this is an instance of ArrayList then getting the last element is only O(1), while if it is a LinkedList then it is O(listObject.size).
Therefore, often it is very important to know the exact underlying data structure, which can be achieved by using the implementation type for variable declaration. For instance, Scala's List is a class that make its data structure explicit.
Thus, I would say that as always, the decision should be an informed one and cater toward the design of your application. If the data structure should be "a list" and no requirements for specific implementation is known then use List for declaration. However, if a set of algorithms that should work on that data structure is well known then use a concrete implementation class (i.e. ArraysList, LinkedList) that would ensure optimal performance of those algorithms.

A: There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
 List myList = new ArrayList();

you can only call methods and reference members that belong to List class. If you define it as:
ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.
Nevertheless, when you call a method of a List class in the first example, which was overridden in ArrayList, then method from ArrayList will be called not the one in the List.
That's called polymorphism.

A: This will ,"Program to an interface and not to an Implementation"
Please have a look at this and this

A: List is an interface, and ArrayList is a class. Best practices say: Program against interfaces, not concrete classes.
Actually, there may be no difference between those two definitions (defining the variable type as interface vs class), but using List makes your code dependent on the interface, not the class. Then you can later change the actual type of the variable, without affecting the code that is using the variable.

A: Because you can use different implementations of the same interface(in this case you may want to change your List implementation to a linkedList instead of an ArrayList ) without changing code.
Why should the interface for a Java class be preferred?

A: As of Java 7 these are the known implementations of List

All Known Implementing Classes:
   AbstractList, AbstractSequentialList,
  ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList,
  RoleUnresolvedList, Stack, Vector

Leaving aside the Abstract classes what this means is that in the future if you want to plug in a different List implementation other than ArrayList you have a variety of options.
Also called Coding to Interfaces this is a widely used programming paradigm.

A: When you use List you use Abstraction.  Imaging a case wherein there is function call expects List<Object>
List<Object> myList = myFunction();

now in function myFunction(),
its better to use
List<Object> myList = new ArrayList<Object>();
return myList;

than
ArrayList<Object> myList = new ArrayList<Object>();

because you will avoid unnecessary casting. The calling function only expects a List irrespective of its implementation.
Moreover, List interface offers a lot of generic functions which are applicable for all the implementations. So you can write some generic code manipulating a list irrespective of whether its LinkedList or ArrayList. This is the advantage of using Abstraction.

A: List is an Interface. when ever you define interface as reference we have to instantiate using it's implementation.


text:
Q: Javascript: if string.charAt doesn't equal a-z or A-Z I'm struggling with a simple problem. I want to instruct a for loop to return string.charAt(i) if string.charAt(i) is not either A-Z or a-z. I'm sure there's a basic regex statement but for the world of me I can't think what it is.
It's for the final else if in this code (the first two ifs are checking against an a-z string and an A-Z string:
for (var j = 0; j < 26; j++) {
  if (message.charAt(i) === lowercase.charAt(j)) {
    output += (j + 13 > 26) ? (lowercase.charAt((j + 13) - 26)) : (lowercase.charAt((j + 13)));
  }
  else if (message.charAt(i) === uppercase.charAt(j)) {
    output += (j + 13 > 26) ? (uppercase.charAt((j + 13) - 26)) : (uppercase.charAt((j + 13)));
  }
  else if (message.charAt(i) != XXXX) {
    output += message.charAt(i);
  }
}

}
Thanks for any help!


text:
Q: Is LastViewedDate field is always present on an object? We always get an error when we try to query LastViewedDate field on an object whose tab has not been created yet. As soon as we create a tab, the error goes away.
Just outta curiosity -
Is it like Salesforce keeps this field as disabled till an object's tab is created or something else is happening. Any ideas ?

A: LastViewedDate is stored as part of the tab. Its importance is not in data analysis by developers, but providing meaningful subsets of records in the UI, per user. See also sfdcfox's answer here.


text:
Q: How to login using 'ion auth'? Regarding 'ion auth', there is an error when I try to login. My status field in db is 1. When I click the login button, an "Account is inactive"  message appears on my auth page. Why am I getting this message?
My ion_auth_model.php:
   public function login($identity, $password, $remember=FALSE)
{
    $this->trigger_events('pre_login');

    if (empty($identity) || empty($password))
    {
        $this->set_error('login_unsuccessful');
        return FALSE;
    }

    $this->trigger_events('extra_where');

    $query = $this->db->select($this->identity_column . ', teacher_username, teacher_email, teacher_id, teacher_password, teacher_role, teacher_name, status, last_login')
                      ->where($this->identity_column, $this->db->escape_str($identity))
                      ->limit(1)
                      ->get($this->tables['users']);

    if($this->is_time_locked_out($identity))
    {
        //Hash something anyway, just to take up time
        $this->hash_password($password);

        $this->trigger_events('post_login_unsuccessful');
        $this->set_error('login_timeout');

        return FALSE;
    }

    if ($query->num_rows() === 1)
    {
        $user = $query->row();

        $password = $this->hash_password_db($user->teacher_id, $password);

        if ($password === TRUE)
        {
            if ($user->status == 0)
            {
                $this->trigger_events('post_login_unsuccessful');
                $this->set_error('login_unsuccessful_not_active');

                return FALSE;
            }

            $this->set_session($user);

            $this->update_last_login($user->teacher_id);

            $this->clear_login_attempts($identity);

            if ($remember && $this->config->item('remember_users', 'ion_auth'))
            {
                $this->remember_user($user->teacher_id);
            }

            $this->trigger_events(array('post_login', 'post_login_successful'));
            $this->set_message('login_successful');

            return TRUE;
        }
    }

    //Hash something anyway, just to take up time
    $this->hash_password($password);

    $this->increase_login_attempts($identity);

    $this->trigger_events('post_login_unsuccessful');
    $this->set_error('login_unsuccessful');

    return FALSE;
}

A: Do you have a value within the empty forgotten_password_code field?
When the field is not empty, the user could be inactive.


text:
Q: Syntax errors in if/else statement I am very new to c# and while working on a basic program I am receiving this error(Error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement) and cannot figure out why it is appearing.
if (pizzaDiameter >= 12 && pizzaDiameter < 16)// begin nested if statement
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 8 slices.");
}
else if (pizzaDiameter >= 16 && pizzaDiameter < 24)//Second pizza diameter range
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 12 slices.");
}
else if (pizzaDiameter >= 24 && pizzaDiameter < 30)
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 16 slices.");
}
else (pizzaDiameter >= 24 && pizzaDiameter <= 30)
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 24 slices.");
}
else // pizza diameter was not a whole number
{
    Console.WriteLine("Pizza diameter must be between 12-36 inclusive.");// Error appears here.
}
else //pizza diameter must be between 12-36
{
    Console.WriteLine("Pizza diameter must be a whole number.");
}

A: There's something wrong with your control structure, i.e. you've got only one if(), but three times else.
Also, try to think about the problem and you'll notice that you can simplify the whole structure significantly (and also skip many checks):
if (pizzaDiameter < 12) // All diameters below 12 will use this branch.
    Console.WriteLine("Your pizza seems to be too small.");
else if (pizzaDiameter < 16) // You don't have to ensure it's bigger than 12, since those smaller already picked the branch above.
    Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 8 slices");
else if (pizzaDiameter < 24) // Again you won't have to care for less than 16.
    Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 12 slices");
// ...
else
    Console.WriteLine("Your pizza seems to be too big.");


text:
Q: WP7 list width issue when orientation changs I want to make a dynamic filling list that fill the screen what ever the content is
so here what I did:
first: the design
<Border BorderBrush="Black" CornerRadius="25" Margin="0,10,0,0" BorderThickness="1" Background="Aqua">
 <Grid>
  <Grid.ColumnDefinitions>
   <ColumnDefinition Width="auto"/>
   <ColumnDefinition Width="*"/>
   <ColumnDefinition Width="auto"/>
  </Grid.ColumnDefinitions>
  <StackPanel Grid.Column="0" Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
   <Button Width="100" Name="RED"  Height="100" Click="ButtonDec_Click">
    <Button.Background>
     <ImageBrush ImageSource="/LifeCounter;component/Images/RED.png" />
    </Button.Background>
   </Button>
  </StackPanel>
  <StackPanel Margin="10,0,0,0" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" >
   <TextBlock Name="name" HorizontalAlignment="Center" VerticalAlignment="Center" Text="AAAAAAAAAAAAA" Foreground="{Binding color}" TextWrapping="Wrap" FontWeight="Bold" FontSize="22" />
   <TextBlock Name="count" HorizontalAlignment="Center" VerticalAlignment="Center" Text="CCCCC" FontWeight="Bold" TextWrapping="Wrap" FontSize="30" />
  </StackPanel>
  <StackPanel Grid.Column="2" Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
   <Button Grid.Column="0" Width="100" Name="GREEN"  Height="100" Click="ButtonInc_Click">
    <Button.Background>
     <ImageBrush ImageSource="/LifeCounter;component/Images/Green.png" />
    </Button.Background>
   </Button>
  </StackPanel>
 </Grid>
</Border>

and the result was an item that fill the screen and doesn't matter in portrait or landscape

and to make it dynamic, simply I made a list of data template
 <ListBox  Grid.Row="1" Name="countersList" HorizontalAlignment="Center" VerticalAlignment="Center" SelectionChanged="countersList_SelectionChanged">
  <ListBox.ItemTemplate>
   <DataTemplate>
    <Border BorderBrush="Black" CornerRadius="25" Margin="0,10,0,0" BorderThickness="1" Background="Aqua">
     <Grid>
      <Grid.ColumnDefinitions>
       <ColumnDefinition Width="auto"/>
       <ColumnDefinition Width="*"/>
       <ColumnDefinition Width="auto"/>
      </Grid.ColumnDefinitions>
      <StackPanel Grid.Column="0" Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
       <Button Width="100" Name="{Binding index}"  Height="100" Click="ButtonDec_Click">
        <Button.Background>
         <ImageBrush ImageSource="/LifeCounter;component/Images/RED.png" />
        </Button.Background>
       </Button>
      </StackPanel>
      <StackPanel Margin="10,0,0,0" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" >
       <TextBlock Name="name" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding name}" Foreground="{Binding color}" TextWrapping="Wrap" FontWeight="Bold" FontSize="22" />
       <TextBlock Name="count" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding count}" FontWeight="Bold" TextWrapping="Wrap" FontSize="30" />
      </StackPanel>
      <StackPanel Grid.Column="2" Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
       <Button Grid.Column="0" Width="100" Name="{Binding index}"  Height="100" Click="ButtonInc_Click">
        <Button.Background>
         <ImageBrush ImageSource="/LifeCounter;component/Images/Green.png" />
        </Button.Background>
       </Button>
      </StackPanel>
     </Grid>
    </Border>
   </DataTemplate>
  </ListBox.ItemTemplate>
 </ListBox>

the result was a list that wrap it's size with it's content

so, how can I fix it, I want a list that fill the screen and it doesn't matter was it in landscape or portrait

A: The problem you are running into is that the item in the listbox isn't stretched.
A listbox item's size is NOT determined by the ItemTemplate but by the ItemContainerStyle and the size of the ListBox.
First add to the ListBox:
<ListBox HorizontalAlignment="Stretch" ...>

to make sure the ListBox itself is stretched horizontally. If you set it at Center it will only become as wide as its content/children request for.
Then add this to the ListBox:
<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment"
                Value="Stretch" />
    </Style>
</ListBox.ItemContainerStyle>

This ItemContainerStyle will cause all Items to be stretched to the width of the parent (ListBox's Item Panel)


text:
Q: IBM Watson SpeechToText empty respond I'm trying to transcribe an audiofile with Watson AI in c#. The problem i encountered is that i get an empty response. This is my code:
 IamAuthenticator authenticator = new IamAuthenticator( apikey: apikey );
 SpeechToTextService speechToText = new SpeechToTextService(authenticator);
 speechToText.SetServiceUrl(url);

 speechToText.DisableSslVerification(true);

 res = speechToText.Recognize(audio: memStream, inactivityTimeout: 180);

 Console.WriteLine("Response: ", res.Response);
 Console.WriteLine("Result: ", res.Result);
 Console.WriteLine("Status: ", res.StatusCode);

On the website I see that I consume my free usage. I'm 99% sure my audio file works.
I've already tried to get the result directly from the method.
res.result = speechToText.Recognize(audio: memStream, inactivityTimeout: 180).Result;

If I do that, I'll get a NullReferenceException.
It would be awesome if someone could help.

A: Either your audio stream is empty, or you are getting errors or warnings that you need to catch. As per the API Documentation - https://cloud.ibm.com/apidocs/speech-to-text?code=dotnet-standard#error-handling
try
{
    // Invoke a method
}
catch(ServiceResponseException e)
{
    Console.WriteLine("Error: " + e.Message);
}
catch (Exception e)
{
    Console.WriteLine("Error: " + e.Message);
}

If an exception is not being thrown, then check res for Warnings.


text:
Q: does Google API KEY can be used only once or twice? I'm just develop Maps in my app's, and i'm curious why i just can used my API KEY only once or twice, and after that i need to open the console and simply save it to makes my API KEY works again,
My question is:

*

*this is the behavior of API KEY itself or there's something wrong about my setup?

*should i have two API KEY (one for IP Address and Android Apps for the 2nd)? even I'm accessing URL in my apps?

below is the success pic:

and below is the failure with full message:
{
   "error_message" : "This IP, site or mobile application is not authorized to use this API key. Request received from IP address <myIp>, with empty referer",
   "routes" : [],
   "status" : "REQUEST_DENIED"
}

EDITED:
I have add my restriction key on google console like this:

A: In cloud console you should set application restrictions for API key, you can choose one of this:

*

*None

*HTTP referrers (web sites)

*IP addresses (web servers, cron jobs, etc.)

*Android apps

*iOS apps

Based on your error message i think you restricting based on IP address.


text:
Q: Excel - Select Column by number and sheetname I have 4 columns on Sheet1 and 4 on Sheet2
I have named the columnson sheet 1 as:
MvarNo = 1
Mdesc = 2
Mfile = 3
Mfield = 4

where 1 = a etc....
How do I name these columns with the sheet name and column number?
Thanks
UPDATE
Sub Compare()

MvarNo = 1 'Sheet1
Mdesc = 2 'Sheet1
Mfile = 3 'Sheet1
Mfield = 4 'Sheet1

XvarNo = 6 'Sheet1
Xdesc = 7 'Sheet1
Xfile = 8 'Sheet1
Xfield = 9 'Sheet1

CvarNo = 1 'Sheet2
Cdesc = 2 'Sheet2
Cfile = 3 'Sheet2
Cfield = 4 'Sheet2

'Count rows on Master Sheet (Sheet1)
MvarNoLastRow = Worksheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
MdesclastRow = Worksheets("Sheet1").Cells(Rows.Count, "B").End(xlUp).Row
 MfilelastRow = Worksheets("Sheet1").Cells(Rows.Count, "C").End(xlUp).Row
MfieldlastRow = Worksheets("Sheet1").Cells(Rows.Count, "D").End(xlUp).Row

'Count rows on Compare Sheet (Sheet2)
CvarNoLastRow = Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
CdesclastRow = Worksheets("Sheet2").Cells(Rows.Count, "B").End(xlUp).Row
CfilelastRow = Worksheets("Sheet2").Cells(Rows.Count, "C").End(xlUp).Row
CfieldlastRow = Worksheets("Sheet2").Cells(Rows.Count, "D").End(xlUp).Row

For i = 2 To MvarNoLastRow
For j = 2 To CvarNoLastRow

  If Cells(i, MvarNo) = Cells(j, CvarNo) Then
  Cells(i, XvarNo).Value = "Yes"
'        If Cells(i, MvarNo) = Cells(j, CvarNo) And Cells(i, Mdesc) = Cells(j, Cdesc) And Cells(i, Mfile) = Cells(j, Cfile) And Cells(i, Mfield) = Cells(j,     Cfield) Then
'        Cells(i, XvarNo).Value = "Yes"
'        ElseIf Cells(i, MvarNo) <> Cells(j, CvarNo) And Cells(i, Mdesc) <>     Cells(j, Cdesc) And Cells(i, Mfile) <> Cells(j, Cfile) And Cells(i, Mfield) <>     Cells(j, Cfield) Then
      j = j + 1
    ElseIf j = CvarNoLastRow Then
    Cells(i, XvarNo).Value = "No"

  End If

  Next j

Next i

End Sub

the reason for this macro is to compare information between sheet 1 and sheet2.
I 'think' from my code it is actually just comparing the data on sheet 1 with sheet1.

A: Does this work?
Here my sheet is called "Ad revenues"
Sub test()
    Dim lC As Long
    Dim strColNames(1 To 4) As String
    For lC = 1 To 4
        strColNames(lC) = Sheet1.Name & vbTab & Str(Cells(1, lC).Column)
    Next lC End Sub
End Sub()

A: If you need to get the sheet name, all of the following will work:
=SUBSTITUTE(CELL("filename"),LEFT(CELL("filename"),FIND("]",CELL("filename"))),"")

=RIGHT(CELL("filename"),LEN(CELL("filename"))-FIND("]",CELL("filename")))

=MID(CELL("filename"),FIND("]",CELL("filename"))+1,31)

The latter works because excel limits you to 31 characters when naming a sheet
To get the name of a column, you can use something like below:
=SUBSTITUTE(MID(ADDRESS(1,CELL("col")),2,2),"$","")

=MID(SUBSTITUTE(ADDRESS(1,COLUMN(R31)),"$1",""),2,2)


text:
Q: Uncertainty in estimating a polygon area in GEE I have 2 methods to compute the area of a polygon:

*

*Using the dedicated method: ee.Feature.area()

*Summing the area of each pixels of an image reduced to the polygon using ee.Image.reduceRegion()
Method 1 is obviously much more straight forward but method 2 is useful if you are not interested only about the polygon area but in the reduction of a band that include the pixel areas (e.g. if you get an image of the fraction of tree coverage, the total area covered by tree in a given polygon is the sum over all pixels of the fraction of tree coverage multiplied by the pixel area).

I find that method 1 and 2 usually differ by about 0.5%. This is not much and most likely not to dominate as an uncertainty in most analysis, but still significantly higher than I would have expected. Especially that using method 2 with different scales give much more consistent results. Any idea where the difference comes from?
var pa1 = ee.Image.pixelArea().reproject({crs:'EPSG:4326',scale:1})
var pa30 = ee.Image.pixelArea().reproject({crs:'EPSG:4326',scale:30})
var pa100 = ee.Image.pixelArea().reproject({crs:'EPSG:4326',scale:100})

var  f = ee.Feature({
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Polygon",
        "coordinates": [[[20, 0], [20, -0.1], [19.9, -0.1], [19.9, 0]]]
  }
})

print('Area from method:', f.area())
print('Area from pixel sum (scale=1):', pa1.reduceRegion({reducer: ee.Reducer.sum(), geometry: f.geometry(), maxPixels: 1000000000}).getInfo()['area'])
print('Area from pixel sum (scale=30):', pa30.reduceRegion(ee.Reducer.sum(), f.geometry()).getInfo()['area'])
print('Area from pixel sum (scale=100):', pa100.reduceRegion(ee.Reducer.sum(), f.geometry()).getInfo()['area'])

Results from the code:
Area from method:
123643364.45103805

Area from pixel sum (scale=1):
123091222.47992136

Area from pixel sum (scale=30):
123090484.71821223

Area from pixel sum (scale=100):
123086593.00383721

Run the code on GEE: https://code.earthengine.google.com/b2b53d3e9e463956e690893474b89450
EDIT: QGIS calculate the area as: 123090660, indicating that the ee.Feature.area() would be off.


text:
Q: dropwizard and jetty-config files Where do I have to put jetty specific configurations in dropwizard, such as

*

*jetty-context.xml

*jetty-env.xml

*...

?
I do not have a src/main/webapp/WEB-INF directory, so what do I do?

A: You don't.
Dropwizard encapsulates most of the jetty configurations on its YAML configuration file. Reference
For others (context etc.) dropwizard has its own way of handling them programmatically. I highly suggest going through dropwizard's Getting started document as well as the user manual.


text:
Q: Amcharts graph - Rotate chart to horizontal at lesser screen-width I am trying to make amchart graph with function that it rotates and becomes horizontal when screenwidth is less than 766px. If screenwidth is less than 766 px, value axes should be on top and category axes should be on the left
I added this script link -

and also added this code to the amcharts API code  -
"responsive": {
    "enabled": true,
    "addDefaultRules": false,
    "rules": [{
        "maxWidth": 766,
        "overrides": {
            "rotate": true,
            "categoryAxis": {
                "position": "left"
            },
            "valueAxes": {
                "position": "top"
            }
        }
    }]
},

But still it does not work. The chart does not revert to horizontal on decreasing screen-width less than 766px. Please tell what I am doing wrong. I do not want to use Jquery and I am new to javascript. Would appreciate if you can show in a jsfiddle or a snippet.
This is my jsfiddle - https://jsfiddle.net/fvurj0xg/ and below is my snippet -

var chart = AmCharts.makeChart("chartdiv", {
    "type": "serial",
    "theme": "light",
    "addClassNames": true,
 "responsive": {
        "enabled": true,
     "addDefaultRules": false,
     "rules": [{
            "maxWidth": 766,
            "overrides": {
                "rotate": true,
                "categoryAxis": {
                    "position": "left"
                },
                "valueAxes": {
                    "position": "top"
                }
            }
        }]
      },
      "titles": [{
        "text": "Open this demo in a separate window for links to work"
      }],
      "dataProvider": [{
        "country": "USA",
        "visits": 2025,
        "url": "https://codepen.io"
      }, {
        "country": "China",
        "visits": 1882,
        "url": "https://codepen.io"
      }, {
        "country": "Japan",
        "visits": 1809,
        "url": "https://codepen.io"
      }, {
        "country": "Germany",
        "visits": 1322,
        "url": "https://codepen.io"
      }, {
        "country": "UK",
        "visits": 1122,
        "url": "https://codepen.io"
      }, {
        "country": "France",
        "visits": 1114,
        "url": "https://codepen.io"
      }, {
        "country": "India",
        "visits": 984,
        "url": "https://codepen.io"
      }, {
        "country": "Spain",
        "visits": 711,
        "url": "https://codepen.io"
      }, {
        "country": "Netherlands",
        "visits": 665,
        "url": "https://codepen.io"
      }, {
        "country": "Russia",
        "visits": 580,
        "url": "https://codepen.io"
      }, {
        "country": "South Korea",
        "visits": 443,
        "url": "https://codepen.io"
      }, {
        "country": "Canada",
        "visits": 441,
        "url": "https://codepen.io"
      }, {
        "country": "Brazil",
        "visits": 395,
        "url": "https://codepen.io"
      }],
      "valueAxes": [{
          "gridColor": "#FFFFFF",
          "gridAlpha": 0.2,
          "dashLength": 0
      }],
      "gridAboveGraphs": true,
      "startDuration": 1,
      "graphs": [{
          "balloonText": "[[category]]: [[value]]",
          "fillAlphas": 0.8,
          "lineAlpha": 0.2,
          "type": "column",
          "valueField": "visits"
      }],
      "chartCursor": {
          "categoryBalloonEnabled": false,
          "cursorAlpha": 0,
          "zoomable": false
      },
      "categoryField": "country",
      "categoryAxis": {
          "gridPosition": "start",
          "gridAlpha": 0,
          "tickPosition": "start",
          "tickLength": 20,
      "listeners": [{
          "event": "clickItem",
          "method": function(event) {
              var url = event.serialDataItem.dataContext.url;
              window.open(url, '_blank');
          }
      }]
    }

});
#chartdiv {
  width: 100%;
  height: 400px;
}

.amcharts-axis-label {
  cursor: pointer;
}

A: the url to responsive.min.js is not correct. Try to add a correct one then it should work. Here the working fiddle: https://jsfiddle.net/fvurj0xg/1/


text:
Q: Java Regex ignoring newline character WITHOUT Dotall I have to parse returned emails for a specific object id. The problem is that, when the email is returned, the id may be split into several lines. Usually it should look like this:
foo#bar-20130101-103000#12345

whereat I'm interested in the last part "12345". The problem is that that string tends to be split by a newline, for example:
foo#bar-20130101-103000#12
345

which causes my regex
[a-zA-Z0-9äöüÄÖÜß]{1,5}#[a-zA-Z0-9äöüÄÖÜß]{1,5}-\d{8}-\d{6}#(\d+)

to only find "12" instead of "12345". Now all the hints i find on the 'net are to use Pattern.MULTILINE and/or Pattern.DOTALL, but multiline only influences the ^ and $ anchors and dotall only makes . match on newline chars too. The problem is that i don't have a . here and it's not really applicable either, because i only want digits.
So how can i make my regex match the whole thing and not stop at the line break?

A: Since your number is in the end you can try:
"(?s)^[a-zA-Z0-9äöüÄÖÜß]{1,5}#[a-zA-Z0-9äöüÄÖÜß]{1,5}-\d{8}-\d{6}#(.*)$"

i.e. capture everything after # with DOTALL
Following should also work without DOTALL:
"^[a-zA-Z0-9äöüÄÖÜß]{1,5}#[a-zA-Z0-9äöüÄÖÜß]{1,5}-\d{8}-\d{6}#[\\d\\r\\n]+$"

A: [\d\r\n] will match a digit or a new line, so try with ([\d\r\n]+).


text:
Q: Shaderc (from conan) not linking in windows I am trying to build a project in debug mode that uses conan for dependency management.
Most dependencies seem to link fine but shaderc is failing with error:
shaderc.lib(shaderc.obj) : error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in winblows.cpp.obj [C:\Users\Makogan\Documents\neverengine\buildvs\WinBlows@exe.vcxproj]
shaderc.lib(shaderc.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MDd_DynamicDebug' in winblows.cpp.obj [C:\Users\Makogan\Documents\neverengine\buildvs\Wi
nBlows@exe.vcxproj]

When I look online people suggest rebuilding the library in debug mode, I tried, I think, by doing:
conan install . -if buildvs -s build_type=Debug -s compiler.runtime=MD -s compiler="Visual Studio" -s compiler.version=17 --build=missing
But the error persists.
What can I do to link it?