问:
Changing subview position in uinavigationbar in iOS 10 after pushing controller
My uinavigationbar has a subview. I've added at index 0. When I push some controller with animation a subview brings to top and hides navigation items, but if I push controller without animation a subview stays below items. It happens only in iOS 10. I can't understand why that.  </p>

答:
I had similar problem with navigation bar subviews reordering when I pushed or popped new view controllers.

What actually did the job for me was setting the delegate on my base UINavigationController in it's viewDidLoadmethod and resetting the visibility on my navigation bar in navigationController:willShow: delegate method.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    delegate = self
}

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    guard let hidden = viewController.navigationController?.isNavigationBarHidden else { return }
    viewController.navigationController?.isNavigationBarHidden = !hidden
    viewController.navigationController?.isNavigationBarHidden = hidden

}
</code>```

UIKit ¯_(ツ)_/¯

Body:
I had similar problem with navigation bar subviews reordering when I pushed or popped new view controllers.

What actually did the job for me was setting the delegate on my base UINavigationController in it's viewDidLoadmethod and resetting the visibility on my navigation bar in navigationController:willShow: delegate method.

override func viewDidLoad() {
    super.viewDidLoad()

    delegate = self
}

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    guard let hidden = viewController.navigationController?.isNavigationBarHidden else { return }
    viewController.navigationController?.isNavigationBarHidden = !hidden
    viewController.navigationController?.isNavigationBarHidden = hidden

}

UIKit ¯_(ツ)_/¯


来源: stackexchange

问:
How to retrieve currently logged in username in Windows?
I wish to retrieve the username of the currently logged in user in Windows (preferably some solution that works from Windows XP to W10) in a Delphi 7 project.

I tried both solutions given in this question, but they all give the name of the user, not the actual "username" that is used to log into Windows.

For example, the "username" I use to log into Windows is "joao.victor" (using a local Windows account), or my e-mail when I use a Microsoft account. But when I tried those 2 solutions, the string it returned was "João", which is my first name and the name configured in those accounts.

Does anyone know of a solution where I can retrieve the username that is used to log into Windows instead of the first name of the user?

答:
Have you tried this?

```<code>procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetCurrentUserName);
end;

function TForm1.GetCurrentUserName: string;
const
  cnMaxUserNameLen = 254;
var
  sUserName: string;
  dwUserNameLen: DWORD;
begin
  dwUserNameLen := cnMaxUserNameLen - 1;
  SetLength(sUserName, cnMaxUserNameLen);
  GetUserName(PChar(sUserName), dwUserNameLen);
  SetLength(sUserName, dwUserNameLen);
  Result := sUserName;
end;
</code>```

or alternatively

```<code>function UserName: String;
var User: PChar;
    i: DWord;
begin
  i := 1024;
  user := StrAlloc(Succ(i));
  if GetUserName(User, i) then
     Result := StrPas(User)
  else
     Result := 'unknown';
end;
</code>```

These 2 functions return the username you see on Windows login

See GetUserName

ContentLicense: CC BY-SA 3.0

Body:
Have you tried this?

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetCurrentUserName);
end;

function TForm1.GetCurrentUserName: string;
const
  cnMaxUserNameLen = 254;
var
  sUserName: string;
  dwUserNameLen: DWORD;
begin
  dwUserNameLen := cnMaxUserNameLen - 1;
  SetLength(sUserName, cnMaxUserNameLen);
  GetUserName(PChar(sUserName), dwUserNameLen);
  SetLength(sUserName, dwUserNameLen);
  Result := sUserName;
end;

or alternatively

function UserName: String;
var User: PChar;
    i: DWord;
begin
  i := 1024;
  user := StrAlloc(Succ(i));
  if GetUserName(User, i) then
     Result := StrPas(User)
  else
     Result := 'unknown';
end;

These 2 functions return the username you see on Windows login

See GetUserName


问:
POST Requests not working using request module in node.js
I want to send data to the java back end which is run on tomcat server.this is what i have tried so far.i have already installed request module.get method is working properly.</p>

```<code>Router.post('/', function(req, res) {

    request({
        uri: "http://localhost:8080/HIS_API/rest/UserService/registerUser",
        method: "POST",
        form: {
            roleId:2,
            employeeId:26,
            userName:"testing",
            password:"123"
        }
    }, function(error, response, body) {
        console.log(body);
    });

});
</code>```

答:
You have to use JSON.stringify to send data like in this format. before that write console.log(error). and check what's the error you are getting.</p>

```<code>request({
        url: url, //URL to hit
        method: 'post',
        headers: { "Authorization": req.headers.authorization},//if required
        timeout: 60 * 1000,
        body: JSON.stringify(body)
    }, function (error, result, body) {
        if (error) {
            console.log(error);
        } else if (result.statusCode === 500) {
            console.log('error');
        } else {
            console.log(body);
        }
    });
</code>```

Body:
I want to send data to the java back end which is run on tomcat server.this is what i have tried so far.i have already installed request module.get method is working properly.

Router.post('/', function(req, res) {

    request({
        uri: "http://localhost:8080/HIS_API/rest/UserService/registerUser",
        method: "POST",
        form: {
            roleId:2,
            employeeId:26,
            userName:"testing",
            password:"123"
        }
    }, function(error, response, body) {
        console.log(body);
    });

});

Body:
You have to use JSON.stringify to send data like in this format. before that write console.log(error). and check what's the error you are getting.

request({
        url: url, //URL to hit
        method: 'post',
        headers: { "Authorization": req.headers.authorization},//if required
        timeout: 60 * 1000,
        body: JSON.stringify(body)
    }, function (error, result, body) {
        if (error) {
            console.log(error);
        } else if (result.statusCode === 500) {
            console.log('error');
        } else {
            console.log(body);
        }
    });


问:
How to do something when a CheckBox is unchecked
I want a select all CheckBox which when Checked, checks all other CheckBoxes and when Unchecked, unchecks the others. I have written this code:

```<code>private void all_CheckedChanged(object sender, RoutedEventArgs e)
{
    if (all.IsChecked == true)//this is working
    {
        issue.IsChecked = true;
        summary.IsChecked = true;
        type.IsChecked = true;
        status.IsChecked = true;
        label.IsChecked = true;
        components.IsChecked = true;
        empty.IsChecked = true;
        reporter.IsChecked = true;
        requester.IsChecked = true;
        team.IsChecked = true;
        assignee.IsChecked = true;
    }
    else if (all.IsChecked == false)//this is not doing anything
    {
        issue.IsChecked = false;
        summary.IsChecked = false;
        type.IsChecked = false;
        //same for other checkboxes
    }
}
</code>```

when I debug it I see that the event takes places when I check the CheckBox but nothing happens when I uncheck it. Someone, please suggest me how to do this in case I am doing something wrong.

答:
In WPF's CheckBox you have not the Changed event. You have used the Checked event so you have to specify the Unchecked also and attach the same handler to both events. So your XAML code should be like this:

```<code><CheckBox Name="all" Checked="All_OnChecked" Unchecked="All_OnChecked"></CheckBox>
</code>```

However I strongly recommend that you use MVVM pattern for this purposes.

Body:
I want a select all CheckBox which when Checked, checks all other CheckBoxes and when Unchecked, unchecks the others. I have written this code:

private void all_CheckedChanged(object sender, RoutedEventArgs e)
{
    if (all.IsChecked == true)//this is working
    {
        issue.IsChecked = true;
        summary.IsChecked = true;
        type.IsChecked = true;
        status.IsChecked = true;
        label.IsChecked = true;
        components.IsChecked = true;
        empty.IsChecked = true;
        reporter.IsChecked = true;
        requester.IsChecked = true;
        team.IsChecked = true;
        assignee.IsChecked = true;
    }
    else if (all.IsChecked == false)//this is not doing anything
    {
        issue.IsChecked = false;
        summary.IsChecked = false;
        type.IsChecked = false;
        //same for other checkboxes
    }
}

when I debug it I see that the event takes places when I check the CheckBox but nothing happens when I uncheck it. Someone, please suggest me how to do this in case I am doing something wrong.

Body:
In WPF's CheckBox you have not the Changed event. You have used the Checked event so you have to specify the Unchecked also and attach the same handler to both events. So your XAML code should be like this:

<CheckBox Name="all" Checked="All_OnChecked" Unchecked="All_OnChecked"></CheckBox>

However I strongly recommend that you use MVVM pattern for this purposes.


问:
why can't able to get values in proper manner for char[][] using fgets in for loop
```<code>#include<stdio.h>
#include<stdlib.h>
int main()
{
     char str[10][50];
     for(int i=0;i<10;i++)
         fgets(str[i],50,stdin);//some runtime error occurs and execution stops completely
     for(int i=0;i<10;i++)
         printf("str[%d]=%s\n",i,str[i]);
     return 0;
}
</code>```

I want to give input as str[0]="hello world" and str[1]="good answer" till str[9] but i am not able to give inputs using below for() loop

答:
Well you are doing dynamic declaration in c program inside for() loop which is not allowed in C programming language but it is allowed in C++.

```<code>#include<stdio.h>
#include<stdlib.h>
int main()
{
     char str[10][50];
     int i;
     for(i=0;i<10;i++)
         fgets(str[i],50,stdin);
     for(i=0;i<10;i++)
         printf("str[%d]=%s\n",i,str[i]);
     system("pause");
     return 0;
}
</code>```

this program works just fine.

Body:
#include<stdio.h>
#include<stdlib.h>
int main()
{
     char str[10][50];
     for(int i=0;i<10;i++)
         fgets(str[i],50,stdin);//some runtime error occurs and execution stops completely
     for(int i=0;i<10;i++)
         printf("str[%d]=%s\n",i,str[i]);
     return 0;
}

I want to give input as str[0]="hello world" and str[1]="good answer" till str[9] but i am not able to give inputs using below for() loop

Body:
Well you are doing dynamic declaration in c program inside for() loop which is not allowed in C programming language but it is allowed in C++.

#include<stdio.h>
#include<stdlib.h>
int main()
{
     char str[10][50];
     int i;
     for(i=0;i<10;i++)
         fgets(str[i],50,stdin);
     for(i=0;i<10;i++)
         printf("str[%d]=%s\n",i,str[i]);
     system("pause");
     return 0;
}

this program works just fine.


问:
Crawling data from web page with content rendered by javascript
I am a newbie in crawling data. I want to crawl data from this site: [http://kbbi.web.id/][

I want to crawl data by input from .csv file and make crawling data work like the above picture for every csv single row and get data only from the red box, ex. mengabadi, mengabadikan, pengabadian, keabadian and save it in the new .csv file like this:

So, what can I do to crawl it (using python maybe)? And I think the web page use javascript to load/render the data.

答:
Use requests and bs4
sample code: (read and implement on your own, this is just for giving you a idea !)

```<code>from bs4 import BeautifulSoup

