问:
not able to bind using ldap_bind through PHP
I am able to connect to LDAP through unix but when I try to do the same through PHP am not able to. Below is the code,

```<code>$server ='server';
$port = 3060;
$ldapconn = ldap_connect($server, $port) or die("Could not connect " .
$server . ":" . $port . ".");
$user = "cn=orcladmin";
$password ='password';
$ldapbind = ldap_bind($ldapconn,$user,$password) ;
if(!$ldapbind)
{
  echo ldap_error($ldapconn);  #I get error invalid credentials
}
</code>```

I am able to connect and also bind anonymously but in that case ldap_search does not work which is my final requirement. using the same credentials i.e cn=orcladmin and 'password' I am able to connect to ODSM.
Also Ihave tested the connection using below on unix,

```<code>ldapbind -h 'server' -p 3060 -D "cn=orcladmin" -w 'password'
</code>```

it gives below message:

```<code>bind successful
</code>```

Is user specified differently while connecting through PHP?
Could someone please help?

答: the issue was with ORACLE_HOME, not sure how to set it in PHP but I wrote a shell script where ORACLE_HOME was set and able to successfully run ldapbind and ldapsearch.</p>

Body:
I am able to connect to LDAP through unix but when I try to do the same through PHP am not able to. Below is the code,

$server ='server';
$port = 3060;
$ldapconn = ldap_connect($server, $port) or die("Could not connect " .
$server . ":" . $port . ".");
$user = "cn=orcladmin";
$password ='password';
$ldapbind = ldap_bind($ldapconn,$user,$password) ;
if(!$ldapbind)
{
  echo ldap_error($ldapconn);  #I get error invalid credentials
}

I am able to connect and also bind anonymously but in that case ldap_search does not work which is my final requirement. using the same credentials i.e cn=orcladmin and 'password' I am able to connect to ODSM.
Also Ihave tested the connection using below on unix,

ldapbind -h 'server' -p 3060 -D "cn=orcladmin" -w 'password'

it gives below message:

bind successful

Is user specified differently while connecting through PHP?
Could someone please help?


来源: stackexchange

问:
Dynamically re-route all Zuul proxied requests to single URL
I'm trying to forward all requests to my API to a single endpoint based upon some condition.

The Gateway app runs on port 8080

I've created the following filter:

```<code>public class OutagePeriodFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "route";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return isOutagePeriod();
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        // if outage - redirect everyone to http://localhost:8082/outage
        try {
            String url = UriComponentsBuilder.fromHttpUrl("http://localhost:8082").path("/outage").build()
                                     .toUriString();
            ctx.setRouteHost(new URL(url));
        } catch(MalformedURLException mue) {
            log.error("Cannot forward to outage period website");
        }
        return null;
    }

    private boolean isOutagePeriod() {
        // returns true if outage
    }
}
</code>```

However after making a request to http://localhost:8080/alerts/public my API logs show:

```<code>2017-03-03 16:11:30.735 EST 0037 DEBUG                    o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/outage/alerts/public'; against '/beans/'
</code>```

For some reason it appends the original PATH to the redirect PATH resulting in a request to /outage/alerts/public which doesn't exist. I want to make a request to just /outage.

