答:
The problem with the code is that you strings in C are null terminated (\0), so StringA, despite having 7 printable characters, actually needs 8 chars to store. The three char arrays are back to back on the stack, so overwriting the terminating null character will result in them being concatenated. Each pointer to the char array starts at a different offset, hence the shorter strings for thingB and thingC, but in all cases printf will read the string until it finds a null character after the end of thingC.

Notice that this is a classic buffer overflow bug, and you are just lucky that there is a null on the stack after thingC, otherwise printf would have continued reading and printing memory way longer.

Title: strcpy and sprintf in C

Body:
I'm trying to set some string variables like this:

char thingA[7], thingB[7], thingC[7];
strcpy(thingA, "StringA");
strcpy(thingB, "StringB");
strcpy(thingC, "StringC");
printf("%s\n", thingA);
printf("%s\n", thingB);
printf("%s\n", thingC);

but instead of outputting like this:

StringA
StringB
StringC

it outputs like this:

StringA StringB StringC
StringB StringC
StringC

I've tried this with sprintf, but get the same result.
I honestly have no idea what's going on, or how to fix this, and I can't find anything on it online, since searching for this kind of stuff has proven hard for some reason.
So basically why is it storing string b and c in a, and c in b?


来源: stackexchange

问:
Print PDF to XPS using Powershell
I would like to convert a folder containing PDF files into XPS files using Powershell. Due to system restrictions, I am unable to download any third party software like iTextSharp to make this work.

I have been able to get Powershell to open the document and open the print window for XPS, but the name is always blank. Is it possible to have the new file name match the original file name?

Also, how can the process be automated so user input is not required (ie entering the file name or pressing print)? Lastly, is it possible to change the directory that it prints to?

```<code>Get-ChildItem -path $pdf_filepath -recurse -include *.pdf | ForEach-Object {Start-Process -FilePath $_.fullname -Verb Print -PassThru | %{sleep 10;$_} }
</code>```

答:
This is how I would do it:

```<code>#Define the directory containing your .pdf files
$mydir="$env:USERPROFILE\Desktop\New folder"
function print_files($mydir){
    #The purpose of this counter is to number your .xps files
    Get-ChildItem $mydir -Filter *.pdf -Recurse | Foreach-Object {
        #For each .pdf file in that directory, continue
        same_time $_.FullName
    }
}
#The following function keeps checking for a new window called "Save Print Output As". When the window shows up, it enters the name of the file and press ENTER.
function enter_my_names($fullname){
    $wshell = New-Object -ComObject wscript.shell;
    while($wshell.AppActivate('Save Print Output As') -ne $true){
        $wshell.AppActivate('Save Print Output As')
    }
    $basename = [io.path]::GetFileNameWithoutExtension($fullname)
    #This is where the name is actually entered
    $wshell.SendKeys("$basename")
    $wshell.SendKeys("{ENTER}")
}
#The following function launches simultaneously a print job on the input file and a function waiting for the print job to show up to name the file.
workflow same_time{
    Param(
        $fullname
    )
    parallel{
        Start-Process -FilePath $fullname –Verb Print -PassThru
        enter_my_names($fullname)
    }
}
#MAIN PROGRAM
#Here the script saves your current printer as default
$defprinter = Get-WmiObject -Query "Select * from Win32_Printer Where Default=$true"
#Queries for a XPS printer
$printer = Get-WmiObject -Query "Select * from Win32_Printer Where Name='Microsoft XPS Document Writer'"
#Sets the XPS printer as Default
$printer.SetDefaultPrinter()
#Starts the main job
print_files($mydir)
#Sets the old default printer back as default again
$defprinter.SetDefaultPrinter()
#This is a small delay to be sure everything is completed before closing Adobe Reader. You can probably shorten it a bit
sleep 5
#Finally, close Adobe Reader
Get-Process "acrord32" | Stop-Process
</code>```

Cheers!

ContentLicense: CC BY-SA 3.0

Title: Print PDF to XPS using Powershell

Body:
I would like to convert a folder containing PDF files into XPS files using Powershell. Due to system restrictions, I am unable to download any third party software like iTextSharp to make this work.

I have been able to get Powershell to open the document and open the print window for XPS, but the name is always blank. Is it possible to have the new file name match the original file name?

Also, how can the process be automated so user input is not required (ie entering the file name or pressing print)? Lastly, is it possible to change the directory that it prints to?

Get-ChildItem -path $pdf_filepath -recurse -include *.pdf | ForEach-Object {Start-Process -FilePath $_.fullname -Verb Print -PassThru | %{sleep 10;$_} }

Body:
This is how I would do it:

#Define the directory containing your .pdf files
$mydir="$env:USERPROFILE\Desktop\New folder"
function print_files($mydir){
    #The purpose of this counter is to number your .xps files
    Get-ChildItem $mydir -Filter *.pdf -Recurse | Foreach-Object {
        #For each .pdf file in that directory, continue
        same_time $_.FullName
    }
}
#The following function keeps checking for a new window called "Save Print Output As". When the window shows up, it enters the name of the file and press ENTER.
function enter_my_names($fullname){
    $wshell = New-Object -ComObject wscript.shell;
    while($wshell.AppActivate('Save Print Output As') -ne $true){
        $wshell.AppActivate('Save Print Output As')
    }
    $basename = [io.path]::GetFileNameWithoutExtension($fullname)
    #This is where the name is actually entered
    $wshell.SendKeys("$basename")
    $wshell.SendKeys("{ENTER}")
}
#The following function launches simultaneously a print job on the input file and a function waiting for the print job to show up to name the file.
workflow same_time{
    Param(
        $fullname
    )
    parallel{
        Start-Process -FilePath $fullname –Verb Print -PassThru
        enter_my_names($fullname)
    }
}
#MAIN PROGRAM
#Here the script saves your current printer as default
$defprinter = Get-WmiObject -Query "Select * from Win32_Printer Where Default=$true"
#Queries for a XPS printer
$printer = Get-WmiObject -Query "Select * from Win32_Printer Where Name='Microsoft XPS Document Writer'"
#Sets the XPS printer as Default
$printer.SetDefaultPrinter()
#Starts the main job
print_files($mydir)
#Sets the old default printer back as default again
$defprinter.SetDefaultPrinter()
#This is a small delay to be sure everything is completed before closing Adobe Reader. You can probably shorten it a bit
sleep 5
#Finally, close Adobe Reader
Get-Process "acrord32" | Stop-Process

Cheers!


问:
Change the colour of bubbles in Google visualization motion chart
I there a way where by I can define the colours of bubbles in a motion chart provided by Google visualization API ? I do not want to use the default colour scheme.

Thank you in advance.

答:
It's 2017 and I have yet to find a good update for this. So here is the solution I came up with. HTH.

```<code>#views.py
# Bubble Chart: ID, X, Y Color, Size
data.append(['ID', 'X', 'Y', 'Category', 'Z'])
data.append(['', 0, 0, 'Cat 1', 0]) #<-- the order of
data.append(['', 0, 0, 'Cat 2', 0]) #<-- these fakeout items
data.append(['', 0, 0, 'Cat 3', 0]) #<-- is important
data.append(['', 0, 0, 'Cat 4', 0]) #<-- Blue, Red, Orange, Green - in that order
</code>```

... for r in source:
       data.append(r.a, r.b, r.c, r.d, r.e)