import requests

url = "http://kbbi.web.id/"

r  = requests.get(url)

data = r.text

soup = BeautifulSoup(data)
</code>```

Now, use the inspect tool to dig through the site, and ..
CODE !!

Installing BeautifulSoup and Requests can be done with pip:

```<code>$ pip install requests

$ pip install beautifulsoup4
</code>```

Body:
Use requests and bs4
sample code: (read and implement on your own, this is just for giving you a idea !)

from bs4 import BeautifulSoup

import requests

url = "http://kbbi.web.id/"

r  = requests.get(url)

data = r.text

soup = BeautifulSoup(data)

Now, use the inspect tool to dig through the site, and ..
CODE !!

Installing BeautifulSoup and Requests can be done with pip:

$ pip install requests

$ pip install beautifulsoup4


问:
How to check MySQL performance?
i have mysql that is used on production server for php webshop application.

sometimes it works very slow. so, i will change indexes for several tables.

but before that, i have to make some kind of "snapshot" of current performances (several times per day). after that, i will change indexes, and create new "performance snapshot". then i will made some more changes in database, and made another "performance snapshot".

how can i make that "performance snapshot"? is it possible to use some kind of tool, or to ckeck some logs, or...?

if you can help me how to do that.

thank you in advance!

答:
If you want to buy a commercial product, there is the MySQL Query Analyzer

Otherwise, you could use the SQL Profiler which is already included with MySQL.

The SQL Profiler is built into the database server and can be dynamically enabled/disabled via the MySQL client utility. To begin profiling one or more SQL queries, simply issue the following command:

```<code>mysql> set profiling=1;
</code>```

Thereafter, you will see the duration of each of your queries as you run them.

ContentLicense: CC BY-SA 2.5

Title: How to check MySQL performance?

Body:
If you want to buy a commercial product, there is the MySQL Query Analyzer

Otherwise, you could use the SQL Profiler which is already included with MySQL.

The SQL Profiler is built into the database server and can be dynamically enabled/disabled via the MySQL client utility. To begin profiling one or more SQL queries, simply issue the following command:

mysql> set profiling=1;

Thereafter, you will see the duration of each of your queries as you run them.


问:
How to write my own functions for comparison?
I wrote a function for vector comparison.

```<code>#include <vector>
#include <iostream>
#include <algorithm>

using std::vector;
using std::cout;

bool mycomp(const vector<int>& vi_a, const vector<int>& vi_b){
    for(auto x:vi_a) cout << x;
    cout << '\n';
    return true;
}

int main(){
    vector<int> vi1{2,9,8};
    vector<int> vi2{3,5,6};
    vector<int> vi = min(vi1, vi2, mycomp);
    for(auto x:vi) cout << x;
    cout << '\n';
}
</code>```

Output:

```<code>356
356
</code>```

What's weird is that the output is 356, instead of 298. It seems that the two vectors are switched when calling mycomp.

p.s. I'd rather not use lambda here, because mycomp contains more than one line of code, which is more readable this way.

答:
If you take a look at the cppreference documentation for std::min() you will see in the possible implementation that the second element is used as the first element in the comparator.

```<code>template<class T, class Compare>
const T& min(const T& a, const T& b, Compare comp)
{
    return (comp(b, a)) ? b : a;
}
</code>```

And when you call min() with the arguments vi2 and vi1, the second argument is passed to the comparator (which in your case is vi2), upon which the comparator returns true (implying that vi2 is the minimum of the two).  While doing this the comparator also prints out 356 because that is the first element passed to the comparator according to the possible implementation above.

After that happens you take the presumably smaller of the two vectors, which is the first one passed to the comparator according to the possible implementation above (which is vi2).  And you print that out.  Therefore you get 356 again.

Note that the reason b is passed as the first argument to std::min is because in the case where the two compare equal the algorithm is required to return a.  At the same time it is required to call the comparator only once.  Combining these two requirements gives the possible implementation above.

Body:
I wrote a function for vector comparison.

#include <vector>
#include <iostream>
#include <algorithm>

using std::vector;
using std::cout;

bool mycomp(const vector<int>& vi_a, const vector<int>& vi_b){
    for(auto x:vi_a) cout << x;
    cout << '\n';
    return true;
}

int main(){
    vector<int> vi1{2,9,8};
    vector<int> vi2{3,5,6};
    vector<int> vi = min(vi1, vi2, mycomp);
    for(auto x:vi) cout << x;
    cout << '\n';
}

Output:

356
356

What's weird is that the output is 356, instead of 298. It seems that the two vectors are switched when calling mycomp.

p.s. I'd rather not use lambda here, because mycomp contains more than one line of code, which is more readable this way.

Body:
If you take a look at the cppreference documentation for std::min() you will see in the possible implementation that the second element is used as the first element in the comparator.

template<class T, class Compare>
const T& min(const T& a, const T& b, Compare comp)
{
    return (comp(b, a)) ? b : a;
}

And when you call min() with the arguments vi2 and vi1, the second argument is passed to the comparator (which in your case is vi2), upon which the comparator returns true (implying that vi2 is the minimum of the two).  While doing this the comparator also prints out 356 because that is the first element passed to the comparator according to the possible implementation above.

After that happens you take the presumably smaller of the two vectors, which is the first one passed to the comparator according to the possible implementation above (which is vi2).  And you print that out.  Therefore you get 356 again.

Note that the reason b is passed as the first argument to std::min is because in the case where the two compare equal the algorithm is required to return a.  At the same time it is required to call the comparator only once.  Combining these two requirements gives the possible implementation above.


问:
How to generate HTML report in jmeter
I ran performance test case in jmeter. Now I can see results in 'View Results in Table'. But I also want same results to be saved as html report.

By default jmeter save html report? or is there a way to generate html report?

Can anyone please help me on this.

答:
JMeter provide dashboard report which is only available since JMeter 3.0.

The dashboard generator is a modular extension of JMeter. Its default
  behavior is to read and process samples from CSV files to generate
  HTML files containing graph views. It can generate the report at end
  of a load test or on demand.

To generate Dashboard report follow the instruction below:

Generating Report Dashboard.

Generation from an existing sample CSV log file:

```<code>jmeter -g <log file> -o <Path to output folder>
</code>```

Generation after load test:

```<code>jmeter -n -t <test JMX file> -l <test log file> -e -o <Path to output folder>
</code>```

Title: How to generate HTML report in jmeter

Body:
JMeter provide dashboard report which is only available since JMeter 3.0.

The dashboard generator is a modular extension of JMeter. Its default
  behavior is to read and process samples from CSV files to generate
  HTML files containing graph views. It can generate the report at end
  of a load test or on demand.

To generate Dashboard report follow the instruction below:

Generating Report Dashboard.

Generation from an existing sample CSV log file:

jmeter -g <log file> -o <Path to output folder>

Generation after load test:

jmeter -n -t <test JMX file> -l <test log file> -e -o <Path to output folder>


问:
Nginx to serve php files from a different server
I am trying to configure nginx to serve PHP from another server.

The files can be located within a directory under /sample on the other server

Fast CGI is running on port 9000 on the other server

Here is what I have tried, which is not working at the moment.

```<code>location ~ [^/]\.php(/|$) {
                proxy_pass      http://192.168.x.xx;
                proxy_redirect http://192.168.x.xx /sample;
                fastcgi_split_path_info ^(.+?\.php)(/.*)$;
                if (!-f $document_root$fastcgi_script_name)
                {
                        return 404;
                }
                # Mitigate https://httpoxy.org/ vulnerabilities
                fastcgi_param HTTP_PROXY "";
                fastcgi_read_timeout 150;
                fastcgi_buffers 4 256k;
                fastcgi_buffer_size 128k;
                fastcgi_busy_buffers_size 256k;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
</code>```

I also need to configure nginx to serve static files from the same server

答:
No need to give /sample path

```<code>location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
    return 404;
}

# Mitigate https://httpoxy.org/ vulnerabilities
fastcgi_param HTTP_PROXY "";

fastcgi_pass IP:9000;
fastcgi_index index.php;
include fastcgi_params;
}
</code>```

For static files from nginx server you need to use try_files for that.

```<code>location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;

    // other CGI parameters
}
</code>```

Make sure you're aware of common pitfalls.

If you want to access static files from another server you need to run a webserver there and just proxy pass  from Nginx

Body:
I am trying to configure nginx to serve PHP from another server.

The files can be located within a directory under /sample on the other server

Fast CGI is running on port 9000 on the other server

Here is what I have tried, which is not working at the moment.

location ~ [^/]\.php(/|$) {
                proxy_pass      http://192.168.x.xx;
                proxy_redirect http://192.168.x.xx /sample;
                fastcgi_split_path_info ^(.+?\.php)(/.*)$;
                if (!-f $document_root$fastcgi_script_name)
                {
                        return 404;
                }
                # Mitigate https://httpoxy.org/ vulnerabilities
                fastcgi_param HTTP_PROXY "";
                fastcgi_read_timeout 150;
                fastcgi_buffers 4 256k;
                fastcgi_buffer_size 128k;
                fastcgi_busy_buffers_size 256k;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }

I also need to configure nginx to serve static files from the same server

Body:
No need to give /sample path

location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
    return 404;
}

# Mitigate https://httpoxy.org/ vulnerabilities
fastcgi_param HTTP_PROXY "";

fastcgi_pass IP:9000;
fastcgi_index index.php;
include fastcgi_params;
}

For static files from nginx server you need to use try_files for that.

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;

    // other CGI parameters
}

Make sure you're aware of common pitfalls.

If you want to access static files from another server you need to run a webserver there and just proxy pass  from Nginx


问:
bring malloc() back to its initial state
Do you know if there is a way to bring back malloc in its initial state, as if the program was just starting ?

reason : I am developing an embedded application with the nintendods devkitpro and I would like to be able to improve debugging support in case of software faults. I can already catch most errors and e.g. return to the console menu, but this fails to work when catching std::bad_alloc.

I suspect that the code I use for "soft reboot" involves malloc() itself at some point I cannot control, so I'd like to "forget everything about the running app and get a fresh start".

答:
Do you ever need to free memory in anything other than last-in-first-out order?  If not, I'd suggest that you define an array to use all available memory (you'll probably have to tweak the linker files to do this) and then initialize a pointer to the start of that array.  Then write your own malloc() function:

```
char *allocation_ptr = big_array;

