问:
Asp NetCore 2 Required validation - ModelState Valid is true when in error
I'm trying to get some required field validation working in AspNetCore 2, and what I expect to happen, isn't happening.

Model

```<code>[Required(ErrorMessage = "The game name cannot be blank")]
[StringLength(100,ErrorMessage = "The game name must be between 2 and 100 characters", MinimumLength = 2)]
[Display(Name = "Name")]
public string GameName { get; set; }
</code>```

Controller

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GameDetail(GameDetail model, IFormCollection form)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // code removed for clarity
}
</code>```

View

```<code><div asp-validation-summary="ModelOnly" class="text-danger"></div>

<form class="form" method="post">
  <div class="form-group">
    <label class="form-label" asp-for="GameName"></label>
    <span asp-validation-for="GameName" class="text-danger"></span>
    <input class="form-control" asp-for="GameName" class="form-control" />
  </div>
  <div class="form-group">
    <input class="button" type="submit" value="Continue">
  </div>
</form>
</code>```

In MVC5, if this form was posted with no value entered, ModelState would be invalid and an error would be returned to the view.

However, in this instance, ModelState.IsValid is true, but the error count is 1 and the error list does show the field is required as an error.

I have tried a few things including adding [Bind("GameName")] on the post parameters against the model and also [BindRequired] on the model as well as this post: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation

Yet, the form submits and redirects to the next page (code removed for clarity) without showing any errors.

I would expect to see the view returned with the field error message showing the required error message and an error summary showing the same error.

答:
Goddamnit! Right, it was a complete and utter screw up on my part and I don't know why I didn't see this first! I coded the page with a simple form first just to get a layout sorted, so just used IFormCollection to save me writing a model

```<code>public IActionResult GameDetail(GameDetail model, IFormCollection form)
</code>```

Removed the IFormCollection form and it works exactly as I expect it to.

Body:
I'm trying to get some required field validation working in AspNetCore 2, and what I expect to happen, isn't happening.

Model

[Required(ErrorMessage = "The game name cannot be blank")]
[StringLength(100,ErrorMessage = "The game name must be between 2 and 100 characters", MinimumLength = 2)]
[Display(Name = "Name")]
public string GameName { get; set; }

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GameDetail(GameDetail model, IFormCollection form)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // code removed for clarity
}

View

<form class="form" method="post">

    <input class="form-control" asp-for="GameName" class="form-control" />

    <input class="button" type="submit" value="Continue">

</form>

In MVC5, if this form was posted with no value entered, ModelState would be invalid and an error would be returned to the view.

However, in this instance, ModelState.IsValid is true, but the error count is 1 and the error list does show the field is required as an error.

I have tried a few things including adding [Bind("GameName")] on the post parameters against the model and also [BindRequired] on the model as well as this post: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation

Yet, the form submits and redirects to the next page (code removed for clarity) without showing any errors.

I would expect to see the view returned with the field error message showing the required error message and an error summary showing the same error.

Body:
Goddamnit! Right, it was a complete and utter screw up on my part and I don't know why I didn't see this first! I coded the page with a simple form first just to get a layout sorted, so just used IFormCollection to save me writing a model

public IActionResult GameDetail(GameDetail model, IFormCollection form)

Removed the IFormCollection form and it works exactly as I expect it to.


来源: stackexchange

问:
Can't check if data exists in database
I know i post a lot of problems lately, but this one problem which i couldn't solve for about 1 week, I tried million times to check if data exists but still nothing. Searched, checked same problem but didn't get a hint. So please tell me what is wrong here. I try everything on my own but if i meet a problem i can't solve for a while. I ask here for help.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Test Title</title>
</head>
<body>
    <?php
        class Database{
            public $db;

            public function __construct($host,$username,$password,$dbname){

                $this->db=new MySQLi($host,$username,$password,$dbname);

            }
            public function getData(){
                $query="SELECT * FROM artisan";
                $result=$this->db->query($query);
                $users=array();
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                    $users[]=array(
                        "id"=>$row['id'],
                        "username"=>$row['username'],
                        "email"=>$row['email']
                        );

                    }
                }else{
                    echo "No results found!";
                }
                return $users;
            }
            public function getContent(){
                $query="SELECT * FROM content";
                $result=$this->db->query($query);
                $values=array();
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                    $values[]=array(
                        "title"=>$row['title'],
                        "body"=>$row['body']
                    );
                }

            }
            return $values;
            }

        public function insertData(){
            $title=$_POST['title'];
            $query="INSERT INTO content(title,body) VALUES (?,?)";
            $result=$this->db->query("SELECT COUNT(*) FROM content WHERE title=$title");
            $stmt=$this->db->prepare($query);
            $stmt->bind_param("ss",$_POST['title'],$_POST['body']);
            if(!empty($_POST['title']) || !empty($_POST['body'])){
            if($result->num_rows){
            echo "User allready exists";
            }else{
                    $stmt->execute();
            }
        }
        }

        private function validate(){
            $query="SELECT title and body FROM contents";
            $result=$this->db->query($query);
            if($result){
                echo "hi";
            }
        }
    }

        $database=new Database('localhost','root','','test');
        $users=$database->getData();
        $values=$database->getContent();
        $database->insertData();
     ?>

     <style type="text/css">
        .container{
            text-align:center;
        }
        table, th, td, {
            border: 1px solid black;
        }
        table{
            width:100%;
        }
        .content{
            border:1px solid black;
        }
     </style>
     <div class="container">
      <?php
        for($i=0;$i<count($values);$i++):
       ?>
    <div class="content">
        <?php echo $values[$i]["title"]."<br>"; ?>
        <?php echo $values[$i]["body"]."<br>";?>
     </div>
    <?php endfor;?>
     </div>
     <table>
  <colgroup>
    <col span="2" style="background-color:red">
    <col style="background-color:yellow">
  </colgroup>
  <tr>
    <th>ID</th>
    <th>username</th>
    <th>email</th>
  </tr>
  <tr>
    <td><?php foreach($users as $user)
    echo $user['id']."<br>";
    ?></td>
    <td><?php foreach($users as $user)
    echo $user['username']."<br>";
    ?></td>
    <td><?php foreach($users as $user)
    echo $user['email']."<br>";
    ?></td>
  </tr>
</table>
<form action="index.php" method="POST">
    <input type="text" name="title">
    <input type="text" name="body">
    <input type="submit" name="submit">
</form>
</body>
</html>
</code>```

答:
"$result=$this->db->query("SELECT title FROM content WHERE title='$title'"); just changed everything to this and it worked,$result was returning false,so i tried to solve it but i guess adding ' ' to $title solved idk why. – DummyTarget 12 mins ago"

That's because $title is a string literal and it needs to be quoted. You really should use a prepared statement for everything though, and will help safeguard against a potential SQL injection.

Reference:

https://dev.mysql.com/doc/refman/5.5/en/string-literals.html

Debugging:

http://php.net/manual/en/mysqli.error.php

http://php.net/manual/en/function.error-reporting.php

ContentLicense: CC BY-SA 3.0

Title: Can't check if data exists in database

Body:
I know i post a lot of problems lately, but this one problem which i couldn't solve for about 1 week, I tried million times to check if data exists but still nothing. Searched, checked same problem but didn't get a hint. So please tell me what is wrong here. I try everything on my own but if i meet a problem i can't solve for a while. I ask here for help.

<!DOCTYPE html>

    <title>Test Title</title>

    <?php
        class Database{
            public $db;

            public function __construct($host,$username,$password,$dbname){

                $this->db=new MySQLi($host,$username,$password,$dbname);

            }
            public function getData(){
                $query="SELECT * FROM artisan";
                $result=$this->db->query($query);
                $users=array();
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                    $users[]=array(
                        "id"=>$row['id'],
                        "username"=>$row['username'],
                        "email"=>$row['email']
                        );

                    }
                }else{
                    echo "No results found!";
                }
                return $users;
            }
            public function getContent(){
                $query="SELECT * FROM content";
                $result=$this->db->query($query);
                $values=array();
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                    $values[]=array(
                        "title"=>$row['title'],
                        "body"=>$row['body']
                    );
                }

            }
            return $values;
            }

        public function insertData(){
            $title=$_POST['title'];
            $query="INSERT INTO content(title,body) VALUES (?,?)";
            $result=$this->db->query("SELECT COUNT(*) FROM content WHERE title=$title");
            $stmt=$this->db->prepare($query);
            $stmt->bind_param("ss",$_POST['title'],$_POST['body']);
            if(!empty($_POST['title']) || !empty($_POST['body'])){
            if($result->num_rows){
            echo "User allready exists";
            }else{
                    $stmt->execute();
            }
        }
        }

        private function validate(){
            $query="SELECT title and body FROM contents";
            $result=$this->db->query($query);
            if($result){
                echo "hi";
            }
        }
    }

        $database=new Database('localhost','root','','test');
        $users=$database->getData();
        $values=$database->getContent();
        $database->insertData();
     ?>

      <?php
        for($i=0;$i<count($values);$i++):
       ?>

        <?php echo $values[$i]["title"]."
"; ?>
        <?php echo $values[$i]["body"]."
";?>

    <?php endfor;?>

  <colgroup>
    <col span="2" style="background-color:red">
    <col style="background-color:yellow">
  </colgroup>

    ID
    username
    email

    <?php foreach($users as $user)
    echo $user['id']."
";
    ?>
    <?php foreach($users as $user)
    echo $user['username']."
";
    ?>
    <?php foreach($users as $user)
    echo $user['email']."
";
    ?>

<form action="index.php" method="POST">
    <input type="text" name="title">
    <input type="text" name="body">
    <input type="submit" name="submit">
</form>


问:
hana types for template-of-templates
I am trying to generate a type that is using template-of-templates using boost::hana but ran into trouble.

I have the following classes

```<code>template<template<typename> typename BarModel>
struct Foo {
    BarModel<double> bar;
}

template<typename T>
struct BarOne {
    T x;
}

template<typename T>
struct BarTwo {
    T y;
}
</code>```