```<code>return render(
    request,
    'Template.html',
    {
        'title':'',
        'year':datetime.now().year,
        'org': org,
        'data': json.dumps(data),
    }

#in the scripts block of template.html

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {

        var data = google.visualization.arrayToDataTable({{data|safe}});

        var options = {
            title: 'Bubble By Category Strategy',
            hAxis: { title: 'X', ticks: [{v: 0, f:''}, {v: 1, f:'L'}, {v: 2, f:'M'}, {v: 3, f:'H'}, {v: 4, f:''}] },
            vAxis: { title: 'Y', ticks: [{v: 0, f:''}, {v: 1, f:'L'}, {v: 2, f:'M'}, {v: 3, f:'H'}, {v: 4, f:''}]  },
            bubble: {
                textStyle: {
                    fontSize: 11,
                    fontName: 'Lato',
                }
            }
        };

        var chart = new google.visualization.BubbleChart(document.getElementById('riskChart'));
        chart.draw(data, options);
    }

</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It's 2017 and I have yet to find a good update for this. So here is the solution I came up with. HTH.

#views.py
# Bubble Chart: ID, X, Y Color, Size
data.append(['ID', 'X', 'Y', 'Category', 'Z'])
data.append(['', 0, 0, 'Cat 1', 0]) #<-- the order of
data.append(['', 0, 0, 'Cat 2', 0]) #<-- these fakeout items
data.append(['', 0, 0, 'Cat 3', 0]) #<-- is important
data.append(['', 0, 0, 'Cat 4', 0]) #<-- Blue, Red, Orange, Green - in that order

... for r in source:
       data.append(r.a, r.b, r.c, r.d, r.e)

return render(
    request,
    'Template.html',
    {
        'title':'',
        'year':datetime.now().year,
        'org': org,
        'data': json.dumps(data),
    }

#in the scripts block of template.html

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {

        var data = google.visualization.arrayToDataTable({{data|safe}});

        var options = {
            title: 'Bubble By Category Strategy',
            hAxis: { title: 'X', ticks: [{v: 0, f:''}, {v: 1, f:'L'}, {v: 2, f:'M'}, {v: 3, f:'H'}, {v: 4, f:''}] },
            vAxis: { title: 'Y', ticks: [{v: 0, f:''}, {v: 1, f:'L'}, {v: 2, f:'M'}, {v: 3, f:'H'}, {v: 4, f:''}]  },
            bubble: {
                textStyle: {
                    fontSize: 11,
                    fontName: 'Lato',
                }
            }
        };

        var chart = new google.visualization.BubbleChart(document.getElementById('riskChart'));
        chart.draw(data, options);
    }

</script>


问:
GDB Remote Debug with CLion not working
Here is my scenario:

I am able to debug using terminal with these commands:

gdb myprog

break myprog.c:4115

run --myarg

the breakpoint works and I can step in the program

I try the remote debug using CLion 16.2.2 in Fedora System:

in server I run:
  gdbserver localhost:8080 myprog --myarg

I get this:
  Process data created; pid = 80199
  Listening on port 8080

In Linux client with CLion:

Settings / Deployment / configure SFTP (upload and download working fine)

Download all files from server

Edit Configuration

Create new GDB Remote Debug:

GDB: Default (Bundled)

Target: tcp:193.101.144.128:8080

Symbol file: {blank}

Sysroot: {blank}

Path Mapping: server path and local path

Run the debugger

on the server terminal I see:

Remote debugging from host 172.24.10.2 (this makes me believe I am close)

address_string = T:servername:4311

In CLion console I see:

Debugger connected to tcp:193.101.144.128:8080 (connection works!)

Although it seems the connection from the GDB server and client is working it seems I am missing something because the debugger tools (step in, step over, continue, etc.) remain grayed out and the breakpoints are never reached.

From the first test I know that the breakpoints I am using should work.

I suspect the way I am using to pass in the program argument (--myarg) in this line: gdbserver localhost:8080 myprog --myarg its not right but I don't know where else to pass it.

I am looking forward to be able to debug using this awesome IDE rather than using the terminal. I am close but got stucked here. I really appreciate some help!

Thank you

答:
I met with the same problem. In my case root cause of problem was that absolute path to the project folder on target device was differ from absolute path on my local machine.
After adding proper path mapping in Run/Debug Configuration dialog debugger start working.

For example:

Path Mapping:

server path: /home/ubuntu/src/yourprojectname/

local path: /home/michael/Documents/src/yourprojectname/

Title: GDB Remote Debug with CLion not working


问:
Measuring time with a resolution of microseconds in C++?
I'm looking for a way to measure microsecs in C++/Windows.

I read about the "clock" function, but it returns only milliseconds...

Is there a way to do it?

答:
http://www.boost.org/doc/libs/1_45_0/doc/html/date_time/posix_time.html

altough

Get the UTC time using a sub second resolution clock. On Unix systems this is implemented using GetTimeOfDay. On most Win32 platforms it is implemented using ftime. Win32 systems often do not achieve microsecond resolution via this API. If higher resolution is critical to your application test your platform to see the achieved resolution.


问:
python substring (slicing) compare not always working
```<code>`list1 = ["Arizona","Atlanta","Baltimore","Buffalo","Carolina","Chicago",
"Cincinnati","Cleveland","Dallas","Denver","Detroit","Green Bay","Houston",
"Indianapolis","Jacksonville","Kansas City","L.A. Chargers","L.A. Rams",
    "Miami","Minnesota","New England","New Orleans","NY Giants","NY Jets",
    "Oakland","Philadelphia","Pittsburgh","San Francisco","Seattle",
    "Tampa Bay","Tennessee","Washington"]
a = "New Orleans at Oakland"
k = a.find("at")
print (k)
for n in range(0,31):
#    b = list1[n]
#    print(b[0:k-1]+"  "+a[0:k-1])
    idx = a.find(list1[n], 0, k-1)
    if idx > 0:
        print(n)
        break
print ("awa team at index" + str(n+1))
for n in range(0,31):
    idx = a.find(list1[n], k+2, len(a))
    if idx > 0:
       print(n)
       break
print ("hom team at index" + str(n+1))`
</code>```

I just started python 2 days ago and I cannot get this to work completely. The program finds the team in the second for loop correctly, but doesn't find the team in the first for loop. I put in the statements that are commented out to see if the strings were somehow truncated, but they are correct. Can anyone tell me what is wrong here?

答:
if you just want to have the index, you can use the .index() you do not have to "loop"

Example code:

```<code>list1 = ["Arizona","Atlanta","Baltimore","Buffalo","Carolina","Chicago",
"Cincinnati","Cleveland","Dallas","Denver","Detroit","Green Bay","Houston",
"Indianapolis","Jacksonville","Kansas City","L.A. Chargers","L.A. Rams",
    "Miami","Minnesota","New England","New Orleans","NY Giants","NY Jets",
    "Oakland","Philadelphia","Pittsburgh","San Francisco","Seattle",
    "Tampa Bay","Tennessee","Washington"]

a = "New Orleans at Oakland"

a = a.split(' at ')

idx_home_team = list1.index(a[0])
idx_away_team = list1.index(a[1])

print(idx_home_team, idx_away_team)
</code>```

Body:
`list1 = ["Arizona","Atlanta","Baltimore","Buffalo","Carolina","Chicago",
"Cincinnati","Cleveland","Dallas","Denver","Detroit","Green Bay","Houston",
"Indianapolis","Jacksonville","Kansas City","L.A. Chargers","L.A. Rams",
    "Miami","Minnesota","New England","New Orleans","NY Giants","NY Jets",
    "Oakland","Philadelphia","Pittsburgh","San Francisco","Seattle",
    "Tampa Bay","Tennessee","Washington"]
a = "New Orleans at Oakland"
k = a.find("at")
print (k)
for n in range(0,31):
#    b = list1[n]
#    print(b[0:k-1]+"  "+a[0:k-1])
    idx = a.find(list1[n], 0, k-1)
    if idx > 0:
        print(n)
        break
print ("awa team at index" + str(n+1))
for n in range(0,31):
    idx = a.find(list1[n], k+2, len(a))
    if idx > 0:
       print(n)
       break
print ("hom team at index" + str(n+1))`

I just started python 2 days ago and I cannot get this to work completely. The program finds the team in the second for loop correctly, but doesn't find the team in the first for loop. I put in the statements that are commented out to see if the strings were somehow truncated, but they are correct. Can anyone tell me what is wrong here?

Body:
if you just want to have the index, you can use the .index() you do not have to "loop"

Example code:

list1 = ["Arizona","Atlanta","Baltimore","Buffalo","Carolina","Chicago",
"Cincinnati","Cleveland","Dallas","Denver","Detroit","Green Bay","Houston",
"Indianapolis","Jacksonville","Kansas City","L.A. Chargers","L.A. Rams",
    "Miami","Minnesota","New England","New Orleans","NY Giants","NY Jets",
    "Oakland","Philadelphia","Pittsburgh","San Francisco","Seattle",
    "Tampa Bay","Tennessee","Washington"]

a = "New Orleans at Oakland"

a = a.split(' at ')

idx_home_team = list1.index(a[0])
idx_away_team = list1.index(a[1])

print(idx_home_team, idx_away_team)


问:
uwp properties await showing wierd behaviour
In my UWP app I have 2 properties and both are bound to the UI. it all works just fine, until I try to delay addition to one of those properties with Task.Delay.

Expectation : Videos collection property should keep getting items without any delay, and Current property should get each item after some delay.

Problem : when I try to delay both properties get delayed because after 1st run of loop the delay actually delays the execution of whole loop, but I only want to delay one line of code.

here is my code

```<code>foreach (var file in VideoFiles)
{
    var props = await file.Properties.GetVideoPropertiesAsync();
    var dur = props.Duration;
    var myviews = await DbHelper.GetMyViews(file.Path);
    var vv = new Video
    {
    MyVideoFile = file,
    Views = myviews,
    Duration = $"{dur.Hours.ToString()} : {dur.Minutes.ToString()} : {dur.Seconds.ToString()}",
    Display = await FileHelper.GetDisplay(file),
    };
    Videos.Add(vv);// this line should be execute without any delay

    await Task.Delay(3000);//if I comment this delay line of code then both properties keep getting filled without any delay, which is not what I want

    Current = vv; // this line should be executed after delay
}
</code>```

UPDATE

Actually "Videos" is a collection of Video objects which I am displaying on a GridView on the UI so I need to add them without delay.
But Current is an object bound to header on my page, which I need to change after every 3 seconds, after every 3 seconds the header should pick up data from next GridView Item and display it, that is why I need the delay only when updating "Current" property.

答:
Use a DispatcherTimer to set the Current property outside of your for loop then. Something like this:

```<code>public MainPage()
{
    this.InitializeComponent();

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(3);
    int currentIndex = 0;
    timer.Tick += (s, e) =>
    {
        //this code will run every 3 seconds...
        if (Videos.Count > currentIndex)
        {
            Current = Videos[currentIndex++];
        }
    };
    timer.Start();
}
</code>```

Body:
In my UWP app I have 2 properties and both are bound to the UI. it all works just fine, until I try to delay addition to one of those properties with Task.Delay.

Expectation : Videos collection property should keep getting items without any delay, and Current property should get each item after some delay.

Problem : when I try to delay both properties get delayed because after 1st run of loop the delay actually delays the execution of whole loop, but I only want to delay one line of code.

here is my code

foreach (var file in VideoFiles)
{
    var props = await file.Properties.GetVideoPropertiesAsync();
    var dur = props.Duration;
    var myviews = await DbHelper.GetMyViews(file.Path);
    var vv = new Video
    {
    MyVideoFile = file,
    Views = myviews,
    Duration = $"{dur.Hours.ToString()} : {dur.Minutes.ToString()} : {dur.Seconds.ToString()}",
    Display = await FileHelper.GetDisplay(file),
    };
    Videos.Add(vv);// this line should be execute without any delay

    await Task.Delay(3000);//if I comment this delay line of code then both properties keep getting filled without any delay, which is not what I want

    Current = vv; // this line should be executed after delay
}

UPDATE

Actually "Videos" is a collection of Video objects which I am displaying on a GridView on the UI so I need to add them without delay.
But Current is an object bound to header on my page, which I need to change after every 3 seconds, after every 3 seconds the header should pick up data from next GridView Item and display it, that is why I need the delay only when updating "Current" property.

Body:
Use a DispatcherTimer to set the Current property outside of your for loop then. Something like this:

public MainPage()
{
    this.InitializeComponent();

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(3);
    int currentIndex = 0;
    timer.Tick += (s, e) =>
    {
        //this code will run every 3 seconds...
        if (Videos.Count > currentIndex)
        {
            Current = Videos[currentIndex++];
        }
    };
    timer.Start();
}


问:
Call Python from Java
I want to call a python script from Java.  My python version is 2.5 and Java is 6.

My current code:

```<code>try{
    Process p= Runtime.getRuntime().exec("path/dirs/file.py");
    p.waitFor();
    } catch (InterruptedException ex){
    System.out.println(ex.getMessage());}
    }