void *malloc(size_t n)
{
  void *temp = (void*)allocation_ptr;
  if (allocation_ptr > END_OF_ALLOCATION_AREA - n)
    return 0;
  allocation_ptr += n;
  return temp;
}

void free_all_after(void *ptr)
{
  if (ptr)
    allocation_ptr = (char*)ptr;
}
```

In this implementation, free_all_after() will free the indicated pointer and everything allocated after it.  Note that unlike other implementations of malloc(), this one has zero overhead.  The LIFO allocation is very limiting, but for many embedded systems it would be entirely adequate.

Body:
Do you ever need to free memory in anything other than last-in-first-out order?  If not, I'd suggest that you define an array to use all available memory (you'll probably have to tweak the linker files to do this) and then initialize a pointer to the start of that array.  Then write your own malloc() function:

char *allocation_ptr = big_array;

void *malloc(size_t n)
{
  void *temp = (void*)allocation_ptr;
  if (allocation_ptr > END_OF_ALLOCATION_AREA - n)
    return 0;
  allocation_ptr += n;
  return temp;
}

void free_all_after(void *ptr)
{
  if (ptr)
    allocation_ptr = (char*)ptr;
}

In this implementation, free_all_after() will free the indicated pointer and everything allocated after it.  Note that unlike other implementations of malloc(), this one has zero overhead.  The LIFO allocation is very limiting, but for many embedded systems it would be entirely adequate.


问:
why I can't use var value in my button action?
I want value send to my button...

why I can't use quizWord in my button action??

it occurs "use of unsolved identifier..." error...

```<code>    import UIKit

extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}
// random

class QuizViewController: UIViewController {

    var tasks : [Task] = []
    var limitRe:Int = 0
    var cards: [Character] = []
    var quizName = [String]()
    var quizfileName = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //get the data from core data
        getData()

        for q in 0...tasks.count-1 {
            let quiz = tasks[q]
            quizName.append(quiz.name!)
            quizfileName.append(quiz.filename!)
            print(quizName, quizfileName)
        }
        var quizWord = quizName[0]
        var countText: Int = (quizWord.characters.count) - 1

        for _ in 0...countText
        {let index1 = quizWord.index(quizWord.startIndex, offsetBy: limitRe)

            cards.append(quizWord[index1])
            limitRe = limitRe + 1
        }
        cards.shuffle()
        quizPhotoView.image = UIImage(named: "1.jpg")