I now want to create a Foo<BarImpl> for each of the BarX<T> classes:

```<code>auto bar_types = hana::tuple_t<hana::template_t<BarOne>, hana::template_t<BarTwo>>;

hana::for_each(bar_types, [](auto t) {
    auto footype = SOMETHING(t);
});
</code>```

Problem, is I am not sure how this is supposed to be done.
My first attempt was to do

```<code>using BarT = typename decltype(t)::type;
auto bar_t = BarT(); // template_t, can create BarX<T> classes

auto foo_t = hana::template_<Foo>; // <-- FAIL
auto foo_bar_t = foo_t(bar_t);
</code>```

but this fails with a

```<code>error: type/value mismatch at argument 1 in template parameter list for ‘template<template<class ...> class F> constexpr const boost::hana::template_t<F> boost::hana::template_<F>’

note:   expected a template of type ‘template<class ...> class F’, got ‘template<template<class> class BarModel> class Foo’
</code>```

The note suggests that hana::template_ does not work with template-of-templates.
Is this the case? If so, is there an alternative solution?

答:
Boost.Hana does not support this directly, but implementing it for this case is just a few lines of code.

Check it out:

```<code>#include <boost/hana.hpp>

namespace hana = boost::hana;

template <template <template <typename...> class> class F>
struct template_template_t
{
  template <template <typename...> class G>
  constexpr auto operator()(hana::basic_type<hana::template_t<G>>) const
    -> hana::type<F<G>>
  { return {}; }
};

template <template <template <typename...> class> class F>
constexpr auto template_template = template_template_t<F>{};

/*****/

template <template <typename...> class BarModel>
struct Foo {
  BarModel<double> bar;
};

template <typename T>
struct BarOne {
  T x;
};

template <typename T>
struct BarTwo {
  T y;
};

int main() {
  constexpr auto bar_types = hana::tuple_t<hana::template_t<BarOne>, hana::template_t<BarTwo>>;

  BOOST_HANA_CONSTANT_ASSERT(hana::equal(
    hana::transform(bar_types, template_template<Foo>)
  , hana::tuple_t<Foo<BarOne>, Foo<BarTwo>>
  ));
}
</code>```

Title: hana types for template-of-templates

Body:
I am trying to generate a type that is using template-of-templates using boost::hana but ran into trouble.

I have the following classes

template<template<typename> typename BarModel>
struct Foo {
    BarModel<double> bar;
}

template<typename T>
struct BarOne {
    T x;
}

template<typename T>
struct BarTwo {
    T y;
}

I now want to create a Foo<BarImpl> for each of the BarX<T> classes:

auto bar_types = hana::tuple_t<hana::template_t<BarOne>, hana::template_t<BarTwo>>;

hana::for_each(bar_types, [](auto t) {
    auto footype = SOMETHING(t);
});

Problem, is I am not sure how this is supposed to be done.
My first attempt was to do

using BarT = typename decltype(t)::type;
auto bar_t = BarT(); // template_t, can create BarX<T> classes

auto foo_t = hana::template_<Foo>; // <-- FAIL
auto foo_bar_t = foo_t(bar_t);

but this fails with a

error: type/value mismatch at argument 1 in template parameter list for ‘template<template<class ...> class F> constexpr const boost::hana::template_t<F> boost::hana::template_<F>’

note:   expected a template of type ‘template<class ...> class F’, got ‘template<template<class> class BarModel> class Foo’

The note suggests that hana::template_ does not work with template-of-templates.
Is this the case? If so, is there an alternative solution?

Body:
Boost.Hana does not support this directly, but implementing it for this case is just a few lines of code.

Check it out:

#include <boost/hana.hpp>

namespace hana = boost::hana;

template <template <template <typename...> class> class F>
struct template_template_t
{
  template <template <typename...> class G>
  constexpr auto operator()(hana::basic_type<hana::template_t<G>>) const
    -> hana::type<F<G>>
  { return {}; }
};

template <template <template <typename...> class> class F>
constexpr auto template_template = template_template_t<F>{};

/*****/

template <template <typename...> class BarModel>
struct Foo {
  BarModel<double> bar;
};

template <typename T>
struct BarOne {
  T x;
};

template <typename T>
struct BarTwo {
  T y;
};

int main() {
  constexpr auto bar_types = hana::tuple_t<hana::template_t<BarOne>, hana::template_t<BarTwo>>;

  BOOST_HANA_CONSTANT_ASSERT(hana::equal(
    hana::transform(bar_types, template_template<Foo>)
  , hana::tuple_t<Foo<BarOne>, Foo<BarTwo>>
  ));
}


问:
Implicit argument in constructor vs method signature
What difference does the compiler see in BroFinder1 and BroFinder2 that causes the first one to fail? I really need BroFinder1 to work as it is without utilizing patterns such as Aux Pattern.

trait Brother[I] {
  type Bro
  def get: Bro
}

class Foo
object Foo {
  implicit object bro extends Brother[Foo] {
    override type Bro = Bar

    override def get = new Bar
  }
}

class Bar {
  def barSpecificAction(): Unit = ()
}

class BroFinder1[I](implicit val b: Brother[I]) {
  def brotherOf: b.Bro = b.get
}

class BroFinder2[I] {
  def brotherOf(implicit b: Brother[I]): b.Bro = b.get
}

new BroFinder1[Foo].brotherOf.barSpecificAction() // Doesn't compile
//error: Error:(73, 32) value barSpecificAction is not a member of _1.b.Bro
//new BroFinder1[Foo].brotherOf.barSpecificAction();
                          ^
new BroFinder2[Foo].brotherOf.barSpecificAction() // Ok

//scala version: 2.12.4
```

答:
This is not a perfect answer but probably will provide some insights. The issue seems to be not related to implicit at all. It seems to be related to another fairly advance Scala feature: path-dependent types. Particularly the trouble seems to come from the fact that Scala type system is not powerful enough to express type difference between finder1 and finder2 precisely in following code:

```<code>object Foo {

  implicit object bro extends Brother[Foo] {
    override type Bro = Bar

    override def get = new Bar
  }

  object bro2 extends Brother[Foo] {
    override type Bro = Foo

    override def get = new Foo
  }

}

val finder1 = new BroFinder1[Foo]
val finder2 = new BroFinder1[Foo]()(Foo.bro2)
val bof1 = finder1.brotherOf
val bof2 = finder2.brotherOf
</code>```

Sidenote: the fact that some parameter is implicit doesn't make it a "constant" because you can always pass the parameter explicitly anyway or you can have different visible implicit values in different contexts.

AFAIU the most precis type the finder1 or finder2 might be assigned in this example is just BroFinder1[Foo]. Particularly there is no way to catch different values of the b implicit variable and thus there is no way to pass further exactly the value of the path-dependent type that is encoded inside that value. Thus the best compiler knows about the types of bof1 and bof2 is that they both have type in form of _1.b.Bro where _1 means some particular instance of BroFinder1[Foo]. And so the compiler can't be sure that bof1 is actually of type Bar while bof2 is of type Foo.

The second example works because implicit parameter is captured in the same context so compiler knows exactly what the result type of brotherOf is.

The only workaround I know is not exactly suitable in your case: use "Aux" type. If your BroFinder took also an explicit parameter of type Foo, the solution might have looked like this:

```<code>type BrotherAux[I, B] = Brother[I] {type Bro = B}

class BroFinder3[I, B](val v: I)(implicit val b: BrotherAux[I, B]) {
  def brotherOf: B = b.get
}

new BroFinder3(new Foo).brotherOf.barSpecificAction()
</code>```

But in your case it has to be much less helpful

```<code>class BroFinder1[I, B](implicit val b: BrotherAux[I, B]) {
  def brotherOf: B = b.get
}

new BroFinder1[Foo, Bar].brotherOf.barSpecificAction()
</code>```

Body:
This is not a perfect answer but probably will provide some insights. The issue seems to be not related to implicit at all. It seems to be related to another fairly advance Scala feature: path-dependent types. Particularly the trouble seems to come from the fact that Scala type system is not powerful enough to express type difference between finder1 and finder2 precisely in following code:

object Foo {

  implicit object bro extends Brother[Foo] {
    override type Bro = Bar

    override def get = new Bar
  }

  object bro2 extends Brother[Foo] {
    override type Bro = Foo

    override def get = new Foo
  }

}

val finder1 = new BroFinder1[Foo]
val finder2 = new BroFinder1[Foo]()(Foo.bro2)
val bof1 = finder1.brotherOf
val bof2 = finder2.brotherOf

Sidenote: the fact that some parameter is implicit doesn't make it a "constant" because you can always pass the parameter explicitly anyway or you can have different visible implicit values in different contexts.

AFAIU the most precis type the finder1 or finder2 might be assigned in this example is just BroFinder1[Foo]. Particularly there is no way to catch different values of the b implicit variable and thus there is no way to pass further exactly the value of the path-dependent type that is encoded inside that value. Thus the best compiler knows about the types of bof1 and bof2 is that they both have type in form of _1.b.Bro where _1 means some particular instance of BroFinder1[Foo]. And so the compiler can't be sure that bof1 is actually of type Bar while bof2 is of type Foo.

The second example works because implicit parameter is captured in the same context so compiler knows exactly what the result type of brotherOf is.

The only workaround I know is not exactly suitable in your case: use "Aux" type. If your BroFinder took also an explicit parameter of type Foo, the solution might have looked like this:

type BrotherAux[I, B] = Brother[I] {type Bro = B}

class BroFinder3[I, B](val v: I)(implicit val b: BrotherAux[I, B]) {
  def brotherOf: B = b.get
}

new BroFinder3(new Foo).brotherOf.barSpecificAction()

But in your case it has to be much less helpful

class BroFinder1[I, B](implicit val b: BrotherAux[I, B]) {
  def brotherOf: B = b.get
}

new BroFinder1[Foo, Bar].brotherOf.barSpecificAction()


问:
merging 2 nested lists in prolog
I am trying to merge 2 nested lists L1 and L2 into a nested list L3, so far this is what I have and it seems to not work:

```<code>merge(L,[],L).
merge([],K,K).
merge([X|L],[Y|K],[X|M]) :- X < Y, merge(L,[Y|K],M).
merge([X|L],[Y|K],[Y|M]) :- X >= Y, merge([X|L],K,M).
</code>```

Expected behaviour:

```<code>?- merge([2,[2,3],[4,5,[5,6,7]]], [[5,[4,3],[2,1]],6,[7,8]], L3).
L3 = [[10, [8,6], [4,2]], [12, 18], [28, 40, [5, 6, 7]]]
</code>```

The trickiest part for me is maintaining the structure.

Thanks in advance!

答:
This seems to work:</p>

```<code>merge([X|L],[Y|K],[Z|M]) :-
  ( is_list(X), is_list(Y) ->
    merge(X,Y,Z)
  ; is_list(X) ->
    scale(Y,X,Z)
  ; is_list(Y) ->
    scale(X,Y,Z)
  ; Z is X * Y ),
  merge(L,K,M).