</code>```

The error I receive is:

Java.IO.IOException: Cannot run program filename: CreateProcess error
  = 193, %1 is not a valid Win32 application

答:
try this,
This works for me

test_python.py

```<code>def addition(a,b):
    c=a+b
    return(c)
</code>```

interpreterPython.java

```<code>package com.pythonconnect;
import org.python.util.PythonInterpreter;

public class interpreterPython {
    public static void main(String[] args) {
        System.setProperty("python.cachedir.skip", "true");
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("test_python.py");
        interpreter.exec("print(addition(7,8))");
    }
}
</code>```

Title: Call Python from Java

Body:
I want to call a python script from Java.  My python version is 2.5 and Java is 6.

My current code:

try{
    Process p= Runtime.getRuntime().exec("path/dirs/file.py");
    p.waitFor();
    } catch (InterruptedException ex){
    System.out.println(ex.getMessage());}
    }

The error I receive is:

Java.IO.IOException: Cannot run program filename: CreateProcess error
  = 193, %1 is not a valid Win32 application

Body:
try this,
This works for me

test_python.py

def addition(a,b):
    c=a+b
    return(c)

interpreterPython.java

package com.pythonconnect;
import org.python.util.PythonInterpreter;

public class interpreterPython {
    public static void main(String[] args) {
        System.setProperty("python.cachedir.skip", "true");
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("test_python.py");
        interpreter.exec("print(addition(7,8))");
    }
}


问:
Can't reset Drupal admin password
I need to reset my Drupal site's admin password and I can't user the email reset because the admin email doesn't exist.

I followed the directions here: http://www.ostraining.com/blog/drupal/reset-your-drupal-admin-password/

I ran the SQL: UPDATE dr_users SET pass = md5('newpassword') WHERE uid = 1; - no luck

I also tried entering a password into the users table manually in plain text. - no luck

At this point I'm not sure what the problem is.

The only thing I can think of, and I can't see why this would be it, is that I have a browser open with Admin logged in using the old password. This seems to be a hint to my problem as I would expect that on page refresh I would get logged out as the password has now changed.

答:
It is pretty easy!

With the access to the table "users" (i.e. this table can have a prefix that you have already mentioned during the installation part, so yourPrefix_ can be your project's name as mywebsitename_, and in this case you'll have mywebsitename_users) in your database via PhpMyAdmin for example.

You should alter the "pass" column associated with the "uid" column with the value 1 (i.e 1 for the admin user account).

As the encrypted value for the password:  Admin_12345  is =>

$S$DifCVXg9tNtHadziyyQJQVLAaZzW5EgS6OjR56D.mk8MpNQs1II2

You can accede to your admin account after replacing the old hashed password value stored in your database that you have totally forgotten.

Don't forget to change the password: Admin_12345 after you accede to your account ;)

Title: Can't reset Drupal admin password


问:
Shorte.st Api python
i was trying to use the shorte.st api to automatically create my short links using my python progam, but i really don't know how to use the Apis!
In the dedicated page there is only this code here:

```<code>curl H "public-api-token: ---" -X -d "urlToShorten=google.com" PUT http://api.shorte.st/v1/data/url {"status":"ok","shortenedUrl":"http:\/\/sh.st\/XXXX"}
</code>```

In the public-api-token i have to insert my private token obviously, but since curl is for c (i think) how can i use them with python?
Thanks so much

答:
And to print out just the created URL use...</p>

```<code>import requests
import json

response = requests.put("https://api.shorte.st/v1/data/url", {"urlToShorten":"google.com"}, headers={"public-api-token": "85d3636f48c112de6e413865afc177b5"})
decoded_response = json.loads(response.content)
print(decoded_response['shortenedUrl'])
</code>```

Title: Shorte.st Api python

Body:
i was trying to use the shorte.st api to automatically create my short links using my python progam, but i really don't know how to use the Apis!
In the dedicated page there is only this code here:

curl H "public-api-token: ---" -X -d "urlToShorten=google.com" PUT http://api.shorte.st/v1/data/url {"status":"ok","shortenedUrl":"http:\/\/sh.st\/XXXX"}

In the public-api-token i have to insert my private token obviously, but since curl is for c (i think) how can i use them with python?
Thanks so much

Body:
And to print out just the created URL use...

import requests
import json

response = requests.put("https://api.shorte.st/v1/data/url", {"urlToShorten":"google.com"}, headers={"public-api-token": "85d3636f48c112de6e413865afc177b5"})
decoded_response = json.loads(response.content)
print(decoded_response['shortenedUrl'])


问:
Rewriting python script to work with python3
I have the following piece of code that I need help rewriting it to work with python3</p>

```<code>from urllib2 import Request, urlopen

headers = {'Authorization': '< Enter your Basic Authorization string here >'}
request = Request('https://ssapi.shipstation.com/orders/orderId', headers=headers)
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body
</code>```

答:
Change the imports

```<code>try:
    from urllib2 import Request, urlopen
except ImportError:
    # python3
    from urllib.request import Request, urlopen
</code>```

Also change the print

```<code>print(response_body)
</code>```

Your code is now cross-compatible and should run on both Python 2 and Python 3.

Body:
I have the following piece of code that I need help rewriting it to work with python3

from urllib2 import Request, urlopen

headers = {'Authorization': '< Enter your Basic Authorization string here >'}
request = Request('https://ssapi.shipstation.com/orders/orderId', headers=headers)
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body

Body:
Change the imports

try:
    from urllib2 import Request, urlopen
except ImportError:
    # python3
    from urllib.request import Request, urlopen

Also change the print

print(response_body)

Your code is now cross-compatible and should run on both Python 2 and Python 3.


问:
Send a SOAP Request over HTTP with Angular?
Im starting a new web application project with simple HTML, CSS and Angular. We are using existing Web Services to retrieve data from some servers, one service we are trying to use is a public service: Global Weather SOAP Service

Is there an "easy" way to make the request with Angular? Actually our "test" code is this (with JQuery, still does not work), but would be better to implement the Angular approach with HTTP or RxJS...

```<code>import { Injectable } from '@angular/core';
import * as $ from 'jquery';

@Injectable()
export class SoapServiceProvider {

    constructor() { }

    testingSoapRequest() {

        $.ajax({
            url: 'http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry',
            data: { CountryName: 'Spain' },
            success: (data) => {
                console.log('Hey, we got a success response', data);
            },
            error: (err) => {
                console.error('We got an error :(', err);
            }
        });

    }

}
</code>```

I have never used JQuery to make requests of any type (I just use $http in AngularJS and RxJS with Angular), so I really don't know the correct way to make it possible.

Note: There is a library to make Angular SOAP Requests in GitHub but it seems that does not work anymore with new Angular versions.

This is the GitHub Autopulous SOAP link...

答:
First of all, don't use jQuery, Angular provides you with everything you need out of the box and it's faster and usually more powerful too.

Here's an example Ionic Page, making http requests:

import {Page, Alert, NavController} from 'ionic/ionic';
import {Http} from 'angular2/http';

@Page({
    templateUrl: 'build/pages/home/home.html',
})

export class HomePage {
    constructor(http: Http, nav: NavController) {
        this.http = http;
        this.nav = nav;
    }

    makeGetRequest() {
        this.http.get("https://httpbin.org/ip")
        .subscribe(data => {
            var alert = Alert.create({
                title: "Your IP Address",
                subTitle: data.json().origin,
                buttons: ["close"]
            });
            this.nav.present(alert);
        }, error => {
            console.log(JSON.stringify(error.json()));
        });
    }

    makePostRequest() {
        this.http.post("https://httpbin.org/post", "firstname=Nic")
        .subscribe(data => {
            var alert = Alert.create({
                title: "Data String",
                subTitle: data.json().data,
                buttons: ["close"]
            });
            this.nav.present(alert);
        }, error => {
            console.log(JSON.stringify(error.json()));
        });
    }
}
```

<p>That logic could be hooked up to a simple template like this one:</p>

<pre class="lang-html prettyprint-override"><code><ion-navbar *navbar>
    <ion-title>
        Home
    </ion-title>
</ion-navbar>

<ion-content class="home">
    <button (click)="makeGetRequest()">GET Request</button>
    <button (click)="makePostRequest()">POST Request</button>