        if countText >= 0 {lblChar1.text = "\(cards[0])"} else {lblChar1.text = ""}
        if countText >= 1 {lblChar2.text = "\(cards[1])"} else {lblChar2.text = ""}
        if countText >= 2 {lblChar3.text = "\(cards[2])"} else {lblChar3.text = ""}
        if countText >= 3 {lblChar4.text = "\(cards[3])"} else {lblChar4.text = ""}
        if countText >= 4 {lblChar5.text = "\(cards[4])"} else {lblChar5.text = ""}
        if countText >= 5 {lblChar6.text = "\(cards[5])"} else {lblChar6.text = ""}
        if countText >= 6 {lblChar7.text = "\(cards[6])"} else {lblChar7.text = ""}
        if countText >= 7 {lblChar8.text = "\(cards[7])"} else {lblChar8.text = ""}

    }

    @IBOutlet weak var lblChar1: UILabel!
    @IBOutlet weak var lblChar2: UILabel!
    @IBOutlet weak var lblChar3: UILabel!
    @IBOutlet weak var lblChar4: UILabel!
    @IBOutlet weak var lblChar5: UILabel!
    @IBOutlet weak var lblChar6: UILabel!
    @IBOutlet weak var lblChar7: UILabel!
    @IBOutlet weak var lblChar8: UILabel!
    @IBOutlet weak var lblTyped: UILabel!
    @IBOutlet weak var quizPhotoView: UIImageView!

    func getData() {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {
            tasks = try context.fetch(Task.fetchRequest())
        }
        catch {
            print("Failed")
        }
    }

    @IBAction func butChar1(_ sender: UIButton) {
    if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar1.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar2(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar2.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}
    }
    @IBAction func butChar3(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar3.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar4(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar4.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar5(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar5.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar6(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar6.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar7(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar7.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar8(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar8.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}

}
</code>```

答:
Here you have declared quizWord inside ViewDidLoad so it is a local variable which will only be available inside ViewDidLoad function.

If you want quizWord to be used through out the viewController QuizViewController then you have to declare it outside all functions just like you did for quizfileName,quizName etc.
May be like

```<code>   var quizfileName = [String]()
   var quizWord:String?
</code>```

Body:
I want value send to my button...

why I can't use quizWord in my button action??

it occurs "use of unsolved identifier..." error...

    import UIKit

extension Array
{
    /** Randomizes the order of an array's elements. */
    mutating func shuffle()
    {
        for _ in 0..<10
        {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}
// random

class QuizViewController: UIViewController {

    var tasks : [Task] = []
    var limitRe:Int = 0
    var cards: [Character] = []
    var quizName = [String]()
    var quizfileName = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //get the data from core data
        getData()

        for q in 0...tasks.count-1 {
            let quiz = tasks[q]
            quizName.append(quiz.name!)
            quizfileName.append(quiz.filename!)
            print(quizName, quizfileName)
        }
        var quizWord = quizName[0]
        var countText: Int = (quizWord.characters.count) - 1

        for _ in 0...countText
        {let index1 = quizWord.index(quizWord.startIndex, offsetBy: limitRe)

            cards.append(quizWord[index1])
            limitRe = limitRe + 1
        }
        cards.shuffle()
        quizPhotoView.image = UIImage(named: "1.jpg")

        if countText >= 0 {lblChar1.text = "\(cards[0])"} else {lblChar1.text = ""}
        if countText >= 1 {lblChar2.text = "\(cards[1])"} else {lblChar2.text = ""}
        if countText >= 2 {lblChar3.text = "\(cards[2])"} else {lblChar3.text = ""}
        if countText >= 3 {lblChar4.text = "\(cards[3])"} else {lblChar4.text = ""}
        if countText >= 4 {lblChar5.text = "\(cards[4])"} else {lblChar5.text = ""}
        if countText >= 5 {lblChar6.text = "\(cards[5])"} else {lblChar6.text = ""}
        if countText >= 6 {lblChar7.text = "\(cards[6])"} else {lblChar7.text = ""}
        if countText >= 7 {lblChar8.text = "\(cards[7])"} else {lblChar8.text = ""}

    }

    @IBOutlet weak var lblChar1: UILabel!
    @IBOutlet weak var lblChar2: UILabel!
    @IBOutlet weak var lblChar3: UILabel!
    @IBOutlet weak var lblChar4: UILabel!
    @IBOutlet weak var lblChar5: UILabel!
    @IBOutlet weak var lblChar6: UILabel!
    @IBOutlet weak var lblChar7: UILabel!
    @IBOutlet weak var lblChar8: UILabel!
    @IBOutlet weak var lblTyped: UILabel!
    @IBOutlet weak var quizPhotoView: UIImageView!

    func getData() {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {
            tasks = try context.fetch(Task.fetchRequest())
        }
        catch {
            print("Failed")
        }
    }

    @IBAction func butChar1(_ sender: UIButton) {
    if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar1.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar2(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar2.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}
    }
    @IBAction func butChar3(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar3.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar4(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar4.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar5(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar5.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar6(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar6.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar7(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar7.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}
    @IBAction func butChar8(_ sender: UIButton) {
        if (lblTyped.text!.characters.count) > (quizWord.characters.count) - 1 {lblTyped.text = ""}
        lblTyped.text = lblTyped.text! + lblChar8.text!
        if lblTyped.text == quizWord {lblTyped.text = "Good"}}

}

Body:
Here you have declared quizWord inside ViewDidLoad so it is a local variable which will only be available inside ViewDidLoad function.

If you want quizWord to be used through out the viewController QuizViewController then you have to declare it outside all functions just like you did for quizfileName,quizName etc.
May be like

   var quizfileName = [String]()
   var quizWord:String?


问:
Runtime of triple nested for loops
I'm currently going through "Cracking the coding interview" textbook and I'm reviewing Big-O and runtime. One of the examples were as such:

Print all positive integer solutions to the equation a^3 + b^3 = c^3 + d^3 where a, b, c, d are integers between 1 and 1000.

The psuedo code solution provided is:

```<code>n = 1000;
for c from 1 to n
  for d from 1 to n
    result = c^3 + d^3
    append (c,d) to list at value map[result]

for each result, list in map
  for each pair1 in list
    for each pair2 in list
      print pair1, pair2

The runtime is O(N^2)
</code>```

I'm not sure how O(N^2) is obtained and after extensive googling and trying to figure out why, I still have no idea. My rational is as following:

Top half is O(N^2) because the outer loop goes to n and inner loop executes n times each.

The bottom half I'm not sure how to calculate, but I got O(size of map) * O(size of list) * O(size of list) = O(size of map) * O(size of list^2).

O(N^2) + O(size of map) * O(size of list^2)

The 2 for loops adding the pairs to the list of the map = O(N) * O(N) b/c it's 2 for loops running N times.

The outer for loop for iterating through the map = O(2N-1) = O(N) b/c the size of the map is 2N - 1 which is essentially N.

The 2 for loops for iterating through the pairs of each list = O(N) * O(N) b/c each list is <= N

Total runtime: O(N^2) + O(N) * O(N^2) = O(N^3)

Not sure what I'm missing here

Could someone help me figure out how O(N^2) is obtained or why my solution is incorrect. Sorry if my explanation is a bit confusing. Thanks

答:
The complexity of the second part is O(sum of (length of lists)^2 in map), since the length of the list varies depending on the we know that sum of length of lists in map is n^2 since we definitely added n^2 pairs in the first bit of the code. Since T(program) = O(n^2) + O(sum of length of lists in map) * O(sum of length of lists in map / size of map) = O(n^2) * O(sum of length of lists in map / size of map), it remains to show that sum of length of lists in map / size of map is O(1). Doing this requires quite a bit of number theory and unfortunately I can't help you there. But do check out these links for more info on how you would go about it: https://en.wikipedia.org/wiki/Taxicab_number

https://math.stackexchange.com/questions/1274816/numbers-that-can-be-expressed-as-the-sum-of-two-cubes-in-exactly-two-different-w

http://oeis.org/A001235

Title: Runtime of triple nested for loops

Body:
I'm currently going through "Cracking the coding interview" textbook and I'm reviewing Big-O and runtime. One of the examples were as such:

Print all positive integer solutions to the equation a^3 + b^3 = c^3 + d^3 where a, b, c, d are integers between 1 and 1000.

The psuedo code solution provided is:

n = 1000;
for c from 1 to n
  for d from 1 to n
    result = c^3 + d^3
    append (c,d) to list at value map[result]

for each result, list in map
  for each pair1 in list
    for each pair2 in list
      print pair1, pair2

The runtime is O(N^2)

I'm not sure how O(N^2) is obtained and after extensive googling and trying to figure out why, I still have no idea. My rational is as following:

Top half is O(N^2) because the outer loop goes to n and inner loop executes n times each.

The bottom half I'm not sure how to calculate, but I got O(size of map) * O(size of list) * O(size of list) = O(size of map) * O(size of list^2).

O(N^2) + O(size of map) * O(size of list^2)

The 2 for loops adding the pairs to the list of the map = O(N) * O(N) b/c it's 2 for loops running N times.

The outer for loop for iterating through the map = O(2N-1) = O(N) b/c the size of the map is 2N - 1 which is essentially N.

The 2 for loops for iterating through the pairs of each list = O(N) * O(N) b/c each list is <= N

Total runtime: O(N^2) + O(N) * O(N^2) = O(N^3)

Not sure what I'm missing here

Could someone help me figure out how O(N^2) is obtained or why my solution is incorrect. Sorry if my explanation is a bit confusing. Thanks


问:
echo HTML with php variable
I'm trying to display the following and I have a css code for it but it doesn't work. Any help would be appreciated.

HTML/PHP

```<code> $var = "Hello World";
    echo '<p>' . 'the value of the variable is : ' . $var . '</p>';
</code>```

CSS

```<code>p
{
    text-align: center;
    color: red;
}
</code>```

Thanks for your help

答:
Its working for me in localhost. </p>

```<code>  <?php
    $var = "Hello World";
        echo '<p>' . 'the value of the variable is : ' . $var . '</p>';
    ?>
    <style type="text/css">
    p
    {
        text-align: center;
        color: red;
    }
    </style>
</code>```

Title: echo HTML with php variable

Body:
I'm trying to display the following and I have a css code for it but it doesn't work. Any help would be appreciated.

HTML/PHP

 $var = "Hello World";
    echo '
' . 'the value of the variable is : ' . $var . '
';

CSS

p
{
    text-align: center;
    color: red;
}

Thanks for your help

Body:
Its working for me in localhost.

  <?php
    $var = "Hello World";
        echo '<p>' . 'the value of the variable is : ' . $var . '</p>';
    ?>
    <style type="text/css">
    p
    {
        text-align: center;
        color: red;
    }
    </style>


问:
Crystal report page changing
How can we handle page changing in crystal report if report consist more than one page.</p>

答:
In Crystal Reports:
1.Go to Report > Section Expert>
2.Highlight the Group Footer section for the group that needs to have the page break>
3.Mark the New Page After checkbox>
4.Click OK
Refresh the report
It's work</p>

Title: Crystal report page changing


问:
need help on generating a non repeating array
Have a interview quiz lately, and I really struggling here. There are few steps of question, but this final one is making me cracking my brain.

I created 4 set of function mainly is to randomize:
1. alphabet (object_one)
2. integer (object_two)
3. real number (object_three)
4. alphanumerical (object_four)

The final one is to create an random array based on my 4 set of object.
Eg: hisadfnnasd, 126263, assfdgsga12348fas, 13123.123,

lizierdjfklaasf, 123192u3kjwekhf, 89181811238,122,
nmarcysfa900jkifh  , 3.781, 2.11, ....

But this is my code for the final one:

```<code>function final_one(min,max,dec){
var obj = [object_one(min,max),object_two(min,max),object_three(min,max,dec),object_four(min,max)];
var output = "";
for (var i = 0; i < 10; i++) {
    output += obj[random(0,3)] + ", ";
}
return output;
</code>```

}

my output will be something like this:

```<code>jkwnh1365624sp, 275995, jkwnh1365624sp, 43, jkwnh1365624sp, 275995, 275995, 43, 275995, 275995,
</code>```

Data are keep repeating.

Please help!

答:
when you create obj, you execute all 4 functions once:

```<code>var obj = [object_one(min,max),object_two(min,max),object_three(min,max,dec),object_four(min,max)];
</code>```

object_one(min,max) is a function call.

This creates an array of 4 elements, somthing like this: ['v', 5, 3.14, 'x']
As @Dat pointed out, random(0,3) picks one of these elements.

What you are trying to do is to have an array of functions:

```<code>var obj = [object_one, object_two, object_three, object_four];
</code>```

and have one of the functions randomly executed (like this):

```<code>obj[random(0,3)](min, max, dec);
</code>```

some of the functions have no dec parameter but that is ok in javascript.

I hope I understood your requirements correctly.

Body:
Have a interview quiz lately, and I really struggling here. There are few steps of question, but this final one is making me cracking my brain.

I created 4 set of function mainly is to randomize:
1. alphabet (object_one)
2. integer (object_two)
3. real number (object_three)
4. alphanumerical (object_four)

The final one is to create an random array based on my 4 set of object.
Eg: hisadfnnasd, 126263, assfdgsga12348fas, 13123.123,

lizierdjfklaasf, 123192u3kjwekhf, 89181811238,122,
nmarcysfa900jkifh  , 3.781, 2.11, ....

But this is my code for the final one:

function final_one(min,max,dec){
var obj = [object_one(min,max),object_two(min,max),object_three(min,max,dec),object_four(min,max)];
var output = "";
for (var i = 0; i < 10; i++) {
    output += obj[random(0,3)] + ", ";
}
return output;

}

my output will be something like this:

jkwnh1365624sp, 275995, jkwnh1365624sp, 43, jkwnh1365624sp, 275995, 275995, 43, 275995, 275995,

Data are keep repeating.

Please help!

Body:
when you create obj, you execute all 4 functions once:

var obj = [object_one(min,max),object_two(min,max),object_three(min,max,dec),object_four(min,max)];

object_one(min,max) is a function call.

This creates an array of 4 elements, somthing like this: ['v', 5, 3.14, 'x']
As @Dat pointed out, random(0,3) picks one of these elements.

What you are trying to do is to have an array of functions:

var obj = [object_one, object_two, object_three, object_four];

and have one of the functions randomly executed (like this):

obj[random(0,3)](min, max, dec);

some of the functions have no dec parameter but that is ok in javascript.

I hope I understood your requirements correctly.


问:
How to set Datepicker default index is string value
I want to show datepicker default index value is string but I am not able to do that. Please suggest any idea. Thanks in advance.

I want to show picker like this:

答:
You can use a UITextField and add date picker as a Input vie. And set PlaceHolder as "Date" or any string you want.

Sample Code

```<code>UITextField TextInput = new UITextField();
            TextInput.Frame = new CGRect(40, 280, View.Frame.Width - 80, 40);

            TextInput.Placeholder = "Date";

            var picker = new UIDatePicker();

            TextInput.InputView = picker;
</code>```

Body:
You can use a UITextField and add date picker as a Input vie. And set PlaceHolder as "Date" or any string you want.

Sample Code

UITextField TextInput = new UITextField();
            TextInput.Frame = new CGRect(40, 280, View.Frame.Width - 80, 40);

            TextInput.Placeholder = "Date";

            var picker = new UIDatePicker();

            TextInput.InputView = picker;


问:
Prestashop Upload Product Image - Unexpected token < in JSON at position 0
i'm trying made an upload image of an product. But when i'll click on the Submit button ("add archives") to send image, i receive this error on helper: Unexpected token < in JSON at position 0.

On the Chrome Networking tab, i receive this response of ajax call:

```<code>Column 'id_product' in where clause is ambiguous

        SELECT * FROM `ps_image` i INNER JOIN ps_image_shop image_shop
    ON (image_shop.id_image = i.id_image AND image_shop.id_shop = 1)
        WHERE `id_product` = 38
        AND image_shop.`cover`= 1 LIMIT 1
</code>```

I'm search for this a long time, but i don't have responses.

I'm using the 1.6.0.11 version of Prestashop.

答:
use this query , it will remove
Column 'id_product' in where clause is ambiguous
This error

```<code>SELECT * FROM `ps_image` i INNER JOIN ps_image_shop image_shop
    ON (image_shop.id_image = i.id_image AND image_shop.id_shop = 1)
        WHERE i.`id_product` = 38
        AND image_shop.`cover`= 1 LIMIT 1
</code>```

Body:
i'm trying made an upload image of an product. But when i'll click on the Submit button ("add archives") to send image, i receive this error on helper: Unexpected token < in JSON at position 0.

On the Chrome Networking tab, i receive this response of ajax call:

Column 'id_product' in where clause is ambiguous

        SELECT * FROM `ps_image` i INNER JOIN ps_image_shop image_shop
    ON (image_shop.id_image = i.id_image AND image_shop.id_shop = 1)
        WHERE `id_product` = 38
        AND image_shop.`cover`= 1 LIMIT 1

I'm search for this a long time, but i don't have responses.

I'm using the 1.6.0.11 version of Prestashop.

Body:
use this query , it will remove
Column 'id_product' in where clause is ambiguous
This error

SELECT * FROM `ps_image` i INNER JOIN ps_image_shop image_shop
    ON (image_shop.id_image = i.id_image AND image_shop.id_shop = 1)
        WHERE i.`id_product` = 38
        AND image_shop.`cover`= 1 LIMIT 1


问:
How can i get dynamic form field values in angular?
Below i have added dynamic form add and delete after submit i want to get all the form values .how can i do this ?? anyone help me out move forward

this is my jsfiddle link

http://jsfiddle.net/rnnb32rm/1438/

below i added my cod

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}];

  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };
  $scope.OnSave = function() {
    console.log('sjs');
  };

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;
}
input[type="text"],
select{
    padding:5px;
}</code>```

   <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />

    <button class="addfields" ng-click="addNewChoice()">Add fields</button>

    name
    <input type="text" ng-model="name" name="" placeholder="Add name">

    email
    <input type="text" ng-model="email" name="" placeholder="Add emalil">

    <fieldset data-ng-repeat="choice in choices">

        Add Question

        <input type="text" ng-model="choice.name" name="" placeholder="Add Question">

        Question order
        <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

        <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
    </fieldset>

    <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>

        {{ choices }}

```
</div>
</div>
</p>

<p>my expected result :</p>

```{

    "name": "test",
    "email": "asdf@gmail.com",
    "questions": [
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "1",

        },
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "2",

        }
    ]
}
```

答:
The function OnSave needs to be changed to this:

```<code>$scope.OnSave = function() {
  var result = {
    name: $scope.name,
    email: $scope.email,
    questions: $scope.choices.map(function(choice) {
      return { question: choice.name, questionorder: choice.order };
    })
  };

  console.log(result);
};
</code>```

The result will contain the desired results. Alternatively, you can change how your data is saved in the model. You can create one variable $scope.data as follows:

```<code>$scope.data = {
  name: '',
  email: '',
  questions: [
    {
      id: 'choice1'
    }
  ]
};
</code>```

And then bind your HTML to this. This way, you won't need to prepare your resultant data again at the time of saving. A working fiddle is here.

Body:
Below i have added dynamic form add and delete after submit i want to get all the form values .how can i do this ?? anyone help me out move forward

this is my jsfiddle link

http://jsfiddle.net/rnnb32rm/1438/

below i added my cod

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}];

  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };
  $scope.OnSave = function() {
    console.log('sjs');
  };

});

fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;
}
input[type="text"],
select{
    padding:5px;
}

   <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />

    <button class="addfields" ng-click="addNewChoice()">Add fields</button>

    name
    <input type="text" ng-model="name" name="" placeholder="Add name">

    email
    <input type="text" ng-model="email" name="" placeholder="Add emalil">

    <fieldset data-ng-repeat="choice in choices">

        Add Question

        <input type="text" ng-model="choice.name" name="" placeholder="Add Question">

        Question order
        <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

        <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
    </fieldset>

    <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>

        {{ choices }}

my expected result :

{

    "name": "test",
    "email": "asdf@gmail.com",
    "questions": [
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "1",

        },
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "2",

        }
    ]
}

Body:
The function OnSave needs to be changed to this:

$scope.OnSave = function() {
  var result = {
    name: $scope.name,
    email: $scope.email,
    questions: $scope.choices.map(function(choice) {
      return { question: choice.name, questionorder: choice.order };
    })
  };

  console.log(result);
};

The result will contain the desired results. Alternatively, you can change how your data is saved in the model. You can create one variable $scope.data as follows:

$scope.data = {
  name: '',
  email: '',
  questions: [
    {
      id: 'choice1'
    }
  ]
};

And then bind your HTML to this. This way, you won't need to prepare your resultant data again at the time of saving. A working fiddle is here.


答:
Try this.. run in your php enviroment</p>

```<code><html>
    <head>
         <style type="text/css">
           p
           {
              text-align: center;
              color: red;
           }
        </style>
    </head>
    <body>
    <?php
      $var = "Hello World";
      echo "<p>The value of the variable is : " . $var . "</p>";
    ?>
    </body>

</html>
</code>```

Title: echo HTML with php variable

Body:
Try this.. run in your php enviroment

<html>
    <head>
         <style type="text/css">
           p
           {
              text-align: center;
              color: red;
           }
        </style>
    </head>
    <body>
    <?php
      $var = "Hello World";
      echo "<p>The value of the variable is : " . $var . "</p>";
    ?>
    </body>

</html>


问:
What are the disadvantages of the Perl Tk module?
What are the disadvantages of the Tk module compared to other solutions to create a GUI in Perl?</p>

答:
Tk has not been developed in a very long time. ActiveState now recommends development with their Tkx toolkit, which provides a thin layer over TclTk. It means that themed widgets are possible. But, TclTk is still quite primitive compared with many other GUI toolkits.

I haven't tried XUL:Gui but it seems the way to go.


问:
PHPWORD - Insert image in front of text on every page of a docx file
Using PhpWord library, please tell me if it is possible to insert an image in front of text and on every page, in the same position, when creating a new docx file.</p>

答:
here is a simple example to illustrate what I meant with using global header to place an image in the top of every page (with single section containing a long table):</p>

```<code>$phpWord = new \PhpOffice\PhpWord\PhpWord();

$section = $phpWord->addSection();

$header = $section->addHeader();
$header->addImage('resources/PhpWord.png', array('width' => 80, 'height' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::START));

// generate long table just for demo that spans over multiple pages
$table = $section->addTable();
for ($i = 0; $i < 200; $i++) {
    $table->addRow();
    $table->addCell(4500)->addText('dummy');
    $table->addCell(4500)->addText("contents $i");
}
</code>```

Body:
here is a simple example to illustrate what I meant with using global header to place an image in the top of every page (with single section containing a long table):

$phpWord = new \PhpOffice\PhpWord\PhpWord();

$section = $phpWord->addSection();

$header = $section->addHeader();
$header->addImage('resources/PhpWord.png', array('width' => 80, 'height' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::START));

// generate long table just for demo that spans over multiple pages
$table = $section->addTable();
for ($i = 0; $i < 200; $i++) {
    $table->addRow();
    $table->addCell(4500)->addText('dummy');
    $table->addCell(4500)->addText("contents $i");
}


问:
Wants to fire an event after 10 days
Wants fire an event after 10 days, Let's say I have an expiry date to show image saved in my app folder. I am saving download time of asset and I want to check that time with 10 days after downloaded time. If that crosses 10 days that asset should remove automatically from app folder.

I know some of the options we have like:

1. GCD:

```<code>int parameter1 = 12;
float parameter2 = 144.1;

// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    NSLog(@"parameter1: %d parameter2: %f", parameter1, parameter2);
});
</code>```

2. Local Notifications/EventKit:

Note: it shouldn't throw any alert, It should delete asset in the background from app folder.

Is there any way to trigger the method with duration.

答:
I keep the date that the file was added on the device in NSUserDefaults.

Then when AppDelegate's application(_, didFinishLaunchingWithOptions:) would fire I would check if 10 days have passed from the last purge. If true I would purge again, if false I would not do anything.

Title: Wants to fire an event after 10 days

Body:
Wants fire an event after 10 days, Let's say I have an expiry date to show image saved in my app folder. I am saving download time of asset and I want to check that time with 10 days after downloaded time. If that crosses 10 days that asset should remove automatically from app folder.

I know some of the options we have like:

1. GCD:

int parameter1 = 12;
float parameter2 = 144.1;

// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    NSLog(@"parameter1: %d parameter2: %f", parameter1, parameter2);
});

2. Local Notifications/EventKit:

Note: it shouldn't throw any alert, It should delete asset in the background from app folder.

Is there any way to trigger the method with duration.


问:
How to add local jar files to a Maven project?
How do I add local jar files (not yet part of the Maven repository) directly in my project's library sources?</p>

答:
Add your own local JAR in POM file and use that in maven build.

```<code>mvn install:install-file -Dfile=path-to-jar -DgroupId=owngroupid -DartifactId=ownartifactid -Dversion=ownversion -Dpackaging=jar
</code>```

For example:

```<code>mvn install:install-file -Dfile=path-to-jar -DgroupId=com.decompiler -DartifactId=jd-core-java -Dversion=1.2 -Dpackaging=jar
</code>```

Then add it to the POM like this:

Body:
Add your own local JAR in POM file and use that in maven build.

mvn install:install-file -Dfile=path-to-jar -DgroupId=owngroupid -DartifactId=ownartifactid -Dversion=ownversion -Dpackaging=jar

For example:

mvn install:install-file -Dfile=path-to-jar -DgroupId=com.decompiler -DartifactId=jd-core-java -Dversion=1.2 -Dpackaging=jar

Then add it to the POM like this:


问:
Textbox enabling
How to set certain textbox mandatory when a radio button is clicked in mvc?

```<code><body>
    <div class="form-group">
        <form action="~/Main/Screen" method="post">
            <div class="panel panel-primary">
                <div class="panel-heading">TEST ORDER FOR PATIENT</div>
                <div class="panel-body">

                    <h3><label class="control-label">PATIENT CODE<span class="inp">*</span></label></h3><input type="text" id="InputPatientCode" name="InputPatientCode" value="" style="height:30px;" /><br />

                    <h3><label class="control-label">VISIT NO<span class="inp">*</span></label></h3><input type="text" id="VisitNo" name="VisitNo" value="" style="height:30px;" /><br />

                    <br />
                    <button class="btn btn-primary" id="add" type="submit" onclick="return IsValid()";>ADD</button>
<input type="radio"/>enable
                </div>
            </div>
            </form>
</code>```

答:
Here are the steps

Have ids for your text boxes and radio buttons.

Add an onClick javascript function for the radio button that you are concerned about.

Within that javascript function, look up for the text box that you are interested in, and set it's required attribute (<input type="text" id="someId" required />)

Title: Textbox enabling

Body:
How to set certain textbox mandatory when a radio button is clicked in mvc?

        <form action="~/Main/Screen" method="post">

TEST ORDER FOR PATIENT

PATIENT CODE*
<input type="text" id="InputPatientCode" name="InputPatientCode" value="" style="height:30px;" />

VISIT NO*
<input type="text" id="VisitNo" name="VisitNo" value="" style="height:30px;" />

                    <button class="btn btn-primary" id="add" type="submit" onclick="return IsValid()";>ADD</button>
<input type="radio"/>enable

            </form>


问:
CakePhp Error: Call to a member function create() on a non-object
I am currently learning how to use CakePhp.

I have created a function in my custom controller as follows:

```<code>class FormatsController extends AppController
{
    // ....

    function admin_add()
    {

        // if the form data is not empty
        if (!empty($this->data)) {
            // initialise the format model
            $this->Format->create();
            // create the slug
            $this->data['Format']['slug'] = $this->slug($this->data['Format']['name']);
            // try saving the format
            if ($this->Format->save($this->data)) {
                // set a flash message
                $this->Session->setFlash('The Format has been saved', 'flash_good');
                // redirect
                $this->redirect(array('action' => 'index'));
            } else {
                // set a flash message
                $this->Session->setFlash('The Format could not be saved. Please, try again.', 'flash_bad');
            }
        }
    }

}
</code>```

However in my view I am getting this error:

Error: Call to a member function create() on a non-object

Why is this error caused and how can I fix it?

My apologies, I believe the line it is referencing is not in the Controller but in my view itself. It refers to my view which has the following line:

```<code><?php echo $form->create('Format');?>
</code>```

Is there something else I need to declare before using this? i.e. $this->Format->create();

答:
Try </p>

```<code>$this->Form->create(null,['url' => ['controller' => 'yourController', 'action' => 'yourAction']])
</code>```

Body:
I am currently learning how to use CakePhp.

I have created a function in my custom controller as follows:

class FormatsController extends AppController
{
    // ....

    function admin_add()
    {

        // if the form data is not empty
        if (!empty($this->data)) {
            // initialise the format model
            $this->Format->create();
            // create the slug
            $this->data['Format']['slug'] = $this->slug($this->data['Format']['name']);
            // try saving the format
            if ($this->Format->save($this->data)) {
                // set a flash message
                $this->Session->setFlash('The Format has been saved', 'flash_good');
                // redirect
                $this->redirect(array('action' => 'index'));
            } else {
                // set a flash message
                $this->Session->setFlash('The Format could not be saved. Please, try again.', 'flash_bad');
            }
        }
    }

}

However in my view I am getting this error:

Error: Call to a member function create() on a non-object

Why is this error caused and how can I fix it?

My apologies, I believe the line it is referencing is not in the Controller but in my view itself. It refers to my view which has the following line:

<?php echo $form->create('Format');?>

Is there something else I need to declare before using this? i.e. $this->Format->create();

Body:
Try

$this->Form->create(null,['url' => ['controller' => 'yourController', 'action' => 'yourAction']])


问:
MySQL SELECT multiple tables at once

If I need all rows from multiple completely unrelated tables, is it more efficient to run a single SELECT query?

So the result returned could be like:

```<code>[{ table: "table1", id: 1 },
 { table: "table1", id: 2 },
 { table: "table2", code: 1 }]
</code>```

Or would it be just as efficient as running separate SELECT query for each of the table?

答:
```<code>Select column1,column2
from table1,table2
where table1.id = table2.id
</code>```

It's better to have a single query to retrieve the data. Also, you can use joins for retrieving data from two tables.

Title: MySQL SELECT multiple tables at once

Body:
If I need all rows from multiple completely unrelated tables, is it more efficient to run a single SELECT query?

So the result returned could be like:

[{ table: "table1", id: 1 },
 { table: "table1", id: 2 },
 { table: "table2", code: 1 }]

Or would it be just as efficient as running separate SELECT query for each of the table?

Body:
Select column1,column2
from table1,table2
where table1.id = table2.id

It's better to have a single query to retrieve the data. Also, you can use joins for retrieving data from two tables.


问:
Creating a fancy search bar with Swing components
I'm trying to come up with an elegant recreation of the search bar component in Thunderbird. The clear button doesn't appear until there is text in the box, so that screen-shot is a bit inaccurate.

Should I use a layered pane and get some buttons to float above the box? (but then getting the text to not appear below the buttons would be hacky)

Maybe just put buttons at the ends of the search bar and have it somehow blend in?

Any ideas or maybe a style reconsideration is welcome, thank you.

答: You might be able to use the Text Prompt for the "Search all text" display.</p>


问:
How to turn bring columns in rows using sql query?
I have the following result which i have got after using this query :

```<code>select SCHOOL_YEAR,COUNT(MUSIC) as ct,MUSIC from [table1]
group by SCHOOL_YEAR,MUSIC;

SCHOOL_YEAR   ct      MUSIC

2011          100     Piano
2011          50      Violin
2012          70      Piano
2012          150     Violin
</code>```

I want it in the following format :

```<code>SCHOOL_YEAR   Piano     Violin

2011           100        50
2012           70         150
</code>```

How can i achieve it ?

答:
Use a pivot query on the original table, but aggregate only on the school year:</p>

```<code>SELECT
    SCHOOL_YEAR,
    SUM(CASE WHEN MUSIC = 'Piano'  THEN 1 ELSE 0 END) AS Piano,
    SUM(CASE WHEN MUSIC = 'Violin' THEN 1 ELSE 0 END) AS Violin
FROM table1
GROUP BY
    SCHOOL_YEAR
</code>```

Body:
I have the following result which i have got after using this query :

select SCHOOL_YEAR,COUNT(MUSIC) as ct,MUSIC from [table1]
group by SCHOOL_YEAR,MUSIC;

SCHOOL_YEAR   ct      MUSIC

2011          100     Piano
2011          50      Violin
2012          70      Piano
2012          150     Violin

I want it in the following format :

SCHOOL_YEAR   Piano     Violin

2011           100        50
2012           70         150

How can i achieve it ?

Body:
Use a pivot query on the original table, but aggregate only on the school year:

SELECT
    SCHOOL_YEAR,
    SUM(CASE WHEN MUSIC = 'Piano'  THEN 1 ELSE 0 END) AS Piano,
    SUM(CASE WHEN MUSIC = 'Violin' THEN 1 ELSE 0 END) AS Violin
FROM table1
GROUP BY
    SCHOOL_YEAR


问:
Object is identified only if it is visible with eye on browser window - UFT
We are automating a web application using UFT/QTP. The issue is that UFT works only on those web objects which are seen in browser window part. If any object/element is at the bottom of the page and require scroll down in window to be seen. UFT is not able to work on those objects. We have written code to  page down to work on those objects. It works fine. But sometimes when page is very lengthy and we don't know at what position that object will be like in middle of the page, or far bottom of the page etc. In that case, only page down does not work. Is there any way that we can make the object visible on the basis of object properties? That means we can bring object in front of the window.</p>

答:
I had once faced a similar issue. For me, changing the Replaytype setting to mouse events worked.
Try changing the ReplayType to Mouse events just before performing any operation(say clicking the object) as shown below:

```<code>Settings.WebPackage("ReplayType") = 2    'Changes to mouse/device events mode
'Perform the Click Operation here
Settings.WebPackage("ReplayType") = 1     'Change back to Browser events mode
</code>```

Additional information on ReplayType:

This setting allows us to change the way mouse operations should
  happen on AUT. It can be either browser events or mouse event.
  Browser event is similar to DOM events using the Browser methods,
  wheras Mouse event simulate the actual user action either from
  keyboard or mouse. For example if you click on a button when
  ReplayType is Mouse, you will notice that mouse pointer moves to the
  location of button and fires the event, but in case of browser event it
  doesn’t.

Values of replaytype can be:

1 – Event

2 – Mouse

By default it is set to Event i.e 1

Body:
I had once faced a similar issue. For me, changing the Replaytype setting to mouse events worked.
Try changing the ReplayType to Mouse events just before performing any operation(say clicking the object) as shown below:

Settings.WebPackage("ReplayType") = 2    'Changes to mouse/device events mode
'Perform the Click Operation here
Settings.WebPackage("ReplayType") = 1     'Change back to Browser events mode

Additional information on ReplayType:

This setting allows us to change the way mouse operations should
  happen on AUT. It can be either browser events or mouse event.
  Browser event is similar to DOM events using the Browser methods,
  wheras Mouse event simulate the actual user action either from
  keyboard or mouse. For example if you click on a button when
  ReplayType is Mouse, you will notice that mouse pointer moves to the
  location of button and fires the event, but in case of browser event it
  doesn’t.

Values of replaytype can be:

1 – Event

2 – Mouse

By default it is set to Event i.e 1


问:
React Native BUILD SUCCEED, but "No devices are booted."
Here's my environment:

```
➜  AwesomeProject node --version
v6.3.0
➜  AwesomeProject npm --version
3.10.3
➜  AwesomeProject react-native --version
react-native-cli: 1.0.0
react-native: 0.29.0
➜  AwesomeProject watchman --version
3.0.0
```

Xcode version 7.3.1

I created the AwesomeProject described on: https://facebook.github.io/react-native/docs/getting-started.html#content

Then execute: sudo react-native run-ios

Here's what I'm getting:

```
...
    export SYSTEM_DEVELOPER_USR_DIR=/Applications/Xcode.app/Contents/Developer/usr
    export SYSTEM_DEVELOPER_UTILITIES_DIR=/Applications/Xcode.app/Contents/Developer/Applications/Utilities
    export SYSTEM_DOCUMENTATION_DIR=/Library/Documentation
    export SYSTEM_KEXT_INSTALL_PATH=/System/Library/Extensions
    export SYSTEM_LIBRARY_DIR=/System/Library
    export TAPI_VERIFY_MODE=ErrorsOnly
    export TARGETED_DEVICE_FAMILY=1
    export TARGETNAME=AwesomeProject
    export TARGET_BUILD_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Products/Debug-iphonesimulator
    export TARGET_DEVICE_MODEL=iPhone7,2
    export TARGET_DEVICE_OS_VERSION=9.3
    export TARGET_NAME=AwesomeProject
    export TARGET_TEMP_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
    export TEMP_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
    export TEMP_FILES_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
    export TEMP_FILE_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
    export TEMP_ROOT=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates
    export TOOLCHAINS=com.apple.dt.toolchain.XcodeDefault
    export TOOLCHAIN_DIR=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
    export TREAT_MISSING_BASELINES_AS_TEST_FAILURES=NO
    export UID=0
    export UNLOCALIZED_RESOURCES_FOLDER_PATH=AwesomeProject.app
    export UNSTRIPPED_PRODUCT=NO
    export USER=root
    export USER_APPS_DIR=/var/root/Applications
    export USER_LIBRARY_DIR=/var/root/Library
    export USE_DYNAMIC_NO_PIC=YES
    export USE_HEADERMAP=YES
    export USE_HEADER_SYMLINKS=NO
    export VALIDATE_PRODUCT=NO
    export VALID_ARCHS="i386 x86_64"
    export VERBOSE_PBXCP=NO
    export VERSIONPLIST_PATH=AwesomeProject.app/version.plist
    export VERSION_INFO_BUILDER=root
    export VERSION_INFO_FILE=AwesomeProject_vers.c
    export VERSION_INFO_STRING="\"@(#)PROGRAM:AwesomeProject  PROJECT:AwesomeProject-\""
    export WRAPPER_EXTENSION=app
    export WRAPPER_NAME=AwesomeProject.app
    export WRAPPER_SUFFIX=.app
    export WRAP_ASSET_PACKS_IN_SEPARATE_DIRECTORIES=NO
    export XCODE_APP_SUPPORT_DIR=/Applications/Xcode.app/Contents/Developer/Library/Xcode
    export XCODE_PRODUCT_BUILD_VERSION=7D1014
    export XCODE_VERSION_ACTUAL=0731
    export XCODE_VERSION_MAJOR=0700
    export XCODE_VERSION_MINOR=0730
    export XPCSERVICES_FOLDER_PATH=AwesomeProject.app/XPCServices
    export YACC=yacc
    export arch=x86_64
    export diagnostic_message_length=124
    export variant=normal
    /bin/sh -c /Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build/Script-00DD1BFF1BD5951E006B06BC.sh
Skipping bundling for Simulator platform

=== BUILD TARGET AwesomeProjectTests OF PROJECT AwesomeProject WITH CONFIGURATION Debug ===

Check dependencies

** BUILD SUCCEEDED **

Installing build/Build/Products/Debug-iphonesimulator/AwesomeProject.app
No devices are booted.
Launching org.reactjs.native.example.AwesomeProject
No devices are booted.
```

And the iOS iPhone 6 simulator is just showing a black screen.

Ideas?

答: Ran into the same problem. Hardware > Restart fixed it.

Body:
Here's my environment:

➜  AwesomeProject node --version
v6.3.0
➜  AwesomeProject npm --version
3.10.3
➜  AwesomeProject react-native --version
react-native-cli: 1.0.0
react-native: 0.29.0
➜  AwesomeProject watchman --version
3.0.0

Xcode version 7.3.1

I created the AwesomeProject described on: https://facebook.github.io/react-native/docs/getting-started.html#content

Then execute: sudo react-native run-ios

Here's what I'm getting:

...
    export SYSTEM_DEVELOPER_USR_DIR=/Applications/Xcode.app/Contents/Developer/usr
    export SYSTEM_DEVELOPER_UTILITIES_DIR=/Applications/Xcode.app/Contents/Developer/Applications/Utilities
    export SYSTEM_DOCUMENTATION_DIR=/Library/Documentation
    export SYSTEM_KEXT_INSTALL_PATH=/System/Library/Extensions
    export SYSTEM_LIBRARY_DIR=/System/Library
    export TAPI_VERIFY_MODE=ErrorsOnly
    export TARGETED_DEVICE_FAMILY=1
    export TARGETNAME=AwesomeProject
    export TARGET_BUILD_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Products/Debug-iphonesimulator
    export TARGET_DEVICE_MODEL=iPhone7,2
    export TARGET_DEVICE_OS_VERSION=9.3
    export TARGET_NAME=AwesomeProject
    export TARGET_TEMP_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
    export TEMP_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
    export TEMP_FILES_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
    export TEMP_FILE_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
    export TEMP_ROOT=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates
    export TOOLCHAINS=com.apple.dt.toolchain.XcodeDefault
    export TOOLCHAIN_DIR=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
    export TREAT_MISSING_BASELINES_AS_TEST_FAILURES=NO
    export UID=0
    export UNLOCALIZED_RESOURCES_FOLDER_PATH=AwesomeProject.app
    export UNSTRIPPED_PRODUCT=NO
    export USER=root
    export USER_APPS_DIR=/var/root/Applications
    export USER_LIBRARY_DIR=/var/root/Library
    export USE_DYNAMIC_NO_PIC=YES
    export USE_HEADERMAP=YES
    export USE_HEADER_SYMLINKS=NO
    export VALIDATE_PRODUCT=NO
    export VALID_ARCHS="i386 x86_64"
    export VERBOSE_PBXCP=NO
    export VERSIONPLIST_PATH=AwesomeProject.app/version.plist
    export VERSION_INFO_BUILDER=root
    export VERSION_INFO_FILE=AwesomeProject_vers.c
    export VERSION_INFO_STRING="\"@(#)PROGRAM:AwesomeProject  PROJECT:AwesomeProject-\""
    export WRAPPER_EXTENSION=app
    export WRAPPER_NAME=AwesomeProject.app
    export WRAPPER_SUFFIX=.app
    export WRAP_ASSET_PACKS_IN_SEPARATE_DIRECTORIES=NO
    export XCODE_APP_SUPPORT_DIR=/Applications/Xcode.app/Contents/Developer/Library/Xcode
    export XCODE_PRODUCT_BUILD_VERSION=7D1014
    export XCODE_VERSION_ACTUAL=0731
    export XCODE_VERSION_MAJOR=0700
    export XCODE_VERSION_MINOR=0730
    export XPCSERVICES_FOLDER_PATH=AwesomeProject.app/XPCServices
    export YACC=yacc
    export arch=x86_64
    export diagnostic_message_length=124
    export variant=normal
    /bin/sh -c /Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build/Script-00DD1BFF1BD5951E006B06BC.sh
Skipping bundling for Simulator platform

=== BUILD TARGET AwesomeProjectTests OF PROJECT AwesomeProject WITH CONFIGURATION Debug ===

Check dependencies

** BUILD SUCCEEDED **

Installing build/Build/Products/Debug-iphonesimulator/AwesomeProject.app
No devices are booted.
Launching org.reactjs.native.example.AwesomeProject
No devices are booted.

And the iOS iPhone 6 simulator is just showing a black screen.

Ideas?


问:
Is it possible to git stash an interactive rebase in progress?
I am currently rebasing origin/master onto a branch that was created from origin/master a while ago and the developer that worked on the branch is not available right now.

I have resolved some conflicts on the first commits of the feature branch but come to a point where I must wait for the developer to know how to finalize the rebase.

Is there a way to keep the conflict resolution I already did (~30 minutes) so that I can move on to another task?

答: Or another idea is to commit and make a branch mid-rebase, then git cherry-pick remaining the un-rebased commits onto it later. </p>


问:
Angular 2. CanActivate is called on load only
I have the following routing that I import to Application Component:

```<code>const routes: Routes = [
  {
    path: '',
    component: MainLayoutComponent,
    children: [
      {
        path: '', redirectTo: 'main', pathMatch: 'full'
      },
      {
        path: 'main', loadChildren: 'app/main/main.module#MaindModule'
      },
      {
        path: 'cars', loadChildren: 'app/cars/cars.module#CarsModule'
      }
    ],
    canActivate: [AuthGuard]
  },
  {
    path: 'auth',
    component: EmptyLayoutComponent,
    loadChildren: 'app/auth/auth.module#AuthModule'
  },
  {
    path: '**',
    redirectTo: 'main'
  }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

As you can see I have canActivate. I noticed that AuthGuard is called when I open application in first time or write address in the browser, but if I use my menu to change url then AuthGuard is not called:

```<code> <a routerLink="/cars">
</code>```

What I have done wrong?

AuthGuard:

```<code>@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService,
              private router: Router) {}

  canActivate() {
    if (!this.authService.authenticated) {
      this.router.navigate(['/auth/login']);
      return false;
    }
    return true;
  }
}
</code>```

答: It appears that CanActivate is only set on the parent empty route. If you want it to execute again when navigating between child routes, consider using canActivateChild instead.

Body:
I have the following routing that I import to Application Component:

const routes: Routes = [
  {
    path: '',
    component: MainLayoutComponent,
    children: [
      {
        path: '', redirectTo: 'main', pathMatch: 'full'
      },
      {
        path: 'main', loadChildren: 'app/main/main.module#MaindModule'
      },
      {
        path: 'cars', loadChildren: 'app/cars/cars.module#CarsModule'
      }
    ],
    canActivate: [AuthGuard]
  },
  {
    path: 'auth',
    component: EmptyLayoutComponent,
    loadChildren: 'app/auth/auth.module#AuthModule'
  },
  {
    path: '**',
    redirectTo: 'main'
  }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

As you can see I have canActivate. I noticed that AuthGuard is called when I open application in first time or write address in the browser, but if I use my menu to change url then AuthGuard is not called:

What I have done wrong?

AuthGuard:

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService,
              private router: Router) {}

  canActivate() {
    if (!this.authService.authenticated) {
      this.router.navigate(['/auth/login']);
      return false;
    }
    return true;
  }
}


问:
Fetch data in ComponentDidMount not working
I am trying to fetch data, set state and change route in componentDidMount, but it can not be done(only after clicking on the screen ). I guess there something has to do with asynchronous nature of fetch but how can it be fixed?

```<code>componentDidMount(){

AsyncStorage.multiGet([USER_TOKEN, USER_REFRESH_TOKEN,USER_REMEMBERED]).then((data) => {
  const userRemembered = JSON.parse(data[2][1])
  const userAccessToken = data[0][1]
  const userRefreshToken = data[1][1]

  if (userRemembered) {
    fetch("SOME_URL", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        refreshToken: userRefreshToken
      })
    })
    .then(response => response.json())
    .then(responseData => {
      console.log(responseData); // only after clicking on the screen it is logged
      if (responseData.success) {
        AsyncStorage.multiSet([[USER_TOKEN,responseData.response.accessToken],[USER_REFRESH_TOKEN,responseData.response.refreshToken],[USER_REMEMBERED,JSON.stringify(true)]])
        this.setState({
          token:responseData.response.accessToken,
          refreshToken: responseData.response.refreshToken,
          isLoggedIn: true
        }) //only after clicking on the screen state is changed
        this.changeRoute(this.state) //only after clicking on the clicking on the screen route is changed
      }
      else {
        console.log("API is not responding");
      }
    })
    .catch((error) => {
      console.log(error)
    })
  }
  else{
    console.log('user has not checked Remember Me');
  }
})
</code>```

}