merge(L,[],L) :- L \= [].
merge([],K,K) :- K \= [].
merge([],[],[]).

scale(F,[H0|T0],[H|T]) :-
  ( is_list(H0) ->
    scale(F,H0,H)
  ; H is F * H0 ),
  scale(F,T0,T).
scale(_,[],[]).
</code>```

Title: merging 2 nested lists in prolog

Body:
I am trying to merge 2 nested lists L1 and L2 into a nested list L3, so far this is what I have and it seems to not work:

merge(L,[],L).
merge([],K,K).
merge([X|L],[Y|K],[X|M]) :- X < Y, merge(L,[Y|K],M).
merge([X|L],[Y|K],[Y|M]) :- X >= Y, merge([X|L],K,M).

Expected behaviour:

?- merge([2,[2,3],[4,5,[5,6,7]]], [[5,[4,3],[2,1]],6,[7,8]], L3).
L3 = [[10, [8,6], [4,2]], [12, 18], [28, 40, [5, 6, 7]]]

The trickiest part for me is maintaining the structure.

Thanks in advance!

Body:
This seems to work:

merge([X|L],[Y|K],[Z|M]) :-
  ( is_list(X), is_list(Y) ->
    merge(X,Y,Z)
  ; is_list(X) ->
    scale(Y,X,Z)
  ; is_list(Y) ->
    scale(X,Y,Z)
  ; Z is X * Y ),
  merge(L,K,M).
merge(L,[],L) :- L \= [].
merge([],K,K) :- K \= [].
merge([],[],[]).

scale(F,[H0|T0],[H|T]) :-
  ( is_list(H0) ->
    scale(F,H0,H)
  ; H is F * H0 ),
  scale(F,T0,T).
scale(_,[],[]).


问:
How to start a new process without administrator privileges from a process with administrator privileges?
I am creating an automatic updater for an application. The application is started by the user, and runs without administrator privileges. The autoupdater is started with administrator privileges, and kills the application before it downloads the new files.

The problem comes when I want to start the updated application after the autoupdater is finished. If I use regular System.Diagnostics.Process.Start(file), the application starts with administrator privileges too, and it has to run on the current user to work as intended.

So, how can I make the autoupdater start the application as the current user instead of the administrator?

I have tried using the following:

```<code>var pSI = new ProcessStartInfo() {
    UseShellExecute = false,
    UserName = Environment.UserName,
    FileName = file
};
System.Diagnostics.Process.Start(pSI);
</code>```

But this throws the error "Invalid user name or password". I have checked that the username is correct, and I understand that the password probably is invalid, as I have not included it. But it is not an option to ask the user to input his/her password, since the entire reason to start the application automatically is to make it easier for the user.

Any suggestions?

答:
This is a really old question that I saw years ago and have revisited now. Since its the first google search result... I'll post my answer here.

All the solutions that I have found are extremely complex and ridiculous. Over the years I have stumbled upon a solution that I have not seen documented anywhere, and haven't really shared until now.

The code is very simple... Essentially we are writing a batch file with the name/path of the executable of the process you want to run, with whatever arguments you want. Then we spawn an explorer.exe process with the path to the batch file...

```<code>File.WriteAllText(@"C:\test.bat", @"C:\test.exe -randomArgs");

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "explorer.exe",
        Arguments = @"C:\test.bat",
        UseShellExecute = true,
        Verb = "runas",
        WindowStyle = ProcessWindowStyle.Hidden
    }
};
proc.Start();
</code>```

The explorer process that we spawn is immediately killed off by the operating system, However! The root explorer.exe process running runs the batch file! You can give explorer.exe the name of your executable and it will do the same thing, however that method does not support arguments.

For all I know this is a bug or undocumented feature. However I cannot imagine how it could be used maliciously, as it allows de-elevation of permissions... This works in windows 7/8/8.1/10.

Body:
I am creating an automatic updater for an application. The application is started by the user, and runs without administrator privileges. The autoupdater is started with administrator privileges, and kills the application before it downloads the new files.

The problem comes when I want to start the updated application after the autoupdater is finished. If I use regular System.Diagnostics.Process.Start(file), the application starts with administrator privileges too, and it has to run on the current user to work as intended.

So, how can I make the autoupdater start the application as the current user instead of the administrator?

I have tried using the following:

var pSI = new ProcessStartInfo() {
    UseShellExecute = false,
    UserName = Environment.UserName,
    FileName = file
};
System.Diagnostics.Process.Start(pSI);

But this throws the error "Invalid user name or password". I have checked that the username is correct, and I understand that the password probably is invalid, as I have not included it. But it is not an option to ask the user to input his/her password, since the entire reason to start the application automatically is to make it easier for the user.

Any suggestions?

Body:
This is a really old question that I saw years ago and have revisited now. Since its the first google search result... I'll post my answer here.

All the solutions that I have found are extremely complex and ridiculous. Over the years I have stumbled upon a solution that I have not seen documented anywhere, and haven't really shared until now.

The code is very simple... Essentially we are writing a batch file with the name/path of the executable of the process you want to run, with whatever arguments you want. Then we spawn an explorer.exe process with the path to the batch file...

File.WriteAllText(@"C:\test.bat", @"C:\test.exe -randomArgs");

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "explorer.exe",
        Arguments = @"C:\test.bat",
        UseShellExecute = true,
        Verb = "runas",
        WindowStyle = ProcessWindowStyle.Hidden
    }
};
proc.Start();

The explorer process that we spawn is immediately killed off by the operating system, However! The root explorer.exe process running runs the batch file! You can give explorer.exe the name of your executable and it will do the same thing, however that method does not support arguments.

For all I know this is a bug or undocumented feature. However I cannot imagine how it could be used maliciously, as it allows de-elevation of permissions... This works in windows 7/8/8.1/10.


问:
SQL Union on the Join subsets
I've got a specific requirement where the backend is supposed to send records that match on a certain criteria from a table. There is a version table that basically contains
[id, ..., modstamp, deleted]
The requirement is to get the records that match between timestamp t1 and t2.
I think I could explain with respect to the sql script:

```<code>create table test (id varchar(10), cv_modstamp DATETIMEOFFSET, sf_deleteddate DATETIMEOFFSET);
insert into test values ('aaa', '2017-10-27 18:45:44 +00:00', null);
insert into test values ('bbb', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('eee', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('aaa', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('bbb', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
insert into test values ('ccc', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('ddd', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
select * from test;

select D1.*, D2.* from
(
select A.*
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
    AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   A.SF_Deleteddate IS NULL
 )
D2 ON D1.ID = D2.ID
</code>```

This gives out the response:

```<code>aaa 2017-10-28 22:45:44 +00:00      aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00      eee 2017-10-27 18:45:44 +00:00
</code>```

But what is required is:

```<code>aaa 2017-10-28 22:45:44 +00:00
aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
</code>```

Is there a way to display the joined sets on union?

Edit:
Thanks all for the solutions. Each one is good enough for SQL Server. I wanted this to be achieved in a single query. Might be porting similar queries to other database flavors too.

Edit2:
What if the entire columnset have to be selected?

This can be achieved with CTE queries

```<code>with subset1 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)
, subset2 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp > '2017-10-27 18:45:44 +00:00'
            AND CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)

select subset1.* from subset1, subset2 where subset1.id = subset2.id
union all
select subset2.* from subset1, subset2 where subset1.id = subset2.id
order by id, cv_modstamp;
</code>```

答:
I reused your query and stored it in a table temp1 using which UNION ALL was done.

```<code>select * into temp1 from (
select D1.*, D2.* from
(
select A.id as A_id, A.cv_modstamp as A_cv_modstamp,  A.sf_deleteddate as A_sf_deleteddate
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select B.id as B_id, B.cv_modstamp as B_cv_modstamp,  B.sf_deleteddate as B_sf_deleteddate
    FROM TEST B, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE B.id = T.T_ALIAS_ID
    AND   B.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   B.SF_Deleteddate IS NULL
 )
D2 ON D1.A_ID = D2.B_ID ) as tt;

select * from temp1;

select A_id, A_cv_modstamp from temp1
UNION ALL
select B_id, B_cv_modstamp from temp1
order by A_id;
</code>```

Title: SQL Union on the Join subsets

Body:
I've got a specific requirement where the backend is supposed to send records that match on a certain criteria from a table. There is a version table that basically contains
[id, ..., modstamp, deleted]
The requirement is to get the records that match between timestamp t1 and t2.
I think I could explain with respect to the sql script:

create table test (id varchar(10), cv_modstamp DATETIMEOFFSET, sf_deleteddate DATETIMEOFFSET);
insert into test values ('aaa', '2017-10-27 18:45:44 +00:00', null);
insert into test values ('bbb', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('eee', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('aaa', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('bbb', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
insert into test values ('ccc', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('ddd', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
select * from test;

select D1.*, D2.* from
(
select A.*
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
    AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   A.SF_Deleteddate IS NULL
 )
D2 ON D1.ID = D2.ID

This gives out the response:

aaa 2017-10-28 22:45:44 +00:00      aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00      eee 2017-10-27 18:45:44 +00:00

But what is required is:

aaa 2017-10-28 22:45:44 +00:00
aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00

Is there a way to display the joined sets on union?

Edit:
Thanks all for the solutions. Each one is good enough for SQL Server. I wanted this to be achieved in a single query. Might be porting similar queries to other database flavors too.

Edit2:
What if the entire columnset have to be selected?

This can be achieved with CTE queries

with subset1 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)
, subset2 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp > '2017-10-27 18:45:44 +00:00'
            AND CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)

select subset1.* from subset1, subset2 where subset1.id = subset2.id
union all
select subset2.* from subset1, subset2 where subset1.id = subset2.id
order by id, cv_modstamp;

Body:
I reused your query and stored it in a table temp1 using which UNION ALL was done.

select * into temp1 from (
select D1.*, D2.* from
(
select A.id as A_id, A.cv_modstamp as A_cv_modstamp,  A.sf_deleteddate as A_sf_deleteddate
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select B.id as B_id, B.cv_modstamp as B_cv_modstamp,  B.sf_deleteddate as B_sf_deleteddate
    FROM TEST B, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE B.id = T.T_ALIAS_ID
    AND   B.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   B.SF_Deleteddate IS NULL
 )
D2 ON D1.A_ID = D2.B_ID ) as tt;

select * from temp1;

select A_id, A_cv_modstamp from temp1
UNION ALL
select B_id, B_cv_modstamp from temp1
order by A_id;


问:
parsing json data from alpha vantage
I am new to Ajax and JSON. I am facing issues with the parsing of Json data from the Alpha Vantage API. My project is to create a stock widget using the jive platform in a html5 widget and I have existing code using the yahoo finance api. The yahoo api url is no longer working and I found another api that is working and giving me json data. I have tried to work with the existing code but the trouble I am stumbling on is how to parse the code from json data to the html.

Also console is giving me the following error for the first line of the json data so I added a callback to the url thinking it would fix it
Uncaught SyntaxError: Unexpected token :

 (common stock)

Retrieving stock information...

        Price

        $

        Change

        Volume

        Average Daily Volume

        52 Week Range

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

<p>This is the json info</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "0787.HK",
        "3. Last Refreshed": "2017-12-07",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2017-12-07": {
            "1. open": "0.6700",
            "2. high": "0.6800",
            "3. low": "0.6600",
            "4. close": "0.6600",
            "5. volume": "20488001"
        }
        // More rows
    }
}</code>```

What am i doing wrong and how do I do this correctly?

答:
Remove &callback=? from

```<code>var theURL = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=0787.HK&interval=1min&apikey=AOIAMG3WFZ8LS58W&callback=?";
</code>```

and change dataType :"jsonp" to dataType :"json".

var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=0787.HK&interval=1min&apikey=AOIAMG3WFZ8LS58W';

jQuery.ajax({
    url: url,
    dataType: 'json',
    contentType: "application/json",
    success: function(data){
      console.log(data);
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: parsing json data from alpha vantage

Body:
I am new to Ajax and JSON. I am facing issues with the parsing of Json data from the Alpha Vantage API. My project is to create a stock widget using the jive platform in a html5 widget and I have existing code using the yahoo finance api. The yahoo api url is no longer working and I found another api that is working and giving me json data. I have tried to work with the existing code but the trouble I am stumbling on is how to parse the code from json data to the html.

Also console is giving me the following error for the first line of the json data so I added a callback to the url thinking it would fix it
Uncaught SyntaxError: Unexpected token :

 (common stock)

Retrieving stock information...

        Price

        $

        Change

        Volume

        Average Daily Volume

        52 Week Range

This is the json info

{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "0787.HK",
        "3. Last Refreshed": "2017-12-07",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2017-12-07": {
            "1. open": "0.6700",
            "2. high": "0.6800",
            "3. low": "0.6600",
            "4. close": "0.6600",
            "5. volume": "20488001"
        }
        // More rows
    }
}

What am i doing wrong and how do I do this correctly?

Body:
Remove &callback=? from

var theURL = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=0787.HK&interval=1min&apikey=AOIAMG3WFZ8LS58W&callback=?";

and change dataType :"jsonp" to dataType :"json".

var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=0787.HK&interval=1min&apikey=AOIAMG3WFZ8LS58W';

jQuery.ajax({
    url: url,
    dataType: 'json',
    contentType: "application/json",
    success: function(data){
      console.log(data);
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
How does the Entity.DbSet.Find() method work in MVC3 context?
I'm following the MVC3 Music Store tutorial and this line of code kind of confuses me.

```<code>public ActionResult Details(int id)
{
    var album = storeDb.Albums.Find(id);
    return View(album);
}
</code>```

Here is the Album.cs model:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcMusicStore.ViewModels
{
    public class Album
    {
        public int AlbumId { get; set; }
        public int GenreId { get; set; }
        public int ArtistId { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string AlbumArtUrl { get; set; }
        public Genre Genre { get; set; }
    }
}
</code>```

When I visit the /Details/5 URL, how does it know to map the 'id' parameter to the Album's AlbumId attribute?

Thanks for the help.

答: Find is a method of DbSet, it finds an object in the DbSet based on its id. It knows the id from the mappings you declared for this class.

OwnerDisplayName: delete

LastEditorDisplayName: delete

ContentLicense: CC BY-SA 2.5

Body:
I'm following the MVC3 Music Store tutorial and this line of code kind of confuses me.

public ActionResult Details(int id)
{
    var album = storeDb.Albums.Find(id);
    return View(album);
}

Here is the Album.cs model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcMusicStore.ViewModels
{
    public class Album
    {
        public int AlbumId { get; set; }
        public int GenreId { get; set; }
        public int ArtistId { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string AlbumArtUrl { get; set; }
        public Genre Genre { get; set; }
    }
}

When I visit the /Details/5 URL, how does it know to map the 'id' parameter to the Album's AlbumId attribute?

Thanks for the help.


问:
Understanding about templates and function pointer

I would like to know Why have to make fun1() as static member function? function pointer in template? in below piece of code.

```<code>#include<iostream>
using namespace std;
class A
{
    int temp;
    public:
    A():temp(1){}
    template<class T, void (*fn)(T* )>
    static void create(T *ptr)
    {
        cout <<"create fn"<<endl;
        //fun1(ptr);
    }
    static void fun1(A* tp)
    {
         cout<<"func temp"<<endl;
    }
    static void fun2(A& ob)
    {
        cout<<"fun2 start"<<endl;
        A::create<A,&A::fun1>(&ob);
        cout<<"fun2 end"<<endl;
    }
};
int main()
{
    A ob,ob1;
    ob.fun2(ob1);
}
</code>```

答:
A static function member of a class is simply a regular function in the class's namespace:

Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.

cppreference.com

In your example, the type of A::f1 would be void(A*) and the type of A::f2 would be void(A&). Notably, static functions do not need an instance to be called.

Alternatively, non-static member functions do require an instance to be called. You would have to use pointers to class members. In your example, you would use &A::f1 and &A::f2 and their types would be (void)A::*f1(A*) and (void)A::*f2(A&) respectively. If pointers to member functions were treated as regular function pointers, how would they be called? They would need an object instance for the this pointer to point to.

You can convert a pointer to a member function to an object that overloads the () operator and behaves like a function (AKA a functor) using std::bind:

```<code>A a;
std::bind(&A::f1, &a); // &a is the value of this
</code>```

However, functors do not have the same type as function pointers. I recommend using std::function in the functional header file instead of function pointers because they accommodate for functors.

(See http://en.cppreference.com/w/cpp/language/pointer for more information.)

Body:
I would like to know Why have to make fun1() as static member function? function pointer in template? in below piece of code.

#include<iostream>
using namespace std;
class A
{
    int temp;
    public:
    A():temp(1){}
    template<class T, void (*fn)(T* )>
    static void create(T *ptr)
    {
        cout <<"create fn"<<endl;
        //fun1(ptr);
    }
    static void fun1(A* tp)
    {
         cout<<"func temp"<<endl;
    }
    static void fun2(A& ob)
    {
        cout<<"fun2 start"<<endl;
        A::create(&ob);
        cout<<"fun2 end"<<endl;
    }
};
int main()
{
    A ob,ob1;
    ob.fun2(ob1);
}

Body:
A static function member of a class is simply a regular function in the class's namespace:

Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.

cppreference.com

In your example, the type of A::f1 would be void(A*) and the type of A::f2 would be void(A&). Notably, static functions do not need an instance to be called.

Alternatively, non-static member functions do require an instance to be called. You would have to use pointers to class members. In your example, you would use &A::f1 and &A::f2 and their types would be (void)A::*f1(A*) and (void)A::*f2(A&) respectively. If pointers to member functions were treated as regular function pointers, how would they be called? They would need an object instance for the this pointer to point to.

You can convert a pointer to a member function to an object that overloads the () operator and behaves like a function (AKA a functor) using std::bind:

A a;
std::bind(&A::f1, &a); // &a is the value of this

However, functors do not have the same type as function pointers. I recommend using std::function in the functional header file instead of function pointers because they accommodate for functors.

(See http://en.cppreference.com/w/cpp/language/pointer for more information.)


问:
Logical operator with different types
I'm trying to solve the famous FizzBuzz quiz but I decided to use the logical operator or instead of else to provide fullback.

for (var num = 1; num <= 100; num++) {
  var output;
 if (num % 5 === 0 && num % 3 === 0) {
     output = "FizzBuzz";
    } else if (num % 5 === 0) {
     output = "Buzz";
    } else if (num % 3 === 0) {
     output = "Fizz";
    }
  console.log(output || num);
}```

This was supposed to print all the numbers from 1 to 100, with some exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5, print "Buzz" instead and "FizzBuzz", for numbers that are divisible by both 3 and 5.

But it doesn't print any numbers.

答:
The output declaration could be num like :

```<code>var output = num;
</code>```

So you don"t have to use the || operator and just print the output directly :

```<code>console.log(output);
</code>```

for (var num = 1; num <= 100; num++) {
  var output = num;
 if (num % 5 === 0 && num % 3 === 0) {
     output = "FizzBuzz";
    } else if (num % 5 === 0) {
     output = "Buzz";
    } else if (num % 3 === 0) {
     output = "Fizz";
    }
  console.log(output);
}```

Title: Logical operator with different types

Body:
I'm trying to solve the famous FizzBuzz quiz but I decided to use the logical operator or instead of else to provide fullback.

for (var num = 1; num <= 100; num++) {
  var output;
 if (num % 5 === 0 && num % 3 === 0) {
     output = "FizzBuzz";
    } else if (num % 5 === 0) {
     output = "Buzz";
    } else if (num % 3 === 0) {
     output = "Fizz";
    }
  console.log(output || num);
}

This was supposed to print all the numbers from 1 to 100, with some exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5, print "Buzz" instead and "FizzBuzz", for numbers that are divisible by both 3 and 5.

But it doesn't print any numbers.

Body:
The output declaration could be num like :

var output = num;

So you don"t have to use the || operator and just print the output directly :

console.log(output);

for (var num = 1; num <= 100; num++) {
  var output = num;
 if (num % 5 === 0 && num % 3 === 0) {
     output = "FizzBuzz";
    } else if (num % 5 === 0) {
     output = "Buzz";
    } else if (num % 3 === 0) {
     output = "Fizz";
    }
  console.log(output);
}


问:
Pass multiple arguments to helper from Meteor template?
this is my problem:
I have an Array of Array: allAnswers and I want to display its rows in a table.
The problem is that I want to pass a value while I'm calling it to set the right row in the right position of the table.
I've try this but it still not works.

HTML file in template name= body

```<code><table>
    <tr>
       <th>Week/Questions</th>
       <th>Q1</th>
       <th>Q2</th>
       <th>Q3</th>
       <th>Q4</th>
     </tr>
     <tr>
       <td>Week</td>
       <td>{{allAnswers "0"}}</td>
       <td>{{allAnswers "1"}}</td>
       <td>{{allAnswers "2"}}</td>
       <td>{{allAnswers "3"}}</td>
    </tr>
</table>
</code>```

JS File

```<code>Template.body.helpers({
  allAnswers: function(N) {
      var i=N;
      for(i=0;i<10;i++){
            var allAnswers(i)=[];
            for(var j=0; j<4; j++){
                allAnswers(i)[j+1] = Quests.find({ userId: this._id, answer: { $exists: true }}).map((el) => el.answer[j]);
                alert(allAnswers(i)[j]);
                return allAnswer(i)[j];
            }
      }
  }
});
</code>```

答:
I'd recommend changing tack and using loop helpers in Blaze to build the table like so:

```<code><table>
    <tr>
       <th>Week/Questions</th>
       <th>Q1</th>
       <th>Q2</th>
       <th>Q3</th>
       <th>Q4</th>
     </tr>

     {{#each week in quests}}
     <tr>
       <td>Week</td>
       {{#each answer in week}}
         <td>{{answer}}</td>
       {{/each}}
    </tr>
    {{/each}}
</table>
</code>```

JS File

```<code>Template.body.helpers({
  quests() {
    return Quests.find({
      userId: Meteor.user(),
      answer: { $exists: true }
    });
  }
});
</code>```

The idea being that your helper returns the data cursor once, and then your template is responsible for structuring that data visually on the page.

The other approach would be to build your two dimensional array in Template.body.onCreated and then reference the data from there. This would disable any reactivity and so the table won't update when the underlying data changes.

Important to note that helpers are run every time they are referenced in the template as well as every time a reactive data source they use changes (in this case, the Quests collection).

Also a minor note that userId checks should be done in the data publication on the server side. The Meteor tutorial has more information about that.

I also strongly recommend this article if you are getting confused about data flow in Meteor:
https://medium.com/meteor-js/data-flow-from-the-database-to-the-ui-three-layers-of-meteor-d5e208b466c3

Body:
this is my problem:
I have an Array of Array: allAnswers and I want to display its rows in a table.
The problem is that I want to pass a value while I'm calling it to set the right row in the right position of the table.
I've try this but it still not works.

HTML file in template name= body

       Week/Questions
       Q1
       Q2
       Q3
       Q4

       Week
       {{allAnswers "0"}}
       {{allAnswers "1"}}
       {{allAnswers "2"}}
       {{allAnswers "3"}}

JS File

Template.body.helpers({
  allAnswers: function(N) {
      var i=N;
      for(i=0;i<10;i++){
            var allAnswers(i)=[];
            for(var j=0; j<4; j++){
                allAnswers(i)[j+1] = Quests.find({ userId: this._id, answer: { $exists: true }}).map((el) => el.answer[j]);
                alert(allAnswers(i)[j]);
                return allAnswer(i)[j];
            }
      }
  }
});

Body:
I'd recommend changing tack and using loop helpers in Blaze to build the table like so:

<table>
    <tr>
       <th>Week/Questions</th>
       <th>Q1</th>
       <th>Q2</th>
       <th>Q3</th>
       <th>Q4</th>
     </tr>

     {{#each week in quests}}
     <tr>
       <td>Week</td>
       {{#each answer in week}}
         <td>{{answer}}</td>
       {{/each}}
    </tr>
    {{/each}}
</table>

JS File

Template.body.helpers({
  quests() {
    return Quests.find({
      userId: Meteor.user(),
      answer: { $exists: true }
    });
  }
});

The idea being that your helper returns the data cursor once, and then your template is responsible for structuring that data visually on the page.

The other approach would be to build your two dimensional array in Template.body.onCreated and then reference the data from there. This would disable any reactivity and so the table won't update when the underlying data changes.

Important to note that helpers are run every time they are referenced in the template as well as every time a reactive data source they use changes (in this case, the Quests collection).

Also a minor note that userId checks should be done in the data publication on the server side. The Meteor tutorial has more information about that.

I also strongly recommend this article if you are getting confused about data flow in Meteor:
https://medium.com/meteor-js/data-flow-from-the-database-to-the-ui-three-layers-of-meteor-d5e208b466c3


问:
Calculate the date difference in the given format in PHP4
I need a function in php4 that will calculate the date difference in the provided date format.
eg.

```<code>$date1 = "2011-08-24 10:03:00";
$date2 = "2012-09-24 10:04:31";
$format1 = "Y W" ; //This format should return the difference in Year and week.
$format2 = "M D"; // This format should return the difference in Months and days.
// The format can be any combination of Year,Month,Day,Week,Hour,Minute,Second.

function ConvertDate($data1,$date2,$format)
</code>```

Please let me know if you need any more details on this.
Thanks in advance.

答:
Get Unix timestamps of your dates using mktime. Then you get the difference for:

```<code>$years = floor(($date2-$date1)/31536000);
$months = floor(($date2-$date1)/2628000);
$days = floor(($date2-$date1)/86400);
$hours = floor(($date2-$date1)/3600);
$minutes = floor(($date2-$date1)/60);
$seconds = ($date2-$date1);
</code>```

Hope this helps.

—Alberto

Body:
I need a function in php4 that will calculate the date difference in the provided date format.
eg.

$date1 = "2011-08-24 10:03:00";
$date2 = "2012-09-24 10:04:31";
$format1 = "Y W" ; //This format should return the difference in Year and week.
$format2 = "M D"; // This format should return the difference in Months and days.
// The format can be any combination of Year,Month,Day,Week,Hour,Minute,Second.

function ConvertDate($data1,$date2,$format)

Please let me know if you need any more details on this.
Thanks in advance.

Body:
Get Unix timestamps of your dates using mktime. Then you get the difference for:

$years = floor(($date2-$date1)/31536000);
$months = floor(($date2-$date1)/2628000);
$days = floor(($date2-$date1)/86400);
$hours = floor(($date2-$date1)/3600);
$minutes = floor(($date2-$date1)/60);
$seconds = ($date2-$date1);

Hope this helps.

—Alberto


问:
Static version of Joomla site with wget
I need to create a static version of a Joomla website. I'm using wget to download files. But the downloaded files have a base url that point to the live site.

If I remove the  tag, then the local files become a mess, since references to css, javascript etc. start with a slash and Chrome errors with "Not allowed to load local resource"

Here some source code from the downloaded site:

```<code><base href="http://www.example.com/" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Home - My Site</title>
<link href="/templates/mytemplate/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
<link href="/templates/mytemplate/css/template.css" rel="stylesheet" type="text/css" />
<link href="/templates/mytemplate/css/custom.css" rel="stylesheet" type="text/css" />
<script src="/templates/mytemplate/js/template.js" type="text/javascript"></script>
</code>```

Does anyone have an idea how to create a good local static copy of a site? What setting am I maybe missing in wget?

答:
To make a really static copy of a site, you need to specify both -k (--convert-links) and -p (--page-requisites):

```<code>$ cd <target-dir>
$ wget -k -p http://www.example.com
$ cd www.example.com
$ firefox index.html
</code>```

This is not Joomla specific, though.

Title: Static version of Joomla site with wget

Body:
I need to create a static version of a Joomla website. I'm using wget to download files. But the downloaded files have a base url that point to the live site.

If I remove the  tag, then the local files become a mess, since references to css, javascript etc. start with a slash and Chrome errors with "Not allowed to load local resource"

Here some source code from the downloaded site:

<base href="http://www.example.com/" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Home - My Site</title>
<link href="/templates/mytemplate/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
<link href="/templates/mytemplate/css/template.css" rel="stylesheet" type="text/css" />
<link href="/templates/mytemplate/css/custom.css" rel="stylesheet" type="text/css" />

Does anyone have an idea how to create a good local static copy of a site? What setting am I maybe missing in wget?

Body:
To make a really static copy of a site, you need to specify both -k (--convert-links) and -p (--page-requisites):

$ cd <target-dir>
$ wget -k -p http://www.example.com
$ cd www.example.com
$ firefox index.html

This is not Joomla specific, though.


问:
Xamarin.Forms UWP - InvalidCastException when trying to set TextDecorations for TextBlock
In a Xamarin.Forms project, I'm trying to allow underlined Labels. So I have a custom renderer, and I'm trying to do something simple:

```<code>Control.TextDecorations = TextDecorations.Underline;
</code>```

It compiles just fine, but when the app launches, I'm getting an InvalidCastException on that line which says:

System.InvalidCastException: 'Unable to cast object of type 'Windows.UI.Xaml.Controls.TextBlock' to type 'Windows.UI.Xaml.Controls.ITextBlock5'.'

Here's a screenshot of the exception:

Also, when inspecting the Control, I noticed there are a ton of InvalidCastException exceptions on other properties of the TextBlock control as well - here's a small sample:

Why is it trying to cast to a ITextBlock5 type? Is this a UWP bug? Is there a workaround to get underline to work?

答:
The TextDecorations property is documented on MSDN to be supported on version 15063 and later.

You can use the ApiInformation class to check at runtime whether the property is avaiable or not.

Body:
In a Xamarin.Forms project, I'm trying to allow underlined Labels. So I have a custom renderer, and I'm trying to do something simple:

Control.TextDecorations = TextDecorations.Underline;

It compiles just fine, but when the app launches, I'm getting an InvalidCastException on that line which says:

System.InvalidCastException: 'Unable to cast object of type 'Windows.UI.Xaml.Controls.TextBlock' to type 'Windows.UI.Xaml.Controls.ITextBlock5'.'

Here's a screenshot of the exception:

Also, when inspecting the Control, I noticed there are a ton of InvalidCastException exceptions on other properties of the TextBlock control as well - here's a small sample:

Why is it trying to cast to a ITextBlock5 type? Is this a UWP bug? Is there a workaround to get underline to work?


问:
Tkinter Grid Dynamic Layout
I am wanting to create a grid layout, with a grid that fills the first row until it runs out of space in the window, and will dynamically move items to the row below (like text line-wrapping).  As the window width is adjusted, the grid adjusts to fit.  The boxes resizing is not desired. I intend to maintain each small box's size, but change where the layout puts each box.

I imagine this functionality is possible by measuring the width of the frame, and if the (number of boxes)*(width of each box) exceeds the width, move to the next row.  I was just wondering if there was a better way built in that I'm not understanding.

If the above is the only option, what is the best way to update that? Do I have to set an event on window resize or something?  It seems like I shouldn't have to rework a layout manager, which is what that feels like.  I just want to check if similar functionality is already built in. Grid seems like a powerful layout manager, but I have not been able to find that option.

The below pics describes the behavior I want using the same set of 6 boxes on a single frame using grid layout.

Window is wide enough to hold all 6 boxes, so they all fit on row 1. They then adjust as window size changes.

答:
If you plan on forcing each box to be a uniform size, the simplest solution is to use the text widget as the container since it has the built-in ability to wrap.

Here is a working example. Click on the "add" button to add additional boxes. Resize the window to see that they automatically wrap as the window grows and shrinks.

```<code>import Tkinter as tk
import random

class DynamicGrid(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.text = tk.Text(self, wrap="char", borderwidth=0, highlightthickness=0,
                            state="disabled")
        self.text.pack(fill="both", expand=True)
        self.boxes = []

    def add_box(self, color=None):
        bg = color if color else random.choice(("red", "orange", "green", "blue", "violet"))
        box = tk.Frame(self.text, bd=1, relief="sunken", background=bg,
                       width=100, height=100)
        self.boxes.append(box)
        self.text.configure(state="normal")
        self.text.window_create("end", window=box)
        self.text.configure(state="disabled")

class Example(object):
    def __init__(self):
        self.root = tk.Tk()
        self.dg = DynamicGrid(self.root, width=500, height=200)
        add_button  = tk.Button(self.root, text="Add", command=self.dg.add_box)

        add_button.pack()
        self.dg.pack(side="top", fill="both", expand=True)

        # add a few boxes to start
        for i in range(10):
            self.dg.add_box()

    def start(self):
        self.root.mainloop()

Example().start()
</code>```

Title: Tkinter Grid Dynamic Layout

Body:
If you plan on forcing each box to be a uniform size, the simplest solution is to use the text widget as the container since it has the built-in ability to wrap.

Here is a working example. Click on the "add" button to add additional boxes. Resize the window to see that they automatically wrap as the window grows and shrinks.

import Tkinter as tk
import random

class DynamicGrid(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.text = tk.Text(self, wrap="char", borderwidth=0, highlightthickness=0,
                            state="disabled")
        self.text.pack(fill="both", expand=True)
        self.boxes = []

    def add_box(self, color=None):
        bg = color if color else random.choice(("red", "orange", "green", "blue", "violet"))
        box = tk.Frame(self.text, bd=1, relief="sunken", background=bg,
                       width=100, height=100)
        self.boxes.append(box)
        self.text.configure(state="normal")
        self.text.window_create("end", window=box)
        self.text.configure(state="disabled")

class Example(object):
    def __init__(self):
        self.root = tk.Tk()
        self.dg = DynamicGrid(self.root, width=500, height=200)
        add_button  = tk.Button(self.root, text="Add", command=self.dg.add_box)

        add_button.pack()
        self.dg.pack(side="top", fill="both", expand=True)

        # add a few boxes to start
        for i in range(10):
            self.dg.add_box()

    def start(self):
        self.root.mainloop()

Example().start()


问:
JQuery: Hiding dynamically added images via generated ID

I am trying to make a program in JavaScript that functions similar to a "Whack-a-Mole" game.  I have everything figured out except for one thing.  I would like to have each "mole" disappear after a brief time if it is not clicked on.  The function that generates the moles is shown below.  I am not entirely sure how to go about hiding the moles, but I would like to do so by selecting them by a uniquely generated ID, as shown in the code.  There is a global variable "count" that is used to generate each ID.

```<code>function addMole(){
var yPos = numOne();
var xPos = numTwo();

if (timeLeft > 0){
$("#gamespace").append('<img id="i'+count+'" src="img/mole.gif" style="top:'+yPos+'px;left:'+xPos+'px;" />');
count++;
setTimeout("addMole()", Math.floor(Math.random()*2000));
};
};
</code>```

I have tried using this function, but it doesn't seem to do anything and I'm not sure how or where to call it or if I'm even using the right selector.

```<code>function noMole(){
$("#i"+count).delay(2000).hide();

};
</code>```

答:
I'd probably go with something like the following:

function addMole() {
  var yPos = numOne();
  var xPos = numTwo();

  if (timeLeft > 0) {
    //make a new mole and have a reference to it
    var newMole = $('');
    //put the mole in the game
    $("#gamespace").append(newMole);
    //add another mole in a random amount of time
    setTimeout(addMole, Math.floor(Math.random() * 2000));
    //remove the created mole after 5 seconds
    setTimeout(function(){ newMole.remove(); }, 5000);
  };
};```

You don't need a lookup.  You just need the reference.

Body:
I am trying to make a program in JavaScript that functions similar to a "Whack-a-Mole" game.  I have everything figured out except for one thing.  I would like to have each "mole" disappear after a brief time if it is not clicked on.  The function that generates the moles is shown below.  I am not entirely sure how to go about hiding the moles, but I would like to do so by selecting them by a uniquely generated ID, as shown in the code.  There is a global variable "count" that is used to generate each ID.

function addMole(){
var yPos = numOne();
var xPos = numTwo();

if (timeLeft > 0){
$("#gamespace").append('');
count++;
setTimeout("addMole()", Math.floor(Math.random()*2000));
};
};

I have tried using this function, but it doesn't seem to do anything and I'm not sure how or where to call it or if I'm even using the right selector.

function noMole(){
$("#i"+count).delay(2000).hide();

};

Body:
I'd probably go with something like the following:

function addMole() {
  var yPos = numOne();
  var xPos = numTwo();

  if (timeLeft > 0) {
    //make a new mole and have a reference to it
    var newMole = $('<img src="img/mole.gif" style="top:' + yPos + 'px;left:' + xPos + 'px;" />');
    //put the mole in the game
    $("#gamespace").append(newMole);
    //add another mole in a random amount of time
    setTimeout(addMole, Math.floor(Math.random() * 2000));
    //remove the created mole after 5 seconds
    setTimeout(function(){ newMole.remove(); }, 5000);
  };
};

You don't need a lookup.  You just need the reference.


问:
Make image fill whole container of stacklayout

Hi I have this Xamarin Forms app where I have the following layout:

```<code> <ContentPage Title="Live" Icon="tv_show-32.png">
        <ScrollView>
            <Grid Margin="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <StackLayout Grid.Row="0" Grid.Column="0" Spacing="50,20,50,30">
                    <Image Source="http://kanal10.se/images/logga/kanal10.png" HorizontalOptions="FillAndExpand"></Image>
                </StackLayout>

                <StackLayout Grid.Column="0" Grid.Row="1" Style="{StaticResource StackBG}">
                    <Label Text="Sverige/Sweden"></Label>
                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="Fill"></Image>
                    <Button x:Name="Sweden" Text="Watch Live" Clicked="Sweden_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="2" Style="{StaticResource StackBG}">
                    <Label Text="Norge/Norway"></Label>
                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Norway" Text="Watch Live" Clicked="Norway_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="3" Style="{StaticResource StackBG}">
                    <Label Text="Asien/Asia"></Label>
                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Asia" Text="Watch Live" Clicked="Asia_OnClicked" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
            </Grid>
        </ScrollView>
    </ContentPage>
</code>```

The problem is that I can't get the image called tvbild.png, to fill the whole  container in the iOS app.

I would like the image to have the same width size as the button (see attached image).

How can I accomplish this?

Thanks for help!

Peter

答:
Assuming image size is known; use separate row in Grid for image and button and
set HeightRequest for Image and ColumnDefinition Width for Grid, see sample below:

Original image width is 100 and height is 50. Width of container is 300.

Find scale factor based on width of container and width of image: 300/100=3

Find HeightRequest based on scale and height of image: 3*50=150:

```<code><ContentPage Padding="10,20"
...
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="300"/>
  </Grid.ColumnDefinitions>
  <Image Grid.Row="0" Source="100x50.png" HeightRequest="150"/>
  <Button Grid.Row="1" Text="Button 1"/>
  <Image Grid.Row="2" Source="200x100.png" HeightRequest="150"/>
  <Button Grid.Row="3" Text="Button 2"/>
</Grid>
</code>```

Sample output from iPhone SE simulator with page width 320. The left and right border is from area left and right of the display:

Body:
Hi I have this Xamarin Forms app where I have the following layout:

 <ContentPage Title="Live" Icon="tv_show-32.png">
        <ScrollView>
            <Grid Margin="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <StackLayout Grid.Row="0" Grid.Column="0" Spacing="50,20,50,30">
                    <Image Source="http://kanal10.se/images/logga/kanal10.png" HorizontalOptions="FillAndExpand"></Image>
                </StackLayout>

                <StackLayout Grid.Column="0" Grid.Row="1" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="Fill"></Image>
                    <Button x:Name="Sweden" Text="Watch Live" Clicked="Sweden_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="2" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Norway" Text="Watch Live" Clicked="Norway_OnClicked" HorizontalOptions="FillAndExpand" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
                <StackLayout Grid.Column="0" Grid.Row="3" Style="{StaticResource StackBG}">

                    <BoxView WidthRequest="100" HeightRequest="1" BackgroundColor="#009fe3"></BoxView>
                    <Image Source="http://kanal10.se/storage/images/kanal10/kanal-10/tvbild.png" HorizontalOptions="FillAndExpand"></Image>
                    <Button x:Name="Asia" Text="Watch Live" Clicked="Asia_OnClicked" Style="{StaticResource PlayButtonStyle}"></Button>
                </StackLayout>
            </Grid>
        </ScrollView>
    </ContentPage>

The problem is that I can't get the image called tvbild.png, to fill the whole  container in the iOS app.

I would like the image to have the same width size as the button (see attached image).

How can I accomplish this?

Thanks for help!

Peter

Body:
Assuming image size is known; use separate row in Grid for image and button and
set HeightRequest for Image and ColumnDefinition Width for Grid, see sample below:

Original image width is 100 and height is 50. Width of container is 300.

Find scale factor based on width of container and width of image: 300/100=3

Find HeightRequest based on scale and height of image: 3*50=150:

<ContentPage Padding="10,20"
...
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
    <RowDefinition Height="Auto"/>
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="300"/>
  </Grid.ColumnDefinitions>
  <Image Grid.Row="0" Source="100x50.png" HeightRequest="150"/>
  <Button Grid.Row="1" Text="Button 1"/>
  <Image Grid.Row="2" Source="200x100.png" HeightRequest="150"/>
  <Button Grid.Row="3" Text="Button 2"/>
</Grid>

Sample output from iPhone SE simulator with page width 320. The left and right border is from area left and right of the display:


问:
How to search for functions in module?
I want to have a search function like a man page inside a Python module.

Is there a built-in or module function to search a string/wildcard char in function name/class name/object name or function of class?

e.g. find(get_*)?

This would find all get_* functions, such as get_height, get_weight, get_area, get_volume as well as square.get_area,rectange.get_area
or have a find(get?int) to find get_int, etc.

I can have a list in help(module) but there is too much clutter and no search function I can find.
If not, how can I write a function to do the same?

答:
As an alternative to using re, for simple matches of the type you've given, use fnmatch.  That provides much friendlier matching.

```<code>def find(value, pattern="*"):
    from fnmatch import fnmatch
    return [x for x in dir(value) if fnmatch(x, pattern)]
</code>```

Then:

```<code>>>> import os
>>> find(os, "u*")
['umask', 'uname', 'unlink', 'unsetenv', 'urandom', 'utime']
>>> find(os, "?n*")
['environ', 'initgroups', 'uname', 'unlink', 'unsetenv']
</code>```

Title: How to search for functions in module?

Body:
As an alternative to using re, for simple matches of the type you've given, use fnmatch.  That provides much friendlier matching.

def find(value, pattern="*"):
    from fnmatch import fnmatch
    return [x for x in dir(value) if fnmatch(x, pattern)]

Then:

>>> import os
>>> find(os, "u*")
['umask', 'uname', 'unlink', 'unsetenv', 'urandom', 'utime']
>>> find(os, "?n*")
['environ', 'initgroups', 'uname', 'unlink', 'unsetenv']


问:
How do I bind onchange event of a TextBox using JQuery?
How can I bind an OnChange event of a TextBox to function using jQuery?

Am trying this and its failing:

```<code>$(document).ready(function() {
    $("input#tags").bind("change",autoFill);
});

function autoFill() {
    $("#tags").autocomplete("/taglookup/", {
        width: 320,
        max: 4,
        highlight: false,
        multiple: true,
        multipleSeparator:",",
        scroll: true,
        scrollHeight: 300,
        delay: 10
    });
}
</code>```

NB: I want to implement a Tag TextBox like the one for stackoverflow which detects OnChange events and calls AJAX functions when a user types in.

答: if you're trying to use jQuery autocomplete plugin, then I think you don't need to bind to onChange event, it will</p>

ContentLicense: CC BY-SA 4.0

Body:
How can I bind an OnChange event of a TextBox to function using jQuery?

Am trying this and its failing:

$(document).ready(function() {
    $("input#tags").bind("change",autoFill);
});

function autoFill() {
    $("#tags").autocomplete("/taglookup/", {
        width: 320,
        max: 4,
        highlight: false,
        multiple: true,
        multipleSeparator:",",
        scroll: true,
        scrollHeight: 300,
        delay: 10
    });
}

NB: I want to implement a Tag TextBox like the one for stackoverflow which detects OnChange events and calls AJAX functions when a user types in.


问:
How to pass compile time parameter for Yocto project?
I am new to Yocto build environment. I have a C code which has some code as below:

```<code>#include <stdio.h>
int main ()
{
    printf("HELLO WORLD\n");

#ifdef MYDEF
    printf("MYDEF is defined\n");
#endif

    return 0;
}
</code>```

I want to pass a flag/parameter MYDEF in local.conf file. I tried following defines but they didn't work. Any thoughts on what am I doing wrong and what possibly can fix it?

```<code>MYDEF = 'y'
MYDEF ?= 'y'
MYDEF ??= 'y'
CFLAGS = "-DMYDEF"
TARGET_CFLAGS = "-DMYDEF"
BUILD_CFLAGS = "-DMYDEF"
</code>```

Thanks.

答:
Taking the same code as @astor555, there are some problems in the way the flag is handled.

```<code>LICENSE = "CLOSED"

SRC_URI = "file://hello_test.cpp"
S = "${WORKDIR}"

inherit native

MYDEF ?= "-DMYDEF"

do_compile (){
  ${CC} ${MYDEF} -o hello_test ${S}/hello_test.cpp
}

do_install () {
    install -d ${D}${bindir}
    install ${B}/hello_test ${D}/${bindir}
}
</code>```

Note the definition of MYDEF variable, and how it is referenced inside the do_compile funciton.
Then in your local.conf you could either disable it by overriding its value:

```<code>MYDEF = ""
</code>```

or force it like:

```<code>MYDEF = "-DMYDEF"
</code>```

But as in the recipe the weak assignment ?= is used, it will be the value by default, so you dont require to add anything in the local.conf if you want it to be defined.

Body:
I am new to Yocto build environment. I have a C code which has some code as below:

#include <stdio.h>
int main ()
{
    printf("HELLO WORLD\n");

#ifdef MYDEF
    printf("MYDEF is defined\n");
#endif

    return 0;
}

I want to pass a flag/parameter MYDEF in local.conf file. I tried following defines but they didn't work. Any thoughts on what am I doing wrong and what possibly can fix it?

MYDEF = 'y'
MYDEF ?= 'y'
MYDEF ??= 'y'
CFLAGS = "-DMYDEF"
TARGET_CFLAGS = "-DMYDEF"
BUILD_CFLAGS = "-DMYDEF"

Thanks.

Body:
Taking the same code as @astor555, there are some problems in the way the flag is handled.

LICENSE = "CLOSED"

SRC_URI = "file://hello_test.cpp"
S = "${WORKDIR}"

inherit native

MYDEF ?= "-DMYDEF"

do_compile (){
  ${CC} ${MYDEF} -o hello_test ${S}/hello_test.cpp
}

do_install () {
    install -d ${D}${bindir}
    install ${B}/hello_test ${D}/${bindir}
}

Note the definition of MYDEF variable, and how it is referenced inside the do_compile funciton.
Then in your local.conf you could either disable it by overriding its value:

MYDEF = ""

or force it like:

MYDEF = "-DMYDEF"

But as in the recipe the weak assignment ?= is used, it will be the value by default, so you dont require to add anything in the local.conf if you want it to be defined.


问:
How can i find file sizes with powershell
We're migrating servers and sometimes the copy of various files doesn't happen successfully and, for example, we end up with PDF files that are 1kb rather than their actual size.

I wrote a simple powershell script to find these files, but it also listed the empty subfolders at the end of the search results.  So i'd see something like this in my output text file -
C:\path\filename1.pdf
c:\path\filename2.pdf
c:\path\subfolder\

What' i'm trying to do is eliminate the empty folders in the results.  I've modified the original script -

```<code>Clear
$username = $env:username
Get-ChildItem -path "C:\users\blah\blah\blah\" -recurse | Where
{$_.Length -lt 1025 } | Sort-Object length | ft fullname, length -AutoSize
|Out-File "C:\Users\$username\Desktop\1kb_Files.txt"
</code>```

In the modified script i've created a read-host to grab the file size to search, but then when i add that variable into the script i get an error.  Here's hte modified script -

```<code>$Size = Read-Host "Enter search size"
$folder = Read-Host "Enter full search path"
Get-ChildItem -path $folder -recurse |Where {($_.Length -lt '$size') -and ($_.Length -gt '0')}
</code>```

But now i get this error -
Cannot convert value "$size" to type "System.Int64". Error: "Input string was not in a correct format."

I'm guessing i need to define the size for $size?

答:
If you add the switch "-File" to the get-childitem command, remove the single quotes enclosing $Size in the where command as they prevent PowerShell from substituting the value of the Size variable for the string '$Size'. You can then remove the second clause of the where statement to finish like so:</p>

```<code>$Size = Read-Host "Enter search size"
$folder = Read-Host "Enter full search path"
Get-ChildItem -File -Recurse -Path $folder | Where $_.Length -lt $Size
</code>```

Body:
We're migrating servers and sometimes the copy of various files doesn't happen successfully and, for example, we end up with PDF files that are 1kb rather than their actual size.

I wrote a simple powershell script to find these files, but it also listed the empty subfolders at the end of the search results.  So i'd see something like this in my output text file -
C:\path\filename1.pdf
c:\path\filename2.pdf
c:\path\subfolder\

What' i'm trying to do is eliminate the empty folders in the results.  I've modified the original script -

Clear
$username = $env:username
Get-ChildItem -path "C:\users\blah\blah\blah\" -recurse | Where
{$_.Length -lt 1025 } | Sort-Object length | ft fullname, length -AutoSize
|Out-File "C:\Users\$username\Desktop\1kb_Files.txt"

In the modified script i've created a read-host to grab the file size to search, but then when i add that variable into the script i get an error.  Here's hte modified script -

$Size = Read-Host "Enter search size"
$folder = Read-Host "Enter full search path"
Get-ChildItem -path $folder -recurse |Where {($_.Length -lt '$size') -and ($_.Length -gt '0')}

But now i get this error -
Cannot convert value "$size" to type "System.Int64". Error: "Input string was not in a correct format."

I'm guessing i need to define the size for $size?

Body:
If you add the switch "-File" to the get-childitem command, remove the single quotes enclosing $Size in the where command as they prevent PowerShell from substituting the value of the Size variable for the string '$Size'. You can then remove the second clause of the where statement to finish like so:

$Size = Read-Host "Enter search size"
$folder = Read-Host "Enter full search path"
Get-ChildItem -File -Recurse -Path $folder | Where $_.Length -lt $Size


问:
Query MS Access using Excel VBA, SQL BETWEEN dates query
all--

I'm attempting to use an SQL query to pull records from an Access db into an Excel VBA userform listbox using the following code:

```<code>Sub FillLBBillIDs()
'build bill ID list box with bill IDs available in database, based on client and/or date range
'<---------------------------------------------------Dimension all variables
Dim con As Object, cmd As Object, rst As Object
Dim Path As String, CName As String
Dim FromDate As Date, ToDate As Date
Dim X As Long, Y As Long
'<---------------------------------------------------Define Default Variables
X = 0
CName = AuditParametersFRM.CBOCxName.Value
FromDate = AuditParametersFRM.DTPFrom.Value
ToDate = AuditParametersFRM.DTPTo.Value
'<---------------------------------------------------Define Access connection
Set con = CreateObject("ADODB.Connection"): Set cmd = CreateObject("ADODB.Command"): Set rst = CreateObject("ADODB.RecordSet"):
Path = Sheets("AuditTool").Range("B2").Value
'<---------------------------------------------------Open Access connection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path & ";Persist Security Info=False;"
con.ConnectionTimeout = 0: con.CommandTimeout = 0: con.Open: cmd.CommandTimeout = 0: Set cmd.ActiveConnection = con
'<---------------------------------------------------Find all bill IDs in the database which match the selected client and
'<---------------------------------------------------are within the consolidated date range
rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.[ConsolidationDate] BETWEEN #" & FromDate & "# AND #" & ToDate & "#", con, 1, 3
On Error Resume Next
rst.MoveLast
rst.MoveFirst
Y = 0
Y = rst.RecordCount
AuditToolFRM.LBBillIDs.Clear
If Not Y = 0 Then
    Do Until rst.EOF
'<---------------------------------------------------Build the listbox with the acquired information
        With AuditToolFRM.LBBillIDs
            .AddItem
            .List(X, 0) = rst![BillID]
            X = X + 1
        End With
        rst.MoveNext
    Loop
End If
rst.Close
On Error GoTo 0
con.Close
End Sub
</code>```

This code works just fine if I use a greater than argument, thusly:

```<code>rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.ConsolidationDate > #" & FromDate & "#", con 1, 3
</code>```

I've gone through all the pertinent questions on this site and can't find anything that works. Any ideas?

Thanks in advance!

12/08/2017 12:54

I've done more testing and it appears that the greater than query isn't working either; it's pulling all records that meet the first criteria whilst ignoring the second, even when using parentheses to enclose the second. This tells me that the issue is definitely in the date portion of the query somehow. Any help is appreciated greatly!

答:
In Access

```<code>DATE_FIELD BETWEEN #2/2/2012# AND #2/4/2012#
</code>```

is the same as

```<code>DATE_FIELD >=#2/2/2012# AND <=#2/4/2012#
</code>```

When you have another AND put parathesis around the date range syntax.

rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND (AdHocReport.[ConsolidationDate] BETWEEN #" & FromDate & "# AND #" & ToDate & "#)", con, 1, 3

Body:
all--

I'm attempting to use an SQL query to pull records from an Access db into an Excel VBA userform listbox using the following code:

Sub FillLBBillIDs()
'build bill ID list box with bill IDs available in database, based on client and/or date range
'<---------------------------------------------------Dimension all variables
Dim con As Object, cmd As Object, rst As Object
Dim Path As String, CName As String
Dim FromDate As Date, ToDate As Date
Dim X As Long, Y As Long
'<---------------------------------------------------Define Default Variables
X = 0
CName = AuditParametersFRM.CBOCxName.Value
FromDate = AuditParametersFRM.DTPFrom.Value
ToDate = AuditParametersFRM.DTPTo.Value
'<---------------------------------------------------Define Access connection
Set con = CreateObject("ADODB.Connection"): Set cmd = CreateObject("ADODB.Command"): Set rst = CreateObject("ADODB.RecordSet"):
Path = Sheets("AuditTool").Range("B2").Value
'<---------------------------------------------------Open Access connection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path & ";Persist Security Info=False;"
con.ConnectionTimeout = 0: con.CommandTimeout = 0: con.Open: cmd.CommandTimeout = 0: Set cmd.ActiveConnection = con
'<---------------------------------------------------Find all bill IDs in the database which match the selected client and
'<---------------------------------------------------are within the consolidated date range
rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.[ConsolidationDate] BETWEEN #" & FromDate & "# AND #" & ToDate & "#", con, 1, 3
On Error Resume Next
rst.MoveLast
rst.MoveFirst
Y = 0
Y = rst.RecordCount
AuditToolFRM.LBBillIDs.Clear
If Not Y = 0 Then
    Do Until rst.EOF
'<---------------------------------------------------Build the listbox with the acquired information
        With AuditToolFRM.LBBillIDs
            .AddItem
            .List(X, 0) = rst![BillID]
            X = X + 1
        End With
        rst.MoveNext
    Loop
End If
rst.Close
On Error GoTo 0
con.Close
End Sub

This code works just fine if I use a greater than argument, thusly:

rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND AdHocReport.ConsolidationDate > #" & FromDate & "#", con 1, 3

I've gone through all the pertinent questions on this site and can't find anything that works. Any ideas?

Thanks in advance!

12/08/2017 12:54

I've done more testing and it appears that the greater than query isn't working either; it's pulling all records that meet the first criteria whilst ignoring the second, even when using parentheses to enclose the second. This tells me that the issue is definitely in the date portion of the query somehow. Any help is appreciated greatly!

Body:
In Access

DATE_FIELD BETWEEN #2/2/2012# AND #2/4/2012#

is the same as

DATE_FIELD >=#2/2/2012# AND <=#2/4/2012#

When you have another AND put parathesis around the date range syntax.

rst.Open "SELECT DISTINCT AdHocReport.[BillID] FROM AdHocReport WHERE AdHocReport.[CxName] = '" & CName & "' AND (AdHocReport.[ConsolidationDate] BETWEEN #" & FromDate & "# AND #" & ToDate & "#)", con, 1, 3


问:
How to count in multiple columns a variable
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

```<code>UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill
</code>```

I need to produce a productivity report like below

```<code>        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3
</code>```

I am not sure how to group the counts by the names that are in the data?

答:
you can also use pivot and unpivot syntax like below:
See working demo

```<code>select
Name,
[approved]=ISNULL([approved],0),
[denied]=ISNULL([denied],0),
[moved]=ISNULL([moved],0),
[pending]=ISNULL([pending],0)
from
(
    select
      Name,activity,count(1) c
    from
    (select * from useractivity )s
    unpivot (Name for activity in ([approved],[denied],[moved],[pending]))up
    group by Name,activity
) s
pivot (sum(c) for activity in ([approved],[denied],[moved],[pending]))p
</code>```

Body:
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill

I need to produce a productivity report like below

        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3

I am not sure how to group the counts by the names that are in the data?

Body:
you can also use pivot and unpivot syntax like below:
See working demo

select
Name,
[approved]=ISNULL([approved],0),
[denied]=ISNULL([denied],0),
[moved]=ISNULL([moved],0),
[pending]=ISNULL([pending],0)
from
(
    select
      Name,activity,count(1) c
    from
    (select * from useractivity )s
    unpivot (Name for activity in ([approved],[denied],[moved],[pending]))up
    group by Name,activity
) s
pivot (sum(c) for activity in ([approved],[denied],[moved],[pending]))p


问:
Info.plist must contain the 'CFBundleIcons.CFBundlePrimaryIcon' key
I am trying to upload a TVOS app to the Apple Store. I have done this several times with no issues. Now when I upload I get an error saying

Missing Info.plist Key. Your app's Info.plist must contain the CFBundleIcons.CFBundlePrimaryIcon key.

Is there something I'm missing?

答: Update: I restarted XCode and it kept happening. I restarted the computer and the error went away. Leaving this in case it happens to someone else.</p>