</ion-content>
</code>```

Now since you are using SOAP messaging, you will need to convert JSON to SOAP compatible XML and similarly deconstruct it when you get a response.

I strongly advise you not to use SOAP because, despite the fact that it's an older tecnology, messages are much larger due to more verbose code needed to annotate the same data and most importantly, converting JSON -> XML is slow, especially in Javascript.

That being said, here's a very popular library to convert between the two types.

Body:
Im starting a new web application project with simple HTML, CSS and Angular. We are using existing Web Services to retrieve data from some servers, one service we are trying to use is a public service: Global Weather SOAP Service

Is there an "easy" way to make the request with Angular? Actually our "test" code is this (with JQuery, still does not work), but would be better to implement the Angular approach with HTTP or RxJS...

import { Injectable } from '@angular/core';
import * as $ from 'jquery';

@Injectable()
export class SoapServiceProvider {

    constructor() { }

    testingSoapRequest() {

        $.ajax({
            url: 'http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry',
            data: { CountryName: 'Spain' },
            success: (data) => {
                console.log('Hey, we got a success response', data);
            },
            error: (err) => {
                console.error('We got an error :(', err);
            }
        });

    }

}

I have never used JQuery to make requests of any type (I just use $http in AngularJS and RxJS with Angular), so I really don't know the correct way to make it possible.

Note: There is a library to make Angular SOAP Requests in GitHub but it seems that does not work anymore with new Angular versions.

This is the GitHub Autopulous SOAP link...

Body:
First of all, don't use jQuery, Angular provides you with everything you need out of the box and it's faster and usually more powerful too.

Here's an example Ionic Page, making http requests:

import {Page, Alert, NavController} from 'ionic/ionic';
import {Http} from 'angular2/http';

@Page({
    templateUrl: 'build/pages/home/home.html',
})

export class HomePage {
    constructor(http: Http, nav: NavController) {
        this.http = http;
        this.nav = nav;
    }

    makeGetRequest() {
        this.http.get("https://httpbin.org/ip")
        .subscribe(data => {
            var alert = Alert.create({
                title: "Your IP Address",
                subTitle: data.json().origin,
                buttons: ["close"]
            });
            this.nav.present(alert);
        }, error => {
            console.log(JSON.stringify(error.json()));
        });
    }

    makePostRequest() {
        this.http.post("https://httpbin.org/post", "firstname=Nic")
        .subscribe(data => {
            var alert = Alert.create({
                title: "Data String",
                subTitle: data.json().data,
                buttons: ["close"]
            });
            this.nav.present(alert);
        }, error => {
            console.log(JSON.stringify(error.json()));
        });
    }
}

That logic could be hooked up to a simple template like this one:

<ion-navbar *navbar>
    <ion-title>
        Home
    </ion-title>
</ion-navbar>

<ion-content class="home">
    <button (click)="makeGetRequest()">GET Request</button>
    <button (click)="makePostRequest()">POST Request</button>
</ion-content>

Now since you are using SOAP messaging, you will need to convert JSON to SOAP compatible XML and similarly deconstruct it when you get a response.

I strongly advise you not to use SOAP because, despite the fact that it's an older tecnology, messages are much larger due to more verbose code needed to annotate the same data and most importantly, converting JSON -> XML is slow, especially in Javascript.

That being said, here's a very popular library to convert between the two types.


问:
AWS RDS MySQL Read Replicas Data Sync time
We have and architecture of a scalable web application on AWS and utilized AWS RDS MySQL. They say you have to create 2 Slave Read-Replicas for your MySQL Master db instance. Using this, the master DB will synchronize your data whenever it finds a change (in its master instance) across all of the read replicas. Your application has to split Read and Write operations so that All the Read Requests goes to Read-Replicas (Via a load-balancer or DNS) and write requests\ops goes to the master db.

Now my question is if a user visits a page which has a write operation, he does the operation and click to a page where a Read Operation is required of that new entered data. How much the Master db will take to sync with slave read-replicas so that the user can successfully see the read-operation result (i.e. the newly created record) on the very next page.

答:
RDS MySQL Read Replica lag is influenced by a number of factors including the load on both the primary and secondary instances, the amount of data being replicated, the number of replicas, if they are within the same region or cross-region, etc.  Lag can stretch to seconds or minutes, though typically it is under one minute.

For low-lag (10s of milliseconds) read replicas in a MySQL-compatible database you can use Amazon Aurora.


问:
argument is missing, with no default, but only in loop
I wrote couple of simple custom functions in purpose to consolidate them in one specific function.

Those are used to subset data. First is less specific:

```<code>unspecific_subsetting=function(x,var1,var2){
  subset(x, x$COL1 %in% var1
         & x$COL2 %in% var2
         & x$COL3 %in% "A")
}
</code>```

In x$COL3 I put "A" because it is constant. Second is more specific, it does exactly same thing but it subsets only a chosen row:

```<code>specific_subsetting=function(x,var1,var2,year){
  subset(x, x$COL1 %in% var1
         & x$COL2 %in% var2
         & x$COL3 %in% "A"
         & x$COL4 %in% (year+1))
}
</code>```

I wrote (year+1) but later on I might change it to variable as well. The last function I use is simple percent change:

```<code>pcchange=function(x){  c( NA, diff(x)/x[-length(x)] ) }
</code>```

So at this point it is about time to explain - I wish to combine all those functions into one convenient function, which calculates percentage change of certain substracted dataset and then returns pcchange value from chose row. It looks like this:

```<code>big_function=function(x,var1,var2,year){
  x=unspecific_subsetting(x, var1, var2)
  x=data.frame(x,"growth"=(pcchange(x$COLn)*100))
  x=getforecast(x,var1,var2,year)}
</code>```

To be more specific - it basically subset certain part of data, then calculates and adds new column with pcchanges to df, and finally return desired row. This function WORKS. And works like a charm. The problem starts when i put it into loop. So far i write loops based on lists so it looks like this:

```<code>for (i in 1:length(df.names.list)){
assign(NEW.df.names.list[i],big_function(get(df.names.list[i])),var1,var2,year.list[i])}
</code>```

So as you can see I am trying to create new dfs with each one consisting only selected row (BTW: I am aware my "subset" functions overlaps in big_function but I dont mind that). And this returns me an error:

```<code>  Error in unspecific_subsetting(x, var1, var2) :
  argument "var1" is missing, with no default
</code>```

I checked, this problem consider every single argument in every function, it only returned first one R stumbled upon.
I have literally no clue what is the issue here, I used similar loop couple of times and never had result like this.

答:
I managed to reproduce error on test data. My test df look like this:

```<code>COL1    COL2        COL3    COL4    COLn
CarBrand1   Gas        A    2014    5.34
CarBrand1   Gas        A    2010    1.46
CarBrand1   Gas        A    2007    1.18
CarBrand1   Diesel     A    2006    1.27
CarBrand1   Electric   A    2013    1.78
CarBrand1   Electric    A   2001    1.44
CarBrand2   Electric    A   2007    1.39
CarBrand2   Diesel      A   2004    1.04
CarBrand2   Gas         A   2009    1.89
CarBrand2   Gas         A   2004    1.83
CarBrand2   Electric    A   2000    1.69
CarBrand2   Electric    A   2001    1.61
CarBrand2   Electric    A   2013    1.29
CarBrand2   Diesel      A   2001    2.00
CarBrand2   Diesel      A   2006    1.78
CarBrand2   Gas         A   2010    1.10
CarBrand2   Gas         A   2002    1.51
CarBrand2   Gas         A   2012    1.78
CarBrand2   Electric    A   2009    1.84
CarBrand3   Gas         A   2013    1.24
CarBrand3   Gas         A   2009    1.98
CarBrand3   Gas         A   2015    1.91
CarBrand3   Gas         A   2007    1.14
CarBrand3   Diesel      A   2000    1.54
CarBrand3   Diesel      A   2013    1.60
</code>```

First two columns are car brand and engine type, third is some constant fourth is year and last is some random value. I put into R my custom functions exactly as in first post so my test code looks like this:

```<code>newdf=0
output=0
NEW.df.names.list=c("output")
df.names.list=c("mydf")
year.list=2012
for (i in 1:length(df.names.list)){
  assign(NEW.df.names.list[i],big_function(get(df.names.list[i])),"CarBrand3","Diesel",year.list[i])}
</code>```

I work on multiple dfs, this only makes on loop but it gives me exactly same error. I know this is not exactly answering my own question, its more like extension...

Body:
I wrote couple of simple custom functions in purpose to consolidate them in one specific function.

Those are used to subset data. First is less specific:

unspecific_subsetting=function(x,var1,var2){
  subset(x, x$COL1 %in% var1
         & x$COL2 %in% var2
         & x$COL3 %in% "A")
}

In x$COL3 I put "A" because it is constant. Second is more specific, it does exactly same thing but it subsets only a chosen row:

specific_subsetting=function(x,var1,var2,year){
  subset(x, x$COL1 %in% var1
         & x$COL2 %in% var2
         & x$COL3 %in% "A"
         & x$COL4 %in% (year+1))
}

I wrote (year+1) but later on I might change it to variable as well. The last function I use is simple percent change:

pcchange=function(x){  c( NA, diff(x)/x[-length(x)] ) }

So at this point it is about time to explain - I wish to combine all those functions into one convenient function, which calculates percentage change of certain substracted dataset and then returns pcchange value from chose row. It looks like this:

big_function=function(x,var1,var2,year){
  x=unspecific_subsetting(x, var1, var2)
  x=data.frame(x,"growth"=(pcchange(x$COLn)*100))
  x=getforecast(x,var1,var2,year)}

To be more specific - it basically subset certain part of data, then calculates and adds new column with pcchanges to df, and finally return desired row. This function WORKS. And works like a charm. The problem starts when i put it into loop. So far i write loops based on lists so it looks like this:

for (i in 1:length(df.names.list)){
assign(NEW.df.names.list[i],big_function(get(df.names.list[i])),var1,var2,year.list[i])}

So as you can see I am trying to create new dfs with each one consisting only selected row (BTW: I am aware my "subset" functions overlaps in big_function but I dont mind that). And this returns me an error:

  Error in unspecific_subsetting(x, var1, var2) :
  argument "var1" is missing, with no default

I checked, this problem consider every single argument in every function, it only returned first one R stumbled upon.
I have literally no clue what is the issue here, I used similar loop couple of times and never had result like this.

Body:
I managed to reproduce error on test data. My test df look like this:

COL1    COL2        COL3    COL4    COLn
CarBrand1   Gas        A    2014    5.34
CarBrand1   Gas        A    2010    1.46
CarBrand1   Gas        A    2007    1.18
CarBrand1   Diesel     A    2006    1.27
CarBrand1   Electric   A    2013    1.78
CarBrand1   Electric    A   2001    1.44
CarBrand2   Electric    A   2007    1.39
CarBrand2   Diesel      A   2004    1.04
CarBrand2   Gas         A   2009    1.89
CarBrand2   Gas         A   2004    1.83
CarBrand2   Electric    A   2000    1.69
CarBrand2   Electric    A   2001    1.61
CarBrand2   Electric    A   2013    1.29
CarBrand2   Diesel      A   2001    2.00
CarBrand2   Diesel      A   2006    1.78
CarBrand2   Gas         A   2010    1.10
CarBrand2   Gas         A   2002    1.51
CarBrand2   Gas         A   2012    1.78
CarBrand2   Electric    A   2009    1.84
CarBrand3   Gas         A   2013    1.24
CarBrand3   Gas         A   2009    1.98
CarBrand3   Gas         A   2015    1.91
CarBrand3   Gas         A   2007    1.14
CarBrand3   Diesel      A   2000    1.54
CarBrand3   Diesel      A   2013    1.60

First two columns are car brand and engine type, third is some constant fourth is year and last is some random value. I put into R my custom functions exactly as in first post so my test code looks like this:

newdf=0
output=0
NEW.df.names.list=c("output")
df.names.list=c("mydf")
year.list=2012
for (i in 1:length(df.names.list)){
  assign(NEW.df.names.list[i],big_function(get(df.names.list[i])),"CarBrand3","Diesel",year.list[i])}

I work on multiple dfs, this only makes on loop but it gives me exactly same error. I know this is not exactly answering my own question, its more like extension...


问:
Select multiple/random elements from an arraylist
How would I select random elements from an array list, except for one element?
Here's my arraylist:

```<code>ArrayList <String> provinces = new ArrayList();

Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");
</code>```

For this example, I would like to select at random the other elements, except for Saskatchewan.

I've tried doing:

```<code> for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {

     int getPossibleAnswers = (int) Math.floor(Math.random()*i);
     String displayPossibleAnswers = provinces.get(getPossibleAnswers);
     outputAnswers.append(displayPossibleAnswers + "\n");
     }