答: I finally figured it out. I had Remote JS Debugging turned on and it was messing things up. I turned it off and everything works fine.

Body:
I am trying to fetch data, set state and change route in componentDidMount, but it can not be done(only after clicking on the screen ). I guess there something has to do with asynchronous nature of fetch but how can it be fixed?

componentDidMount(){

AsyncStorage.multiGet([USER_TOKEN, USER_REFRESH_TOKEN,USER_REMEMBERED]).then((data) => {
  const userRemembered = JSON.parse(data[2][1])
  const userAccessToken = data[0][1]
  const userRefreshToken = data[1][1]

  if (userRemembered) {
    fetch("SOME_URL", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        refreshToken: userRefreshToken
      })
    })
    .then(response => response.json())
    .then(responseData => {
      console.log(responseData); // only after clicking on the screen it is logged
      if (responseData.success) {
        AsyncStorage.multiSet([[USER_TOKEN,responseData.response.accessToken],[USER_REFRESH_TOKEN,responseData.response.refreshToken],[USER_REMEMBERED,JSON.stringify(true)]])
        this.setState({
          token:responseData.response.accessToken,
          refreshToken: responseData.response.refreshToken,
          isLoggedIn: true
        }) //only after clicking on the screen state is changed
        this.changeRoute(this.state) //only after clicking on the clicking on the screen route is changed
      }
      else {
        console.log("API is not responding");
      }
    })
    .catch((error) => {
      console.log(error)
    })
  }
  else{
    console.log('user has not checked Remember Me');
  }
})

}