Putting a breakpoint in my filter just as the ctx.setRouteHost() is called shows that correct URL (http://10.50.36.43:8082/outage/).

My application.properties:

zuul.routes.api.path=/api/**
zuul.routes.api.url=http://localhost:8082/

答:
First, use PRE_TYPE instead of ROUTE_TYPE (aka "route")

```<code>@Override
public String filterType() {
    return FilterConstants.PRE_TYPE;
}
</code>```

Second, specify correct filterOrder

```<code>@Override
public int filterOrder() {
    return FilterConstants.SEND_FORWARD_FILTER_ORDER;
}
</code>```

Third, you need to remove URI containing "/alerts/public", which is appended to the routeHost by zuul

```<code>@Override
public Object run() {

    ctx.set("requestURI", "");

    // your code

    return null;
}
</code>```

Finally, override forwarding url in the code (//your code). And you have to specify at least one route (cause zuul filters don't work if there are no routes) to proxy "not outaged" requests to the same host 8080 like this

```<code>zuul.routes.api.path=/api/**
zuul.routes.api.url=http://localhost:8080/api
</code>```

IMHO, zuul is not a very convenient way to do this.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to forward all requests to my API to a single endpoint based upon some condition.

The Gateway app runs on port 8080

I've created the following filter:

public class OutagePeriodFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "route";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return isOutagePeriod();
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        // if outage - redirect everyone to http://localhost:8082/outage
        try {
            String url = UriComponentsBuilder.fromHttpUrl("http://localhost:8082").path("/outage").build()
                                     .toUriString();
            ctx.setRouteHost(new URL(url));
        } catch(MalformedURLException mue) {
            log.error("Cannot forward to outage period website");
        }
        return null;
    }

    private boolean isOutagePeriod() {
        // returns true if outage
    }
}

However after making a request to http://localhost:8080/alerts/public my API logs show:

2017-03-03 16:11:30.735 EST 0037 DEBUG                    o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/outage/alerts/public'; against '/beans/'

For some reason it appends the original PATH to the redirect PATH resulting in a request to /outage/alerts/public which doesn't exist. I want to make a request to just /outage.

Putting a breakpoint in my filter just as the ctx.setRouteHost() is called shows that correct URL (http://10.50.36.43:8082/outage/).

My application.properties:

zuul.routes.api.path=/api/**
zuul.routes.api.url=http://localhost:8082/

Body:
First, use PRE_TYPE instead of ROUTE_TYPE (aka "route")

@Override
public String filterType() {
    return FilterConstants.PRE_TYPE;
}

Second, specify correct filterOrder

@Override
public int filterOrder() {
    return FilterConstants.SEND_FORWARD_FILTER_ORDER;
}

Third, you need to remove URI containing "/alerts/public", which is appended to the routeHost by zuul

@Override
public Object run() {

    ctx.set("requestURI", "");

    // your code

    return null;
}

Finally, override forwarding url in the code (//your code). And you have to specify at least one route (cause zuul filters don't work if there are no routes) to proxy "not outaged" requests to the same host 8080 like this

zuul.routes.api.path=/api/**
zuul.routes.api.url=http://localhost:8080/api

IMHO, zuul is not a very convenient way to do this.


问:
Using vector of a class that contains static member variable
I had an Airplane class and this Airplane had a vector of Seat class named "m_seat".
In the Constructor of my Airplane, I used the number of seats as the needed parameter to resize the m_seat vector size to the requested size of the user. This was my code:

```<code>class Seat;

class Airplane {
    vector<Seat> m_seat;
public:
    Airplane(int);
};

class Seat{
    static int m_seatNumber;
public:
    Seat() { m_seatNumber += 10; }
};

int Seat::m_seatNumber = 100;

Airplane::Airplane(int numberOfSeats) {
    for (int i = 0; i<numberOfSeats; ++i) {
        m_seat.push_back();
    }
}

int main()
{
    Airplane(80);
    return 0;
}
</code>```

But it gave this error.

std::vector<_Ty,_Aloc>::push_back no overload of function takes 0 arguments,

and if this was really the problem, I had no idea what should I have put in my push_back()? So I tried {}

```<code>m_seat.push_back({});
</code>```

and It worked!

Now, I have another problem which is my main problem(SO rule: Ask only one question at a time!) that all seat numbers appear to be increased to the same number! I also used the "resize" member function of the vector, instead of that loop:

```<code>m_seat.resize(numberOfSeats);
</code>```

But the problem (same increase in the number of the m_seatNumber) remains unsolved.
Non-native English Speaker, Sorry.

答:
Disclaimer: This is a "best guess" answer.

If you wanted each seat to have a different, automatically increasing number, you need two values; one non-static, describing each seat, and one static, describing last-used number:

```<code>class Seat{
    static int lastSeatNumber;
    int seatNumber;

public:
    Seat() { seatNumber = lastSeatNumber; lastSeatNumber += 10; }
};
int Seat::lastSeatNumber = 100;
</code>```

That way each seat will receive its distinct number. This design is bad, however, as it doesn't allow e.g. seat number sharing between two airplanes! It also doesn't allow you to "free up" the numbers of seats you're no longer using, and the number can only keep growing. Also copying a Seat, while possible, won't manipulate that number at all. It'd be much better to allow the Airplane class to assign the seat numbers:

```<code>class Seat{
    int seatNumber;

public:
    Seat(int seatNumber) : seatNumber(seatNumber) { }
};

Airplane::Airplane(int numberOfSeats) {
    int seatNumber = 100;
    const int numberIncrement = 10;

    for (int i = 0; i < numberOfSeats; ++i) {
        m_seat.push_back(Seat(seatNumber));
        seatNumber += numberIncrement;
    }
}
</code>```

This way you can get the old behavior by adding another parameter to the airplane constructor telling it which number to start counting from.

Body:
I had an Airplane class and this Airplane had a vector of Seat class named "m_seat".
In the Constructor of my Airplane, I used the number of seats as the needed parameter to resize the m_seat vector size to the requested size of the user. This was my code:

class Seat;

class Airplane {
    vector<Seat> m_seat;
public:
    Airplane(int);
};

class Seat{
    static int m_seatNumber;
public:
    Seat() { m_seatNumber += 10; }
};

int Seat::m_seatNumber = 100;

Airplane::Airplane(int numberOfSeats) {
    for (int i = 0; i<numberOfSeats; ++i) {
        m_seat.push_back();
    }
}

int main()
{
    Airplane(80);
    return 0;
}

But it gave this error.

std::vector<_Ty,_Aloc>::push_back no overload of function takes 0 arguments,

and if this was really the problem, I had no idea what should I have put in my push_back()? So I tried {}

m_seat.push_back({});

and It worked!

Now, I have another problem which is my main problem(SO rule: Ask only one question at a time!) that all seat numbers appear to be increased to the same number! I also used the "resize" member function of the vector, instead of that loop:

m_seat.resize(numberOfSeats);

But the problem (same increase in the number of the m_seatNumber) remains unsolved.
Non-native English Speaker, Sorry.

Body:
Disclaimer: This is a "best guess" answer.

If you wanted each seat to have a different, automatically increasing number, you need two values; one non-static, describing each seat, and one static, describing last-used number:

class Seat{
    static int lastSeatNumber;
    int seatNumber;

public:
    Seat() { seatNumber = lastSeatNumber; lastSeatNumber += 10; }
};
int Seat::lastSeatNumber = 100;

That way each seat will receive its distinct number. This design is bad, however, as it doesn't allow e.g. seat number sharing between two airplanes! It also doesn't allow you to "free up" the numbers of seats you're no longer using, and the number can only keep growing. Also copying a Seat, while possible, won't manipulate that number at all. It'd be much better to allow the Airplane class to assign the seat numbers:

class Seat{
    int seatNumber;

public:
    Seat(int seatNumber) : seatNumber(seatNumber) { }
};

Airplane::Airplane(int numberOfSeats) {
    int seatNumber = 100;
    const int numberIncrement = 10;

    for (int i = 0; i < numberOfSeats; ++i) {
        m_seat.push_back(Seat(seatNumber));
        seatNumber += numberIncrement;
    }
}

This way you can get the old behavior by adding another parameter to the airplane constructor telling it which number to start counting from.


问:
Replacing column values in R
Example df:

```<code>index    name    V1    V2   etc
1        x       2     1
2        y       1     2
3        z       3     4
4        w       4     3
</code>```

I would like to replace values in columns V1 and V2 with related values in name column for particular index value. Output should look like this:

```<code>index    name    V1    V2   etc
1        x       y     x
2        y       x     y
3        z       z     w
4        w       w     z
</code>```

I have tried multiple merge statements in loop but not sure how I can replace the values instead of creating new columns and also got a duplicate name error.

```<code>V<-2 # number of V columns
names<-c()
for (i in 1:k){names[[i]]<-paste0('V',i)}
lookup_table<-df[,c('index','name'),drop=FALSE] # it's at unique index level

for(col in names){
df<- merge(df,lookup_table,by.x=col,by.y="index",all.x = TRUE)
}
</code>```

答:
We can do

```<code>df[3:4] <- lapply(df[3:4], function(x) df$name[x])
</code>```

Or without looping

```<code>df[3:4] <- df$name[as.matrix(df[3:4])]
df
#  index name V1 V2
#1     1    x  y  x
#2     2    y  x  y
#3     3    z  z  w
#4     4    w  w  z
</code>```

data

```<code>df <- structure(list(index = 1:4, name = c("x", "y", "z", "w"), V1 = c(2L,
1L, 3L, 4L), V2 = c(1L, 2L, 4L, 3L)), .Names = c("index", "name",
"V1", "V2"), class = "data.frame", row.names = c(NA, -4L))
</code>```

Title: Replacing column values in R

Body:
Example df:

index    name    V1    V2   etc
1        x       2     1
2        y       1     2
3        z       3     4
4        w       4     3

I would like to replace values in columns V1 and V2 with related values in name column for particular index value. Output should look like this:

index    name    V1    V2   etc
1        x       y     x
2        y       x     y
3        z       z     w
4        w       w     z

I have tried multiple merge statements in loop but not sure how I can replace the values instead of creating new columns and also got a duplicate name error.

V<-2 # number of V columns
names<-c()
for (i in 1:k){names[[i]]<-paste0('V',i)}
lookup_table<-df[,c('index','name'),drop=FALSE] # it's at unique index level

for(col in names){
df<- merge(df,lookup_table,by.x=col,by.y="index",all.x = TRUE)
}

Body:
We can do

df[3:4] <- lapply(df[3:4], function(x) df$name[x])

Or without looping

df[3:4] <- df$name[as.matrix(df[3:4])]
df
#  index name V1 V2
#1     1    x  y  x
#2     2    y  x  y
#3     3    z  z  w
#4     4    w  w  z

data

df <- structure(list(index = 1:4, name = c("x", "y", "z", "w"), V1 = c(2L,
1L, 3L, 4L), V2 = c(1L, 2L, 4L, 3L)), .Names = c("index", "name",
"V1", "V2"), class = "data.frame", row.names = c(NA, -4L))


问:
Beginning Java web development for experienced PHP web developers?
Feedback on a question I asked earlier has me wondering if there exists such a document or book as the one alluded to in this question title. I have searched the web in general, and previous StackOverflow questions (maybe I missed the right one?), but I have not been able to find what I am looking for.

I have several years experience with web development using PHP. My PHP work is mostly procedural, but I do use objects when appropriate. I like the PHP environment; that is, I like not having to compile and deploy for code changes to take effect. I like being able to use the same language for business logic and presentation logic. I like the ease of finding decent documentation for PHP. And I like how simple it is to setup an execution environment for PHP scripts (e.g. mod_php).

However, I am in the position of administering, and doing almost all of the in-house development for, a Java web application (a portal) being served with Apache Tomcat. Coming from the background described, I have been applying my "PHP way" of thinking to the Java work I have to do. Which basically means I forget about figuring out how to setup a development environment and just stick JSP scripts in the web root and avoiding writing full classes.

So, to list the things I am looking for in such a book:

Differences in terminology (e.g. why a web server is called a "container")

Differences in operating environment

Comparison of language best practices

I am not looking for "Java is object oriented and PHP isn't." I understand that the languages are different. I also don't want the silliness that is Head First Servlets & JSP (a book my office has lying around).

答:
To be honest, and i don't have a whole lot of experience developing on Java application servers, but i think you would do better just using a pure Java book (college/uni level), learning object oriented principles(inheritance, polymorphism, encapsulation)  and java's OO constructs if that is not your strong suit. During the process you'll be able to compare and contrast the features to php you've already seen. The reason i say this is because the java API's are constructed using these things very heavily (abstract classes, packages, inheritance etc.) and you'll have to work with them, not against them to get anything done in terms of plumbing. In my experience, comparative books don't work, because it comes from the mindset that the two languages just have differing terminology, but are fundamentally the same in some way. This is misleading, because java ee has a lot more underlying building blocks that you have to be aware of before you jump in and start writing code for HTTP requests.

I would look at the official documentation for your preferred server, and for the java ee background reading I would stick to oracle's documentation, as it avoids misinterpretation of definitions.

just out of curiosity, is there a particular reason you have not moved toward a more object oriented approach of PHP before moving to the monstrosity of java ee?

ContentLicense: CC BY-SA 2.5


问:
Call to a member function tasks() on null on laravel 5
Let me explain with a couple of word my problem.
On my controller i have this line:

```<code>$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
</code>```

This works for existing users, but when i try to create new ones i receive

Call to a member function tasks() on null

Can i with something like this or what do you suggest ?

```<code>if(!is_null($tasks))
    $tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
}
</code>```

This i my show function on controller

```<code>public function show(){
    $user = Auth::user();

    if(!$user)
        return redirect('/')->withErrors(config('constants.NA'));

    $countries = Country::all()->lists('name', 'id')->toArray();
    $profile = $user->profile;
  $student = $profile->student;

  // Tasks showed on students profile
  if ($student->group) {
      $tasks = $student->group->tasks()
          ->orderBy('created_at', 'desc')
          ->withPivot('id')
          ->get();
  }
  // Classmates
  if ($student->group) {
      $classmates = $student->group->students()
      ->where('id', '!=', $student->id)
      ->get();

  }

  // Activated books
  $books = Auth::user()->books()->orderBy('grade_id', 'asc')->get();

  if(!is_null($student->group))
    $iTasks = $student->group->tasks->count();
  else {
    $iTasks = 0;
  }

  $iTodos = $user->todos->count();

    return view('student.profile.show',compact('user','profile', 'countries', 'iTasks', 'iTodos', 'tasks', 'classmates', 'books'));
}
</code>```

This is my show view, for the tasks

```<code><div class="tab-pane <?php if(isset($tab) && $tab == 'timeline'): ?> active <?php endif; ?>" id="timeline">
                        @if($tasks->count())
                          <div class="timeline">
                            @foreach($tasks as $task)
                              <!-- TIMELINE ITEM -->
                              <div class="timeline-item">
                                <div class="timeline-badge">
                                  <div class="timeline-icon">
                                    <i class="mdi mdi-clipboard-text font-red-intense"></i>
                                  </div>
                                </div>
                                <div class="timeline-body">
                                  <div class="timeline-body-arrow"> </div>
                                  <div class="timeline-body-head">
                                    <div class="timeline-body-head-caption">
                                      <span class="timeline-body-title font-blue-madison">
                                        {{ $task->professor->profile->user->name }}
                                      </span>
                                      <span class="timeline-body-time font-grey-cascade">ju ca caktuar një <a href="/student/tasks" class="font-red sbold">detyrë</a> të re.</span>
                                    </div>
                                  </div>
                                  <div class="timeline-body-content">
                                    <span class="font-grey-cascade">
                                      {{ $task->pivot->comment }}
                                    </span>
                                  </div>
                                  <hr>
                                  Lenda: <span class="timeline-body-time font-grey-cascade sbold">{{ $task->subject->name }}</span>
                                  <div class="pull-right">
                                    Krijuar më: <span class="timeline-body-time font-grey-cascade sbold">{{ $task->created_at->format(Config::get('klasaime.date_format')) }}</span>
                                  </div>
                                </div>
                              </div>
                              <!-- END TIMELINE ITEM -->
                            @endforeach
                          </div>
                        @else
                          <div class="alert">
                            Ju nuk keni asnje detyrë të caktuar!
                          </div>
                        @endif
                      </div>
</code>```

答:
Do a simple check to see if the group exists and then carry on with whatever action you need to perform.

```<code>// controller
$tasks = null;

if ($student->group) {
    $tasks = $student->group->tasks()
        ->orderBy('created_at', 'desc')
        ->withPivot('id')
        ->get();
}

// view
@if($tasks)
    {{ $tasks->id }}
@else
    No tasks found
@endif
</code>```

Edit : In your controller add $tasks = null; and $classmates = null; at top. And in your view change @if($tasks->count()) to @if($tasks). I'm not sure where your use the classmates variable, but add a check to see if it's null before you use it.

Body:
Let me explain with a couple of word my problem.
On my controller i have this line:

$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();

This works for existing users, but when i try to create new ones i receive

Call to a member function tasks() on null

Can i with something like this or what do you suggest ?

if(!is_null($tasks))
    $tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
}

This i my show function on controller

public function show(){
    $user = Auth::user();

    if(!$user)
        return redirect('/')->withErrors(config('constants.NA'));

    $countries = Country::all()->lists('name', 'id')->toArray();
    $profile = $user->profile;
  $student = $profile->student;

  // Tasks showed on students profile
  if ($student->group) {
      $tasks = $student->group->tasks()
          ->orderBy('created_at', 'desc')
          ->withPivot('id')
          ->get();
  }
  // Classmates
  if ($student->group) {
      $classmates = $student->group->students()
      ->where('id', '!=', $student->id)
      ->get();

  }

  // Activated books
  $books = Auth::user()->books()->orderBy('grade_id', 'asc')->get();

  if(!is_null($student->group))
    $iTasks = $student->group->tasks->count();
  else {
    $iTasks = 0;
  }

  $iTodos = $user->todos->count();

    return view('student.profile.show',compact('user','profile', 'countries', 'iTasks', 'iTodos', 'tasks', 'classmates', 'books'));
}

This is my show view, for the tasks

<div class="tab-pane <?php if(isset($tab) && $tab == 'timeline'): ?> active <?php endif; ?>" id="timeline">
                        @if($tasks->count())

                            @foreach($tasks as $task)

                                        {{ $task->professor->profile->user->name }}

                                      ju ca caktuar një detyrë të re.

                                      {{ $task->pivot->comment }}

                                  Lenda: {{ $task->subject->name }}

                                    Krijuar më: {{ $task->created_at->format(Config::get('klasaime.date_format')) }}

                            @endforeach

                        @else

                            Ju nuk keni asnje detyrë të caktuar!

                        @endif

Body:
Do a simple check to see if the group exists and then carry on with whatever action you need to perform.

// controller
$tasks = null;

if ($student->group) {
    $tasks = $student->group->tasks()
        ->orderBy('created_at', 'desc')
        ->withPivot('id')
        ->get();
}

// view
@if($tasks)
    {{ $tasks->id }}
@else
    No tasks found
@endif

Edit : In your controller add $tasks = null; and $classmates = null; at top. And in your view change @if($tasks->count()) to @if($tasks). I'm not sure where your use the classmates variable, but add a check to see if it's null before you use it.


问:
When does a closure take ownership of its environment without the move keyword?
```<code>use std::thread;

fn test2() {
    let x = "abc".to_string();
    thread::spawn(|| {
        foo2(x);
    });
}

fn foo2(x: String) {}

fn test1() {
    let x = 1;
    thread::spawn(|| {
        foo1(x);
    });
}

fn foo1(x: i32) {}

fn main() {}
</code>```

Playground

The error:

error[E0373]: closure may outlive the current function, but it borrows `x`, which is owned by the current function
  --> <anon>:12:19
   |
12 |     thread::spawn(|| { foo1(x); });
   |                   ^^        - `x` is borrowed here
   |                   |
   |                   may outlive borrowed value `x`
   |
help: to force the closure to take ownership of `x` (and any other referenced variables), use the `move` keyword, as shown:
   |     thread::spawn(move || { foo1(x); });
```

Why does the closure in test1 not take ownership of x, which is specified by the signature (x: i32) of foo1? (I know I can add move to make it work.) I guess it is due to that x is copyable, but if it is copied into the closure then why do I still have the lifetime problem?

However test2 works.

答:
Because it doesn't have to take ownership.  Moving is more destructive than simply borrowing, so if the compiler thinks it can get away with not moving a captured value, it won't.  It moves the String because it has no other option.  It borrows the i32 because it's Copy.

But it can't get away with not borrowing it!

Aah, but the compiler doesn't know that until after it's decided if it's borrowing or moving a captured value.  The heuristic it uses is just that: not always correct.

Couldn't it just work it out properly?

Probably, but no one's taught it how.

Body:
use std::thread;

fn test2() {
    let x = "abc".to_string();
    thread::spawn(|| {
        foo2(x);
    });
}

fn foo2(x: String) {}

fn test1() {
    let x = 1;
    thread::spawn(|| {
        foo1(x);
    });
}

fn foo1(x: i32) {}

fn main() {}

Playground

The error:

error[E0373]: closure may outlive the current function, but it borrows `x`, which is owned by the current function
  --> <anon>:12:19
   |
12 |     thread::spawn(|| { foo1(x); });
   |                   ^^        - `x` is borrowed here
   |                   |
   |                   may outlive borrowed value `x`
   |
help: to force the closure to take ownership of `x` (and any other referenced variables), use the `move` keyword, as shown:
   |     thread::spawn(move || { foo1(x); });

Why does the closure in test1 not take ownership of x, which is specified by the signature (x: i32) of foo1? (I know I can add move to make it work.) I guess it is due to that x is copyable, but if it is copied into the closure then why do I still have the lifetime problem?

However test2 works.


问:
How to find the focal length from camera matrix?
I have OpenCV code for calculating camera matrix and fixing distortion in image.

Here is the part of the code in OpenCV and C++.

```<code>//default capture width and height
const int FRAME_WIDTH = 1288;
const int FRAME_HEIGHT = 964;
//max number of objects to be detected in frame
const int MAX_NUM_OBJECTS=50;
//minimum and maximum object area
const int MIN_OBJECT_AREA = 2*2;
const int MAX_OBJECT_AREA = FRAME_HEIGHT*FRAME_WIDTH/1.5;

Mat DistortedImg;                                           //storage for copy of the image raw
Mat UndistortedImg;                                         //

double cameraM[3][3] = {{1103.732864, 0.000000, 675.056365}, {0.000000, 1100.058630, 497.063376}, {0, 0, 1}}; //camera matrix to be edited
Mat CameraMatrix = Mat(3, 3, CV_64FC1, cameraM);

double distortionC[5] = {-0.346476, 0.142352, -0.000084, -0.001727, 0.000000};              //distortioncoefficient to be edited
Mat DistortionCoef = Mat(1, 5, CV_64FC1, distortionC);

double rArray[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
Mat RArray = Mat(3, 3, CV_64FC1, rArray);                   //originally CV_64F

double newCameraM[3][3] = {{963.436584, 0.000000, 680.157832}, {0.000000, 1021.688843, 498.825528}, {0, 0, 1}};
Mat NewCameraMatrix = Mat(3, 3, CV_64FC1, newCameraM);
Size UndistortedSize(1288,964);

Mat map1;
Mat map2;

string intToString(int number)
{
    std::stringstream ss;
    ss << number;
    return ss.str();
}

void imageCb(const sensor_msgs::ImageConstPtr& msg)                               //callback function defination
{
   cv_bridge::CvImagePtr cv_ptr;
   try
   {
        cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);              //convert ROS image to CV image and make copy of it storing in cv_ptr(a pointer)
   }
   catch (cv_bridge::Exception& e)
   {
      ROS_ERROR("cv_bridge exception: %s", e.what());
      return;
   }

    /*  image working procedure starting from here inside the main function.
     *  The purpose of the image processing is to use the existing video to working out the
     *  cordinate of the detected object, using color extraction technique.
     */

    bool trackObjects = true;
    bool useMorphOps = true;

    Mat cameraFeed;
    Mat HSV;
    Mat threshold;
    Mat ideal_image;

    //x and y values for the location of the object
    int x=0, y=0;
    createTrackbars();

    //store image to matrix
    cv_ptr->image.copyTo(DistortedImg);                                         //=Tan= copy the image from ardrone to DistortedImg for processing
    initUndistortRectifyMap(CameraMatrix, DistortionCoef, RArray, NewCameraMatrix, UndistortedSize, CV_32FC1, map1, map2);
    remap(DistortedImg, cameraFeed, map1, map2, INTER_LINEAR, BORDER_CONSTANT, Scalar(0,0,0));

    cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);                                  //convert frame from BGR to HSV colorspace

    //output the after-threshold matrix to Mat threshold
    inRange(HSV,Scalar(iLowH_1, iLowS_1, iLowV_1),Scalar(iHighH_1, iHighS_1, iHighV_1),threshold);
    //inRange(HSV,Scalar(0, 87, 24),Scalar(9, 255, 255),threshold);  //red

    morphOps(threshold);
    GaussianBlur( threshold, ideal_image, Size(9, 9), 2, 2 );

    trackFilteredObject1(x,y,ideal_image,cameraFeed);

    namedWindow( "Image with deal1", 0 );
    namedWindow( "Original Image", 0 );

    imshow("Image with deal1",ideal_image);
    imshow("Original Image", cameraFeed);

    //delay 30ms so that screen can refresh.
    //image will not appear without this waitKey() command
    cv::waitKey(30);
}
</code>```

Im not sure how to use this code in order to find the focal length from camera matrix. This code should calculate camera matrix and from the need to find the focal lenght. But some how Im not sure this is the way to get the camera matrix and then the focal lenght. The camera matrix 3x3 matrix. But how those parameters are calculated?

Any help?

答:
First a little bit about the camera matrix:

The camera matrix is of the following form:

```<code>f_x  s    c_x
0    f_y  c_y
0    0    1
</code>```

where f_x is the camera focal length in the x axis in pixels

f_y is the camera focal length in the y axis in pixels

s is a skew parameter (normally not used)

c_x is the optical center in x

c_y is the optical center in y

Normally f_x and f_y are identical but it is possible to be different.
In this link you can get even more information about it.

Now lets go back to your code.

In your code the camera matrix is hardcoded, not calculated!, specifically in here:

```<code>double cameraM[3][3] = {{1103.732864, 0.000000, 675.056365}, {0.000000, 1100.058630, 497.063376}, {0, 0, 1}}; //camera matrix to be edited
Mat CameraMatrix = Mat(3, 3, CV_64FC1, cameraM);
</code>```

And in any part of your code there is anything about calculating it.

The calibration of a camera has several steps:

Get images of chessboard like pattern

find the intersections of the squares in this images
    (findChessBoardCorners

then use the CalibrateCamera function to get the matrix and other information

More information about it here.

Once you get the camera matrix, you can get the focal length, and if you want it in millimeters, you will need the size of the sensors of the camera (you have to ask the manufacturer or find it in the internet)

Body:
I have OpenCV code for calculating camera matrix and fixing distortion in image.

Here is the part of the code in OpenCV and C++.

//default capture width and height
const int FRAME_WIDTH = 1288;
const int FRAME_HEIGHT = 964;
//max number of objects to be detected in frame
const int MAX_NUM_OBJECTS=50;
//minimum and maximum object area
const int MIN_OBJECT_AREA = 2*2;
const int MAX_OBJECT_AREA = FRAME_HEIGHT*FRAME_WIDTH/1.5;

Mat DistortedImg;                                           //storage for copy of the image raw
Mat UndistortedImg;                                         //

double cameraM[3][3] = {{1103.732864, 0.000000, 675.056365}, {0.000000, 1100.058630, 497.063376}, {0, 0, 1}}; //camera matrix to be edited
Mat CameraMatrix = Mat(3, 3, CV_64FC1, cameraM);

double distortionC[5] = {-0.346476, 0.142352, -0.000084, -0.001727, 0.000000};              //distortioncoefficient to be edited
Mat DistortionCoef = Mat(1, 5, CV_64FC1, distortionC);

double rArray[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
Mat RArray = Mat(3, 3, CV_64FC1, rArray);                   //originally CV_64F

double newCameraM[3][3] = {{963.436584, 0.000000, 680.157832}, {0.000000, 1021.688843, 498.825528}, {0, 0, 1}};
Mat NewCameraMatrix = Mat(3, 3, CV_64FC1, newCameraM);
Size UndistortedSize(1288,964);

Mat map1;
Mat map2;

string intToString(int number)
{
    std::stringstream ss;
    ss << number;
    return ss.str();
}

void imageCb(const sensor_msgs::ImageConstPtr& msg)                               //callback function defination
{
   cv_bridge::CvImagePtr cv_ptr;
   try
   {
        cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);              //convert ROS image to CV image and make copy of it storing in cv_ptr(a pointer)
   }
   catch (cv_bridge::Exception& e)
   {
      ROS_ERROR("cv_bridge exception: %s", e.what());
      return;
   }

    /*  image working procedure starting from here inside the main function.
     *  The purpose of the image processing is to use the existing video to working out the
     *  cordinate of the detected object, using color extraction technique.
     */

    bool trackObjects = true;
    bool useMorphOps = true;

    Mat cameraFeed;
    Mat HSV;
    Mat threshold;
    Mat ideal_image;

    //x and y values for the location of the object
    int x=0, y=0;
    createTrackbars();

    //store image to matrix
    cv_ptr->image.copyTo(DistortedImg);                                         //=Tan= copy the image from ardrone to DistortedImg for processing
    initUndistortRectifyMap(CameraMatrix, DistortionCoef, RArray, NewCameraMatrix, UndistortedSize, CV_32FC1, map1, map2);
    remap(DistortedImg, cameraFeed, map1, map2, INTER_LINEAR, BORDER_CONSTANT, Scalar(0,0,0));

    cvtColor(cameraFeed,HSV,COLOR_BGR2HSV);                                  //convert frame from BGR to HSV colorspace

    //output the after-threshold matrix to Mat threshold
    inRange(HSV,Scalar(iLowH_1, iLowS_1, iLowV_1),Scalar(iHighH_1, iHighS_1, iHighV_1),threshold);
    //inRange(HSV,Scalar(0, 87, 24),Scalar(9, 255, 255),threshold);  //red

    morphOps(threshold);
    GaussianBlur( threshold, ideal_image, Size(9, 9), 2, 2 );

    trackFilteredObject1(x,y,ideal_image,cameraFeed);

    namedWindow( "Image with deal1", 0 );
    namedWindow( "Original Image", 0 );

    imshow("Image with deal1",ideal_image);
    imshow("Original Image", cameraFeed);

    //delay 30ms so that screen can refresh.
    //image will not appear without this waitKey() command
    cv::waitKey(30);
}

Im not sure how to use this code in order to find the focal length from camera matrix. This code should calculate camera matrix and from the need to find the focal lenght. But some how Im not sure this is the way to get the camera matrix and then the focal lenght. The camera matrix 3x3 matrix. But how those parameters are calculated?

Any help?

Body:
First a little bit about the camera matrix:

The camera matrix is of the following form:

f_x  s    c_x
0    f_y  c_y
0    0    1

where f_x is the camera focal length in the x axis in pixels

f_y is the camera focal length in the y axis in pixels

s is a skew parameter (normally not used)

c_x is the optical center in x

c_y is the optical center in y

Normally f_x and f_y are identical but it is possible to be different.
In this link you can get even more information about it.

Now lets go back to your code.

In your code the camera matrix is hardcoded, not calculated!, specifically in here:

double cameraM[3][3] = {{1103.732864, 0.000000, 675.056365}, {0.000000, 1100.058630, 497.063376}, {0, 0, 1}}; //camera matrix to be edited
Mat CameraMatrix = Mat(3, 3, CV_64FC1, cameraM);

And in any part of your code there is anything about calculating it.

The calibration of a camera has several steps:

Get images of chessboard like pattern

find the intersections of the squares in this images
    (findChessBoardCorners

then use the CalibrateCamera function to get the matrix and other information

More information about it here.

Once you get the camera matrix, you can get the focal length, and if you want it in millimeters, you will need the size of the sensors of the camera (you have to ask the manufacturer or find it in the internet)


问:
Ember model Not Bind Dynamically using Link-to
I created an ember demo,A parent view and it's child
this is the parent view

```<code><h1>A list of Todo Tasks</h1>
<ul>
{{#each model as |todo|}}
<li>{{#link-to "todos.details" todo}}{{todo.desc}}{{/link-to}}</li>
{{/each}}
</ul>

{{outlet}}
</code>```

and Its js login is
import Ember from 'ember';

```<code>export default Ember.Route.extend({
    model (){
        return [{
            "id" : 1,
            "desc" : "Try use ember"
        },
        {
            "id" : 2,
            "desc" : "Add it to github"
        },
        ];

    }
});
</code>```

but when i use the link-to and navigate the data didn't show unless i refresh the page
This is the child view

```<code><h2>The Details for <span style="color: green;">{{model.name}}</span> is : </h2>
{{#if model.error}}
<p>{{model.message}}</p>
{{else}}
<ul>
 {{#each model.steps as |task|}}
    <li>{{task.do}}</li>
    {{/each}}
</ul>
{{/if}}

{{outlet}}
</code>```

and its js logic

```<code>import Ember from 'ember';

export default Ember.Route.extend({
    model(params){

        if(params.id == "1"){
            return {
                name : "Ember SetUp",
                steps : [{
                    id :1,
                    do : "Download Ember Cli"
            },
            {
                    id :2,
                    do : "Generate New Project"
            },
            {
                    id :3,
                    do : "Generate Pages&Routes"
            }
                ]
            };
        }
        else{
            return {
                error : true,
                name : "Not Found",
                message : "There is no task with this id"
            }
        }
    }
});
</code>```

iam using ember 2.5 and this is part of the router

```<code>this.route('todos', function() {
    this.route('details',{path : "/:id"});
  });
</code>```

答: Ack, OP of video here. Sorry about that. Small misspeaking on my part, I should address this in the comments of the video and try to revise that. Sorry for the confusion! D:</p>

Body:
I created an ember demo,A parent view and it's child
this is the parent view

A list of Todo Tasks

{{#each model as |todo|}}

{{#link-to "todos.details" todo}}{{todo.desc}}{{/link-to}}

{{/each}}

{{outlet}}

and Its js login is
import Ember from 'ember';

export default Ember.Route.extend({
    model (){
        return [{
            "id" : 1,
            "desc" : "Try use ember"
        },
        {
            "id" : 2,
            "desc" : "Add it to github"
        },
        ];

    }
});

but when i use the link-to and navigate the data didn't show unless i refresh the page
This is the child view

The Details for {{model.name}} is :

{{#if model.error}}

{{model.message}}

{{else}}

 {{#each model.steps as |task|}}

{{task.do}}

    {{/each}}

{{/if}}

{{outlet}}

and its js logic

import Ember from 'ember';

export default Ember.Route.extend({
    model(params){

        if(params.id == "1"){
            return {
                name : "Ember SetUp",
                steps : [{
                    id :1,
                    do : "Download Ember Cli"
            },
            {
                    id :2,
                    do : "Generate New Project"
            },
            {
                    id :3,
                    do : "Generate Pages&Routes"
            }
                ]
            };
        }
        else{
            return {
                error : true,
                name : "Not Found",
                message : "There is no task with this id"
            }
        }
    }
});

iam using ember 2.5 and this is part of the router

this.route('todos', function() {
    this.route('details',{path : "/:id"});
  });


问:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'column_name'
I am using Java JDBC with MySQL and I get this error:

```<code>com.mysql.jdbc.MysqlDataTruncation: Data truncation:
Data too long for column 'column_name'
</code>```

How do I remedy this error?

答:
This error appears because,the size of data you tried to insert into column is too large.

Solution - Change the column size to max.Assuming your column is of type VARCHAR,then in mySQL

```<code>ALTER TABLE table_name CHANGE COLUMN col_name col_name  VARCHAR(1000);  //assuming 1000 is enough
</code>```

Body:
I am using Java JDBC with MySQL and I get this error:

com.mysql.jdbc.MysqlDataTruncation: Data truncation:
Data too long for column 'column_name'

How do I remedy this error?

Body:
This error appears because,the size of data you tried to insert into column is too large.

Solution - Change the column size to max.Assuming your column is of type VARCHAR,then in mySQL

ALTER TABLE table_name CHANGE COLUMN col_name col_name  VARCHAR(1000);  //assuming 1000 is enough


问:
Less wrong TryGetValue then null check syntax
I'm a little new to C# still... I'm finding myself reusing a specific procedure over and over. Before I go writing a helper method for personal laziness, is there a shorter or less wrong way to write this sort of statement?

```<code>Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = createdBy ?? "Unknown",
    //set 15 other values
    ...
}
</code>```

Essentially, set a property on an object by trying to get a value, then if it's null use a default value. I have a LOT of properties, it would be better if I could just

```<code>MyEntity me = new MyEntity{
    CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
    ...
}
</code>```

Again, I am perfectly capable of writing my own helper function. I'm looking for an existing native functionality or shorthand before I do so.

答:
TryGetValue returns a bool indicating if the key was found in the dictionary. So you should use that and set the variable to the default if it was not found:

```<code>string createdBy;
if (!data.TryGetValue("CreatedBy", out createdBy)) createdBy="Unknown";
</code>```

Body:
I'm a little new to C# still... I'm finding myself reusing a specific procedure over and over. Before I go writing a helper method for personal laziness, is there a shorter or less wrong way to write this sort of statement?

Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = createdBy ?? "Unknown",
    //set 15 other values
    ...
}

Essentially, set a property on an object by trying to get a value, then if it's null use a default value. I have a LOT of properties, it would be better if I could just

MyEntity me = new MyEntity{
    CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
    ...
}

Again, I am perfectly capable of writing my own helper function. I'm looking for an existing native functionality or shorthand before I do so.

Body:
TryGetValue returns a bool indicating if the key was found in the dictionary. So you should use that and set the variable to the default if it was not found:

string createdBy;
if (!data.TryGetValue("CreatedBy", out createdBy)) createdBy="Unknown";


问:
trying to implement live search in a input box
i'm trying to implement live search in a textbox, the list of options coming from the server, if the item is not available it should add dynamically, like if i type "gre" and selects that, it should added to the list or it should show in the top of the lists

Codeply :
https://www.codeply.com/go/d6WaXok32m

as specified in the code, the element 'entranceExamSearch' input box contails list of items

答:
This code will give you some idea.

HTML:

```<code><input type="text" id="searchPro" />
Your all the dynamic result will be show inside the div
<div id="searchLog"></div>
</code>```

JQuery:

```<code>$("#searchPro").autocomplete({
    source: function(request,response) {
        $.ajax({
            url: "php.func.php",
            type: "POST",
            data: { term: request.term },
            success: function (searchData) {
                $('#searchLog').html(searchData);
            }
        })
    }
});
</code>```

PHP: php.func.php

```<code>$find = "SELECT *
        FROM tbl_products
        WHERE (`product_name` LIKE '%".$_REQUEST['term']."%')";

$resset = $conn->query($find);
    while ($res = mysqli_fetch_object($resset)) {
    $findRes[] = $res;
}
if (!empty($findRes)) {
    foreach ($findRes as $ResultSet) {
        echo "<tr><td>".$ResultSet->product_name."</td>";
    }
}else{
    echo "<p>No Result Found for keyword <b>".$_REQUEST['term']."</b>..<p><hr/>";
}
</code>```

Here is the link: [JQuery Autocomplete][1]

This is for your basic reference code i have use in my project. you can modify as per your need. Hope this will help you.
For more https://jqueryui.com/autocomplete/

Body:
This code will give you some idea.

HTML:

<input type="text" id="searchPro" />
Your all the dynamic result will be show inside the div
<div id="searchLog"></div>

JQuery:

$("#searchPro").autocomplete({
    source: function(request,response) {
        $.ajax({
            url: "php.func.php",
            type: "POST",
            data: { term: request.term },
            success: function (searchData) {
                $('#searchLog').html(searchData);
            }
        })
    }
});

PHP: php.func.php

$find = "SELECT *
        FROM tbl_products
        WHERE (`product_name` LIKE '%".$_REQUEST['term']."%')";

$resset = $conn->query($find);
    while ($res = mysqli_fetch_object($resset)) {
    $findRes[] = $res;
}
if (!empty($findRes)) {
    foreach ($findRes as $ResultSet) {
        echo "<tr><td>".$ResultSet->product_name."</td>";
    }
}else{
    echo "<p>No Result Found for keyword <b>".$_REQUEST['term']."</b>..<p><hr/>";
}

Here is the link: [JQuery Autocomplete][1]

This is for your basic reference code i have use in my project. you can modify as per your need. Hope this will help you.
For more https://jqueryui.com/autocomplete/


问:
How to get aws instance metadata remotely using CLI?
I am very new to AWS. I have a Windows Server EC2 instance. I installed AWS CLI on my laptop. Then I opened a CMD window, typed in "aws configure", put in the access key credentials, and was able to connect to the EC2.

From here, how do I get the http://169.254.169.254/latest/meta-data working? How do I retrieve some meta data?

答:
You cannot use http://169.254.169.254/latest/meta-data from AWS cli on your laptop

Use the ec2  describe-instances command instead for getting instance details

More details here


问:
MySQL Syntax Error, Unrecognized keyword null
MySqli/phpmyadmin query not working - unrecognized keyword 'NULL'

I use

```<code>PHP - mysqli
MySQL + phpMyAdmin
</code>```

Sql :

```<code>update User set name = null;
</code>```

Error :

Unrecognized keyword null

thank for any help !

答:
User is a reserved/keyword word in mySQL.  offset it in backticks.

```<code>update `User` set name = null;
</code>```

http://rextester.com/YSTH80658 using muser.... I don't think they will let me create a table called user or drop it.

Body:
MySqli/phpmyadmin query not working - unrecognized keyword 'NULL'

I use

PHP - mysqli
MySQL + phpMyAdmin

Sql :

update User set name = null;

Error :

Unrecognized keyword null

thank for any help !

Body:
User is a reserved/keyword word in mySQL.  offset it in backticks.

update `User` set name = null;

http://rextester.com/YSTH80658 using muser.... I don't think they will let me create a table called user or drop it.


问:
Can't set headers after they are sent - routing
I have seen multiple answers for the question but I am not able to solve this issue, so I am re-posting it with my code. I am new to this and need help to understand and fix this.

My Code

```<code>// Get logs from DB
router.get("/getlogs/:dbtype", function (req, res, next) {
var dbtype = req.params.dbtype;
if (dbtype == "mongodb") {
    list = Logs.find(function (err, log) {
        res.json(log);
    })
} else if (dbtype == "mssql") {
    var config = {
        userName: 'user',
        password: 'pass',
        server: 'server',
        options: {
            instanceName: 'instance',
            database: 'db',
        }
    };

    // SQL Server connection
    var connection = new Tedious.Connection(config);
    connection.on('connect', function (err) {
       // if (err) { console.log(err); res.json(err);}
        // If no error, then good to proceed.
        //console.log("SQL Server Connected SQL SQL");
        //connection.on('debug', function(err) { console.log('debug:', err);});

        var request = new Tedious.Request(`select top 1 * from table1`, function (err) {
            //if (err)  { console.log(err); res.json(err);}
        });

        request.on('row', function (columns) {
            var row = {};
            columns.forEach(function (column) {
                row[column.metadata.colName] = column.value;
            });
            rows.push(row);
            res.json(rows); **<-- this is where I get error**
        });
        request.on('end', function () {
            res.json(rows);
        })
        connection.execSql(request);
    });
}
});
</code>```

答:
It's because you are sending response every time you recive row.

Change this:

```<code>request.on('row', function (columns) {
    var row = {};
    columns.forEach(function (column) {
        row[column.metadata.colName] = column.value;
    });
    rows.push(row);
    res.json(rows);
});
</code>```

to:

```<code>request.on('row', function (columns) {
    var row = {};
    columns.forEach(function (column) {
        row[column.metadata.colName] = column.value;
    });
    rows.push(row);
});
request.on('doneInProc', function () {
    res.json(rows);
});
</code>```

Body:
I have seen multiple answers for the question but I am not able to solve this issue, so I am re-posting it with my code. I am new to this and need help to understand and fix this.

My Code

// Get logs from DB
router.get("/getlogs/:dbtype", function (req, res, next) {
var dbtype = req.params.dbtype;
if (dbtype == "mongodb") {
    list = Logs.find(function (err, log) {
        res.json(log);
    })
} else if (dbtype == "mssql") {
    var config = {
        userName: 'user',
        password: 'pass',
        server: 'server',
        options: {
            instanceName: 'instance',
            database: 'db',
        }
    };

    // SQL Server connection
    var connection = new Tedious.Connection(config);
    connection.on('connect', function (err) {
       // if (err) { console.log(err); res.json(err);}
        // If no error, then good to proceed.
        //console.log("SQL Server Connected SQL SQL");
        //connection.on('debug', function(err) { console.log('debug:', err);});

        var request = new Tedious.Request(`select top 1 * from table1`, function (err) {
            //if (err)  { console.log(err); res.json(err);}
        });

        request.on('row', function (columns) {
            var row = {};
            columns.forEach(function (column) {
                row[column.metadata.colName] = column.value;
            });
            rows.push(row);
            res.json(rows); **<-- this is where I get error**
        });
        request.on('end', function () {
            res.json(rows);
        })
        connection.execSql(request);
    });
}
});

Body:
It's because you are sending response every time you recive row.

Change this:

request.on('row', function (columns) {
    var row = {};
    columns.forEach(function (column) {
        row[column.metadata.colName] = column.value;
    });
    rows.push(row);
    res.json(rows);
});

to:

request.on('row', function (columns) {
    var row = {};
    columns.forEach(function (column) {
        row[column.metadata.colName] = column.value;
    });
    rows.push(row);
});
request.on('doneInProc', function () {
    res.json(rows);
});


问:
How to return to previously nested `while True` loops?
Say I have something in this kind of format:

```<code>while True1:
    if something:
        do some thing
    elif something else:
        do something else
        while True2:
            if something1:
                do some thing1
            if something2:
                do some thing2
            if want to end this while True2 loop
                go back to first while True1 loop
    elif something else else:
        do some thing else else
</code>```

etc.

How can I make something within a while True loop go back to a previous while True loop that it was nested inside?

答:
The break statement does just that.

```<code>while True: #1
    if something:
        do something
    elif something else:
        do something else
        while True: #2
            if something1:
                do something
            if something2:
                do something else
            if want to end this while True #2 loop:
                break            # will break out of the innermost loop only
    elif something else else:
        do some thing else else
</code>```

Read more: Control Flow Tools

Body:
Say I have something in this kind of format:

while True1:
    if something:
        do some thing
    elif something else:
        do something else
        while True2:
            if something1:
                do some thing1
            if something2:
                do some thing2
            if want to end this while True2 loop
                go back to first while True1 loop
    elif something else else:
        do some thing else else

etc.

How can I make something within a while True loop go back to a previous while True loop that it was nested inside?

Body:
The break statement does just that.

while True: #1
    if something:
        do something
    elif something else:
        do something else
        while True: #2
            if something1:
                do something
            if something2:
                do something else
            if want to end this while True #2 loop:
                break            # will break out of the innermost loop only
    elif something else else:
        do some thing else else

Read more: Control Flow Tools


问:
excel: change format dates in advanced filter
I'm using the Advanced Filter to search between dates in a database.
I placed my criteria side by side so I can seach for one or more information together.

Here is the example:

This is the code:

```<code>Sub FiltroAutomatico()
'
' FiltroAutomatico Macro
'

'
    Sheets("BASE_TOTAL_ATUAL").Range("A1:J445").AdvancedFilter Action:= _
        xlFilterCopy, CriteriaRange:=Range("CONSULTA!Criteria"),
CopyToRange:=Range _
        ("CONSULTA!Extract"), Unique:=False
    Range("H25").Select
    ActiveWindow.SmallScroll Down:=-15
    Range("G3").Select
End Sub
</code>```

Anyway, the problem is that when I search for something like >03/03/2017 and <25/03/2017 it didn't work as I expected.

I think the problem it's because Excel it's not recognizing my dates correctly (my Excel is in portuguese and the date here has the dd/mm/yyyy format). I tested using US dates instead and it worked perfectly.

Is there any way to change the format dates from an Advanced Filter to understand that the format of my criteria is dd/mm/yyyy instead of mm/dd/yyyy?

答:
I cannot test this, but dates in VBA filters have always been US-centric.  I would suggest that you have your users enter the actual starting and end date in your local format (but NOT in the actual criteria range).  In the criteria range itself, use this formula:

```<code>=">" & StartDate
="<" & EndDate
</code>```

Where StartDate and EndDate refer to the dates entered by your user.
You could even leave it in the same physical location as you show above, but have the criteria range elsewhere.  Or you could have them enter it on a User Form.

The cell will display something like >49076  where the number is the number of days since (usually) 1/1/1900.  But it should work.

If you have them enter the dates elsewhere, be sure to LOCK and PROTECT the criteria cells so the user cannot delete or change the formula.

Body:
I'm using the Advanced Filter to search between dates in a database.
I placed my criteria side by side so I can seach for one or more information together.

Here is the example:

This is the code:

Sub FiltroAutomatico()
'
' FiltroAutomatico Macro
'

'
    Sheets("BASE_TOTAL_ATUAL").Range("A1:J445").AdvancedFilter Action:= _
        xlFilterCopy, CriteriaRange:=Range("CONSULTA!Criteria"),
CopyToRange:=Range _
        ("CONSULTA!Extract"), Unique:=False
    Range("H25").Select
    ActiveWindow.SmallScroll Down:=-15
    Range("G3").Select
End Sub

Anyway, the problem is that when I search for something like >03/03/2017 and <25/03/2017 it didn't work as I expected.

I think the problem it's because Excel it's not recognizing my dates correctly (my Excel is in portuguese and the date here has the dd/mm/yyyy format). I tested using US dates instead and it worked perfectly.

Is there any way to change the format dates from an Advanced Filter to understand that the format of my criteria is dd/mm/yyyy instead of mm/dd/yyyy?

Body:
I cannot test this, but dates in VBA filters have always been US-centric.  I would suggest that you have your users enter the actual starting and end date in your local format (but NOT in the actual criteria range).  In the criteria range itself, use this formula:

=">" & StartDate
="<" & EndDate

Where StartDate and EndDate refer to the dates entered by your user.
You could even leave it in the same physical location as you show above, but have the criteria range elsewhere.  Or you could have them enter it on a User Form.

The cell will display something like >49076  where the number is the number of days since (usually) 1/1/1900.  But it should work.

If you have them enter the dates elsewhere, be sure to LOCK and PROTECT the criteria cells so the user cannot delete or change the formula.


问:
How can I get query string values in JavaScript?
Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how? If not, is there a plugin which can do so?

答:
Roshambo jQuery method wasn't taking care of decode URL

http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

Just added that capability also while adding in  the return statement

```<code>return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
</code>```

Now you can find the updated gist:

```<code>$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}
</code>```

Body:
Roshambo jQuery method wasn't taking care of decode URL

http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

Just added that capability also while adding in  the return statement

return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;

Now you can find the updated gist:

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}


问:
Taking a photo with camera using Xamarin Forms nuget Xam.Plugin.Media
I just used NUGET and installed Xam.Plugin.Media so that I can take photos using my mobile app.

I wrote the following code in the click event of the button as per the sample code in the xamarin component website:

```<code>private async void btnTake1_Clicked(object sender, EventArgs e)
        {
            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
                return;
            }

            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {

                Directory = "Sample",
                Name = "test.jpg"
            });

            if (file == null)
                return;

            await DisplayAlert("File Location", file.Path, "OK");

            imgPhoto1.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                file.Dispose();
                return stream;
            });

        }
</code>```

All went well and the Solution is building successfully, I am running only UWP now. But when I click the button it breaks at some location in

```<code>if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
</code>```

Can somebody help me with this?
Thanks in advance.
Sarin Gopalan

答:
Have you tried to InitializeComponent like the documentation on github?

```<code>await CrossMedia.Current.Initialize();
</code>```

https://github.com/jamesmontemagno/MediaPlugin

Body:
I just used NUGET and installed Xam.Plugin.Media so that I can take photos using my mobile app.

I wrote the following code in the click event of the button as per the sample code in the xamarin component website:

private async void btnTake1_Clicked(object sender, EventArgs e)
        {
            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
                return;
            }

            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {

                Directory = "Sample",
                Name = "test.jpg"
            });

            if (file == null)
                return;

            await DisplayAlert("File Location", file.Path, "OK");

            imgPhoto1.Source = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                file.Dispose();
                return stream;
            });

        }

All went well and the Solution is building successfully, I am running only UWP now. But when I click the button it breaks at some location in

if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();

Can somebody help me with this?
Thanks in advance.
Sarin Gopalan

Body:
Have you tried to InitializeComponent like the documentation on github?

await CrossMedia.Current.Initialize();

https://github.com/jamesmontemagno/MediaPlugin


问:
How to write an SQL query that counts number of employees in a manager's department?
The question is as follows:

List the "manager's name" and the "number of employees" in that manager's department.

I am new to SQL and having some trouble writing a statement that queries the above statement.

This is the statement I wrote but it queries 6 employees as manager's when there should only be 3 manager's.

```<code>SELECT b.ENAME AS "Manager", COUNT(*) AS "Number of Employees"
FROM EMP e
JOIN EMP b ON b.EMPNO = e.MGR
GROUP BY b.EMPNO, b.ENAME;
</code>```

The main question is how do I write it to only query the 3 manager's along with the employee count?

Thanks for the help in advance

答:
```<code>  select count(distinct e.mgr), e.ename
  from emp e
  where e.mgr is not null;
</code>```

try using distinct and mgr is not null.

Body:
The question is as follows:

List the "manager's name" and the "number of employees" in that manager's department.

I am new to SQL and having some trouble writing a statement that queries the above statement.

This is the statement I wrote but it queries 6 employees as manager's when there should only be 3 manager's.

SELECT b.ENAME AS "Manager", COUNT(*) AS "Number of Employees"
FROM EMP e
JOIN EMP b ON b.EMPNO = e.MGR
GROUP BY b.EMPNO, b.ENAME;

The main question is how do I write it to only query the 3 manager's along with the employee count?

Thanks for the help in advance

Body:
  select count(distinct e.mgr), e.ename
  from emp e
  where e.mgr is not null;

try using distinct and mgr is not null.


问:
Where Are the JavaDocs for Room?
Room sounds interesting, but I cannot find any of the classes in the Android Developer site's JavaDocs, as they do not show up when searching. Are JavaDocs available for Room?</p>

答:
Here're what I found:

Docs

Reference

Title: Where Are the JavaDocs for Room?

Body:
Here're what I found:

Docs

Reference


问:
Illegal start of expression in jcreator
I am not sure why there is an error, which keeps on saying that there is an illegal start of expression and  ')' is expected  error. It occurs in line 14.

```<code>1 import java.io.*;
2 public class LeapYear{
3 public static void main(String[] args){
4   String leapYear="";
5   int intleapYear;
6
7   BufferedReader input = new BufferedReader(
8       new InputStreamReader(System.in));
9
10  try{
11      System.out.print("Enter a year: " +leapYear);
12      leapYear=input.readLine();
13      intleapYear=Integer.parseInt(leapYear);
14      boolean isleapyear= ((intleapYear%4==0)&&(intleapYear%100!==0)||(intleapYear%400==0));
16
17
18  if(isleapyear){
19      System.out.println(intleapYear + " is a leap year.");
20  } else
21  System.out.println(intleapYear + " is not a leap year.");
22
23  }catch(IOException e){
24      System.out.println("Error");
25  }
26
27
28
29
30  /*if ((intleapYear%4==0)&&(intleapYear%100!==0)||(intleapYear%400==0)){
31          System.out.println(intleapYear+" is a leap year.");
32      }else
33      System.out.println(intleapYear+" is not a leap year.");*/
}
</code>```

}

答:
It is because you are using !==

you should use !=

so line 14 would be:

```<code>boolean isleapyear= ((intleapYear%4==0)&&(intleapYear%100!=0)||(intleapYear%400==0));
</code>```

Title: Illegal start of expression in jcreator

Body:
I am not sure why there is an error, which keeps on saying that there is an illegal start of expression and  ')' is expected  error. It occurs in line 14.

1 import java.io.*;
2 public class LeapYear{
3 public static void main(String[] args){
4   String leapYear="";
5   int intleapYear;
6
7   BufferedReader input = new BufferedReader(
8       new InputStreamReader(System.in));
9
10  try{
11      System.out.print("Enter a year: " +leapYear);
12      leapYear=input.readLine();
13      intleapYear=Integer.parseInt(leapYear);
14      boolean isleapyear= ((intleapYear%4==0)&&(intleapYear%100!==0)||(intleapYear%400==0));
16
17
18  if(isleapyear){
19      System.out.println(intleapYear + " is a leap year.");
20  } else
21  System.out.println(intleapYear + " is not a leap year.");
22
23  }catch(IOException e){
24      System.out.println("Error");
25  }
26
27
28
29
30  /*if ((intleapYear%4==0)&&(intleapYear%100!==0)||(intleapYear%400==0)){
31          System.out.println(intleapYear+" is a leap year.");
32      }else
33      System.out.println(intleapYear+" is not a leap year.");*/
}

}

Body:
It is because you are using !==

you should use !=

so line 14 would be:

boolean isleapyear= ((intleapYear%4==0)&&(intleapYear%100!=0)||(intleapYear%400==0));


问:
java parsing a string like "0:ADD(10)"
i am having a string array like this {"0:ADD(10)","1:ADD(20)"} how can i parse this and get the value '10','20' from this string ,

Scenario is : i am trying to write a client and server app using Apache Mina server , when i sent message between client and server i am getting response as "0:ADD(10)"

答:
Using guava:</p>

```<code>String digits=(digits=CharMatcher.DIGIT.retainFrom("0:ADD(10)")).substring(1,digits.length());
</code>```

Title: java parsing a string like "0:ADD(10)"

Body:
Using guava:

String digits=(digits=CharMatcher.DIGIT.retainFrom("0:ADD(10)")).substring(1,digits.length());


问:
How to map/deserialize a JSON array to a POJO or POJO List?
I know this question or similar ones have been asked multiple times here, but I swear I've read tons of related posts and none of the solutions seems to be working for me.

I'm trying to map some JSON data, which I receive from a specific REST API, to a Java class. The JSON has this format:

```<code>{"netStatLinks":[

{"src":"of:0000000000000002/3",
"dst":"of:0000000000000000/1",
"bw":10000.0,
"rate":0.0,
"usage":0.0,
"available":10000.0},

{"src":"of:0000000000000005/3",
"dst":"of:0000000000000006/1",
"bw":10000.0,
"rate":0.0,
"usage":0.0,
"available":10000.0},
{...and so on}

]}
</code>```

The Java class I want to map the JSON to is this:

```<code>public class NetStatLinkList {
    private List<NetStatLink> netStatLinks;

    // Generated getter and setter

    @Override
    public String toString(){
        return netStatLinks.toString();
    }
}
</code>```

and

```<code>public class NetStatLink {

    public String src;
    public String dst;
    public double bw;
    public double rate;
    public double usage;
    public double available;

    public NetStatLink(String src, String dst, double bw, double rate, double usage, double available){
        this.src = src;
        this.dst = dst;
        this.bw = bw;
        this.rate = rate;
        this.usage = usage;
        this.available = available;
    }

    // Generated getters and setters

    @Override
    public String toString() {
        return "Link "+src +"to"+ dst+" -- "+"rate: "+rate;
    }
}
</code>```

I can read the JSON correctly but I can't manage to map it in any way. I've tried all this options without success (note that url is an URL object created based on the url string and that all the neccessary exceptions are implicitly catched):

Using Jackson to directly map the JSON to NetStatLinkList

```<code>ObjectMapper mapper = new ObjectMapper();
NetStatLinkList linkLst = mapper.readValue(url,NetStatLinkList.class);
</code>```

Using Jackson to map the JSON to a List of NetStatLink objects

```<code>TypeReference<List<NetStatLink>> type = new TypeReference<List<NetStatLink>>() {};
List<NetStatLink> linkLst = mapper.readValue(url, mapType);
</code>```

Using Jackson to map the JSON string directly to the class/to a List of objects

```<code>JsonNode rootNode = mapper.readValue(url,JsonNode.class);
JsonNode data = rootNode.get("netStatLinks");
List<NetStatLink> linkLst = mapper.readValue(data.toString(), mapType);
// or
NetStatLink[] linkLst = mapper.readValue(data.toString(), NetStatLink[].class)
// or
List<NetStatLink> linkLst = mapper.readValue(data.traverse(), mapType);
</code>```

Using Jackson to map the JSON to an ArrayNode and iterate through it

```<code>JsonNode linkData = mapper.readTree(url);
ArrayNode linkDataArray = (ArrayNode)linkData.get("netStatLinks");
List<NetStatLink> linkLst;

while(linkDataArray.elements().hasNext()){
    linkLst.add(mapper.readValue(linkDataArray.elements().next().toString(),NetStatLink.class));
}
</code>```

Using the external library json-simple to read the JSON and then map it with Jackson

```<code>String location = IOUtils.toString(url);
JSONObject jo = (JSONObject) JSONValue.parseWithException(location);

JSONArray val = (JSONArray) jo.get("NetStatLinks");
List<NetStatLink> linkLst = mapper.readValue(val.toJSONString(), mapType);
// or
NetStatLink[] linksList = mapper.readValue(val.toJSONString(), NetStatLink[].class);
</code>```

Do you know if there's any other way I could map this JSON data to my classes, or if there's any mistake in those methods which is the reason I cannot get them to work?

答:
You can use gson</p>

```<code>    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.1</version>
    </dependency>

JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("netStatLinks");

    List<NetStatLink> users = new ArrayList<NetStatLink>();
       Gson gson = new Gson();
       Type listType = new TypeToken<List<NetStatLink>>(){}.getType();
       netStatLink = gson.fromJson(jsonArr ,listType);
</code>```

Body:
I know this question or similar ones have been asked multiple times here, but I swear I've read tons of related posts and none of the solutions seems to be working for me.

I'm trying to map some JSON data, which I receive from a specific REST API, to a Java class. The JSON has this format:

{"netStatLinks":[

{"src":"of:0000000000000002/3",
"dst":"of:0000000000000000/1",
"bw":10000.0,
"rate":0.0,
"usage":0.0,
"available":10000.0},

{"src":"of:0000000000000005/3",
"dst":"of:0000000000000006/1",
"bw":10000.0,
"rate":0.0,
"usage":0.0,
"available":10000.0},
{...and so on}

]}

The Java class I want to map the JSON to is this:

public class NetStatLinkList {
    private List<NetStatLink> netStatLinks;

    // Generated getter and setter

    @Override
    public String toString(){
        return netStatLinks.toString();
    }
}

and

public class NetStatLink {

    public String src;
    public String dst;
    public double bw;
    public double rate;
    public double usage;
    public double available;

    public NetStatLink(String src, String dst, double bw, double rate, double usage, double available){
        this.src = src;
        this.dst = dst;
        this.bw = bw;
        this.rate = rate;
        this.usage = usage;
        this.available = available;
    }

    // Generated getters and setters

    @Override
    public String toString() {
        return "Link "+src +"to"+ dst+" -- "+"rate: "+rate;
    }
}

I can read the JSON correctly but I can't manage to map it in any way. I've tried all this options without success (note that url is an URL object created based on the url string and that all the neccessary exceptions are implicitly catched):

Using Jackson to directly map the JSON to NetStatLinkList

ObjectMapper mapper = new ObjectMapper();
NetStatLinkList linkLst = mapper.readValue(url,NetStatLinkList.class);

Using Jackson to map the JSON to a List of NetStatLink objects

TypeReference<List<NetStatLink>> type = new TypeReference<List<NetStatLink>>() {};
List<NetStatLink> linkLst = mapper.readValue(url, mapType);

Using Jackson to map the JSON string directly to the class/to a List of objects

JsonNode rootNode = mapper.readValue(url,JsonNode.class);
JsonNode data = rootNode.get("netStatLinks");
List<NetStatLink> linkLst = mapper.readValue(data.toString(), mapType);
// or
NetStatLink[] linkLst = mapper.readValue(data.toString(), NetStatLink[].class)
// or
List<NetStatLink> linkLst = mapper.readValue(data.traverse(), mapType);

Using Jackson to map the JSON to an ArrayNode and iterate through it

JsonNode linkData = mapper.readTree(url);
ArrayNode linkDataArray = (ArrayNode)linkData.get("netStatLinks");
List<NetStatLink> linkLst;

while(linkDataArray.elements().hasNext()){
    linkLst.add(mapper.readValue(linkDataArray.elements().next().toString(),NetStatLink.class));
}

Using the external library json-simple to read the JSON and then map it with Jackson

String location = IOUtils.toString(url);
JSONObject jo = (JSONObject) JSONValue.parseWithException(location);

JSONArray val = (JSONArray) jo.get("NetStatLinks");
List<NetStatLink> linkLst = mapper.readValue(val.toJSONString(), mapType);
// or
NetStatLink[] linksList = mapper.readValue(val.toJSONString(), NetStatLink[].class);

Do you know if there's any other way I could map this JSON data to my classes, or if there's any mistake in those methods which is the reason I cannot get them to work?

Body:
You can use gson

    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.1</version>
    </dependency>

JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("netStatLinks");

    List<NetStatLink> users = new ArrayList<NetStatLink>();
       Gson gson = new Gson();
       Type listType = new TypeToken<List<NetStatLink>>(){}.getType();
       netStatLink = gson.fromJson(jsonArr ,listType);


问:
ExtJS 4: add success/failure callbacks to form.dom.submit() action
I have a button which creates a hidden form and calls form.dom.submit() on click. I need to add a success and failure callbacks to submit action.
Here's the code:

```<code>Ext.define("DownloadButton", {
  extend: 'Ext.button.Button',
  download: function (me, event) {
    this.form.dom.submit();
  },
  initComponent: function () {
    this.handler = Ext.Function.bind(this.download, this.scope || this);
    this.callParent(arguments);
  },
  afterRender: function () {
    this.callParent(arguments);
    this.form = this.getEl().createChild({
        tag: 'form',
        cls: 'x-hidden',
        method: 'POST',
        action: this.fileUrl,
        target: this.getId() + '-form-iframe'
    });
    this.getEl().appendChild(this.form);
  }
});
</code>```

Have tried to add params to submit

```<code>this.form.dom.submit({
  success: function(response) {
    console.log('success');
  },
  failure: function(response) {
    console.log('failure');
  }
});
</code>```

But this didn't help.

答:
https://www.sencha.com/forum/showthread.php?136662-Form-submit-doesn-t-callback-success

May be your response is not in the correct format. Check the link.

Body:
I have a button which creates a hidden form and calls form.dom.submit() on click. I need to add a success and failure callbacks to submit action.
Here's the code:

Ext.define("DownloadButton", {
  extend: 'Ext.button.Button',
  download: function (me, event) {
    this.form.dom.submit();
  },
  initComponent: function () {
    this.handler = Ext.Function.bind(this.download, this.scope || this);
    this.callParent(arguments);
  },
  afterRender: function () {
    this.callParent(arguments);
    this.form = this.getEl().createChild({
        tag: 'form',
        cls: 'x-hidden',
        method: 'POST',
        action: this.fileUrl,
        target: this.getId() + '-form-iframe'
    });
    this.getEl().appendChild(this.form);
  }
});

Have tried to add params to submit

this.form.dom.submit({
  success: function(response) {
    console.log('success');
  },
  failure: function(response) {
    console.log('failure');
  }
});

But this didn't help.


问:
How to pass long number through javascript?
I want to convert numberLong date from the mongo db database into dd/mm/yyyy format in javascript.

When I put direct hardcoded value like the following code, it gives me correct result:

```<code>function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));
</code>```

Here is my code :

```<code>for(var i=0;i<keys;i++)
                {
                var tr="<tr>";
                tr+= "<td><input type='checkbox' name='record'></td>"
                tr+="<td>"+positionList[i]["fromDate"]+"</td>";
                var j = (positionList[i]["fromDate"]);
                console.log("value of j is =========="+j);
                console.log(getDateIfDate("/Date(j)/")); // actual conversion should happen here
}
</code>```

What changes I should make in my code to get the date in required format?

答:
```<code>tr+="<td>"+positionList[i][new Date("fromDate").toLocaleString()]+"</td>";
</code>```

try to replace old line by this new one

Body:
I want to convert numberLong date from the mongo db database into dd/mm/yyyy format in javascript.

When I put direct hardcoded value like the following code, it gives me correct result:

function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));

Here is my code :

for(var i=0;i<keys;i++)
                {
                var tr="
";
                tr+= "<input type='checkbox' name='record'>	"
                tr+=""+positionList[i]["fromDate"]+"	";
                var j = (positionList[i]["fromDate"]);
                console.log("value of j is =========="+j);
                console.log(getDateIfDate("/Date(j)/")); // actual conversion should happen here
}

What changes I should make in my code to get the date in required format?

Body:
tr+="<td>"+positionList[i][new Date("fromDate").toLocaleString()]+"</td>";

try to replace old line by this new one


问:
TextView with background color and line spacing
I'd like to show the text like the below...

My coding is the following:

```<code>SpannableString sText = new SpannableString(text);
sText.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

holder.txtText.setLineSpacing(0, 1.5f);
textView.setText(sText);
</code>```

答:
It has been a long time but I'll put the static method below. Hopefully it will help another.

```<code>public static void setTextWithSpan(final TextView textView, int backgroundColor, String text, float lineSpacingMultiplier) {
    class BackgroundColorSpanWithPaddingAndLineSpacing implements LineBackgroundSpan {
        private float roundedCornerSize;
        private int backgroundColor;
        private int paddingSize;
        private RectF rect;

        private BackgroundColorSpanWithPaddingAndLineSpacing(int backgroundColor, int paddingSize, float roundedCornerSize) {
            super();
            this.backgroundColor = backgroundColor;
            this.paddingSize = paddingSize;
            this.roundedCornerSize = roundedCornerSize;
            this.rect = new RectF();
        }

        @Override
        public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int currentLineNumber) {
            final int textWidth = Math.round(p.measureText(text, start, end));
            final int paintColor = p.getColor();

            rect.set(left - paddingSize / 2, top - paddingSize / 4, left + textWidth + paddingSize / 2, top + textView.getTextSize() + paddingSize / 2);
            p.setColor(backgroundColor);
            c.drawRoundRect(rect, roundedCornerSize, roundedCornerSize, p);
            p.setColor(paintColor);
        }
    }

    int padding = textView.getPaddingLeft();
    int radius = padding / 2;

    SpannableStringBuilder builder = new SpannableStringBuilder(text);
    BackgroundColorSpanWithPaddingAndLineSpacing backgroundSpan = new BackgroundColorSpanWithPaddingAndLineSpacing(backgroundColor, padding, radius);
    builder.setSpan(backgroundSpan, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    textView.setShadowLayer(padding, 0, 0, 0);
    textView.setLineSpacing(0, lineSpacingMultiplier);

    textView.setText(builder, TextView.BufferType.SPANNABLE);
}
</code>```

Usage :

```<code>SpanUtils.setTextWithSpan(titleTv, android.graphics.Color.BLUE, textStr, 1.4f);
</code>```

I'm sure you'll manage to modify according to your needs.

Body:
I'd like to show the text like the below...

My coding is the following:

SpannableString sText = new SpannableString(text);
sText.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

holder.txtText.setLineSpacing(0, 1.5f);
textView.setText(sText);

Body:
It has been a long time but I'll put the static method below. Hopefully it will help another.

public static void setTextWithSpan(final TextView textView, int backgroundColor, String text, float lineSpacingMultiplier) {
    class BackgroundColorSpanWithPaddingAndLineSpacing implements LineBackgroundSpan {
        private float roundedCornerSize;
        private int backgroundColor;
        private int paddingSize;
        private RectF rect;

        private BackgroundColorSpanWithPaddingAndLineSpacing(int backgroundColor, int paddingSize, float roundedCornerSize) {
            super();
            this.backgroundColor = backgroundColor;
            this.paddingSize = paddingSize;
            this.roundedCornerSize = roundedCornerSize;
            this.rect = new RectF();
        }

        @Override
        public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int currentLineNumber) {
            final int textWidth = Math.round(p.measureText(text, start, end));
            final int paintColor = p.getColor();

            rect.set(left - paddingSize / 2, top - paddingSize / 4, left + textWidth + paddingSize / 2, top + textView.getTextSize() + paddingSize / 2);
            p.setColor(backgroundColor);
            c.drawRoundRect(rect, roundedCornerSize, roundedCornerSize, p);
            p.setColor(paintColor);
        }
    }

    int padding = textView.getPaddingLeft();
    int radius = padding / 2;

    SpannableStringBuilder builder = new SpannableStringBuilder(text);
    BackgroundColorSpanWithPaddingAndLineSpacing backgroundSpan = new BackgroundColorSpanWithPaddingAndLineSpacing(backgroundColor, padding, radius);
    builder.setSpan(backgroundSpan, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    textView.setShadowLayer(padding, 0, 0, 0);
    textView.setLineSpacing(0, lineSpacingMultiplier);

    textView.setText(builder, TextView.BufferType.SPANNABLE);
}

Usage :

SpanUtils.setTextWithSpan(titleTv, android.graphics.Color.BLUE, textStr, 1.4f);

I'm sure you'll manage to modify according to your needs.

ContentLicense: CC BY-SA 4.0


问:
R Function to write 3 calculated columns to a data.table
This may have already been answered, but couldn't quite find the answer I am looking for. I am trying to write the output of a function that calculates 3 variables to a data.table.

Currently I am copying the function three times (with three different names), each time returning a different variable. This is taking a lot more time as it runs thrice. I understand
there may be a better way to do it, using list or some unique data.table command.

I would greatly appreciate any input you can provide to simplify this. Below is the example of how I am calling it one variable at a time.

Example

```<code>  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_1)
  }

  data[ ,column_1 := fn_1(a,b,c,d) ,by= .(e,f) ]

  fn_2 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_2)
  }

  data[ ,column_2 := fn_2(a,b,c,d) ,by= .(e,f) ]