</code>```

Obviously, this code doesn't work, and I don't know what to do.
Thanks in advance!

答:
To keep it concise , As mentioned Simply create a list without Saskatchewan

```<code>    ArrayList <String> provinces = new ArrayList<>(Arrays.asList("New Brunswick",
                                     "Ontario", "Nova Scotia",
                                     "Quebec",   "Alberta"));
</code>```

then shuffle the list

```<code>Collections.shuffle(provinces);
</code>```

Demo

```<code>ArrayList <String> provinces = new ArrayList<>(Arrays.asList("New Brunswick",
                                     "Ontario", "Nova Scotia",
                                     "Quebec",   "Alberta"));
Collections.shuffle(provinces);
StringBuilder builder = new StringBuilder();
for (String s:provinces) {
    builder.append(s+"\n");
}
System.out.println(builder);
</code>```

Output :

```<code>Quebec
New Brunswick
Alberta
Ontario
Nova Scotia
</code>```

Body:
How would I select random elements from an array list, except for one element?
Here's my arraylist:

ArrayList <String> provinces = new ArrayList();

Collections.addAll(
    provinces,
    "New Brunswick",
    "Saskatchewan",
    "Ontario",
    "Nova Scotia",
    "Quebec",
    "Alberta");

For this example, I would like to select at random the other elements, except for Saskatchewan.

I've tried doing:

 for(int i == provinces.get (0); i < provinces.get(1); i > provinces.get(2); i < provinces.get(5)) {

     int getPossibleAnswers = (int) Math.floor(Math.random()*i);
     String displayPossibleAnswers = provinces.get(getPossibleAnswers);
     outputAnswers.append(displayPossibleAnswers + "\n");
     }

Obviously, this code doesn't work, and I don't know what to do.
Thanks in advance!

Body:
To keep it concise , As mentioned Simply create a list without Saskatchewan

    ArrayList <String> provinces = new ArrayList<>(Arrays.asList("New Brunswick",
                                     "Ontario", "Nova Scotia",
                                     "Quebec",   "Alberta"));

then shuffle the list

Collections.shuffle(provinces);

Demo

ArrayList <String> provinces = new ArrayList<>(Arrays.asList("New Brunswick",
                                     "Ontario", "Nova Scotia",
                                     "Quebec",   "Alberta"));
Collections.shuffle(provinces);
StringBuilder builder = new StringBuilder();
for (String s:provinces) {
    builder.append(s+"\n");
}
System.out.println(builder);

Output :

Quebec
New Brunswick
Alberta
Ontario
Nova Scotia


问:
Error while accessing jsonObject in couchbase
I'm having this JSON as a couchbase document :

```<code>{
  "document": [
    {
      "Value 1": 36.29,
      "Date 1": 1495144800000,
      "Date 2": 1495144800000,
      "Date 3": 1495144800000,
      "Value 2": "5444158076"
    }
  ],
  "exception": null
}
</code>```

What I want to do is to get the Date 1, Date 2 and Date 3 then change them (with JAVA).

I'm using doc.content().getString(jsonKey); to get, but it only work at the first level of the JSON (i can only get the exception value).

I don't know if I can ask at the same question, but if you also can help me with updating some value in a JSONArray (modify the Date 1/2/3 values) it would be great.

Thanks !

答: Have you tried getting the array associated with "document" key (jsonKey should be "document" and then get the map associated with the first element in the array.</p>

Body:
I'm having this JSON as a couchbase document :

{
  "document": [
    {
      "Value 1": 36.29,
      "Date 1": 1495144800000,
      "Date 2": 1495144800000,
      "Date 3": 1495144800000,
      "Value 2": "5444158076"
    }
  ],
  "exception": null
}

What I want to do is to get the Date 1, Date 2 and Date 3 then change them (with JAVA).

I'm using doc.content().getString(jsonKey); to get, but it only work at the first level of the JSON (i can only get the exception value).

I don't know if I can ask at the same question, but if you also can help me with updating some value in a JSONArray (modify the Date 1/2/3 values) it would be great.

Thanks !


问:
Is it possible to enable/disable all breakpoints with project scope only (Visual Studio 2015 and above)?
Let's say I have a solution with 10 projects, it is an old code base and I am just getting familiar with it. I am doing a lot of debugging and putting breakpoints here and there. I would like to enable or disable all breakpoint in a given project (i.e data access project) but not in all the solution. I want to do this without manually disabling each breakpoint. </p>

<p>Is there a way to do this? If so, which is it? Is there an extension or third party tool that could help me? (I am using resharper but did not find any way to do this) </p>

答:
In the breakpoint panel, in the toolbar you can click on Columns and check Function. It will add a column with the fully qualified location of the breakpoint (well, up to the function name). Click on the Function header to sort by Function and your breakpoints will be sorted and thus grouped together. You can then shift select the range you want to disable and uncheck one of them, they will all be disabled.

This assumes a somewhat sane naming convention though.

ContentLicense: CC BY-SA 4.0

Body:
Let's say I have a solution with 10 projects, it is an old code base and I am just getting familiar with it. I am doing a lot of debugging and putting breakpoints here and there. I would like to enable or disable all breakpoint in a given project (i.e data access project) but not in all the solution. I want to do this without manually disabling each breakpoint.

Is there a way to do this? If so, which is it? Is there an extension or third party tool that could help me? (I am using resharper but did not find any way to do this)


问:
Import data from Excel using SSIS without knowing sheet name
I have a spreadsheet that is updated by another server (out of my control) and I need to automate bringing that data into SQL 2005.  The data is always the first page of the spreadsheet.  However, the name of that sheet changes depending on the number of rows.

Is there a way to run an SSIS job that pulls in data from Excel without knowing the sheetname beforehand?  It seems to rely on the sheet name as the data source, but I'm looking to tell it "sheet number 1" or something similar.

答:
I don't think so...I don't know of any ordinal reference syntax, e.g., Sheets[0] that you could use.

So if you can't get the data without knowing the sheet name - you just need to dynamically find out the sheet name. This link on getting Excel schema info in SSIS should help you do that. Once you have that, you can pass the sheet name in as a variable, and away you go.


问:
cmake:missing and no known rule to make it when I import a prebuilt library
I want to import a prebuilt library using this CmakeLists.txt snippet:

```<code>add_library(openssl-crypto
            SHARED
            IMPORTED )
set_target_properties(openssl-crypto
                      PROPERTIES
                      IMPORTED_LOCATION
                      ${external_DIR}/libs/${ANDROID_ABI}/libcrypto.so )
include_directories(${external_DIR}/include/openssl)
</code>```

I linked this to my library as:

target_link_libraries(aes-crypto openssl-crypto)

Attempting to build returns this error:

```<code>'/libs/arm64-v8a/libcrypto.so', needed by ...,  missing and no known rule to make it
</code>```

答:
I found that the IMPORTED_LOCATION property, when passed to the set_target_properties function doesn't like relative paths.

From the CMake Documentation on IMPORTED_LOCATION

Full path to the main file on disk for an IMPORTED target.

To resolve this issue, I used the full path to the library instead.

Example:

```<code>set_target_properties ( curl-lib
                        PROPERTIES IMPORTED_LOCATION
                        libs/${ANDROID_ABI}/libcurl.a )

. . . becomes . . .

set_target_properties ( curl-lib
                        PROPERTIES IMPORTED_LOCATION
                        ${PROJECT_SOURCE_DIR}/src/main/cpp/libs/${ANDROID_ABI}/libcurl.a )