问:
Build and reuse android open source Dialer source code in my project
I have to integrate android opensource Dialer source code into my application and also need to do customizations on the same.

Currently I cloned the Dialer source code from https://android.googlesource.com/platform/packages/apps/Dialer/

It doesn't seems to be a gradle project. How can I build this project ?

I need to add this entire project as reusable module in my project. Could you please help me on this. How can I start with this ?

This Answer seems very informative https://stackoverflow.com/a/8668334/3020568 but I need to get some more help from guys those who tried to build this type of applications.

WE tried below steps.

Checked out source code from google source.

Tried to import the project in Android Studio.

It has dependencies outside the project which are not able to resolve. - Some classes and methods has no reference inside the source code.

Thanks in advance.

答:
I know this is old but this is for future reference.

You cannot build the Dialer application without access to the rest of the source code. You need to first download the whole Android source (AOSP) and then build it because the Dialer application that comes with AOSP requires some framework files which is included in AOSP; hence the Dialer code may not actually work on all devices. Your best bet is using a tutorial to build a dialer application from scratch.


问:
Difference between pip3 and `python3 setup.py install` regarding cmdclass argument
I tried to configure my package such that a script is executed on the installation process. Therefore, I inherited from setuptools.command install and created my custom class ActionOnInstall to do stuff when package is installed. This class is called via setuptools setup() argument cmdclass as described here.