</code>```

答:
Does it have to be a data.table?  If not , then you can just use mutate in dplyr

```<code>a <- c(1,2,2,1,2,3,4,2)
b <- c(3,3,2,3,5,4,3,2)
c <- c(9,9,8,7,8,9,8,7)
d <- c(0,1,1,0,1,1,0,1)

have <- data.frame(a,b,c,d)

want <-
  have %>%
  mutate(abc = a+ b + c,
         db = d * b,
         aa = 2 * a)
</code>```

Body:
This may have already been answered, but couldn't quite find the answer I am looking for. I am trying to write the output of a function that calculates 3 variables to a data.table.

Currently I am copying the function three times (with three different names), each time returning a different variable. This is taking a lot more time as it runs thrice. I understand
there may be a better way to do it, using list or some unique data.table command.

I would greatly appreciate any input you can provide to simplify this. Below is the example of how I am calling it one variable at a time.

Example

  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_1)
  }

  data[ ,column_1 := fn_1(a,b,c,d) ,by= .(e,f) ]

  fn_2 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_2)
  }

  data[ ,column_2 := fn_2(a,b,c,d) ,by= .(e,f) ]

Body:
Does it have to be a data.table?  If not , then you can just use mutate in dplyr

a <- c(1,2,2,1,2,3,4,2)
b <- c(3,3,2,3,5,4,3,2)
c <- c(9,9,8,7,8,9,8,7)
d <- c(0,1,1,0,1,1,0,1)

have <- data.frame(a,b,c,d)

want <-
  have %>%
  mutate(abc = a+ b + c,
         db = d * b,
         aa = 2 * a)


问:
Filter array and cast array to different type of array
I'm building a game with GameObjects. In my game i have separated GameObjects from CollidableObject. All objects (GameObjects and CollidableGameObjects) are pushed to one single array called gameObjects.

When it comes to collision detection i wish to filter the gameObjects array so i can loop over only objects of type CollidableObject. I created the following code for this:

```<code>let temp : any = this.gameObjects.filter(g => g instanceof CollidableObject);

