text:
Q: Perfomance improvement - Looping with Get Method I've built a program to fill up a databank and, by the time, it's working. Basically, the program makes a request to the app I'm using (via REST API) returns the data I want and then manipulate to a acceptable form for the databank.
The problem is: the GET method makes the algorithm too slow, because I'm acessing the details of particular entries, so for each entry I have to make 1 request. I have something close to 15000 requests to do and each row in the bank is taking 1 second to be made.
Is there any possible way to make this requests faster? How can I improve the perfomance of this method? And by the way, any tips to measure the perfomance of the code?
Thanks in advance!!
here's the code:
# Retrieving all the IDs I want to get the detailed info
abc_ids = serializers.serialize('json', modelExample.objects.all(), fields=('id'))
abc_ids = json.loads(abc_ids)
abc_ids_size = len(abc_ids)

# Had to declare this guys right here because in the end of the code I use them in the functions to create and uptade the back
# And python was complaining that I stated before assign. Picked random values for them.
age = 0
time_to_won = 0
data = '2016-01-01 00:00:00'

# First Loop -> Request to the detailed info of ABC
for x in range(0, abc_ids_size):

id = abc_ids[x]['fields']['id']
url = requests.get(
    'https://api.example.com/v3/abc/' + str(
        id) + '?api_token=123123123')

info = info.json()
dealx = dict(info)

# Second Loop -> Picking the info I want to uptade and create in the bank
for key, result in dealx['data'].items():
    # Relevant only for ModelExample -> UPTADE
    if key == 'age':
        result = dict(result)
        age = result['total_seconds']
    # Relevant only For ModelExample -> UPTADE
    elif key == 'average_time_to_won':
        result = dict(result)
        time_to_won = result['total_seconds']

    # Relevant For Model_Example2 -> CREATE
    # Storing a date here to use up foward in a datetime manipulation
    if key == 'add_time':
        data = str(result)

    elif key == 'time_stage':

        # Each stage has a total of seconds that the user stayed in.
        y = result['times_in_stages']
        # The user can be in any stage he want, there's no rule about the order.
        # But there's a record of the order he chose.
        z = result['order_of_stages']

        # Creating a list to fill up with all stages info and use in the bulk_create.
        data_set = []
        index = 0

        # Setting the number of repititions base on the number of the stages in the list.
        for elemento in range(0, len(z)):
            data_set_i = {}
            # The index is to define the order of the stages.
            index = index + 1

            for key_1, result_1 in y.items():
                if int(key_1) == z[elemento]:
                    data_set_i['stage_id'] = int(z[elemento])
                    data_set_i['index'] = int(index)
                    data_set_i['abc_id'] = id

                    # Datetime manipulation
                    if result_1 == 0 and index == 1:
                        data_set_i['add_date'] = data

                    # I know that I totally repeated the code here, I was trying to get this part shorter
                    # But I could not get it right.
                    elif result_1 > 0 and index == 1:
                        data_t = datetime.strptime(data, "%Y-%m-%d %H:%M:%S")
                        data_sum = data_t + timedelta(seconds=result_1)
                        data_sum += timedelta(seconds=3)
                        data_nova = str(data_sum.year) + '-' + str(formaters.DateNine(
                            data_sum.month)) + '-' + str(formaters.DateNine(data_sum.day)) + ' ' + str(
                            data_sum.hour) + ':' + str(formaters.DateNine(data_sum.minute)) + ':' + str(
                            formaters.DateNine(data_sum.second))
                        data_set_i['add_date'] = str(data_nova)

                    else:
                        data_t = datetime.strptime(data_set[elemento - 1]['add_date'], "%Y-%m-%d %H:%M:%S")
                        data_sum = data_t + timedelta(seconds=result_1)
                        data_sum += timedelta(seconds=3)
                        data_nova = str(data_sum.year) + '-' + str(formaters.DateNine(
                            data_sum.month)) + '-' + str(formaters.DateNine(data_sum.day)) + ' ' + str(
                            data_sum.hour) + ':' + str(formaters.DateNine(data_sum.minute)) + ':' + str(
                            formaters.DateNine(data_sum.second))
                        data_set_i['add_date'] = str(data_nova)

                    data_set.append(data_set_i)

Model_Example2_List = [Model_Example2(**vals) for vals in data_set]
Model_Example2.objects.bulk_create(Model_Example2_List)

ModelExample.objects.filter(abc_id=id).update(age=age, time_to_won=time_to_won)

A: if the bottleneck is in your network request, there isn't much you can do except to perhaps use gzip or deflate but with requests ..

The gzip and deflate transfer-encodings are automatically decoded for
  you.

If you want to be doubly sure, you can add the following headers to the get request.
{ 'Accept-Encoding': 'gzip,deflate'}

The other alternative is to use threading and have many requests operate in parrallel, a good option if you have lot's of bandwidth and multiple cores.
Lastly, there are lots of different ways to profile python including with cprofile + kcachegrind combo.


text:
Q: Question on Banach matchbox problem I was looking through stackexchange for some answers regarding this problem and am curious on one answer in particular. I've posted it below. Here is the link: Find probabilty of having r matchsticks in one box when other is empty
begin quote "
The number of routes starting at $(N,N)$ and ending at $(0,r)$ equals $\binom{2N-r}{N}$ and the same is true for the number of routes starting at $(N,N)$ and ending at $(r,0)$.
For each route the probability that this route will be taken equals $2^{r-2N}$.
That leads to probability $$\binom{2N-r}{N}2^{r-2N}\frac12+\binom{2N-r}{N}2^{r-2N}\frac12=\binom{2N-r}{N}2^{r-2N}$$ that one of the routes $(N,N)\to(0,r)\to(-1,r)$  and $(N,N)\to(r,0)\to(r,-1)$ will be chosen.
"
end quote
My question(s): Question 1.) Why would combinations be of use in this problem as wouldnt we consider the following distinct events:
(1) pick match #1A from box A, match #1B from box B , then match #2A
vs
(2) pick match #1B from box B, then #1A from box A, then #2A from box A.
where I've numbered the elements of box A and B 1 through $N$ in each box.
Question 2.) Why are there $\binom{2N-r}{N}$ ways to be left with $r$ matches in a single box? It seems like you choose $N$ then you will not take away enough matches to be left with only $r$ total and $2N - r - N = 1N - r \neq r$ .
Thanks for the help!

A: Question 1.  We don't care which matches have been pulled out, or in what order; only how many have been pulled out of each box.  You can describe the situation as a sequence of $R$'s and $L$'s, meaning rights and lefts, so it just like heads and tails in tossing a coin.
Question 2.  If he exhausts the matches in the left pocket say, and has $r$ matches left in the right pocket, then he has used $2N-r$ matches in all, and drawn $N$ of them from the left pocket.  So this is the same as asking how many sequences of $N$ $R$'s and $N-r$ $L$'s are there?
$${(2N-r)!\over N!(N-r)!}={2N-r\choose N}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to find a matching SQL Class. Drush cannot find your database connection. error I am new to XAMPP and Drush, Mysql doesnt appear in Drush at all. I have no clue what is going on. When I type mysql, I get the mysql command prompt. But when I try drush status command, I dont see mysql in there.
# drush status
 PHP executable         :  php.exe
 PHP configuration      :  C:\xampp\php\php.ini
 PHP OS                 :  WINNT
 Drush script           :      C:\xampp\htdocs\mysite\vendor\drush\drush\drush.php
 Drush version          :  8.0.3
 Drush temp directory   :  C:\Users\USER~1\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :

I also tried
#drush sql-connect

This returns an error:
Unable to load class Drush\Sql\Sql exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL Class. Drush cannot find your database connection details.' in 'drush\commands\sql\sql.drush.inc:588'
Thanks in advance.

A: Try adding --root=/full/path/to/your/webroot in your drush command.
I am running into exactly this right now, and this worked for me. I hadn't needed to do it before with drush 6 (?) on the same server but need to now that I've installed drush 8.0.5 via composer.

A: texas-bronius had the solution for me.
On Digital Ocean, after reinstalling Drush from Composer, I had to give the command:
drush up --root=/var/www/html

although just regular drush up had always worked before.  I'm not sure why, and it's annoying, but it worked.

A: Drush commands are best run from the root folder of your Drupal installation.
For eg. if you have folder structure like this :
ABC
|
-Drupal
|
-XYZ
|
:
:
then run Drush commands from inside the Drupal folder. I guess that should do it.


text:
Q: Django cannot run manage.py commands I'm taking a python project that was originally developed on ubuntu and trying to get it to run on windows.
I have python35 & python27 both installed on my system however only python35 in my path environment because that's the only one I reference outside of a virtualenv.
I used the command virtualenv -p python27 dlenv to create a new environment directory and dragged the project inside.
I then opened the project in pycharm and directed the interpreter to the virtualenv python.exe
Now the setup.py file allowed me to install all the dependencies from pycharm.
pip freeze shows I have everything installed including django 1.5.1 (the version it was developed in).
If I activate the environment then cd to the manage.py file and try to run any command (e.g. python manage.py validate) I get ImportError: cannot import name ForeignObjectRel
Although python --version proves I'm accessing python 2.7.11 I tried running just manage.py validate and I get ImportError: No module named django.core.management
Anyone have any ideas what the problem could be? Appreciate any help.


text:
Q: zsh compose command using variable What's the equivalent in zsh of the following in bash?
export del='--timeout=0 --wait=0 --force'
kubectl delete pod testpod $del

executed in bash it return the correct command without problem while the same in zsh is returning:
Error: invalid argument "0 --wait=0 --force" for "--timeout" flag: time: unknown unit " --wait=" in duration "0 --wait=0 --force"

Because this will be using to write repeating command it should do simple to be reproduced.
Current solutions but "too long" to be the answer:
echo $del | xargs kubectl delete pod testpod

eval kubectl delete pod testpod $del

kubectl delete pod testpod ${=del}

A: In zsh you would write
kubectl delete pod testpod ${(z)del}

The (z) tells zsh to do word splitting on the argument.

A: Try with xargs:
echo $del | xargs kubectl delete pod testpod

A: The faster solution I have found is to enable the zsh flag for work split variable by default as bash is normally doing
setopt SH_WORD_SPLIT
kubectl delete pod testpod $del

this way I can use the name form of bash
Thanks @user1934428 for give me the right hint


text:
Q: Generic Extension Method for Enum I have a problem. I want to make a generic method to convert my errors enums to specific response.
for instance my response object
public class ErrorResponse
{
    public ulong Code { get; set; }
    public string Description { get; set; }
    public string OrigionationSystem { get; set; }
}

and I want to convert my all errors to this response
for eg
public enum ProductErrors:ulong
{
    None,
    [Description("Prouct Not Found")]
    ProductNotFound,
    [Description("Invalid Product Isbn")]
    InvalidIsbn
}

public enum CustomerErrors:ulong
{
    None,
    AlreadyExists,
    InvalidEmailAddress
}

and now i want to make generic method to convert my enums to ErrorResponse.
previously i was using this method to convert my error codes to error response.
public static IList<ErrorResponse> ParseErrorCodeToErrorResponse(this IEnumerable<ProductErrors> errorCodes)
{
    return errorCodes.Select(x => new ErrorResponse
    {
        Code = (ulong)x,
        Description = x.GetDescription(),
        OriginatingSystem = Extensions.GetCurrentSystemName()
    } ).ToList();
}