A minimal example of such a setup.py file looks like

```<code>from setuptools import find_packages, setup
from setuptools.command.install import install

class ActionOnInstall(install):
    def run(self):
        print("Call install.run(self) works!")
        install.run(self)

setup(name='name',
      cmdclass={
      'install': ActionOnInstall})
</code>```

Building the package by executing

```<code>pip3 install <path-to-dir-with-setup.py>
</code>```

runs successfully but does not execute commands specified in ActionOnInstall.run(). More directly calling this setup.py by

```<code>python3 setup.py install
</code>```

executes commands specified in ActionOnInstall.run().

Then, I found myself asking: what is the actual difference of these both approaches to install a package. I know, like other posts tell us, pip makes life easier regarding package installation. But how these both approaches treat the cmdclass argument of setup() differently is not explained. Thus, I would highly appreciate to hear from you guys.

答:
pip does run python setup.py install when installing your package - it does not change the way your setup.py feel is executed.

The reason you don't see any output is, as @phd mentioned, that pip by default hides all the output from running the setup.py file since most of the information printed when running python setup.py install is not useful to most users.

You can see this hidden output, along with everything else pip does, by passing the "--verbose" option to pip install:

```<code>$ pip install --verbose ./foo
Processing ./foo
Running setup.py (path:/private/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-ti0o0gtu-build/setup.py) egg_info for package from file:///Users/pradyunsg/.venvwrap/venvs/t
mp-c0ebb35987c76ad/foo
    Running command python setup.py egg_info
    running egg_info
    creating pip-egg-info/foo.egg-info
    writing pip-egg-info/foo.egg-info/PKG-INFO
    writing dependency_links to pip-egg-info/foo.egg-info/dependency_links.txt
    writing top-level names to pip-egg-info/foo.egg-info/top_level.txt
    writing manifest file 'pip-egg-info/foo.egg-info/SOURCES.txt'
    reading manifest file 'pip-egg-info/foo.egg-info/SOURCES.txt'
    writing manifest file 'pip-egg-info/foo.egg-info/SOURCES.txt'
Source in /private/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-ti0o0gtu-build has version 0.0.0, which satisfies requirement foo==0.0.0 from file:///Users/pradyunsg/.ve
nvwrap/venvs/tmp-c0ebb35987c76ad/foo
Could not parse version from link: file:///Users/pradyunsg/.venvwrap/venvs/tmp-c0ebb35987c76ad/foo
Installing collected packages: foo
Running setup.py install for foo ...     Running command /Users/pradyunsg/.venvwrap/venvs/tmp-c0ebb35987c76ad/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/privat
e/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-ti0o0gtu-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(comp
ile(code, __file__, 'exec'))" install --record /var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-cetn8xa9-record/install-record.txt --single-version-externally-managed --compi
le --install-headers /Users/pradyunsg/.venvwrap/venvs/tmp-c0ebb35987c76ad/bin/../include/site/python3.6/foo
    running install
    Call install.run(self) works!
    running build
    running install_egg_info
    running egg_info
    creating foo.egg-info
    writing foo.egg-info/PKG-INFO
    writing dependency_links to foo.egg-info/dependency_links.txt
    writing top-level names to foo.egg-info/top_level.txt
    writing manifest file 'foo.egg-info/SOURCES.txt'
    reading manifest file 'foo.egg-info/SOURCES.txt'
    writing manifest file 'foo.egg-info/SOURCES.txt'
    Copying foo.egg-info to /Users/pradyunsg/.venvwrap/venvs/tmp-c0ebb35987c76ad/lib/python3.6/site-packages/foo-0.0.0-py3.6.egg-info
    running install_scripts
    writing list of installed files to '/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-cetn8xa9-record/install-record.txt'
done
Removing source in /private/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-ti0o0gtu-build
Successfully installed foo-0.0.0
Cleaning up...
</code>```