//optional
let collidables : Array<CollidableObject> = temp;

for (let obj1 of collidables) {
    for (let obj2 of collidables){
        if (obj1 != obj2) {
            if(obj1.hasCollision(obj2)) {
                obj1.onCollision(obj2);
                this.gameOver();
            }
        }
    }
}
</code>```

Question 1: Why is it not possible to directly filter to an array of CollidableObject?

Question 2: Is there an easier way to filter the array on a certain type?

答:
You can do this:

```<code>let temp = this.gameObjects.filter(g => g instanceof CollidableObject) as CollidableObject[];
</code>```

Or add a signature to the array interface:

```<code>interface Array<T> {
    filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[];
}
</code>```

And then:

```<code>let temp = this.gameObjects.filter<CollidableObject>(g => g instanceof CollidableObject);
</code>```

If you're using a module system (that is you are importing/exporting) then you need to augment the global module:

```<code>declare global {
    interface Array<T> {
        filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[];
    }
}
</code>```

Body:
I'm building a game with GameObjects. In my game i have separated GameObjects from CollidableObject. All objects (GameObjects and CollidableGameObjects) are pushed to one single array called gameObjects.

When it comes to collision detection i wish to filter the gameObjects array so i can loop over only objects of type CollidableObject. I created the following code for this:

let temp : any = this.gameObjects.filter(g => g instanceof CollidableObject);

//optional
let collidables : Array<CollidableObject> = temp;

for (let obj1 of collidables) {
    for (let obj2 of collidables){
        if (obj1 != obj2) {
            if(obj1.hasCollision(obj2)) {
                obj1.onCollision(obj2);
                this.gameOver();
            }
        }
    }
}

Question 1: Why is it not possible to directly filter to an array of CollidableObject?

Question 2: Is there an easier way to filter the array on a certain type?

Body:
You can do this:

let temp = this.gameObjects.filter(g => g instanceof CollidableObject) as CollidableObject[];

Or add a signature to the array interface:

interface Array<T> {
    filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[];
}

And then:

let temp = this.gameObjects.filter<CollidableObject>(g => g instanceof CollidableObject);

If you're using a module system (that is you are importing/exporting) then you need to augment the global module:

declare global {
    interface Array<T> {
        filter<S>(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): S[];
    }
}


问:
MediaScannerConnection, this syntax won't compile
I'm trying to add a file in my data directory on my sdcard to the mediastore content provider. However, I fear that I may have a java education issue on my hands. MediaScannerConnectionClient is purportedly a nested class of MediaScannerConnection, but this syntax won't compile.

Here is the link to the MediaScannerConnection API: http://developer.android.com/reference/android/media/MediaScannerConnection.html

What would be the appropriate way to reference scanner?

Thanks!

```<code>final String filename = (new File(img.uri.toString())).getAbsolutePath().substring(6);

        final MediaScannerConnection scanner = new MediaScannerConnection(this,
                new MediaScannerConnectionClient() {
                    public void onMediaScannerConnected() {
                        MediaScannerConnection.this.scanFile(filename, null /*mimeType*/);
                    }

                    public void onScanCompleted(String path, Uri uri) {
                         MediaScannerConnection.this.disconnect();
                    }
            });
        scanner.connect();