problem raise here :
public static IList<ErrorResponse> ParseErrorCodeToErrorResponse<T>(this IEnumerable<T> errorCodes) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new ArgumentException("T must be an enumerated type");
    }
    return errorCodes.Select(x => new ErrorResponse
    {
        Code = (ulong)x,
        Description = x.GetDescription(),
        OriginatingSystem = Extensions.GetSystemName()
    }).ToList();
}

when it's for only one enum it's working fine but when i made it generic it said

Type T can't convert to ulong and on x.GetDescription() it is saying can't resolve GetDescription()


text:
Q: Remember/Forget device function on android app I am building an app which connects & then controls a device.
I am wanting to add a remember device function and forget device function so the user can stick to one device or switch.
I am new to android so any help on how to implement this would be great.

A: You can keep the information in SharedPreferences. If you are connecting to a Bluetooth device then you need to remember the Mac address of the device.
Store and retrieve the info using the following functions.
 public static void addDataToSharedPrefsString(String key, String value,Context context) {

    SharedPreferences.Editor sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(
                    context).edit();
    sharedPreferences.putString(key, value);
    sharedPreferences.commit();
}

public static String getDataFromSharedPrefString(String key,Context context) {
    SharedPreferences preferences = PreferenceManager
            .getDefaultSharedPreferences(context);
    String value = preferences.getString
            (key, "");
    return value;
}

Add to shared pref by
addDataToSharedPrefsString("macAddress", "MAC123q4e",context);

get the shared value by
getDataFromSharedPrefString("macAddress",context);

if you want to delete an existing item in shared pref, set the value null.
addDataToSharedPrefsString("key", null,context);

I hope this is your requirement and this solution would help you.


text:
Q: multiprocessing (HoG features) in Python - Empty arrays returned Trying to extract HoG features on a large data set of images - 70K in total.
So test_X is 28x28x70000
I am trying to use Pool. Trying out the first 10 images
from multiprocessing import Pool

def get_hog(inputImg):
    fd,hi=hog(inputImg, orientations=4, pixels_per_cell=(4, 4),
                    cells_per_block=(1, 1), visualize=True, multichannel=False)
    return fd

with Pool(5) as p:
    V = p.map(get_hog,test_X[:,:,range(0,10)]))

What I endup with empty arrays in V.
Probably the pass of data to the function is incorrect?

A: in multi-processing in python,
one should always try and give the callbacks methods to store the return data from the process.
so for your example we can use the Pool and run the pool over the list of images in your case it is test_X and let the call back handle the data returned by each process in the pool.
here is the example code:
import numpy as np
from multiprocessing import Pool
V=[]
test_X = np.transpose(test_x)
def get_hog(inputImg):
    fd,hi=hog(inputImg, orientations=4, pixels_per_cell=(4, 4),
                cells_per_block=(1, 1), visualize=True, multichannel=False)
    return fd

def poolCallback(returnDataFromPool):
    global V
    V.append(returnDataFromPool)

p = Pool(5)
for x in test_X:
    p.apply_async(get_hog ,args=(x,),callback=poolCallback)
p.close()
p.join()


text:
Q: What is the result of the code? please interpret for me about the result that the following code run.
#include <stdio.h>

int get_array_size(int *arr){
    return sizeof(arr)/sizeof(int);
}

int main(int argc, char const *argv[]){
    int arr[10];
    printf("%d\n", sizeof(arr)/sizeof(int));
    printf("%d\n",get_array_size(arr));
    printf("%d\n",arr[10]);
    printf("%d\n",get_array_size(arr));
    return 0;
}

which is:
10
2
0
2

A: All sizes are in bytes.
sizeof(arr)/sizeof(int) = size of array / size of int = 40/4 = 10

get_array_size(arr) = size of array pointer(which is 4) / size of int = 4/4 = 1.

arr[10] = the eleventh entry of array(array size=10). (undefined number).

A: #include <stdio.h>

int get_array_size(int *arr){
    return sizeof(arr)/sizeof(int);
}

int main(int argc, char const *argv[]){
    int arr[10];
    printf("%d\n", sizeof(arr)/sizeof(int));//10
    printf("%d\n",get_array_size(arr));//1
    printf("%d\n",arr[10]);//if a[9] adress=x a[10] prints undefined value from x+4 adress
    printf("%d\n",get_array_size(arr));1
    return 0;
}

When you call the function local variable arr is given priority so 4/4 always gives 1 when called

A: printf("%d\n", sizeof(arr)/sizeof(int));

sizeof(arr) returns size of array in bytes. Since it is an int array of length 10, "sizeof(arr)" will be "10*sizeof(int)". You are deviding it by sizeof(int). So output will be 10.
printf("%d\n",get_array_size(arr));

This is interesting!
You are passing address of "arr" to get_array_size(). In that function first you are getting size of address. The address size depends on the machine you are running, i.e. In 32-bit machine address size will be 4bytes and in 64-bit machine it will be 8bytes. I think you are using 64-bit machine so sizeof(arr) is returning 8. But sizeof(int) is 4bytes. So effectively it is 8/4 = 2.
printf("%d\n",arr[10]);

Your array size is 10, so you can access from arr[0] to arr[9]. arr[10] is not part of your array. That address might be used for some other variable. You are just writing whatever present in that address. The output is completely random. I think that address had 0 when you executed the program, so you got the output as 0.
printf("%d\n",get_array_size(arr));

This is repeated print (Output is 2).


text:
Q: An addition of non-existing **trailing** zeros at importing csv file by pandas Importing a .csv file given by
a
1.4
1.12

leads to an addition of a trailing zero in the first line. How to avoid it?

A: This is just the visual representation of the float data in your df. If you want it different, change the format string for it.
For your numbers '{:,g}' would work (see format specification mini language - scroll down for the table that explains it).
Example:
import pandas as pd
import numpy as np

with open("data.txt","w") as f:
    f.write("a\n1.4\n1.12")

df = pd.read_csv("data.txt")
print(df)

# change the way floats are formatted
pd.options.display.float_format = '{:,.06f}'.format

# change the way floats are formatted
pd.options.display.float_format = '{:,g}'.format

df = pd.read_csv("data.txt")
print(df)

Output:
# default formatting
      a
0  1.40
1  1.12

# {:,06f}
          a
0 1.400000
1 1.120000

# {:,g}
      a
0   1.4
1  1.12

From a numerical standpoint there is no difference between 1.4 and 1.40 or 00001.40000000000.

Guarav Kumar's suggestion to use

df = pd.read_csv('minExamp.csv' , dtype = str)

is bad advice - it changes the data type for the (single) column to be of type string.
This will prevent you from calculating anything with the numbers of your dataframe.

A: df = pd.read_csv('minExamp.csv' , dtype = str)


text:
Q: Why does a TidTCPClient in a separate thread block the main thread? A separate thread creates a TidTCPClient and a TTimer. The TTimer is set to 3s and if the TCPClient is not connected, it calls TCPClient.Connect.
If there is no server to connect to, this results in an attempt to connect every 3 seconds.
The main thread (UI) does nothing, but if I grab the window with the mouse and move it slowly across the screen, it get's stuck every 3 seconds for about 2 seconds, then it jumps to the mouse-cursor position and follows the mouse again, until the next attempt to connect occurs.
In other words, the main thread seems to be blocked when the TCPClient tries to connect.
Why does this happen, even though the TCPClient is in it's separate thread?

A: Your TTimer works by receiving WM_TIMER messages; Those messages are dispatched using the VCL's main message pump, in the VCL threads. After the 3 seconds expire your TTimer.OnTimer event runs in the main thread, so the call to Connect runs in the main VCL thread.
You get blocked because you're not threading!


text:
Q: Using Perl to capture ADB logcat into a txt file and then stop/save txt file when string is found using Perl and ADB commands I am looking to capture a logcat log and simultaneously save to a text file (whilst perfoming a manual PLMN search on a mobile handset).  I am more familiar with Python, but legacy reasons require I use Perl.
during the log capture I am hoping to wait for a the following logcat string >> /EVENT_NETWORK_SCAN_COMPLETED/ << before saving/stop capturing the log and then exiting.
I have made an attempt in the script below with the help of a few online pointers, but the script never exits, which leads me to conclude that my method is probably too simplistic for the task in hand.  Would anyone be able to direct me on where I am going wrong, or indeed if this task is possible?  Thanks.
  use strict;
  use warnings;
  use diagnostics;

     sleep(5);
     system('adb wait-for-device');
     my $CollectLog = system('adb logcat > logcat.txt');
     my @Lines = split("\n", $CollectLog);

  # process lines
  foreach my $Line ( @Lines )
  {
        if($CollectLog =~ /EVENT_NETWORK_SCAN_COMPLETED/m)
        {
            print "string matches the pattern\n";
            system('adb logcat -d');
            last;
        }
  }

A: Another possible solution is to open a socket to the ADB service and execute the logcat via the shell command.  You can then simply process the output using the standard IO::Handle::getline().
use strict;
use warnings;
use IO::Socket;

# Connect to the local ADB service
my $adbsock = IO::Socket::INET->new('127.0.0.1:5037') || die "Cannot connect to ADB service: $!";
# Connect to the device
my $data = 'host:transport-usb';
$adbsock->write(sprintf("%04X%s",length($data), $data));
$adbsock->read($data, 4);
die "connect connect to USB device" unless $data eq "OKAY";
# Execute logcat
$data = 'shell:logcat';
$adbsock->write(sprintf("%04X%s",length($data), $data));
$adbsock->read($data, 4);
die "Cannot execute logcat" unless $data eq "OKAY";
# Process the lines
my @fifo;
while(defined( my $line = $adbsock->getline())) {
    push @fifo, $line;
    shift @fifo if (scalar(@fifo) > 100);
    if($line =~ /EVENT_NETWORK_SCAN_COMPLETED/) {
        # dump the FIFO queue
        print @fifo;
        last;
    }
}

There are two assumptions for the above:

*

*The local ADB service is running correctly (the OP method of running 'adb wait-for-device' should accomplish this)

*There is only one device attached and it's attached via USB

There is a (fairly terse) reference to the protocol here and the commands you can execute here.  From experience, not all work exactly as described, so I would suggest experimentation.
PS.  Apologies for resurrecting an old question, but I encountered the same problem and found the answers to this one were not quite suitable for my purpose.

A: There is module for this, called expect: http://search.cpan.org/~rgiersig/Expect-1.15/Expect.pod
Your problem that system forks and does not return anything. You should use backtick, but expect is better suited for this job.
  use Expect;
  use Data::Dumper;

  # create an Expect object by spawning another process
  my $exp = Expect->spawn('adb wait-for-device') or die "Cannot spawn 'adb wait-for-device': $!\n";
  ### wait timeout sec or the string
  $exp->expect($timeout,'-re',/EVENT_NETWORK_SCAN_COMPLETED/);
  ### get everything before this string
  my $CollectLog = $exp->exp_before();
  ### print out
  print Dumper($CollectLog);
  # if no longer needed, do a soft_close to nicely shut down the command
  $exp->soft_close();

A: I'd try a piped open to stream the data from 'adb' and then writing the log yourself:
open my $OUT, "> logcat.txt" or die;
open my $IN, "adb logcat |" or die;