</code>```

The path to the library may differ slightly for you from the one above, but ${PROJECT_SOURCE_DIR} is normally a good starting point as it is defined as:

...the source directory of the last call to the project() command made in the current directory scope or one of its parents. Note, it is not affected by calls to project() made within a child directory scope (i.e. from within a call to add_subdirectory() from the current scope).

Body:
I want to import a prebuilt library using this CmakeLists.txt snippet:

add_library(openssl-crypto
            SHARED
            IMPORTED )
set_target_properties(openssl-crypto
                      PROPERTIES
                      IMPORTED_LOCATION
                      ${external_DIR}/libs/${ANDROID_ABI}/libcrypto.so )
include_directories(${external_DIR}/include/openssl)

I linked this to my library as:

target_link_libraries(aes-crypto openssl-crypto)

Attempting to build returns this error:

'/libs/arm64-v8a/libcrypto.so', needed by ...,  missing and no known rule to make it

Body:
I found that the IMPORTED_LOCATION property, when passed to the set_target_properties function doesn't like relative paths.

From the CMake Documentation on IMPORTED_LOCATION

Full path to the main file on disk for an IMPORTED target.

To resolve this issue, I used the full path to the library instead.

Example:

set_target_properties ( curl-lib
                        PROPERTIES IMPORTED_LOCATION
                        libs/${ANDROID_ABI}/libcurl.a )

. . . becomes . . .

set_target_properties ( curl-lib
                        PROPERTIES IMPORTED_LOCATION
                        ${PROJECT_SOURCE_DIR}/src/main/cpp/libs/${ANDROID_ABI}/libcurl.a )

The path to the library may differ slightly for you from the one above, but ${PROJECT_SOURCE_DIR} is normally a good starting point as it is defined as:

...the source directory of the last call to the project() command made in the current directory scope or one of its parents. Note, it is not affected by calls to project() made within a child directory scope (i.e. from within a call to add_subdirectory() from the current scope).


问:
Opening a Sitecore website in visual studio
Complete Sitecore newbie here i'm afraid.  I've downloaded Sitecore 8.2 and have set it up to run through IIS which works fine.  i have 3 folders

```<code>-- data
-- databases
-- website
</code>```

I have created a TDS project in vs2015 and can sync with Sitecore.  I want to create a new MVC project in my vs solution and then I presume publish it to the website folder of Sitecore, but Sitecore comes with a lot of files / dlls etc already in there.  I'm wondering what type of web project I create in vs2015 and how I get the existing files into the web project.  Do I simply create an MVC web application and copy and paste them over or is there a different way of doing this?

答:
Yes. you can initially start with a simple MVC application. You dont have to include all the config files in your project.

That being said, you should include the config files that you customize or create.

The most common one would be yoursite.Config that should have the site details .
As your site keeps growing or if you add something like glassmapper or sitecore ship - your App_Config files will keep getting added.

Body:
Complete Sitecore newbie here i'm afraid.  I've downloaded Sitecore 8.2 and have set it up to run through IIS which works fine.  i have 3 folders

-- data
-- databases
-- website

I have created a TDS project in vs2015 and can sync with Sitecore.  I want to create a new MVC project in my vs solution and then I presume publish it to the website folder of Sitecore, but Sitecore comes with a lot of files / dlls etc already in there.  I'm wondering what type of web project I create in vs2015 and how I get the existing files into the web project.  Do I simply create an MVC web application and copy and paste them over or is there a different way of doing this?


问:
Import 64bit floating point value from binary file into python
Background:
Good day, I need to extract information from a binary file produced by an equipment. The equipment comes with a matlab function to import binary file. From what i understand from the manual, the binary file contains a 64-bit floating point value between 0 and 1.

```<code>function phase = importData(folder, qUnit);

fileName = sprintf('%s\\%s.PH', folder, qUnit);

file = fopen(fileName, 'rb');

fseek(file, 0, 'bof');
phase = fread(file, inf, 'float64');
</code>```

Question: The matlab function works fine, but I wish to import the data into python. May I know how can this be done on Python? I did some research myself and tried something like this at the bottom. But when I do print(fileContent) to check the imported data, python simply stops responding in windows.

```<code>with open('sample.PH', mode='rb') as binary_file:
    fileContent = binary_file.read()
</code>```

答:
You can't read binary files like that into a useful form. You should use numpy.fromfile. This will give you a numerical vector with the data, similar to what you would get in MATLAB.  You don't even need to open it (although you can if you want).  Just give it a filename and it will automatically open, read, then close the file for you.

```<code>import numpy as np

file_content = np.fromfile('sample.PH', np.float64)
</code>```

Edit: here is how you can do multiple repeated values:

```<code>import numpy as np

file_content = np.fromfile('sample.PH', [('data', np.float32),
                                         ('time', np.float64)])
</code>```

(I put the last line on two lines for clarity, it could be one line if you prefer, or 10 for that matter, python doesn't care)

This will give you the equivalent of a MATLAB struct where one field is the data and the other field is the time. You can then access the data using file_content['data'] and the time using file_content['time'].  There is more information at the link I provided above.

Body:
Background:
Good day, I need to extract information from a binary file produced by an equipment. The equipment comes with a matlab function to import binary file. From what i understand from the manual, the binary file contains a 64-bit floating point value between 0 and 1.

function phase = importData(folder, qUnit);

fileName = sprintf('%s\\%s.PH', folder, qUnit);

file = fopen(fileName, 'rb');

fseek(file, 0, 'bof');
phase = fread(file, inf, 'float64');

Question: The matlab function works fine, but I wish to import the data into python. May I know how can this be done on Python? I did some research myself and tried something like this at the bottom. But when I do print(fileContent) to check the imported data, python simply stops responding in windows.

with open('sample.PH', mode='rb') as binary_file:
    fileContent = binary_file.read()

Body:
You can't read binary files like that into a useful form. You should use numpy.fromfile. This will give you a numerical vector with the data, similar to what you would get in MATLAB.  You don't even need to open it (although you can if you want).  Just give it a filename and it will automatically open, read, then close the file for you.

import numpy as np

file_content = np.fromfile('sample.PH', np.float64)

Edit: here is how you can do multiple repeated values:

import numpy as np

file_content = np.fromfile('sample.PH', [('data', np.float32),
                                         ('time', np.float64)])

(I put the last line on two lines for clarity, it could be one line if you prefer, or 10 for that matter, python doesn't care)

This will give you the equivalent of a MATLAB struct where one field is the data and the other field is the time. You can then access the data using file_content['data'] and the time using file_content['time'].  There is more information at the link I provided above.


答:
You could do an explicit merge:

```<code>m = test.merge(rul, on=['dataset_id', 'unit_id'], how='left')
test['rul'] = m['rul_x'] + m['rul_y']
</code>```

or do a groupby statement:

```<code>pd.concat([test, rul]).groupby(['dataset_id', 'unit_id'], as_index=False)['rul'].sum()
</code>```

Title: Sum columns of two dataframes based on dataframes' id's

Body:
I have these dataframes named test and rul. The rul dataframe contains constants in the RUL column which need to be added to the test's RUL based on the dataset and unit id. I have no clue how to achieve this and would be happy if anyone could lead me in the right direction.

Thanks.

Test:
+-------+------------+---------+-----+
|       | dataset_id | unit_id | RUL |
+-------+------------+---------+-----+
|     0 | FD001      |       1 |  30 |
|     1 | FD001      |       1 |  29 |
|     2 | FD001      |       1 |  28 |
|     3 | FD001      |       1 |  27 |
|     4 | FD001      |       1 |  26 |
|   ... | ...        |     ... | ... |
| 41209 | FD004      |     248 |   4 |
| 41210 | FD004      |     248 |   3 |
| 41211 | FD004      |     248 |   2 |
| 41212 | FD004      |     248 |   1 |
| 41213 | FD004      |     248 |   0 |
+-------+------------+---------+-----+

rul
+-----+------------+---------+-----+
|     | dataset_id | unit_id | RUL |
+-----+------------+---------+-----+
|   3 | FD004      |       4 |  75 |
|  63 | FD003      |      64 |  28 |
|  70 | FD002      |      71 | 148 |
| 203 | FD002      |     204 | 121 |
| 225 | FD004      |     226 |  88 |
| ... | ...        |     ... | ... |
|  45 | FD004      |      46 | 134 |
|  60 | FD002      |      61 | 169 |
| 140 | FD004      |     141 | 130 |
|  94 | FD001      |      95 | 128 |
| 161 | FD002      |     162 |  41 |
+-----+------------+---------+-----+

Body:
You could do an explicit merge:

m = test.merge(rul, on=['dataset_id', 'unit_id'], how='left')
test['rul'] = m['rul_x'] + m['rul_y']

or do a groupby statement:

pd.concat([test, rul]).groupby(['dataset_id', 'unit_id'], as_index=False)['rul'].sum()


问:
Powershell or cmd - How to search for a file on client and replace with a different file on network share?
We are looking to replace the defaultlayouts.xml for all profiles when upgrading to Windows 10 Pro v. 1607.  This will be accomplished with SCCM site-wide.  We have the new layoutmodification.xml configured and ready for deployment however, we are struggling to push this to all profiles due to the variation of users on a client machine.  No issues deploying to the 'default' profile.

The defaultlayouts.xml lives here: C:\Users\johndoe\AppData\Local\Microsoft\Windows\Shell

The variable will be johndoe.

Multiple users' profiles may exist on the client, so we need to search the 'c:\users' folder for the defaultlayouts.xml in each user's profile.

If the file exists in any of the profiles we want to delete it then copy the layoutmodification.xml from a network share.

I have experience in scripting, powershell and SCCM. Any ideas, thoughts, comments, and recommendations would be greatly appreciated.

Thank you!

答:
you can just use a wildcard in the path for the username portion and it will search for every user available. So, you could do something like this:</p>

```<code>gci C:\Users\*\AppData\Local\Microsoft\Windows\shell\defaultlayouts.xml | % {

    move $_.fullname "$($_.fullname)_bak"
    copy sourcelocation $_.fullname
    #alternatively to copy, you could do something like call a download if it's stored on a intranet site for example

}
</code>```

Body:
you can just use a wildcard in the path for the username portion and it will search for every user available. So, you could do something like this:

gci C:\Users\*\AppData\Local\Microsoft\Windows\shell\defaultlayouts.xml | % {

    move $_.fullname "$($_.fullname)_bak"
    copy sourcelocation $_.fullname
    #alternatively to copy, you could do something like call a download if it's stored on a intranet site for example

}


问:
Angular 2 routing not working with ASP.net core MVC
i'm working in an ASP.NET Core Web Application, using Angular 2 and VS 2015 as IDE. This is totally new for me, so i've been following every tutorial to get this page work. When i finally put everything together i face a routing problem: The page stays in the loading... tag and never show the content in the ModuleViewComponent. Read a lot of stackoverflow questions but I could not fix it.

My main.ts file looks like this:

```<code>// main entry point
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

the app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { NgForm } from '@angular/forms';
import { AppComponent } from './app.component';

import { ModuleViewComponent } from './components/CommonComponents/moduleView.component/moduleView.component';

const myRoutes: Routes = [
{
    path: 'home',
    component: ModuleViewComponent
},
{
    path: '/',
    redirectTo: 'home',
    pathMatch: 'full'
}
];