</code>```

答:
I finally found my answer in an example. </p>

<p>.../android-8/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java</p>

```<code>// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
    new String[] { filename }, null,
    new MediaScannerConnection.OnScanCompletedListener() {
    public void onScanCompleted(String path, Uri uri) {
    Log.i("ExternalStorage", "Scanned " + path + ":");
        Log.i("ExternalStorage", "-> uri=" + uri);
    }
});
</code>```

Body:
I'm trying to add a file in my data directory on my sdcard to the mediastore content provider. However, I fear that I may have a java education issue on my hands. MediaScannerConnectionClient is purportedly a nested class of MediaScannerConnection, but this syntax won't compile.

Here is the link to the MediaScannerConnection API: http://developer.android.com/reference/android/media/MediaScannerConnection.html

What would be the appropriate way to reference scanner?

Thanks!

final String filename = (new File(img.uri.toString())).getAbsolutePath().substring(6);

        final MediaScannerConnection scanner = new MediaScannerConnection(this,
                new MediaScannerConnectionClient() {
                    public void onMediaScannerConnected() {
                        MediaScannerConnection.this.scanFile(filename, null /*mimeType*/);
                    }

                    public void onScanCompleted(String path, Uri uri) {
                         MediaScannerConnection.this.disconnect();
                    }
            });
        scanner.connect();

Body:
I finally found my answer in an example.

.../android-8/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java

// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
    new String[] { filename }, null,
    new MediaScannerConnection.OnScanCompletedListener() {
    public void onScanCompleted(String path, Uri uri) {
    Log.i("ExternalStorage", "Scanned " + path + ":");
        Log.i("ExternalStorage", "-> uri=" + uri);
    }
});