while (<$IN>) {
  if (/EVENT_NETWORK_SCAN_COMPLETED/) {
    `adb logcat -d`
    last;
  }
}
close $OUT;
close $IN;

I'm not sure about this working under Windows, though.
A (lousy) fallback would be to start the log writing in one process, then continually open the file for reading seek to your last position, and read to the end searching for your halt-string.


text:
Q: ITunes review URL and iOS 7 (ask user to rate our app) AppStore show a blank page Does anybody knows if the technique used to ask the user to rate our app and open for him the App Store directly on the rating page is still working on iOS 7 ?
I used to open this url from my app :
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=353372460&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software

But it looks like it's not working anymore (AppStore show a blank page). I have also tried this url wihout luck:
http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?pageNumber=0&sortOrdering=1&type=Purple+Software&mt=8&id=353372460

A: + (NSString *)getReviewUrlByAppId:(int)appId
{
    NSString *templateReviewURL = @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APP_ID";
    NSString *templateReviewURLiOS7 = @"itms-apps://itunes.apple.com/app/idAPP_ID";
    NSString *templateReviewURLiOS8 = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=APP_ID&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software";

    //ios7 before
    NSString *reviewURL = [templateReviewURL stringByReplacingOccurrencesOfString:@"APP_ID" withString:[NSString stringWithFormat:@"%d", appId]];

    // iOS 7 needs a different templateReviewURL @see https://github.com/arashpayan/appirater/issues/131
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 7.1)
    {
        reviewURL = [templateReviewURLiOS7 stringByReplacingOccurrencesOfString:@"APP_ID" withString:[NSString stringWithFormat:@"%d", appId]];
    }
    // iOS 8 needs a different templateReviewURL also @see https://github.com/arashpayan/appirater/issues/182
    else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        reviewURL = [templateReviewURLiOS8 stringByReplacingOccurrencesOfString:@"APP_ID" withString:[NSString stringWithFormat:@"%d", appId]];
    }

    return reviewURL;
}

A: The review link has once again broken in iOS9. In doing some experimenting, I figured out that Apple reverted it back to how it was before iOS7. So you have to do:
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=247423477&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software

Where 247423477 is your 9 digit app ID (the main difference is you have to append &onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software after the app ID).

A: All the answers above have now been deprecated (iOS 7, but may work) thus, I provide the new way Apple recommends to provide links to the Apps.
The link for your App is the one from iTunes (use Copy Link), this one is recommended for use in code:
Swift 3.0
let path = URL(string: "https://itunes.apple.com/us/app/calcfast/id876781417?mt=8")
UIApplication.shared.open(path!)

Or better -- treat the optional correctly and handle the possibility of not being able to reach the link:
if let path = URL(string: "https://itunes.apple.com/us/app/calcfast/id876781417?mt=8") {
    UIApplication.shared.open(path) {
        (didOpen:Bool) in
        if !didOpen {
            print("Error opening:\(path.absoluteString)")
        }
    }
}

Objective-C
#define APP_URL_STRING  @"https://itunes.apple.com/us/app/calcfast/id876781417?mt=8"

then you can call APP_URL_STRING in your code:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: APP_URL_STRING] options:@{} completionHandler:nil];

Note, that this is the recommended way now by Apple, as the previous method of processing redirect links has been deprecated and are not supported.
The link for all your Apps, if you have more than one:
#define MYCOMPANY_URL_PATH @"http://appstore.com/mycompany"
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: MYCOMPANY_URL_PATH] options:@{} completionHandler:nil];

The App link above is recommended for use in code or links that are not seen directly by the user. If you want to provide link that may be seen and remembered by the user then use the following:
http://appstore.com/calcfast

A: This works on my end (Xcode 5 - iOS 7 - Device!):
itms-apps://itunes.apple.com/app/idYOUR_APP_ID

For versions lower than iOS 7 use the old one:
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=YOUR_APP_ID

A: Using this URL was the perfect solution for me. It takes the user directly to the Write a Review section. Credits to @Joseph Duffy.
For a sample code try this :
Swift 3, Xcode 8.2.1 :
 let openAppStoreForRating = "itms-apps://itunes.apple.com/gb/app/id1136613532?action=write-review&mt=8"
 if UIApplication.shared.canOpenURL(URL(string: openAppStoreForRating)!) {
      UIApplication.shared.openURL(URL(string: openAppStoreForRating)!)
 } else {
      showAlert(title: "Cannot open AppStore",message: "Please select our app from the AppStore and write a review for us. Thanks!!")
 }

Here showAlert is a custom function for an UIAlertController.

A: I have this to get the Product ID automatically and generate App Store Review and Product page links.
- (void) getAppStoreLinks {
productID = [[NSUserDefaults standardUserDefaults] objectForKey:@"productID"]; //NSNumber instance variable
appStoreReviewLink = [[NSUserDefaults standardUserDefaults] objectForKey:@"appStoreReviewLink"]; //NSString instance variable
appStoreLink = [[NSUserDefaults standardUserDefaults] objectForKey:@"appStoreLink"]; //NSString instance variable

if (!productID || !appStoreReviewLink || !appStoreLink) {
    NSString *iTunesServiceURL = [NSString stringWithFormat:@"https://itunes.apple.com/lookup?bundleId=%@", [NSBundle mainBundle].bundleIdentifier];
    NSURLSession *sharedSes = [NSURLSession sharedSession];
    [[sharedSes dataTaskWithURL:[NSURL URLWithString:iTunesServiceURL]
              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                  NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;

                  if (data && statusCode == 200) {

                      id json = [[NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingOptions)0 error:nil][@"results"] lastObject];

                      //productID should be NSNumber but integerValue also work with NSString
                      productID = json[@"trackId"];

                      if (productID) {
                          appStoreReviewLink = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%d&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8",productID.integerValue];
                          appStoreLink = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%d",productID.integerValue];

                          [[NSUserDefaults standardUserDefaults] setObject:productID forKey:@"productID"];
                          [[NSUserDefaults standardUserDefaults] setObject:appStoreReviewLink forKey:@"appStoreReviewLink"];
                          [[NSUserDefaults standardUserDefaults] setObject:appStoreLink forKey:@"appStoreLink"];

                      }
                  } else if (statusCode >= 400) {
                      NSLog(@"Error:%@",error.description);
                  }
              }
      ] resume];
}
}

Open app's Review Page
- (IBAction) rateButton: (id)sender {
   NSString *appStoreReviewLink = appStoreReviewLink;
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStoreReviewLink]];
}

Open app's App Store page
 - (IBAction) openAppPageButton: (id)sender {
   NSString *appStoreLink = appStoreLink;
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString: appStoreLink]];
 }

A: It is said that this bug will be fixed on iOS7.1. Read here on the corona forum, and here on the iPhoneDevSDK.

A: Starting with iOS7 the URL has changed and cannot direct for the review page but only to the app
itms-apps://itunes.apple.com/app/idAPP_ID

Where APP_ID need to be replaced with your Application ID. Based on the App ID from the question it would be the following
itms-apps://itunes.apple.com/app/id353372460

Notice the id in front of the number ... that string is is id353372460, not just 353372460
For anything pre iOS7 the 'old' URL needs to be used, only those could get you straight to the review page. You should also take note that these calls will only work on devices. Running them in the simulator will do nothing since the simulator does not have the App Store app installed.

Have a look at for instance Appirater for an implementation. https://github.com/arashpayan/appirater
Can't help you with phonegap specifics (never used it). But it basically comes down to checking the iOS version your user is running and then either use the old URL or then new iOS7 URL.

A: One-Line-of-Code Simple Alternative:    ** Also See Simulator Comments Below **
http://itunes.apple.com/app/idAPP_ID
EDIT:  Now that iOS 7.1 allows direct-link to the Reviews tab in the App Store, it's worth investing the extra lines of code to get there directly: see other answers for the rest.
here we are using http: instead of itms-apps:, let iOS do the rest of the work
I get the same results testing on iOS 6.1 & 7 devices (iPad/iPhone/iPod touch 4)

Specifically, this shortcut, for iOS 6 takes the user to the Details tab and not the Reviews tab.
The Purple+Software link gets the user all the way to the Reviews tab in iOS 6, which is obviously preferred if you know how to check the OS.
Important note: This will cause error in the simulator for iOS 5.1, 6.1 and 7.Cannot Open Page Safari can not open the page because the address is invalid (we know it is a valid URL outside the simulator, on any browser)
Just to be clear: On iOS 7: http:// provides the same experience as itms-apps: with no noticeable delay. * keep in mind that the simulator behavior noted above. This is not entire dissimilar from trying to access the camera via a simulator: the simulator is not the place to test it. *

A: It's not clear which versions of iOS this is supported by, but as part of iOS 10.3 there's a new query parameter that can be added to the URL: action=write-review. I have tested this on iOS 10.2 and 9.3.5 and it works. However, it does not work on iOS 7.1.2, so support was added between iOS 8.0 and 9.3.5. Further investigation is required!
Example: https://itunes.apple.com/app/id929726748?action=write-review&mt=8
This will open the "Write a Review" dialogue, rather than just showing the review tab.

A: Opening review page directly from app is possible in iOS7.
Please use the following url...
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=YOUR_APP_ID

This will definitely works.. :)

A: The following URL works perfectly on iOS 7.1:
http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=xxxxxxxx&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8

where the xxxxxxxx is your app ID.
UPDATE. Works on iOS 9.3.4 and iOS 10 GM (by Jeet)


text:
Q: makeindex "Extra `@' at position n of first argument", when inside newcommand using math mode I'm a long time LaTeX user, and over the years this forum has been extremely useful. I have always found an answer here, except this time.
I'm trying to create a newcommand to define some math symbols. The command defines a macro, and that macro uses \index{} when the symbol is used. It works most of the time. However, there is some math notation that generate extra @ characters, which it is not appreciated by makeindex.
I know this question is similar (but different) to question 254977, but I have been unable to adapt that solution to this situation.
This is a sample test.tex file:
% arara: pdflatex: { synctex: on }
% arara: makeindex
% arara: pdflatex: { synctex: on }
\documentclass{article}
\usepackage{amsmath,amssymb,mathrsfs,makeidx}
\makeindex

\newcommand{\MKMathSymbol}[4]{%
    \expandafter\newcommand\csname #1\endcsname{\ensuremath{#2}\index{#4!#3@\ensuremath{#2}}}
        %%% More stuff in here (glossaries, etc.)
}

\MKMathSymbol{TestOne}{\widehat{\varphi}}{phi}{Type A}
\MKMathSymbol{TestTwo}{\widehat{\mathscr{A}}}{A}{Type A}
\MKMathSymbol{TestThree}{\widehat{d_C}}{dCw}{Type B}
\MKMathSymbol{TestFour}{{\prod}}{P}{Type B}

\begin{document}
Outside math mode (\TestOne, \TestTwo, \TestThree, \TestFour).
\clearpage
Inside math mode  ($\TestOne$, $\TestTwo$, $\TestThree$, $\TestFour$).
\clearpage
Inside macro: (\emph{\TestOne, \TestTwo, \TestThree, \TestFour}).

Let now print the index:
\printindex
\end{document}