@NgModule({
imports: [
    RouterModule.forRoot(myRoutes),
    BrowserModule,
    FormsModule,
    HttpModule
],
declarations: [
    AppComponent,
    NavbarComponent,
    ModuleViewComponent
],
bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template:'<router-outlet></router-outlet>'
})
export class AppComponent {
}
</code>```

And the index.cshtml

```<code>@{
ViewData["Title"] = "Home Page";
}

<my-app>loading...</my-app>
</code>```

How can i get this to work and show the component content? Any help is more than welcome, thanks in advance.

答:
I have created a sample application which explains step by step details to create angular (Angular v4) applications with Asp.net MVC framework. Below is the link. Hope this helps you. You have to update route config file in your project so that angular can receive requests.

http://hive.rinoy.in/angular4-and-asp-net-mvc-hybrid-application/

http://hive.rinoy.in/routing-in-angular-asp-net-mvc-application/

Body:
i'm working in an ASP.NET Core Web Application, using Angular 2 and VS 2015 as IDE. This is totally new for me, so i've been following every tutorial to get this page work. When i finally put everything together i face a routing problem: The page stays in the loading... tag and never show the content in the ModuleViewComponent. Read a lot of stackoverflow questions but I could not fix it.

My main.ts file looks like this:

// main entry point
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

the app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { NgForm } from '@angular/forms';
import { AppComponent } from './app.component';

import { ModuleViewComponent } from './components/CommonComponents/moduleView.component/moduleView.component';

const myRoutes: Routes = [
{
    path: 'home',
    component: ModuleViewComponent
},
{
    path: '/',
    redirectTo: 'home',
    pathMatch: 'full'
}
];

@NgModule({
imports: [
    RouterModule.forRoot(myRoutes),
    BrowserModule,
    FormsModule,
    HttpModule
],
declarations: [
    AppComponent,
    NavbarComponent,
    ModuleViewComponent
],
bootstrap: [AppComponent]
})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template:'<router-outlet></router-outlet>'
})
export class AppComponent {
}

And the index.cshtml

@{
ViewData["Title"] = "Home Page";
}

<my-app>loading...</my-app>

How can i get this to work and show the component content? Any help is more than welcome, thanks in advance.


问:
splash screen android trouble load images in main page
pls any body help me...
i want to add splashscreen tp my android app using this tutorial :
http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/

, my aps built with eclipse, cordova,jquerymobile.
last time before i add splash screen, all images in main page (index.html) loaded succesfully, but where i implemented splash screen, images in my main page is not loaded.

this is my manifest.xml

```<code><activity
            android:name=".SplashScreen"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

splashscreen.java

```<code>package com.example.package;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class SplashScreen extends Activity {

    // Splash screen timer
    private static int SPLASH_TIME_OUT = 6000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }

}
</code>```

activity_splash.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/lcr" >

    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/w_logo" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:textSize="12dp"
        android:textColor="#454545"
        android:gravity="center_horizontal"
        android:layout_alignParentBottom="true"
        android:text="www.androidhive.info" />

</RelativeLayout>
</code>```

答:
problem with your Manifest file try above code</p>

```<code><activity
        android:name=".SplashScreen"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@android:style/Theme.Black.NoTitleBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"/>
</code>```

Body:
pls any body help me...
i want to add splashscreen tp my android app using this tutorial :
http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/

, my aps built with eclipse, cordova,jquerymobile.
last time before i add splash screen, all images in main page (index.html) loaded succesfully, but where i implemented splash screen, images in my main page is not loaded.

this is my manifest.xml

<activity
            android:name=".SplashScreen"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

splashscreen.java

package com.example.package;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class SplashScreen extends Activity {

    // Splash screen timer
    private static int SPLASH_TIME_OUT = 6000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }

}

activity_splash.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/lcr" >

    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/w_logo" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:textSize="12dp"
        android:textColor="#454545"
        android:gravity="center_horizontal"
        android:layout_alignParentBottom="true"
        android:text="www.androidhive.info" />

</RelativeLayout>

Body:
problem with your Manifest file try above code

<activity
        android:name=".SplashScreen"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@android:style/Theme.Black.NoTitleBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"/>


问:
How to select all checkboxes with a class name inside a table by table id
I have several tables on my page, and a table with the id of workOneTable. I have several rows in the table with class name of .rsvLine and more with class name .vtoLine. I need to be able to select all checkboxes in workOneTable with class name .rsvLine.
I have tried several things.

```<code>$( '#workOneTable :checkbox.rsvLine' ).prop( 'checked', this.checked );

$( '#workOneTable' ).find( 'input[type=checkbox]' ).prop( 'checked', true );

$( '#workOneTable tbody .rsvLine :checkbox' ).prop( 'checked' );
</code>```

Any help is greatly appreciated.

EDIT

Here is the most relevant part of the html code.

```<code><table id=workOneTable>
<thead>
    several rows here
</thead>
<tbody>
    <tr>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="rsvLine">other stuff</td>
        <td class="rsvLine">other stuff</td>
    </tr>
</tbody>
</code>```

I can select the right ones if I do not use the table id. It will select the .rsvLine in all tables. this is the code I used for that.

```<code>$( '.rsvLine :checkbox' ).each( function ()
            {
                if ( !$( this ).prop( "checked" ) )
                {
                    this.click();
                }
            } );
</code>```

答:
You need this

```<code>$( "#workOneTable .rsvLine input[type=checkbox]" ).each(function() {
  $( this ).prop('checked', true);
});
</code>```

Here is an example

$( "#workOneTable .rsvLine input[type=checkbox]" ).each(function() {
  $( this ).prop('checked', true);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id=workOneTable>
<thead>
    several rows here
</thead>
<tbody>
    <tr>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="rsvLine">other stuff</td>
        <td class="rsvLine">other stuff</td>
    </tr>
</tbody>

</div></code>```

Body:
I have several tables on my page, and a table with the id of workOneTable. I have several rows in the table with class name of .rsvLine and more with class name .vtoLine. I need to be able to select all checkboxes in workOneTable with class name .rsvLine.
I have tried several things.

$( '#workOneTable :checkbox.rsvLine' ).prop( 'checked', this.checked );

$( '#workOneTable' ).find( 'input[type=checkbox]' ).prop( 'checked', true );

$( '#workOneTable tbody .rsvLine :checkbox' ).prop( 'checked' );

Any help is greatly appreciated.

EDIT

Here is the most relevant part of the html code.

    several rows here

        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        other stuff
        other stuff

I can select the right ones if I do not use the table id. It will select the .rsvLine in all tables. this is the code I used for that.

$( '.rsvLine :checkbox' ).each( function ()
            {
                if ( !$( this ).prop( "checked" ) )
                {
                    this.click();
                }
            } );

Body:
You need this

$( "#workOneTable .rsvLine input[type=checkbox]" ).each(function() {
  $( this ).prop('checked', true);
});

Here is an example

$( "#workOneTable .rsvLine input[type=checkbox]" ).each(function() {
  $( this ).prop('checked', true);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id=workOneTable>
<thead>
    several rows here
</thead>
<tbody>
    <tr>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="rsvLine">other stuff</td>
        <td class="rsvLine">other stuff</td>
    </tr>
</tbody>

</div>


问:
Unable to run .apk on some off Genymotion devices
I simulate Samsung Galaxy S7 (API 23) using Genymotion, and then install arm-translation and after restarting device I install my application by drag and drop.
but I get following error:

```<code>Unfortunately, <application name> has stopped.
</code>```

Here is terminal log:

```<code>Failed to connect to VM (TcpStream) for main host connection, IP:Port=192.168.56.101:25000!!!
OpenGPL connected to 192.168.56.101:25000
port 22468 will be used for OpenGL data connections
</code>```

and here is log file from when I run device and application:

```<code>Mar 12 13:14:24 [Genymotion Player] [debug] Proxy configuration: no proxy used
Mar 12 13:14:24 [Genymotion Player] [debug] Host date and time: "12 Mar 2017 13:14:24 -0400"
Mar 12 13:14:24 [Genymotion Player] [debug] Proxy configuration: no proxy used
Mar 12 13:14:24 [Genymotion Player] [debug] GET  QUrl( "https://cloud.genymotion.com/content/video" )
Mar 12 13:14:24 [Genymotion Player] [debug] "Local socket created at path : /tmp/0054dd293a15aa9e4d99002d5631b4ca"
Mar 12 13:14:24 [Genymotion Player] [warning] ****  STARTING VIRTUAL DEVICE  ****
Mar 12 13:14:24 [Genymotion Player] [warning] Player version: "2.8.1"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Loading "vboxmanage" plugin
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Plugin "vboxmanage" loaded
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Chipset: "GenuineIntel"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] CPUID 0x1 (Intel): ECX= "c00e3bd"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Path: "VBoxManage"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("list", "hostinfo")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [System properties] Online physical CPU number: 2
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [System properties] Online virtual CPU number: 2
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [System properties] Max CPU number: 4
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [System properties] Max memory size: 3953
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] get "vboxnet0" from host.only.interface
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [findHostOnlyInterface] Looking for compatible host-only interface
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("list", "hostonlyifs")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [warning] [VBox] [getSavedHostOnlyInterface] Checking "vboxnet0" interface status (  QHostAddress( "192.168.56.1" )  )
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [getSavedHostOnlyInterface] "vboxnet0" Interface seems compatible
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("list", "dhcpservers")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [checkIfInterfaceHasValidDhcp] "HostInterfaceNetworking-vboxnet0" DHCP server is associated with "vboxnet0" interface
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [checkIfInterfaceHasValidDhcp] "vboxnet0" interface is compatible
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("--version")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] VM engine version: "4.3.36_Ubuntur105129"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("showvminfo", "S7_API23")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("guestproperty", "enumerate", "S7_API23")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("showvminfo", "S7_API23")
Mar 12 13:14:25 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:25 [Genymotion Player] [debug] [VBox] Call: ("showvminfo", "S7_API23")
Mar 12 13:14:25 [Genymotion Player] [debug] [VBox] Return code: 0
</code>```

but the application run successfully on HTC ONE (API 17). what's the problem and how can I fix it?
The .apk is from play store so the apk file is ok.

答: It seems the problem occurred by arm-translation. I find the x86 version of the application apk and could install it on all Genymotion devices with out need to flash using arm-translation.

Body:
I simulate Samsung Galaxy S7 (API 23) using Genymotion, and then install arm-translation and after restarting device I install my application by drag and drop.
but I get following error:

Unfortunately, <application name> has stopped.

Here is terminal log:

Failed to connect to VM (TcpStream) for main host connection, IP:Port=192.168.56.101:25000!!!
OpenGPL connected to 192.168.56.101:25000
port 22468 will be used for OpenGL data connections

and here is log file from when I run device and application:

Mar 12 13:14:24 [Genymotion Player] [debug] Proxy configuration: no proxy used
Mar 12 13:14:24 [Genymotion Player] [debug] Host date and time: "12 Mar 2017 13:14:24 -0400"
Mar 12 13:14:24 [Genymotion Player] [debug] Proxy configuration: no proxy used
Mar 12 13:14:24 [Genymotion Player] [debug] GET  QUrl( "https://cloud.genymotion.com/content/video" )
Mar 12 13:14:24 [Genymotion Player] [debug] "Local socket created at path : /tmp/0054dd293a15aa9e4d99002d5631b4ca"
Mar 12 13:14:24 [Genymotion Player] [warning] ****  STARTING VIRTUAL DEVICE  ****
Mar 12 13:14:24 [Genymotion Player] [warning] Player version: "2.8.1"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Loading "vboxmanage" plugin
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Plugin "vboxmanage" loaded
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Chipset: "GenuineIntel"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] CPUID 0x1 (Intel): ECX= "c00e3bd"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Path: "VBoxManage"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("list", "hostinfo")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [System properties] Online physical CPU number: 2
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [System properties] Online virtual CPU number: 2
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [System properties] Max CPU number: 4
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [System properties] Max memory size: 3953
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] get "vboxnet0" from host.only.interface
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [findHostOnlyInterface] Looking for compatible host-only interface
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("list", "hostonlyifs")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [warning] [VBox] [getSavedHostOnlyInterface] Checking "vboxnet0" interface status (  QHostAddress( "192.168.56.1" )  )
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [getSavedHostOnlyInterface] "vboxnet0" Interface seems compatible
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("list", "dhcpservers")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [checkIfInterfaceHasValidDhcp] "HostInterfaceNetworking-vboxnet0" DHCP server is associated with "vboxnet0" interface
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] [checkIfInterfaceHasValidDhcp] "vboxnet0" interface is compatible
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("--version")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] VM engine version: "4.3.36_Ubuntur105129"
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("showvminfo", "S7_API23")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("guestproperty", "enumerate", "S7_API23")
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:24 [Genymotion Player] [debug] [VBox] Call: ("showvminfo", "S7_API23")
Mar 12 13:14:25 [Genymotion Player] [debug] [VBox] Return code: 0
Mar 12 13:14:25 [Genymotion Player] [debug] [VBox] Call: ("showvminfo", "S7_API23")
Mar 12 13:14:25 [Genymotion Player] [debug] [VBox] Return code: 0