Body:
I tried to configure my package such that a script is executed on the installation process. Therefore, I inherited from setuptools.command install and created my custom class ActionOnInstall to do stuff when package is installed. This class is called via setuptools setup() argument cmdclass as described here.

A minimal example of such a setup.py file looks like

from setuptools import find_packages, setup
from setuptools.command.install import install

class ActionOnInstall(install):
    def run(self):
        print("Call install.run(self) works!")
        install.run(self)

setup(name='name',
      cmdclass={
      'install': ActionOnInstall})

Building the package by executing

pip3 install <path-to-dir-with-setup.py>

runs successfully but does not execute commands specified in ActionOnInstall.run(). More directly calling this setup.py by

python3 setup.py install

executes commands specified in ActionOnInstall.run().

Then, I found myself asking: what is the actual difference of these both approaches to install a package. I know, like other posts tell us, pip makes life easier regarding package installation. But how these both approaches treat the cmdclass argument of setup() differently is not explained. Thus, I would highly appreciate to hear from you guys.

Body:
pip does run python setup.py install when installing your package - it does not change the way your setup.py feel is executed.

The reason you don't see any output is, as @phd mentioned, that pip by default hides all the output from running the setup.py file since most of the information printed when running python setup.py install is not useful to most users.

You can see this hidden output, along with everything else pip does, by passing the "--verbose" option to pip install:

$ pip install --verbose ./foo
Processing ./foo
Running setup.py (path:/private/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-ti0o0gtu-build/setup.py) egg_info for package from file:///Users/pradyunsg/.venvwrap/venvs/t
mp-c0ebb35987c76ad/foo
    Running command python setup.py egg_info
    running egg_info
    creating pip-egg-info/foo.egg-info
    writing pip-egg-info/foo.egg-info/PKG-INFO
    writing dependency_links to pip-egg-info/foo.egg-info/dependency_links.txt
    writing top-level names to pip-egg-info/foo.egg-info/top_level.txt
    writing manifest file 'pip-egg-info/foo.egg-info/SOURCES.txt'
    reading manifest file 'pip-egg-info/foo.egg-info/SOURCES.txt'
    writing manifest file 'pip-egg-info/foo.egg-info/SOURCES.txt'
Source in /private/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-ti0o0gtu-build has version 0.0.0, which satisfies requirement foo==0.0.0 from file:///Users/pradyunsg/.ve
nvwrap/venvs/tmp-c0ebb35987c76ad/foo
Could not parse version from link: file:///Users/pradyunsg/.venvwrap/venvs/tmp-c0ebb35987c76ad/foo
Installing collected packages: foo
Running setup.py install for foo ...     Running command /Users/pradyunsg/.venvwrap/venvs/tmp-c0ebb35987c76ad/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/privat
e/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-ti0o0gtu-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(comp
ile(code, __file__, 'exec'))" install --record /var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-cetn8xa9-record/install-record.txt --single-version-externally-managed --compi
le --install-headers /Users/pradyunsg/.venvwrap/venvs/tmp-c0ebb35987c76ad/bin/../include/site/python3.6/foo
    running install
    Call install.run(self) works!
    running build
    running install_egg_info
    running egg_info
    creating foo.egg-info
    writing foo.egg-info/PKG-INFO
    writing dependency_links to foo.egg-info/dependency_links.txt
    writing top-level names to foo.egg-info/top_level.txt
    writing manifest file 'foo.egg-info/SOURCES.txt'
    reading manifest file 'foo.egg-info/SOURCES.txt'
    writing manifest file 'foo.egg-info/SOURCES.txt'
    Copying foo.egg-info to /Users/pradyunsg/.venvwrap/venvs/tmp-c0ebb35987c76ad/lib/python3.6/site-packages/foo-0.0.0-py3.6.egg-info
    running install_scripts
    writing list of installed files to '/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-cetn8xa9-record/install-record.txt'
done
Removing source in /private/var/folders/4d/bt0_xfx56bjfmmt2bv3r5_qh0000gn/T/pip-ti0o0gtu-build
Successfully installed foo-0.0.0
Cleaning up...