The output of makeindex (test.ilg file) contains the following:
This is makeindex, version 2.15 [MiKTeX 2.9.6100 64-bit] (kpathsea + Thai support).
Scanning input file test.idx...
!! Input index error (file = test.idx, line = 1):
   -- Extra `@' at position 36 of first argument.
 . . .
 . . .
done (0 entries accepted, 12 rejected).
Nothing written in test.ind.
Transcript written in test.ilg.

And the file text.idx will contain entries like these:
\indexentry{Type A!phi@\ensuremath  {\setbox \z@ \hbox {\frozen@everymath \@emptytoks \mathsurround \z@ $\textstyle \varphi $}\mathaccent "0362{\varphi }}}{1}
\indexentry{Type A!A@\ensuremath  {\setbox \z@ \hbox {\frozen@everymath \@emptytoks \mathsurround \z@ $\textstyle \mathscr  {A}$}\mathaccent "0362{\mathscr  {A}}}}{1}
\indexentry{Type B!dCw@\ensuremath  {\setbox \z@ \hbox {\frozen@everymath \@emptytoks \mathsurround \z@ $\textstyle d_C$}\mathaccent "0362{d_C}}}{1}
\indexentry{Type B!P@\ensuremath  {{\DOTSB \prod@ \slimits@ }}}{1}

The generated pdf file does not print the index, because test.ind is empty.
So, the question is how do I make this work? I have tried several approaches, but none of them seems to work.

A: Use \unexpanded:
\documentclass{article}
\usepackage{amsmath,amssymb,mathrsfs,makeidx}
\makeindex

\newcommand{\MKMathSymbol}[4]{%
  \expandafter\newcommand\csname #1\endcsname{%
    \ensuremath{#2}\index{#4!#3@\unexpanded{\unexpanded{\ensuremath{#2}}}}%
    %%% More stuff in here (glossaries, etc.)
  }%
}

\MKMathSymbol{TestOne}{\widehat{\varphi}}{phi}{Type A}
\MKMathSymbol{TestTwo}{\widehat{\mathscr{A}}}{A}{Type A}
\MKMathSymbol{TestThree}{\widehat{d_C}}{dCw}{Type B}
\MKMathSymbol{TestFour}{\prod}{P}{Type B}

\begin{document}
Outside math mode (\TestOne, \TestTwo, \TestThree, \TestFour).
\clearpage
Inside math mode  ($\TestOne$, $\TestTwo$, $\TestThree$, $\TestFour$).
\clearpage
Inside macro: (\emph{\TestOne, \TestTwo, \TestThree, \TestFour}).

Let now print the index:
\printindex
\end{document}

Here's the contents of the .idx file
\indexentry{Type A!phi@\ensuremath {\widehat {\varphi }}}{1}
\indexentry{Type A!A@\ensuremath {\widehat {\mathscr {A}}}}{1}
\indexentry{Type B!dCw@\ensuremath {\widehat {d_C}}}{1}
\indexentry{Type B!P@\ensuremath {\prod }}{1}
\indexentry{Type A!phi@\ensuremath {\widehat {\varphi }}}{2}
\indexentry{Type A!A@\ensuremath {\widehat {\mathscr {A}}}}{2}
\indexentry{Type B!dCw@\ensuremath {\widehat {d_C}}}{2}
\indexentry{Type B!P@\ensuremath {\prod }}{2}
\indexentry{Type A!phi@\ensuremath {\widehat {\varphi }}}{3}
\indexentry{Type A!A@\ensuremath {\widehat {\mathscr {A}}}}{3}
\indexentry{Type B!dCw@\ensuremath {\widehat {d_C}}}{3}
\indexentry{Type B!P@\ensuremath {\prod }}{3}

A: You are seeing the internal expansion of the commands "fragile command in a moving argument" in the terminology of the latex book. use
\MKMathSymbol{TestOne}{\protect\widehat{\varphi}}{phi}{Type A}
\MKMathSymbol{TestTwo}{\protect\widehat{\mathscr{A}}}{A}{Type A}
\MKMathSymbol{TestThree}{\protect\widehat{d_C}}{dCw}{Type B}
\MKMathSymbol{TestFour}{{\protect\prod}}{P}{Type B}

The index is then
\indexentry{Type A!phi@\ensuremath  {\widehat {\varphi }}}{1}
\indexentry{Type A!A@\ensuremath  {\widehat {\mathscr  {A}}}}{1}
\indexentry{Type B!dCw@\ensuremath  {\widehat {d_C}}}{1}
\indexentry{Type B!P@\ensuremath  {{\prod }}}{1}
\indexentry{Type A!phi@\ensuremath  {\widehat {\varphi }}}{2}
\indexentry{Type A!A@\ensuremath  {\widehat {\mathscr  {A}}}}{2}
\indexentry{Type B!dCw@\ensuremath  {\widehat {d_C}}}{2}
\indexentry{Type B!P@\ensuremath  {{\prod }}}{2}
\indexentry{Type A!phi@\ensuremath  {\widehat {\varphi }}}{3}
\indexentry{Type A!A@\ensuremath  {\widehat {\mathscr  {A}}}}{3}
\indexentry{Type B!dCw@\ensuremath  {\widehat {d_C}}}{3}
\indexentry{Type B!P@\ensuremath  {{\prod }}}{3}


text:
Q: Threading on Android Tablet causing freezes I'm working on a Firemonkey application in Delphi Tokyo and decided to add a loader screen that does some animation.  I have a form with a list animation that is run within one thread, and then my calls to the datasnap server runs within another thread.  I'm doing it like this because I couldn't get the animation to work if both calls wasn't within a thread.
Now running this on the windows version works fine.  Running it on both my Huawei phone and another samsung tablet works 70% of the time.  The other 30% of the time it freezes and I have to kill the app.  When the datasnap load is done the loader form is supposed to be freed and closed and the main panels opacity is set to 1 and I enable the panel again.  I'm not sure 100% if the app freezes and if the code is not run successfully thats supposed to enable the panel again.  I was able to debug it one time while not working which produced an out of memory error, but I'm unable to recreate the issue while debugging on the phone.
The idea was that when the logging button is pressed a loader screen shows some animation while the data is retrieved and then hides it again.  Am I doing something wrong in the below code?
  ShowLoader;

  fThread := TTask.Create
  (
    procedure ()
    begin
      try
        LoDataset := fmxDataModule.ServerMethods.GetLoginDetails(edtEmail.Text, edtPassword.Text);
      except on E:Exception do
        begin
          TThread.Synchronize(TThread.CurrentThread,
            procedure()
            begin
              ShowMessage('The system could not log you in.  Error Details: '+slinebreak+slinebreak+E.Message+slinebreak+slinebreak+'Please try again.');
              HideLoader;
            end
          )
        end;
      end;

      TThread.Synchronize(TThread.CurrentThread,
        procedure()
        begin
          fmxDataModule.LoggedInUser.LoadFromDataset(LoDataset);
          if fmxDataModule.LoggedInUser.CompanyID.Value > 0 then
          begin
            Toolbarheader.Visible := True;
            lblLoginInfo.Visible := false;
            lblWelcome.Text := 'Welcome ' + fmxDataModule.LoggedInUser.FirstName.Value + ', ' + fmxDataModule.LoggedInUser.LastName.Value;
            GoToProfilesTab.Execute;
            GenerateProfiles;
            pnlButtons.Visible := True;
            fLoggedIn := True;
            FormResize(nil);
          end else
          begin
            lblLoginInfo.Visible := True;
            lblLoginInfo.Text := 'User does not exist, or login details invalid';
          end;
        end
      );

      HideLoader;
    end
  );

  fThread.Start;

Here is the code for ShowLoader:
procedure TfrmLogin.CreateLoaderForm;
begin
  if Assigned(fLoader) then
    FreeAndNil(fLoader);
  fLoader := TfrmLoader.Create(Self);
  floader.Parent := Self;
  fLoader.Left := Self.Left + (Self.Width div 2) - (fLoader.Width div 2);
  fLoader.Top  := Self.Top + (Self.Height div 2) - (fLoader.Height div 2);
  fLoader.Show;
end;

procedure TfrmLogin.ShowLoader;
begin

  pnlMain.Enabled := false;
  pnlMain.Opacity := 0.4;

  TTask.Create (
    procedure ()
        begin

          TThread.Queue(TThread.CurrentThread,
            procedure()
            begin
              CreateLoaderForm
            end);

        end
    ).Start;

end;

Hiding the loader:
procedure TfrmLogin.HideLoader;
begin
  pnlMain.Enabled := True;
  pnlMain.Opacity := 1;
//  pnlMain.Repaint;
  fLoader.Visible := False;
end;

Am I missing something in the code above?
Another question is why does my form not open in the middle of the screen?  I've tried different things, setting the position in the form properties, and manually calculating it.  It always opens up top left corner on the device, but works on windows.

A: After trying a different approach like @nolaspeaker suggested, and syncronising the username and passwords fields like @RemyLebeau suggested, I removed the form loader that was in a different thread, and the problem still persisted.  Doing that became obvious that there must be a problem in the below piece of code I posted initially, only a bit refactored:
TThread.CreateAnonymousThread
  (
    procedure
    var
      LsUsername,LsPassword:String;
    begin
      try
        TThread.Synchronize(TThread.CurrentThread,
          procedure()
          begin
            LsUsername := edtEmail.Text;
            LsPassword := edtPassword.Text;
          end
        );

        LoDataset := fmxDataModule.ServerMethods.GetLoginDetails(LsUsername, LsPassword);
      except on E:Exception do
        begin
          TThread.Synchronize(TThread.CurrentThread,
            procedure()
            begin
              ShowMessage('The system could not log you in.  Error Details: '+slinebreak+slinebreak+E.Message+slinebreak+slinebreak+'Please try again.');
              HideLoader;
            end
          )
        end;
      end;

      TThread.Synchronize(TThread.CurrentThread,
        procedure()
        begin
          fmxDataModule.LoggedInUser.LoadFromDataset(LoDataset);
          if fmxDataModule.LoggedInUser.CompanyID.Value > 0 then
            GoToProfilesTab.Execute
          else
          begin
            lblLoginInfo.Visible := True;
            lblLoginInfo.Text := 'User does not exist, or login details invalid';
          end;
        end
      );

      HideLoader;
    end
  ).Start;

Trying a couple more times to debug the scenario I ended up in TTabControl.SetActiveTabWithTransition.
The issue occurs on this line
LocalAnimateIntWait(Layout2, 'Position.X', Round(P.X), Duration, TAnimationType.In,
              TInterpolationType.Linear);

in this block of code:
procedure TTabControl.SetActiveTabWithTransition(const ATab: TTabItem; ATransition: TTabTransition;
const ADirection: TTabTransitionDirection = TTabTransitionDirection.Normal);

  ...
begin
  case ATransition of
    TTabTransition.Slide:
      begin
        FTransitionRunning := True;
        ClipChildren := True;
        try
          ...

          if ADirection = TTabTransitionDirection.Normal then
          begin
            P...
          end
          else
          begin
            ...

            LocalAnimateIntWait(Layout2, 'Position.X', Round(P.X), Duration, TAnimationType.In,
              TInterpolationType.Linear);

          end;
        finally
          SetLength(FTransitionTabs, 0);
          ClipChildren := False;
          FTransitionRunning := False;
          Realign;
        end;
        // Force repaint
        Application.ProcessMessages;
      end
  else
    ActiveTab := ATab;
  end;
end;

So I remove the tab transitioning for that one click and it finally works as expected.  The moment I put the transitioning back to Slide, it freezes again on that line. I'll be sure to report this issue.


text:
Q: String aggregation in postgresql table using psycopg2 I have following table in Postgresql 11.0.
id   code   name1    name2
1    XXX    abc      sdf
1    XXX    def      null
2    ZZZ    zut      null
3    YYY    gtj      bzu
3    YYY    null     nuz

I would like to aggregate the values in name1 and name2 column for each id (in python). The below query runs perfectly in pgadmin but gives error through python script.
try:
    cursor.execute("""
            UPDATE tbl t1
            SET name1 = sub_q.name1,
                name2 = sub_q.name2
            FROM
                (
                SELECT id, code, string_agg(name1, ' ; ') as name1, string_agg(name2, ' ; ') as name2
                FROM tbl as t2
                GROUP BY t2.id, t2.code
                ) AS sub_q
            WHERE sub_q.id= t1.id
            ;
                        )
            """)
except:
    print ("The table cannot be created")

The expected output is:
id   code   name1       name2
1    XXX    abc; def     sdf
2    ZZZ    zut      null
3    YYY    gtj      bzu; nuz


text:
Q: Converting a Binary Tree into a Singly Link list I am trying to convert a binary tree into a Singly linked list.I am trying to solve the problem in O(n) time complexity.To achieve O(n) time complexity I am returning both head and tail of the link list.I am getting Wrong output please help me out.
Approach 1 is Working correctly.To reduce time complexity of Approach 1. I need to remove the while loop which is being used to traverse left link list.Therefore I need to return both Head and Tail pointer of the Link list.
Both Approach are Recursive in nature.
/**************** To Construct LL from a BST ***************/

#include <iostream>
using namespace std;
#include "BinaryTreeNode.h"
#include "linklist_class.cpp"
#include <queue>

void printTreeLevelWise(BinaryTreeNode<int>* root){
    if(root == NULL){       //Base case
        return;
    }
    queue<BinaryTreeNode<int>*> pendingNodes;
    pendingNodes.push(root);
    while(pendingNodes.size() != 0){
        BinaryTreeNode<int>* front = pendingNodes.front();
        pendingNodes.pop();
        cout<<front->data<<":";
        if(front->left != NULL){
            cout<<"L"<<front->left->data;
            pendingNodes.push(front->left);
        }
        if(front->right != NULL){
            cout<<"R"<<front->right->data;
            pendingNodes.push(front->right);
        }
        cout<<endl;
    }

}

BinaryTreeNode<int>* takeInputLevelWise(){
    int rootData;
    cout<<"Enter root data"<<endl;
    cin>>rootData;
    if(rootData == -1){
        return NULL;
    }
    BinaryTreeNode<int>* root = new BinaryTreeNode<int>(rootData);
    queue<BinaryTreeNode<int>*> pendingNodes;
    pendingNodes.push(root);

    while(pendingNodes.size() != 0){
        BinaryTreeNode<int>* front = pendingNodes.front();
        pendingNodes.pop();

        cout<<"Enter Left Child of "<<front->data<<endl;
        int leftChildData;
        cin>>leftChildData;
        if(leftChildData != -1){
                BinaryTreeNode<int>* child = new BinaryTreeNode<int>(leftChildData);
                front->left = child;
                pendingNodes.push(child);
        }

        cout<<"Enter right Child of "<<front->data<<endl;
        int rightChildData;
        cin>>rightChildData;
        if(rightChildData != -1){
                BinaryTreeNode<int>* child = new BinaryTreeNode<int>(rightChildData);
                front->right = child;
                pendingNodes.push(child);
        }

    }
    return root;
}
/******* To print Link list  *********/
void print(node *head){
    while(head != NULL){
        cout<<head ->data<<" ";
        head = head->next;
    }
    cout<<endl;
}

/***************************** Approach1 ******************************/
/* Working Correctly */

node* LLfromBST(BinaryTreeNode<int>* root){
    if(root == NULL){
        return NULL;
    }
    node* lhead = LLfromBST(root->left);
    node* rhead = LLfromBST(root->right);
    node* newNode = new node(root->data);

    newNode->next = rhead;

    // lhead head is NULL Then we will try to access NULL->next
    // to stop this let's put a check
    if(!lhead){
        return newNode;
    }

    node* temp = lhead ;
    while(temp->next != NULL){
        temp = temp->next;
    }
    temp->next = newNode;

    return lhead;
}

/***************************** Approach2 ******************************/
/* Not Working */
//O(n)  //head = p.first and tail = p.second

pair<node*,node*> LLfromBST2(BinaryTreeNode<int>* root){
    if(root == NULL){
        pair<node*,node*> p ;
        p.first = NULL;
        p.second = NULL;
        return p;
    }
    pair<node*,node*> lp  = LLfromBST2(root->left);
    pair<node*,node*> rp  = LLfromBST2(root->right);

    node* newNode = new node(root->data);
    newNode->next = rp.first;

    // lhead head is NULL Then we will try to access NULL->next
    // to stop this let's put a check
    if(!lp.first){
        pair <node*,node*> p;
        p.first = newNode;
        p.second = rp.second;
        return p;
    }
    lp.second->next = newNode;
    pair <node*,node*> p;
    p.first = lp.first;
    p.second = rp.second;
    return p;
}

int main(){
    // BST :   4 2 6 1 3 5 7 -1 -1 -1 -1 -1 -1 -1 -1

    BinaryTreeNode<int>* root = takeInputLevelWise();
    printTreeLevelWise(root);
    cout<<endl;
    //Approach 1
    /*node* head = LLfromBST(root);
    print(head);
    cout<<endl;*/
    //Approach 2
    node* head2 = LLfromBST2(root).first;
    print(head2);
    delete root;
    return 0;
}

A: Just an inorder traversal of BST will yield a sorted list of the nodes. So you need something like below:
        void buildLLFromBST(BinaryTreeNode<int>* root, ListNode<int>* node) {
            if (root) {
               buildLLFromBST(root->left, node);
               node->next = root;
               node = node->next;
               buildLLFromBST(root->right, node);
            }
        }

and you could call it like : buildLLFromBST(root, dummynode)


text:
Q: issues with implementing bogosort For some reason I decided to implement the almighty bogosort in python, and I wrote the code below:
import numpy as np

def checkSorted(x):
  if x == sorted(x[:]):
    return True
  else:
    return False

def bogosort(x):
  np.random.shuffle(x)
  if checkSorted(x):
    return
  else:
    bogosort(x)

arr = [1,3,2]
bogosort(arr)
print(arr)

when the array size exceeded 4, I would get the following error:

RecursionError: maximum recursion depth exceeded while calling a Pythonobject

Yikes! I found the workaround which is:
import sys
sys.setrecursionlimit(50000)

this should be fine with an array size of 8, since 8! is 40320, but this time I ran into a segmentation fault!

repl process died unexpectedly: signal: segmentation fault (core
  dumped)

Yikes again! I think this time it's running out of memory and crashing. Is there a way to increase the allowed memory usage to prevent this?
I really want this algorithm to work with at least an array size of 10 so I can draw a graph comparing it to other algorithms, since something like quicksort can't even be timed with inputs of less than 10.

A: Since bogosort can take a very, very long time to run as the array size increases, you might be better off using iteration rather than recursion. This is because larger arrays will easily exceed the recursion depth.
Here, I have edited your code to use a loop. I also made some of your code more concise.
import random

def checkSorted(x):
    # A more concise way is to just return the comparison,
    # which will evaluate to either True or False.
    return x == sorted(x)

def bogosort(x):
    # Instead of using recursion, you could use iteration.
    # List x will continue to be shuffled until it is sorted.
    while not checkSorted(x):
        random.shuffle(x)
    # Once x is sorted, return it.
    return x

# Here, I just initialized arr as a list of integers from 0 to 5, excluding 5
arr = list(range(5))
# To test bogosort, let's shuffle the list beforehand
random.shuffle(arr)
# Run bogosort, then print the sorted array
bogosort(arr)
print(arr)

I also used Python's built-in random module. Though if you need to, you can freely use numpy instead.


text:
Q: Ruby regex parse string for two sets of numbers? I have been using Rubular.com to come up with a regex pattern to try to parse this string for the values 596 and 777 and put them in an array:
Current mouse position: 596,777

I have been building this in IRB and testing it with t.scan(/(?:\d)/)
This yields: ["4", "5", "1", "1", "1", "3", "7"] which is not correct.
Does anyone have any pointers?

A: You have forgotten to put a quantifier:
t.scan(/\d+/)

The quantifier + means one or more
Note: The non-capturing group (?:...) is useless.

A: str = "Current mouse position: 596,777"

x, y = str.split()[-1].split(",")
puts x, y

--output:--
596
777

...
str = "Current mouse position: 596,777"

x = str[-7..-5]
y = str[-3..-1]
puts x, y

--output:--
596
777


text:
Q: How to bind TextBox to multiple datacontext I want to update the Person data in batch.
public class Person
{
    public long personID { get; set; }
    public long FirstName { get; set; }
    public long LastName { get; set; }
    public long Department { get; set; }
}

List m_list = new List();
I have a TextBox "TextBox1" control which I want to bind to "Department" attribute of every Person of m_list.
foreach(Person current in m_list)
{
    //string bindingPath = "Department";
    //Binding binding = new Binding(bindingPath);
    //binding.Mode = BindingMode.TwoWay;
    //binding.Source = current;
    //TextBox1.SetBinding(TextBox1.Text, binding);
}

A: Pretty easy to do in your view model with something like this:
public class MainViewModel
    {
        private readonly Lazy<ObservableCollection<Person>> _people = new Lazy<ObservableCollection<Person>>(
            () =>
                {
                    return new ObservableCollection<Person>
                            {
                                new Person {Department = "Dept1", FirstName = "Person", LastName = "1"},
                                new Person {Department = "Dept2", FirstName = "Person", LastName = "2"},
                            };
                });
        public ObservableCollection<Person> People { get { return _people.Value; } }

        public string Department
        {
            set
            {
                foreach (var p in People)
                    p.Department = value;
            }
        }
    }

Sample XAML:
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBox Grid.Column="0" Text="{Binding Department, UpdateSourceTrigger=PropertyChanged}" />
        <ListView ItemsSource="{Binding People}" Grid.Column="1">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Margin="0,0,0,15">
                        <TextBlock Text="{Binding Department}"/>
                        <TextBlock>
                            <TextBlock.Text>
                                <MultiBinding StringFormat="{}{0} {1}">
                                   <Binding Path="FirstName"/>
                                   <Binding Path="LastName"/>
                                 </MultiBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>

A: I think you may be misunderstanding the DataContext
WPF applications contain two layers: the UI layer and the data layer. The DataContext is the data layer, while your controls (such as a TextBox) is the UI layer.
If you want to update your data in a batch, simply perform your update in the data layer. You do not need to get the UI layer involved at all (unless you're getting a value from it).
For example, if you have a single TextBox and you want to set the Department property of every Person in the List<Person> to TextBox.Text, then simply loop through your Person list, and set the Department property of each one to TextBox1.Text
foreach(Person current in m_list)
{
    current.Department = TextBox1.Text;
}


text:
Q: ExtJS infinite loop on grid focus We're using ExtJS 4.2 and ran into weird problem.
There's a grouped grid panel from which we drag elements to a tree panel. In most cases everything is working fine, but sometimes for unknown reason wrong item is dragged or it doesn't happen at all. In these cases call stack that's printed in console shows infinite loop:
Ext.dom.Query.Ext.core.DomQuery.Ext.DomQuery.DQ.filter
Ext.dom.Query.Ext.core.DomQuery.Ext.DomQuery.DQ.is
Ext.define.is
Ext.define.getNode
Ext.define.indexOf
Ext.define.onLastFocusChanged
Ext.define.setLastFocused
Ext.define.focusRow
Ext.define.onRowFocusExt.define.onLastFocusChanged
Ext.define.setLastFocused
Ext.define.focusRow
Ext.define.onRowFocus
....
Ext.define.onLastFocusChanged
Ext.define.setLastFocused
Ext.define.focusRow
Ext.define.onRowFocus
....

Any attempts to deliberatelly replicate the bug had failed, and logging all information on grid events to console doesn't show anything unusual.
Has anybody had this problem, and maybe fixed it successfully?
Thanks


text:
Q: MongoDB .NET Group by with list result of whole objects I was digging into the documentation of MongoDB http://mongodb.github.io/mongo-csharp-driver/2.7/reference/driver/crud/linq/ and I saw, using .NET drive is possible to make group by on the database.
For 1 ProductId I can have few elements in a database. I want to get whole Last element.
So I am trying to do something like:
var query = _collection.AsQueryable()
            .GroupBy(p => p.ProductId, (k, s) =>
                new { Name = k, Result = s.First() })
            .Select(x => new { Name = x.Name, Result = x.Result }).First();

The problem is that I see an error message like:

System.NotSupportedException: Specified method is not supported.
at
MongoDB.Driver.Linq.Processors.AccumulatorBinder.GetAccumulatorArgument(Expression node)

I know that for now in my example i didnt order by the result.. But this will be my second step. For now i see that i cannot group by. Is it possible to do this kind of group by?

A: My solution for that is:
var query = _collection.Aggregate(new AggregateOptions { AllowDiskUse = true })
            .Match(x => ElementIds.Contains(x.ElementId))
            .SortByDescending(x => x.StartDate).ThenByDescending(x => x.CreatedAt)
            .Group(x => x.ElementId, x => new
            {
                StartDate = x.First().StartDate,
                Grades = x.First().Grades,
                SellingId = x.First().SellingId,
                CreatedAt = x.First().CreatedAt,
                ModifiedAt = x.First().ModifiedAt,
                Id = x.First().Id,
                ElementId = x.First().ElementId
            })
            .ToEnumerable(token);

After that, I parsed it into my model.
AllowDiskUse = true, because in my case MongoDB's memory is not enough to handle this operation.


text:
Q: Automapper - flattening of object property let's say I have
public class EFObject
{
    public int Id { get; set; }
    public int NavId { get; set; }
    public NavObject Nav { get; set; }
}

public class DTOObject
{
    public int Id { get; set; }
    public int NavId { get; set; }
    public string NavName { get; set; }
}

My expectation was high, and I thought to my self the built-in flattening should handle this, so my mapping is very simple
CreateMap<DTOObject, EFObject>().ReverseMap();

Unfortunately, converting DTOObject to EFObject does not work as expected because EFObject.Nav is null. Since I used the name NavId and NavName I would expect it to create a new NavObject and set the Nav.Id and Nav.Name accordingly.
My Problem : Is there a feature in Automapper that will allow me to achieve the intended result without having to manually write a rule to create an NavObject when mapping the Nav property?.

A:
Unflattening is only configured for ReverseMap. If you want unflattening, you must configure Entity -> Dto then call ReverseMap to create an unflattening type map configuration from the Dto -> Entity.

as noted by Automapper documentation here


text: Q: Are factorization machines robust to outliers? Factorization machines (FMs) seem great for modeling very sparse data. However, I have not come across much discussion regarding the impact of outliers. If FMs are robust, why is that so?


text:
Q: Need url navigation From DropDown Value onClick Button with passing url variables If I submit Go Button Without Selecting it will goto url like This.."&age=10". I need code for navigate to url with post url variable for my wordpress site.

A: You have 2 options:

*

*Use the button to submit a form. Your form should have method="POST".
<form action="yoururl" method="POST">
    <input name="age" type="text">
    <button type="submit">Go</button>
</form>

*Use ajax to perform a POST. Here are the docs: https://api.jquery.com/jquery.post/
And here's a quick snippet:
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

For future reference, you should probably post what you've tried and some of your existing code to get quicker/better help from stackoverflow.


text:
Q: XPath Substring-After Help / Query/Evaluate? I'm building a php script to transfer selected contents of an xml file to an sql database..
One of the hardcoded XML contents is formatted like this:
<visualURL>
id=18144083|img=http://upload.wikimedia.org/wikipedia/en/8/86/Holyrollernovacaine.jpg
</visualURL>

And I'm looking for a way to just get the contents of the URL (all text after img=).
$Image = $xpath->query("substring-after(/Playlist/PlaylistEntry[1]/visualURL[1]/text(), 'img=')", $element)->item(0)->nodeValue;

Displays a property non-object error on my php output.
There must be another way to just extract the URL contents using XPath that I want, no?
Any help would be greatly appreciated!
EDIT:
Here is the minimum code
<?php

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML('<Playlist>
<PlaylistEntry>
<visualURL>
id=12582194|img=http://upload.wikimedia.org/wikipedia/en/9/96/Sometime_around_midnight.jpg
</visualURL>
</PlaylistEntry>
</Playlist>');
$xpath = new DOMXpath($xmlDoc);
$elements = $xpath->query("/Playlist/PlaylistEntry[1]");

if (!is_null($elements))
foreach ($elements as $element)
$Image = $xpath->query("substring-after(/Playlist/PlaylistEntry[1]/visualURL[1]/text(), 'img=')", $element)-  >item(0)->nodeValue;
print "Finished Item: $Image";

?>

EDIT 2:
After some research I believe I must use
    $xpath->evaluate
instead of my current use of
    $xpath->query
see this link
Same XPath query is working with Google docs but not PHP
I'm not exactly sure how to do this yet.. but i will investigate more in the morning. Again, any help would be appreciated.

A: You're in right direction. Use DOMXPath::evaluate() for xpath expression that doesn't return node(s) like substring-after() (it returns string as documented in the linked page). The following codes prints expected output :
$xmlDoc = new DOMDocument();
$xml = <<<XML
<Playlist>
<PlaylistEntry>
<visualURL>
id=12582194|img=http://upload.wikimedia.org/wikipedia/en/9/96/Sometime_around_midnight.jpg
</visualURL>
</PlaylistEntry>
</Playlist>
XML;

$xmlDoc->loadXML($xml);
$xpath = new DOMXpath($xmlDoc);
$elements = $xpath->query("/Playlist/PlaylistEntry");

foreach ($elements as $element) {
    $Image = $xpath->evaluate("substring-after(visualURL, 'img=')", $element);
    print "Finished Item: $Image <br>";
}

output :
Finished Item: http://upload.wikimedia.org/wikipedia/en/9/96/Sometime_around_midnight.jpg

Demo


text:
Q: Delay hide() from toggle() I have an element that when clicked is either visible or hidden using jQuery's toggle() method.
Using toggle() is it possible to delay it from being hidden for a few seconds, while not delaying the visibility?
$('.myelement').click(function() {
    $('.myelement').toggle();
});

A: Just try with:
$('.myelement').click(function() {
  if ($(this).is(':visible')) {
    $(this).delay(1000).hide();
  } else {
    $(this).show();
  }
});

Or simplier:
$('.myelement').click(function() {
  $(this).delay($(this).is(':visible') ? 1000 : 0).toggle();
});


text:
Q: Selenium explicit waits (importing folder) I'm new to the site and the website wouldn't let me upload my question because i didnt "indent my code" which I have. I spent 1.5h trying to type my question, so i decided to use screen shot. I need help with Selenium Explicit Waits.
[EDIT]:I realised I was using python idle 3.6 instead of idle 2.7. SMH sorry for wasting everyone's time. this is why it wouldn't run.
Links to websites:
https://www.hongkiat.com/blog/automate-create-login-bot-python-selenium/
http://selenium-python.readthedocs.io/waits.html
Please check out the question.
Thank you.

A: Well, I'm going to try to answer with some assumptions.
I assume that you are new like me and had no concept of pip install.
Generally, if you are new, you think of downloading and pressing an exe. file to install something. You probably(I did) tried something like this and installed it incorrectly. Pip install tends to be very consistent and avoid making this an issue.
I find this to be a general benign issue with the coding community if you're brand new. There's just so many concepts that are taken for granted that explanation to beginners tends to be not so great. You have to be very specific and give a lot of context and your own thought processes to even type the right question.
Here are the steps:
1.Find where your python folder is located and write down the path:
C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts

2.Click on your windows start button and type "cmd" in the search bar and click on it to open that wonderful black box.
3.Now copy paste the address and add '\pip install selenium and hit enter
C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts\pip install selenium

All you need to now is wait for it to tell you to that it was successful. There are other functions for pip like uninstalling, updating and etc. Just so you know. Sometimes one of the annoying things for me is making sure I have the right term/name when I use pip install. Keep in mind that not everything is installed through pip, just most of the things you will use probably.
More examples:
 C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts\pip install numpy
 C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts\pip install openpyxl
 C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts\pip install <libraryname>

This is the video that taught me how to install things:
https://www.youtube.com/watch?v=jnpC_Ib_lbc


text:
Q: Is there a way to let some traefik services manage their tls certificates themselves? I'll try to configure traefik for something like that:
1) server.example.com --> traefik --> httpChallengeToLetsEncrypt
2) client --> traefik (passthrough tls) --> server.example.com( with let's encrypt )
N.B.: traefik receives its requests at example.com level
What is happening:
1) Works correctly only if traefik does not manage let's encrypt certificates itself (otherwise it does not transmit any request whose pathPrefix begins with ".well-known/acme-challenge" :-\ )
2) Does not work with a config for tcp router like this:
tcp:
  routers:
    example:
      entryPoints:
        - web-secure
      rule: "HostSNI(`server.example.com`)"
      service: example
      tls:
        passthrough: true

  services:
    example:
      loadBalancer:
        servers:
          - url: "https://192.168.0.1:443/"

How would you let one or more services manage their let's encrypt certificates themselves ?
And is it possible to do it at the same time that traefik also manages let's encrypt certificates or the problem mentioned in point 1 is it redibitory?
Best regards,
jmc

A: use tls.passthrough=true and a tcp router instead of http
below is a fully working example where apache is responsible for its own certificates.
traefik never touches them
version: "3"

services:
    traefik:
        image: traefik
        command:
            - --api.insecure=true
            - --providers.docker=true
        ports:
            - "80:80"
            - "443:443"
            - "8080:8080"
        volumes:
            - /var/run/docker.sock:/var/run/docker.sock
        labels:
            - traefik.http.routers.api.rule=Host(`traefik.docker.local`)
            - traefik.http.routers.api.service=api@internal

    whoami:
        image: containous/whoami
        labels:
            - traefik.http.routers.whoami.rule=Host(`whoami.docker.local`)
            - traefik.http.routers.whoami.service=whoami@docker
            - traefik.http.services.whoami.loadbalancer.server.port=80

    apache:
        build: php-apache
        depends_on: [traefik]
        env_file: ./php-apache/env
        volumes:
            - "./php-apache/cert/haproxy/:/etc/ssl/haproxy/"
            - "./php-apache/cert/private/:/etc/ssl/private/"
            - "./php-apache/cert/trusted/:/usr/local/share/ca-certificates/"
            - "./php-apache/conf/:/etc/apache2/conf-enabled/"
            - "./php-apache/log/:/var/log/apache2/"
            - "./php-apache/sites/available/:/etc/apache2/sites-available/"
            - "./php-apache/sites/enabled/:/etc/apache2/sites-enabled/"
            - "./php-apache/www/:/var/www/"
        labels:
            - "traefik.http.routers.apache.entrypoints=http"
            - "traefik.http.routers.apache.priority=1"
            - "traefik.http.routers.apache.rule=HostRegexp(`{catchall:.*}`)"
            - "traefik.http.routers.apache.service=apache@docker"
            - "traefik.http.services.apache.loadbalancer.server.port=80"

            - "traefik.tcp.routers.apache.entrypoints=https"
            - "traefik.tcp.routers.apache.rule=HostSNI(`*`)"
            - "traefik.tcp.routers.apache.service=apache@docker"
            - "traefik.tcp.routers.apache.tls.passthrough=true"
            - "traefik.tcp.services.apache.loadbalancer.server.port=443"


text:
Q: Spring MVC request and response flow explanation I can't find correct client request flow in below syntax.Could someone please clarify what is happening here?
Client(1) --> Dispatcher Servlet(2) --> Handler Mapping(3) --> Controller(4) -->
ModelAndView(5) --> viewResolver(6) --> View(7) --> Client(1)

If possible please specify what are the corresponding spring classes/interfaces used in spring MVC process.

A: *

*Request will be received by DispatcherServlet.

*DispatcherServlet will take the help of HandlerMapping and get to know the @Controller class name associated with the given request.

*So request transfer to the @Controller, and then @Controller will process the request by executing appropriate methods and returns ModelAndView object (contains Model data and View name) back to the DispatcherServlet

*Now DispatcherServlet send the model object to the ViewResolver to get the actual view page.

*Finally, DispatcherServlet will pass the Model object to the View page to display the result.

A:
Spring Flow
  First  Request from JSP/HTML will hit the dispacher servlet,
  Based on the xml file it will go to particular controller,
  After going to controller it search for request mapping , based on request mapping it will go to the particular method and follows instructions and takes the model and view and give it to view resolver via dispacher servlet and view resolver will display the view.

A: I supplement the above explanations. request flow is like below.
Client --> WAS(go through filters) --> DispatcherServlet.doService, doDispatch --> Dispatcher Servlet.handlerMapping,hanlderAdapter --> Controller return ModelAndView --> DispatcherServlet.processDispatchResult, render, resolveViewName --> View --> Client.
I think debugging DispatcherServlet's methods with break points is a good way to understand request flow.


text:
Q: Delete object in handle class potentially causes undefined behavior I have the following piece of code (from Koening & Moo Accelerated C++ page 255) that defines a generic handle class Handle. Handle is used to manage the memory of objects:
#include <iostream>
#include <stdexcept>

///Handle
template <class T>
class Handle
{
  public:
    Handle() : p(0) {}
    Handle &operator=(const Handle &);
    T *operator->() const;
    ~Handle() { delete p; }
    Handle(T *t) : p(t) {}

  private:
    T *p;
};

template <class T>
Handle<T> &Handle<T>::operator=(const Handle &rhs)
{
    if (&rhs != this)
    {
        delete p;
        p = rhs.p ? rhs.p->clone() : 0;
    }
    return *this;
};

template <class T>
T *Handle<T>::operator->() const
{
    if (p)
        return p;
    throw std::runtime_error("error");
};

class test_classA
{
    friend class Handle<test_classA>;

  private:
    virtual test_classA *clone() const { return new test_classA; }

  public:
    virtual void run() { std::cout << "HiA"; }
};

class test_classB : public test_classA
{
  private:
    virtual test_classB *clone() const { return new test_classB; }

  public:
    virtual void run() { std::cout << "HiB"; }
};

int main()
{

    Handle<test_classA> h;
    h = new test_classA;
    h->run();

    return 0;
}

When I compile this using g++ -o main main.cpp -Wall I get the warning:
warning: deleting object of polymorphic class type 'test_classA' which has non-virtual destructor might cause undefined behaviour [-Wdelete-non-virtual-dtor]
     ~Handle() { delete p; }

I don't quite understand the warning. The handle class automatically deletes the pointer *p in the destructor regardless of its type, so where is the potential pitfall?

A: Your warning says it all. Your class A is polymorphic, but destructor is non-virtual. Deleting object of derived class through the pointer to base class when base class doesn't have virtual destructor is undefined behavior.
In your specific example there is no undefined behavior, because you do not have the object of derived class, but compiler probably can't make sure of it, so it warns you regardless.

A: The problem is that if the object handled is of a subclass of the template instanciation type wrong deletion will happen.
In your case it will happen if your Handle<test_classA> h; will handle object of type test_classB...

A: Handle h has type Handle<test_classA> so it will store a pointer to test_classA and call a destructor of test_classA. However you can store a pointer to test_classB in your handle and in this case test_classB destructor won't be called since test_classA destructor is not virtual:
h = static_cast< test_classA * >(new test_classB);

Also note that this Handle class has poorly chosen name and it is essentially a smart pointer kind of class.

A: In C++, if you have a base class (here, test_classA) that has other classes derive from it (here, test_classB), you have to be careful about deleting pointers of type test_classA if those pointers might actually point at objects of type test_classB. Notice that you're doing precisely this in the code that you've written here.
If you do something like this, you need to give your base class (test_classA) a virtual destructor, like this:
class test_classA {
public:
    virtual ~test_classA() = default;
    // ...
};

This way, when C++ tries to delete a pointer of type test_classA, it knows that the pointer in question might not actually point at a test_classA object and will correctly call the right destructor.
This issue is completely independent of your wrapper type, by the way. You could get the same issue by writing
test_classA* ptr = new test_classB;
delete ptr; // <--- Warning! Not good unless you have a virtual dtor.

A: The warning is due to the fact that your base class' destructor is not virtual. If you want to use your class polymorhically (For instance creating a vector with base class pointers where the pointed to object is a derived class) you gonna have undefined behavior.
Another thing to mention is that you declare the Handle class as a friend of class test_classA in order to gain access to the clone function. Pay attention that the friend keyword is not transitive so in your derived class the Handle class has no access to the clone function.
Finally your clone function is not so clear to me. Let's look at the main function:
Handle<test_classA> h;
h = new test_classA

*

*You instantiate a class Handle  with its default constructor which initialize p to be a nullpointer (by the way, if you use C++11 it is much better to initialize it with nullptr instead of 0 or NULL)

*In the next line you call the operator= of the instance h. Here, your operator= waits for a Handle class. So the expression new test_classA will implicitly call your Handle class constructor Handle(T *t) : p(t) {}. Then this will be used in your operator= function where you check whether rhs.p is NULL or not. As it is not null you will call the clone function (what you wrote is equivalent to (rhs.p)->clone  so its not the Handle class' operator-> which is called but the pointer p) which will create a memory again in the HEAP.

I think it was not what you wanted.


text:
Q: Sql Image column conversion I am trying to convert an image column to a tif file. I understand the code and how it works but the column contents aren't making much sense to me.
I am hoping someone may recognize the contents and give me an idea how to proceed.
I pull the image column from my database and stuffed into into a byte array.
then created a filestream object and wrote out tif files (i kept getting invalid parameter when i used the memory stream method)
The filestream created the tif files but they could not be opened (message saying the file was corrupted.
So on a whim, i tried converting it to a string.
i suspect this is correct because the contents are now readable
"\0\u0001\0\0\0ÿÿÿÿ\u0001\0\0\0\0\0\0\0\f\u0002\0\0\0ISystem, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\u0005\u0001\0\0\0-System.Collections.Specialized.ListDictionary\u0004\0\0\0\u0004head\aversion\u0005count\bcomparer\u0004\0\0\u0003<System.Collections.Specialized.ListDictionary+DictionaryNode\u0002\0\0\0\b\b\u001cSystem.Collections.IComparer\u0002\0\0\0\t\u0003\0\0\0\b\0\0\0\b\0\0\0\n\u0005\u0003\0\0\0<System.Collections.Specialized.ListDictionary+DictionaryNode\u0003\0\0\0\u0003key\u0005value\u0004next\u0002\u0002\u0004<System.Collections.Specialized.ListDictionary+DictionaryNode\u0002\0\0\0\u0002\0\0\0\u0006\u0004\0\0\0\u00040001\u0006\u0005\0\0\0\u0004Text\t\u0006\0\0\0\f\a\0\0\0QSystem.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\u0001\u0006\0\0\0\u0003\0\0\0\u0006\b\0\0\0\n0001Center\t\t\0\0\0\t\n\0\0\0\u0005\t\0\0\0\u0015System.Drawing.PointF\u0002\0\0\0\u0001x\u0001y\0\0\v\v\a\0\0\0u\u001eÔ¿éÉÑÀ\u0001\n\0\0\0\u0003\0\0\0\u0006\v\0\0\0\r0001Expansion\t\f\0\0\0\t\r\0\0\0\u0005\f\0\0\0\u0014System.Drawing.SizeF\u0002\0\0\0\u0005width\u0006height\0\0\v\v\a\0\0\0e€Y@TžK?\u0001\r\0\0\0\u0003\0\0\0\u0006\u000e\0\0\0\t0001Color\t\u000f\0\0\0\t\u0010\0\0\0\u0005\u000f\0\0\0\u0014System.Drawing.Color\u0004\0\0\0\u0004name\u0005value\nknownColor\u0005state\u0001\0\0\0\t\a\a\a\0\0\0\n \0\0ÿ\0\0\0\0\0\0\u0002\0\u0001\u0010\0\0\0\u0003\0\0\0\u0006\u0011\0\0\0\b0001Text\u0006\u0012\0\0\0\u001bPARTIAL RELEASE IN  09/2573\t\u0013\0\0\0\u0001\u0013\0\0\0\u0003\0\0\0\u0006\u0014\0\0\0\b0001Font\t\u0015\0\0\0\t\u0016\0\0\0\u0005\u0015\0\0\0\u0013System.Drawing.Font\u0004\0\0\0\u0004Name\u0004Size\u0005Style\u0004Unit\u0001\0\u0004\u0004\v\u0018System.Drawing.FontStyle\a\0\0\0\u001bSystem.Drawing.GraphicsUnit\a\0\0\0\a\0\0\0\u0006\u0017\0\0\0\u0014Microsoft Sans Serif\0\0\u001cA\u0005èÿÿÿ\u0018System.Drawing.FontStyle\u0001\0\0\0\avalue__\0\b\a\0\0\0\u0001\0\0\0\u0005çÿÿÿ\u001bSystem.Drawing.GraphicsUnit\u0001\0\0\0\avalue__\0\b\a\0\0\0\u0003\0\0\0\u0001\u0016\0\0\0\u0003\0\0\0\u0006\u001a\0\0\0\v0001Charset\b\b\u0001\0\0\0\t\u001b\0\0\0\u0001\u001b\0\0\0\u0003\0\0\0\u0006\u001c\0\0\0\u00130001TextOrientation\b\b\0\0\0\0\n\v"

So now it looks like i have a string of meta data:
name\u0005
System.Drawing.FontStyle\u0001\0\0\0\a
etc etc
My question is how do i convert what appears to be name value pairs into something readable?
I am expecting a string such as
"Satisified on 1/1/2016" with the other attributes applied as neccessary.
Thanks
Edit:
Here is the code that produces the string
        foreach (var item in guids)
        {

            string docGUID = item.DocGuid;
            string path = "C:\\TestAnnotations\\" + docGUID;

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }

            var rows = results.AsEnumerable().Where(rw => (string)rw["DocGUID"] == docGUID);
            Bitmap img = new Bitmap(800, 800);
            int lastImagePos = 1;

            foreach (var annotation in rows)
            {

                string fileName = path + "\\" + docGUID + lastImagePos.ToString() + ".tif";
                byte[] buffer = (byte[])annotation["Annotations"];

                var str = System.Text.Encoding.Default.GetString(buffer);

            }

        }

A: I was able to get rid of the bad characters and return just a string by running the value above through this code:
                    for (int i = 0; i < text.Length; i++)
                    {
                        char c = text[i];
                        byte b = (byte)c;
                        if (b < 32)
                            test += " ";
                        else
                            test += c;
                    }


text:
Q: Ionic 2 , cordova-plugin-geolocation not work in android 7.0 and higher Cordova plugin geolocation does not support android 7.0 and higher
How can i get geolocation in IONIC 2 for android 7 and higher

A: try https://www.joshmorony.com/ionic-2-how-to-use-google-maps-geolocation-video-tutorial/
 there are tons of tutorials. just search.. :)


text:
Q: Approximated number of elastic in a box is 100 with 1 significant figure. How to express this in $x \pm y$ notation? Question from stackexchange
How many significant figures are there after 96
is correct to 1 significant figure?
From this statement:

It is given that the approximated number of elastic in a box is 100.
If the number is correct to 1
significant figure, what is the smallest possible number of elastic?
Answer: 100

How would one express this in $x \pm y$ notation?:
All x in 100 <= x <= 149 gets mapped to $1 \times 10^2$ = 100.
How to express this in $x \pm y$ notation?
I would have supposed $100 \pm 49$, because 51..149 gets rounded to 100,
but then the statement from the correct answer will be violated:
"smallest possible number is 100".

A: Significant "numbers" is not significant "figures"!  In any case, "96 correct to 1 significant figure" means that it has been rounded to the "ones" place.  And that means the number can be anywhere from 95.5 to 96.5.  [tex]x= 96\pm 0.5[/tex].


text:
Q: Is there a way to flag the use of non-reentrant C library calls? I'm working on a project that's heavily multi-threaded, and was wondering if there's a way to have the compiler flag the use of non-reentrant calls to the C library (e.g. strtok intsead of strtok_r)?  If not, is there a list of calls that are non-reentrant so I can grep through my code base periodically?
A related question is if there's a way to flag 3d party library use of non-reentrant calls.
I'm assuming reentrancy implies thread-safety, but not necessarily the other way around.  Is there a good reason to use non-reentrant calls in a threaded project?

A: For source, you could possibly insist that every source file contains the line:
#include <beware.h>

after the C headers, and then the beware.h header file contains:
#define strtok   unsafe_function_call_detected_strtok
#define getenv   unsafe_function_call_detected_getenv

or some other suitable set of names that are unlikely to be real functions. That will result in compilation and/or linker errors.
For libraries, it's a bit more difficult. You can look into using nm to extract all the unresolved names in each object file and ensure none of the unsafe ones are called.
This wouldn't be the compiler doing it but it would be easy enough to incorporate into the build scripts. See the following transcript:
$ cat qq.c
    #include <stdio.h>

    int main (int argc, char *argv[]) {
        printf ("Hello, world.\n");
        return 0;
    }

$ gcc -c -o qq.o qq.c

$ nm qq.o
00000000 b .bss
00000000 d .data
00000000 r .rdata
00000000 t .text
         U ___main
00000000 T _main
         U _puts

You can see the unresolved symbols in that output with a U marker (and gcc has very sneakily decided to use puts instead of printf since I gave it a constant string with no formatting commands).

A:
is there a list of calls that
  are non-reentrant so I can grep
  through my code base periodically?

I looked through the GNU libc function list, and picked out the ones with _r.  Here's the list.
asctime, crypt, ctime, drand48, ecvt, encrypt, erand48, fcvt, fgetgrent, fgetpwent, getdate, getgrent, getgrgid, getgrnam, gethostbyaddr, gethostbyname2, gethostbyname, getmntent, getnetgrent, getpwent, getpwnam, getpwuid, getutent, getutid, getutline, gmtime, hcreate, hdestroy, hsearch, initstate, jrand48, lcong48, lgamma, lgammaf, lgammal, localtime, lrand48, mrand48, nrand48, ptsname, qecvt, qfcvt, rand, random, readdir64, readdir, seed48, setkey, setstate, srand48, srandom, strerror, strtok, tmpnam, ttyname

A: Addressing the second part of your question:
Non re-entrant calls may be implemented in a way that gives them a performance advantage. In this case if you know you're only making those calls from one thread (or within one critical section), and they're your bottleneck then choosing the non-reentrant call makes sense. But I'd only do it if there were performance measurements suggesting that it was critical to do so... And carefully document it..

A: For binaries, you can use LD_PRELOAD to intercept whatever C library functions you like and take whatever action you want (abort, log an error but proceed, etc.)
During development, you can also use valgrind to do the same.
For some sample code and references, see the answers to how could I intercept linux sys calls?

A: Cppcheck will flag use of non-reentrant standard library functions.  Enable the portability warnings to enable this check.
Refer to non_reentrant_functions_list in checknonreentrantfunctions.h for a list of the functions Cppcheck will flag.
Example of the message Cppcheck will emit:

Non reentrant function 'strtok' called. For threadsafe applications it is recommended to use the reentrant replacement function 'strtok_r'. (portability: nonreentrantFunctionsstrtok)


text:
Q: Get number first and second and third from text line I have the following format in my txt file:

1   1,30705856804525E-7 2,64163961816166E-8
1,12201845645905    1,24157281788939E-7 2,45690063849224E-8
1,25892543792725    1,18248813407718E-7 2,29960868125545E-8
1,41253757476807    1,13006606738963E-7 2,16654658657944E-8
1,58489322662354    1,0842624220686E-7  2,05472137082552E-8
1,77827942371368    1,04479198625995E-7 1,96135836461053E-8
1,99526226520538    1,01119816520168E-7 1,8839035220708E-8
2,23872113227844    9,82917924829962E-8 1,82003176973922E-8
2,51188635826111    9,59338279926669E-8 1,76765304615856E-8
2,81838297843933    9,39840489877497E-8 1,72491425587395E-8
3,16227769851685    9,23831819932275E-8 1,69019571671924E-8
3,54813385009766    9,10766573269939E-8 1,66210121221866E-8
3,98107171058655    9,00157104410937E-8 1,63944182673958E-8
4,46683597564697    8,91577514039454E-8 1,62121711611007E-8
5,01187229156494    8,8466336478632E-8  1,60659361370108E-8
5,6234130859375 8,7910699164695E-8  1,59488209305891E-8
6,30957365036011    8,74651959748007E-8 1,58551749507296E-8
7,07945775985718    8,71086527354237E-8 1,57803938805046E-8
7,94328212738037    8,68237393092386E-8 1,57207402651238E-8
8,91250896453857    8,65963372120859E-8 1,56731942979604E-8
10  8,64150138113473E-8 1,56353241465013E-8
11,2201843261719    8,62705391568852E-8 1,5605175818223E-8

I need to get only value for integers on left and right value so in this example I need to get:

1
2,64163961816166E-8

10
1,56353241465013E-8

This is what I've tried:
' Check Noise Spectral Density.txt exists
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(fso.GetParentFolderName(WScript.ScriptFullName) + "\Projects\Noise Spectral Density.txt")) Then
    ' Open the file for input.
    Set NoiseSpectralDensity = fso.OpenTextFile(fso.GetParentFolderName(WScript.ScriptFullName) + "\Projects\Noise Spectral Density.txt", 1)

    ' Noise Variables
    Dim Noise

    ' Read from the file and display the results.
    Do While NoiseSpectralDensity.AtEndOfStream <> True
        ' Read Line By Line
        TextLine = NoiseSpectralDensity.ReadLine

        ' Check If Number
        'If (IsNumeric(Left(TextLine, 5))) Then
            ' Get Noise

            ' Noise @ 1kHz
            Noise = Right(TextLine, InStr(Mid(TextLine, 2), InStr(TextLine, " ")-1))
            x = MsgBox("SNR: " & Split(Left(TextLine, 5), " ")(0) & " NOISE: " & Noise & "",0, "Noise Spectral Density")
        'End If
    Loop

    ' Close the file for input.
    NoiseSpectralDensity.Close
Else
    x = MsgBox("Noise Spectral Density.txt NOT Found!" & vbCrLf & "Wave->Save As Text...", 0, "Noise Spectral Density")
End If

But I could not get left and right numbers in VBScript using Split(TextLine, " ")(0).

A: Your data seems to be tab-separated, so you could do something like this:
arr = Split(TextLine, vbTab)
If Not (InStr(arr(0), ",") > 0) Then
    'first number doesn't have decimals
    snr   = arr(0)
    noise = arr(2)
End If

A: Though the solution provided by @AnsgarWiechers should work but in case, if it doesn't, you can make use of regular expressions(Replace the whole Do-while loop with the following):
Set objReg = New RegExp
objReg.Pattern = "^(\d+)(?=\s).*\s+([\d,Ee-]+)$"     'See the explanation below
Do While NoiseSpectralDensity.AtEndOfStream <> True
    'Read Line By Line
    TextLine = NoiseSpectralDensity.ReadLine

    ' Check If Number
    Set objMatches = objReg.Execute(TextLine)
    For Each objMatch In objMatches
        SNR = objMatch.submatches.item(0)
        Noise = objMatch.submatches.item(1)
        MsgBox "SNR: "&SNR&"; Noise: "&Noise
    Next
Loop

Click for Regex Demo
Regex Explanation:

*

*^ - asserts the start of the string

*(\d+) - matches 1+ occurrences of a digit and captures it in Group 1

*(?=\s) - positive lookahead to find the position immediately preceded by a white-space. So the digits in the step 2 will be matched until a whitespace(spaces,tabs etc.) is encountered

*.* - matches 0+ occurrences of any character except a newline

*\s+ - matches 1+ occurrences of a whitespace

*([\d,Ee-]+) - matches 1+ occurrences of a digit or , or - or the letter E or e and capture it in group 2

*$ - asserts the end of the string