but the application run successfully on HTC ONE (API 17). what's the problem and how can I fix it?
The .apk is from play store so the apk file is ok.


问:
Now able to click on small pop up window using selenium web-driver with Java
I am not able to click on a dialog box which opens after clicking on Logout button in a website.
The role of the div tag  is dialog and it is inside an iframe.
I am not able to click on the logout button inside that opened dialog box.

I have tried switching to the iframe before clicking on that button. But not working.Still after switching when  I click on the button it gives me error.
When I call getWindowHandles() function it gives me only 1 open window.

Please help.

答:
Frames are special, in general, you need to use </p>

```<code>driver.switchTo().frame()
</code>```

Body:
Frames are special, in general, you need to use

driver.switchTo().frame()


问:
Trouble getting working directory
This is how I am trying to get the current working directory:

```<code>    char* ch;
    if( (ch = _getcwd( NULL, 0 )) == NULL )
    {
        cout << "Could not get working directory!" << endl;
    }
    // skonvertujme char* na string, s tym sa nizsie bude lahsie pracovat
    stringstream ss;
    string workingDirectory;
    ss << ch;
    ss >> workingDirectory;

    cout << workingDirectory << endl;
    cin.get();
    cin.get();
</code>```

Which prints out:

```<code>C:\Users\Richard\Documents\Visual
</code>```

Instead of the actual working directory:

```<code>C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug
</code>```

It seems like ti cuts everything after a space.

How can I get the working directory correctly even if there are spaces in the path?

答:
If you really want to use your solution - which is overkill - use the noskipws io-manipulator like so:</p>

```<code>ss >> noskipws >> workingDirectory;
</code>```

Title: Trouble getting working directory

Body:
This is how I am trying to get the current working directory:

    char* ch;
    if( (ch = _getcwd( NULL, 0 )) == NULL )
    {
        cout << "Could not get working directory!" << endl;
    }
    // skonvertujme char* na string, s tym sa nizsie bude lahsie pracovat
    stringstream ss;
    string workingDirectory;
    ss << ch;
    ss >> workingDirectory;

    cout << workingDirectory << endl;
    cin.get();
    cin.get();

Which prints out:

C:\Users\Richard\Documents\Visual

Instead of the actual working directory:

C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug

It seems like ti cuts everything after a space.

How can I get the working directory correctly even if there are spaces in the path?

Body:
If you really want to use your solution - which is overkill - use the noskipws io-manipulator like so:

ss >> noskipws >> workingDirectory;


问:
Call function in controller from eventlistener in .run
Using Ionic v1, I am trying to call a function in my controller when an event listener in my app.run fires. The event is created by a Cordova (Phonegap) plugin that detects changes in the headphone jack.

I must be doing something wrong because I can't find a solution that works. Here is my example:

```<code>(function() {
 var app = angular.module('mymodule', ['ionic']);
    app.run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
           if(window.HeadsetDetection){
                /*Monitor for changes in the headphone jack*/
                document.addEventListener('deviceready', function() {
                  window.HeadsetDetection.registerRemoteEvents(function(status){
                    // *HERE* is where I want to call or somehow trigger
                        an action in my controller
                 });
                }, false);
              }
        });
  });
</code>```

When the headphone jack is sensed I am trying to close an ionic popup created in my controller.

答:
You are defining your events from .run part of your angular application.

Therefore; to communicate with a controller; you need to use :
 - a global variable ($rootScope) on your app that is watched in your controller : this is an ugly solution; that I do not recommand
 - Broadcast / on an event in your app:  this is the clean solution

You need ; when you detect the event to broadcast to your app the news :

```<code>$rootScope.$broadcast('headphones-Updated');
</code>```

Within your controller; you have juste now to catch the event :

```<code>$scope.$on('headphones-Updated', function(event, args) {

});
</code>```

Another solution would have to set your event listener right in the controller

Body:
Using Ionic v1, I am trying to call a function in my controller when an event listener in my app.run fires. The event is created by a Cordova (Phonegap) plugin that detects changes in the headphone jack.

I must be doing something wrong because I can't find a solution that works. Here is my example:

(function() {
 var app = angular.module('mymodule', ['ionic']);
    app.run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
           if(window.HeadsetDetection){
                /*Monitor for changes in the headphone jack*/
                document.addEventListener('deviceready', function() {
                  window.HeadsetDetection.registerRemoteEvents(function(status){
                    // *HERE* is where I want to call or somehow trigger
                        an action in my controller
                 });
                }, false);
              }
        });
  });

When the headphone jack is sensed I am trying to close an ionic popup created in my controller.

Body:
You are defining your events from .run part of your angular application.

Therefore; to communicate with a controller; you need to use :
 - a global variable ($rootScope) on your app that is watched in your controller : this is an ugly solution; that I do not recommand
 - Broadcast / on an event in your app:  this is the clean solution

You need ; when you detect the event to broadcast to your app the news :

$rootScope.$broadcast('headphones-Updated');

Within your controller; you have juste now to catch the event :

$scope.$on('headphones-Updated', function(event, args) {

});

Another solution would have to set your event listener right in the controller


问:
Vue: shared data between different pages
```<code>var app = new Vue({
    el: '#app',
    data: {
        sharedData : ""
    },

    methods: {
        goToPageB: function() {
             if (some condition is met) {
                window.location.href="pageB.html";
                sharedData = 1234;  <------- I want to access sharedData in page B as well
             }

        }
    }
</code>```

I am new to Vue, i made a dummy login page and try to make my main page display sharedData according to the username. But the data is always lost after my app directs to Page B. How can I fix this?

答:
It doesn't really look like you need to employ state management for something that minor. If you're simply looking to pass data from one child component to another then I would suggest using an event bus.

Non Parent-Child Communication

Sometimes two components may need to communicate with one-another but they are not parent/child to each other. In simple scenarios, you can use an empty Vue instance as a central event bus:

```<code>var bus = new Vue()

// in component A's method
bus.$emit('id-selected', 1)

// in component B's created hook
bus.$on('id-selected', function (id) {
  // ...
})
</code>```

In more complex cases, you should consider employing a dedicated state-management pattern.

Body:
var app = new Vue({
    el: '#app',
    data: {
        sharedData : ""
    },

    methods: {
        goToPageB: function() {
             if (some condition is met) {
                window.location.href="pageB.html";
                sharedData = 1234;  <------- I want to access sharedData in page B as well
             }

        }
    }

I am new to Vue, i made a dummy login page and try to make my main page display sharedData according to the username. But the data is always lost after my app directs to Page B. How can I fix this?

Body:
It doesn't really look like you need to employ state management for something that minor. If you're simply looking to pass data from one child component to another then I would suggest using an event bus.

Non Parent-Child Communication

Sometimes two components may need to communicate with one-another but they are not parent/child to each other. In simple scenarios, you can use an empty Vue instance as a central event bus:

var bus = new Vue()

// in component A's method
bus.$emit('id-selected', 1)

// in component B's created hook
bus.$on('id-selected', function (id) {
  // ...
})

In more complex cases, you should consider employing a dedicated state-management pattern.