问:
How to access innerHTML of a div produced after some other process takes place using DOM
I want to access the innerHTML property of a div, the text inside which is generated after some function is executed.
Say, for example, I have this login mechanism:

```<code>   <?php
        $message = "";

        if(isset($_POST['user'] ) )
            $user = $_POST['user'];
        if(isset($_POST['pass']))  {
            $pass = $_POST['pass'];

        if($user == "ans" && $pass == "ans" )
        {
            $message = "success";
        }

        else
            $message = "fail";

}

?>

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<div class="msgDiv">
                <?php
                    if(isset($message) )
                        echo $message;
                ?>
</div>
    <form  action="#" method="POST">

            <input type="text" name="user" class="user">

            <input type="text" name="pass" class="user">

            <input type="submit" name="submit" id="button" value="submit">
    </form>

    <script>

            var user = document.getElementsByClassName('user')[0];
            var pass = document.getElementsByClassName('user')[1];
            var button = document.getElementById('button');
            var msg = document.getElementsByClassName('msgDiv');
            button.onclick= function()
            {
                user.value= "ans";
                pass.value="an";

                msg.onchange = function()  {
                alert(msg.textContent);
                } //THIS CODE IS WRONG, I SUPPOSE
            }

    </script>
</body>
</html>
</code>```

The text in the "msgDiv" will be generated only when either the login succeeds or fails.
How can I fetch this generated text using DOM functions?

答:
Use document.getElementById("msgDiv").textContent

function modifier(){
    document.getElementById("msgDiv").textContent = "message";
}

modifier();

console.log(document.getElementById("msgDiv").textContent);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="msgDiv"></div>
    <form>
     <input type="text" name="user">
     <input type="password" name="password">
     <input type="submit" value="submit">
    </form></code>```

EDIT: The #button is bound with 2 events: one is form submission and other is the onclick function you have written to alert the response string message. So now when you are clicking on the submit button the form is getting submitted and probably your msgDiv is showing the response message. And, since you have written your alert function inside your onclick event, clicking it again will eventually trigger another form submission.

You can simply write <?php if(isset($message)){echo "alert('".$message."');";} ?>

EDIT 2:

No need to initialize $message. Remove or comment out the line $message = "";

Add <?php if(isset($message)){echo "alert('".$message."');";} ?> just before closing the script tag. This will alert the message value whenever it is set after form submission.

Body:
I want to access the innerHTML property of a div, the text inside which is generated after some function is executed.
Say, for example, I have this login mechanism:

   <?php
        $message = "";

        if(isset($_POST['user'] ) )
            $user = $_POST['user'];
        if(isset($_POST['pass']))  {
            $pass = $_POST['pass'];

        if($user == "ans" && $pass == "ans" )
        {
            $message = "success";
        }

        else
            $message = "fail";

}

?>

<!DOCTYPE html>

    <title></title>

                <?php
                    if(isset($message) )
                        echo $message;
                ?>

    <form  action="#" method="POST">

            <input type="text" name="user" class="user">

            <input type="text" name="pass" class="user">

            <input type="submit" name="submit" id="button" value="submit">
    </form>

The text in the "msgDiv" will be generated only when either the login succeeds or fails.
How can I fetch this generated text using DOM functions?

Body:
Use document.getElementById("msgDiv").textContent

function modifier(){
    document.getElementById("msgDiv").textContent = "message";
}

modifier();

console.log(document.getElementById("msgDiv").textContent);

<div id="msgDiv"></div>
    <form>
     <input type="text" name="user">
     <input type="password" name="password">
     <input type="submit" value="submit">
    </form>

EDIT: The #button is bound with 2 events: one is form submission and other is the onclick function you have written to alert the response string message. So now when you are clicking on the submit button the form is getting submitted and probably your msgDiv is showing the response message. And, since you have written your alert function inside your onclick event, clicking it again will eventually trigger another form submission.

You can simply write <?php if(isset($message)){echo "alert('".$message."');";} ?>

EDIT 2:

No need to initialize $message. Remove or comment out the line $message = "";

Add <?php if(isset($message)){echo "alert('".$message."');";} ?> just before closing the script tag. This will alert the message value whenever it is set after form submission.


来源: stackexchange

问:
Cython equivalent for "using Time = cppClassDefinition<withT>"
I'm trying to wrap a cpp application and the source code contains the following in a header file

```<code>using Time = cppClassDefinition<withT>

...

void setDefaultTime(Time x)
</code>```

What would be the Cython equivalent for this?

I've tried

```<code>cdef extern from "headerfile.h" namespace "ns":
    ctypedef cppClassDefinition<withT> Time
</code>```

to no success. Although Cython does not complain at this step, it throws a compilation error when I try to use the function setDefaultTime(1.0). The error states "Cannot assign type 'double' to 'Time'. In the CPP code however, this seems to be working fine.

I've also tried

```<code>cdef extern from "headerfile.h" namespace "ns":
    cdef cppclass Time:
        pass
</code>```

and that also failed. Any suggestions? Is this possible using Cython?

答:
As you suggest in the question, you should be able to use use

```<code>ctypedef cppClassDefinition[withT] Time
</code>```

since using ... = ... in this context is equivalent to a typedef. (Note the change to square brackets compared to the code in your question).

I believe the problem is instead with your attempt to do setDefaultTime(1.0). Cython has no way of knowing that double can be converted to Time and there isn't any way of telling it about implicit C++ conversions.

The easiest way round this is to just tell Cython that the function signature is

```<code>void setDefaultTime(double x)
</code>```

(You can leave the C++ signature as is). This will satisfy Cython, and then the C++ code it generates should end up working correctly provided that double can be implicitly converted to Time (as the question implies)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to wrap a cpp application and the source code contains the following in a header file

using Time = cppClassDefinition<withT>

...

void setDefaultTime(Time x)

What would be the Cython equivalent for this?

I've tried

cdef extern from "headerfile.h" namespace "ns":
    ctypedef cppClassDefinition<withT> Time

to no success. Although Cython does not complain at this step, it throws a compilation error when I try to use the function setDefaultTime(1.0). The error states "Cannot assign type 'double' to 'Time'. In the CPP code however, this seems to be working fine.

I've also tried

cdef extern from "headerfile.h" namespace "ns":
    cdef cppclass Time:
        pass

and that also failed. Any suggestions? Is this possible using Cython?

Body:
As you suggest in the question, you should be able to use use

ctypedef cppClassDefinition[withT] Time

since using ... = ... in this context is equivalent to a typedef. (Note the change to square brackets compared to the code in your question).

I believe the problem is instead with your attempt to do setDefaultTime(1.0). Cython has no way of knowing that double can be converted to Time and there isn't any way of telling it about implicit C++ conversions.

The easiest way round this is to just tell Cython that the function signature is

void setDefaultTime(double x)

(You can leave the C++ signature as is). This will satisfy Cython, and then the C++ code it generates should end up working correctly provided that double can be implicitly converted to Time (as the question implies)


问:
Parsing JSON Name Pair in C#
Using C# to parse JSON URL I am facing some issues. As you know JSON data is written as name/value pairs. now in URL JSON I have  these data:

```<code>{
   "currentVersion":10.41,
   "serviceDescription":"There are some text here",
   "hasVersionedData":true,
   "supportsDisconnectedEditing":false,
   "syncEnabled":false,
   "supportedQueryFormats":"JSON",
   "maxRecordCount":1000
 }
</code>```

and I want to only print out the name part of the JSON data using this code

```<code>using (var wc = new WebClient())
{
    string json = wc.DownloadString("http://xxxxxxxxx?f=pjson");
    try
    {
        dynamic data = Json.Decode(json);
        for (int i = 0; i <= data.Length - 1; i++)
        {
            Console.WriteLine(data[0]);
        }

    }
    catch (Exception e)
    {

    }
}
</code>```

but this is  not printing any thing on the console! can you please let me know what I am doing wrong?

答:
If you are running this under Debug, see here: Attempt by method 'System.Web.Helpers.Json..cctor()' to access method 'System.Web.Helpers.Json.CreateSerializer()' failed  once I unchecked Enable the Visual Studio hosting process it run with results.  However, to get what I think you want (a listing of each of the key/value pairs I switched to a foreach and it printed it out nicely:</p>

```<code>try

    {
        var data = Json.Decode(jsonData);
        //for (var i = 0; i <= data.Length - 1; i++)
        foreach (var j in data)
        {
            Console.WriteLine(j);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
</code>```

Title: Parsing JSON Name Pair in C#

Body:
Using C# to parse JSON URL I am facing some issues. As you know JSON data is written as name/value pairs. now in URL JSON I have  these data:

{
   "currentVersion":10.41,
   "serviceDescription":"There are some text here",
   "hasVersionedData":true,
   "supportsDisconnectedEditing":false,
   "syncEnabled":false,
   "supportedQueryFormats":"JSON",
   "maxRecordCount":1000
 }

and I want to only print out the name part of the JSON data using this code

using (var wc = new WebClient())
{
    string json = wc.DownloadString("http://xxxxxxxxx?f=pjson");
    try
    {
        dynamic data = Json.Decode(json);
        for (int i = 0; i <= data.Length - 1; i++)
        {
            Console.WriteLine(data[0]);
        }

    }
    catch (Exception e)
    {

    }
}

but this is  not printing any thing on the console! can you please let me know what I am doing wrong?

Body:
If you are running this under Debug, see here: Attempt by method 'System.Web.Helpers.Json..cctor()' to access method 'System.Web.Helpers.Json.CreateSerializer()' failed  once I unchecked Enable the Visual Studio hosting process it run with results.  However, to get what I think you want (a listing of each of the key/value pairs I switched to a foreach and it printed it out nicely:

try

    {
        var data = Json.Decode(jsonData);
        //for (var i = 0; i <= data.Length - 1; i++)
        foreach (var j in data)
        {
            Console.WriteLine(j);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }


答:
You have get the element with getElementById(id) and then access the innerHTML property with .innerHTML. Depending on exactly what you want, you might be looking for innerText or textContent.

Quick notes about innerHTML, innerText, and textContent:

innerHTML can alter the actual html elements on the page, including removing or adding elements.

innerText will get or set plain text to elements; however, is aware of certain situations and may leave out some text.

textContent will get everything as plain text.

```<code>var $ = function(id){
    //commonly used function to easily access html elements from javascript
    return document.getElementById(id);
}

$("msgDiv").innerHTML = "something";
</code>```

Title: How to access innerHTML of a div produced after some other process takes place using DOM

Body:
You have get the element with getElementById(id) and then access the innerHTML property with .innerHTML. Depending on exactly what you want, you might be looking for innerText or textContent.

Quick notes about innerHTML, innerText, and textContent:

innerHTML can alter the actual html elements on the page, including removing or adding elements.

innerText will get or set plain text to elements; however, is aware of certain situations and may leave out some text.

textContent will get everything as plain text.

var $ = function(id){
    //commonly used function to easily access html elements from javascript
    return document.getElementById(id);
}

$("msgDiv").innerHTML = "something";


问:
What are the necessary special member functions that should to be declared?
I am currently learning about C++. I learnt about some special member functions which are generated by the compiler.

• Default constructor. • Copy constructor • Move Constructor • Copy assignment operator • Move assignment operator • Destructor

I know about the functionalities of each member function. But I wanna know which of these member function are necessary and should be declared (instead of being generated by the compiler), as a part of good coding practices, keeping memory and efficiency in mind.

答:
The default constructor is sort of the odd man out here. Whether or not you have a default construct doesn't necessarily have any relationship to whether you write the others (although, writing a move constructor without a default constructor can be hard in practice).

In most cases you should try to follow the Rule of Zero (http://en.cppreference.com/w/cpp/language/rule_of_three, http://www.nirfriedman.com/2015/06/27/cpp-rule-of-zero/), which means that you would not write any of these member functions for your class. Instead, choose members that correctly express the ownership semantics you want for various resources. A member std::vector correctly handles copying and movement the way you would want, so a class with such a member wouldn't necessarily need any special members. If you tried to use a raw pointer that was created with new[], however, as an array, then you would have many of these issues to deal with, and would need to write special member functions.

If you need to write one, you should explicitly think about all of them, but it doesn't mean you have to write all of them. Sometimes you may want to =default or =delete some of them. A quick example:

```<code>template <class T>
copy_ptr {
  copy_ptr() = default;
  copy_ptr(copy_ptr&&) = default;
  copy_ptr& operator=(copy_ptr&&) = default;

  copy_ptr(const copy_ptr& other)
    : m_resource(make_unique<T>(*other.m_resource)
 {}

 copy_ptr& operator=(const copy_ptr& other) {
   m_resource = make_unique<T>(*other.m_resource);
 }
 // define operator*, etc

  std::unique_ptr<T> m_resource;
};
</code>```

This is a pointer, that instead of being uncopyable like unique_ptr, makes a deep copy of the object that it holds. However, we were able to use the default constructor, move operators, and destructors "as-is" from unique_ptr, so we defaulted them. We only rewrote the copy operations, doing the minimum work.

Basically, the idea with special operators in C++ is to push them "downwards", into smaller objects/classes. Which are typically solely responsible for managing that resource. Bigger classes that coordinate business logic should try very hard to defer resource management concerns to members.

Body:
The default constructor is sort of the odd man out here. Whether or not you have a default construct doesn't necessarily have any relationship to whether you write the others (although, writing a move constructor without a default constructor can be hard in practice).

In most cases you should try to follow the Rule of Zero (http://en.cppreference.com/w/cpp/language/rule_of_three, http://www.nirfriedman.com/2015/06/27/cpp-rule-of-zero/), which means that you would not write any of these member functions for your class. Instead, choose members that correctly express the ownership semantics you want for various resources. A member std::vector correctly handles copying and movement the way you would want, so a class with such a member wouldn't necessarily need any special members. If you tried to use a raw pointer that was created with new[], however, as an array, then you would have many of these issues to deal with, and would need to write special member functions.

If you need to write one, you should explicitly think about all of them, but it doesn't mean you have to write all of them. Sometimes you may want to =default or =delete some of them. A quick example:

template <class T>
copy_ptr {
  copy_ptr() = default;
  copy_ptr(copy_ptr&&) = default;
  copy_ptr& operator=(copy_ptr&&) = default;

  copy_ptr(const copy_ptr& other)
    : m_resource(make_unique<T>(*other.m_resource)
 {}

 copy_ptr& operator=(const copy_ptr& other) {
   m_resource = make_unique<T>(*other.m_resource);
 }
 // define operator*, etc

  std::unique_ptr<T> m_resource;
};

This is a pointer, that instead of being uncopyable like unique_ptr, makes a deep copy of the object that it holds. However, we were able to use the default constructor, move operators, and destructors "as-is" from unique_ptr, so we defaulted them. We only rewrote the copy operations, doing the minimum work.

Basically, the idea with special operators in C++ is to push them "downwards", into smaller objects/classes. Which are typically solely responsible for managing that resource. Bigger classes that coordinate business logic should try very hard to defer resource management concerns to members.


问:
Javascript setTimeout function call with event argument?
What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

```<code>function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}
</code>```

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

答:
Firstly why are you using two timeouts? It looks to me like setInterval() would be better

```<code>function MouseDownEvent(e) {
 *snip*
 clearInterval(intervalID);
 intervalID = setInterval(function(){checkPos(e);}, 500);
}
</code>```

Secondly could you please clarify this : "...but never updates the e object as the user moves the mouse." Why would the event object be updated when the user moves the mouse? You've only assigned a mouseDown handler. If you wanted to do something on every mouse move then you should use a mouseMove event, in which case the timeout / interval would be unnecessary anyway.

```<code>function MouseMoveEvent(e) {
 //called every time the mouse is moved, event object will contain position
}
</code>```

As always in JavaScript you should look for an event driven solution first and only use timed handlers when you absolutely have to.

*Edit - addressing issues op raised in comments *

```<code>var handler = {
    i : 0,
    function : mouseMoveEvent(e) {
      handler.i++;
      if (handler.i % 100 == 0) {
        //Do expensive operations
      }
    }
}

$(myElement).bind("mousemove", handler.mouseMoveEvent);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

Body:
Firstly why are you using two timeouts? It looks to me like setInterval() would be better

function MouseDownEvent(e) {
 *snip*
 clearInterval(intervalID);
 intervalID = setInterval(function(){checkPos(e);}, 500);
}

Secondly could you please clarify this : "...but never updates the e object as the user moves the mouse." Why would the event object be updated when the user moves the mouse? You've only assigned a mouseDown handler. If you wanted to do something on every mouse move then you should use a mouseMove event, in which case the timeout / interval would be unnecessary anyway.

function MouseMoveEvent(e) {
 //called every time the mouse is moved, event object will contain position
}

As always in JavaScript you should look for an event driven solution first and only use timed handlers when you absolutely have to.

*Edit - addressing issues op raised in comments *

var handler = {
    i : 0,
    function : mouseMoveEvent(e) {
      handler.i++;
      if (handler.i % 100 == 0) {
        //Do expensive operations
      }
    }
}

$(myElement).bind("mousemove", handler.mouseMoveEvent);


问:
DI with arguments in the constructor
So I'm implementing a Dependency Injection framework into my Java project (Google Guice) and everything is pretty good, I like it but there's a small problem;
I want to make a static instance of my main project's class (where it instantiates the dependencies, etc). But I don't know any method to instantiate it using Guice, I can't instantiate it manually because I'm using DI in the constructor of it (I have objects in the constructor) which means that I am not able to access the class' non-static variables needed to instantiate the class.
I tried using a Provider but I couldn't really understand where to bind it, because I don't want to have an interface for the main class (will if needed).

答:
If you are wanting to mix a static instance of a class with dependency injection, you have somewhat missed the point of dependency injection: you can simply inject the instance of the class.

If you want there to be a single instance of a class for your injector, bind it in @Singleton scope: either:

```<code>bind(YourClass.class).in(Singleton.class);
</code>```

in your module's configure() method, or

```<code>@Provides @Singleton YourClass provideYourClassInstance() {
  // ...
}
</code>```

in your module, or

```<code>@Singleton class YourClass {
  // ...
}
</code>```

in the actual class declaration.

Then just inject this instance like any other:

```<code>class SomeOtherClass {
  @Inject SomeOtherClass(YourClass instance) {
    // ... Do something with instance, like assign it to a field.
  }
}
</code>```

The point is that SomeOtherClass shouldn't need know anything about the lifetime of instance: it simply doesn't matter whether this is a singleton instance, or every class using it has its own instance.

Title: DI with arguments in the constructor

Body:
If you are wanting to mix a static instance of a class with dependency injection, you have somewhat missed the point of dependency injection: you can simply inject the instance of the class.

If you want there to be a single instance of a class for your injector, bind it in @Singleton scope: either:

bind(YourClass.class).in(Singleton.class);

in your module's configure() method, or

@Provides @Singleton YourClass provideYourClassInstance() {
  // ...
}

in your module, or

@Singleton class YourClass {
  // ...
}

in the actual class declaration.

Then just inject this instance like any other:

class SomeOtherClass {
  @Inject SomeOtherClass(YourClass instance) {
    // ... Do something with instance, like assign it to a field.
  }
}

The point is that SomeOtherClass shouldn't need know anything about the lifetime of instance: it simply doesn't matter whether this is a singleton instance, or every class using it has its own instance.


问:
graphQL join on common column
how we can do data join on a common column in graphQL.

For example in SQL : Select t.name and z.address where t.id=z.id;

how is this managed by graphQL query.

答:
How is this managed by GraphQL query?

The short answer: It's not (managed). You have to write it in your resolvers.

Your GraphQL schema is basically just a declaration of types that represent nodes, and fields that represent edges in a graph. GraphQL is the language to query this graph. At each edge in your schema, you write a function for how to get the data when the query traverses that edge. This function is called a "resolver", and you can put pretty much any code in your resolvers as long as it returns valid data. This means GraphQL is completely, absolutely database-independent. Your resolvers are responsible for talking to your database(s).

So when it comes to SQL, and joins, the concern of making the queries is entirely the responsibility of the API developer. GraphQL knows nothing about SQL or joins, so this is essentially custom logic for your application which you must write. It turns out that building SQL queries to resolve data for GraphQL queries is very difficult without running into problems like eagerly fetching too much data or the "N+1" problem.

Some tools in the open-source community have emerged to help solve this problem. Here are a couple I would recommend in the Node.js space:

DataLoader - A database-agnostic tool that batches queries and caches individual records.

Join Monster - A SQL-tailored tool for efficient data-retrieval and query batching. It examines each query and your schema and generates SQL queries dynamically.

Disclaimer: I'm a co-creator of Join Monster.

Title: graphQL join on common column


问:
Tab navigation in bootstrap not working with another jquery
I am in dilemna on how to get this resolved. Basically I am using tab in bootstrap modal and is using button to navigate from one tab to another. I incorporatyed jquery for that. But I also wrote a jquery to allow me to select multiple radio button with same name (using value), But when I incorprated jquery library it seems to stop navigation from happening and when I remove this jquery navigation strrats happening. I believe this happening because jquery for radio button is v1.3.2 while for navigation is v2.1.1 . however I need to use both to fulfil the requirement? please suggest on how to resolve this. Below is the code :

 $(document).ready(function(){
            $("#selectINTI").click(function () {
            $('input:radio[name=app_decision]:nth(0)').attr('checked',true);
            //$('input:radio[name=app_decision]')[0].checked = true;
            });
            $("#selectINTE").click(function () {
            $('input:radio[name=app_decision]:nth(1)').attr('checked',true);
            //$('input:radio[name=app_decision]')[1].checked = true;
            });
            $("#selectR").click(function () {
            $('input:radio[name=app_decision]:nth(2)').attr('checked',true);
            //$('input:radio[name=app_decision]')[2].checked = true;
            });
          });

 $('.btnNext').click(function(){
  $('.nav-tabs > .active').next('li').find('a').trigger('click');
});

  $('.btnPrevious').click(function(){
  $('.nav-tabs > .active').prev('li').find('a').trigger('click');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset {
border:2px solid black;
border-radius:10px;
padding:20px;
position:relative;
}
legend {
background: #FF9;
border: solid 1px black;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
padding: 4px;
margin:0px;
}
    .modal .modal-dialog {
    width: 90%;
        }</code>```

        <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
        <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>admission_dec</title>
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
        <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <fieldset>
        <legend> Search</legend>

        Academic Year
        <input class="form-control input-sm"  name="acad_period" required>

        Class
        <select name="stuclass" class="form-control" required>
        <option value="">Please select...</option>
        <option value="13">XII</option>
        <option value="12">XI</option>
        <option value="11">X</option>
        <option value="10">IX</option>
        <option value="9">VIII</option>
        <option value="8">VII</option>
        <option value="7">VI</option>
        <option value="6">V</option>
        <option value="5">IV</option>
        <option value="4">III</option>
        <option value="3">II</option>
        <option value="2">I</option>
        <option value="1">KG/Prep</option>
        <option value="Nurs">Nursery</option>
        </select>

        Application Status
        <select name="appstatus" class="form-control" required>
        <option value="">Please select...</option>
        <option value="N">New</option>
        <option value="INTI">Invited for Interview</option>
        <option value="INTE">Invited for Exam</option>
        </select>

        <input name="adm_search" value="Search" class="btn btn-success" type="submit">
        <input name="adm_cancel" value="Cancel" class="btn btn-danger" type="reset">

        </fieldset>

         Result
        Decision

        Student ID
        Name
        App.Status
        App.Date

        <button name="app_intall"  class="btn btn-info btn-md" value="Interview All" id="selectINTI">Interview All</button>
        <button name="app_eall" class="btn btn-info btn-md" value="Exam All" id="selectINTE">Exam All</button>
        <button name="app_rall" class="btn btn-info btn-md" value="Reject All" id="selectR">Reject All</button>

        <button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#myModal">
         View</button>

        <input name="app_decision" value="INTI" type="radio" >Interview

        <input name="app_decision" value="INTE" type="radio">Exam

        <input name="app_decision" value="R" type="radio">Reject

        <button type="button" name="adm_submit"  class="btn btn-success"> Process</button>
        <button type="reset" name="adm_cancel"  class="btn btn-danger"> Cancel</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Student Appilcation Form

Applicant Detail

Additional Details

Father's Detail

Mother's Detail

Guardian's Detail

Sibling's Detail

                        <fieldset>
        <legend>Personal Details</legend>

        Title
        <input class="form-control input-sm" name="stutitle" readonly>

        Gender
        <input class="form-control input-sm" name="stugender" readonly>

        Age(yrs)
        <input class="form-control input-sm" name="stuage" readonly>

        Firstname
        <input class="form-control input-sm" name="stufname" readonly>

        Height(cm)
        <input class="form-control input-sm" name="stuheight" readonly>

        Birthdate
        <input class="form-control input-sm" name="studob" readonly>

        Surname
        <input name="stusname" class="form-control input-sm" readonly>

        Mobile
        <input name="stumobile" class="form-control input-sm" readonly>

        Homephone
        <input name="stuhphone" class="form-control input-sm" readonly>

        Nationality
        <input name="stunatn" class="form-control input-sm" readonly>

        Middlename
        <input name="stumname" class="form-control input-sm" readonly>

        Email Address
        <input size="52" class="form-control input-sm" name="stuemail" readonly>

        </fieldset>

        <fieldset>
        <legend>Address Details</legend>

        Address Line 1
        <input  name="stuadd1" size="40" class="form-control input-sm" readonly>

        Address Line 2
        <input  name="stuadd2" size="40"  class="form-control input-sm" readonly>

        Address Line 3
        <input  name="stuadd3" size="40"  class="form-control input-sm" readonly>

        City
        <input  name="stucity" class="form-control input-sm" readonly>

        State
        <input name="stustate" class="form-control input-sm" readonly>

        Country
        <input  name="stucountry" class="form-control input-sm" readonly>

        Pincode
        <input  name="stupostcode" class="form-control input-sm" readonly>

        </fieldset>

        <fieldset>
        <legend>Application Details</legend>

        Class Applied for
        <input  name="appclass_applied" class="form-control input-sm" readonly>

        Year Applied for
        <input  name="acad_period" class="form-control input-sm" readonly>

        Previous Class
        <input  name="app_prevclass"  size="5" class="form-control input-sm" readonly>

        Year Passed
        <input  name="app_prevyear"  size="5" class="form-control input-sm" readonly>

        Previous CGPA/Percentage
        <input name="app_prevcgpaper"  size="5" class="form-control input-sm" readonly>

        Previous School Name
        <input name="app_prevschlname" type="text" class="form-control input-sm" readonly>

        Previous School Board
        <input name="app_prevboard" type="text" class="form-control input-sm" readonly>
        <input name="app_prevboard_oth" class="form-control input-sm" readonly>

        </fieldset>

                 Next >>
                 <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        Blood Group
        <input name="stublgrp" class="form-control input-sm" readonly>

        Weight(kg)
        <input name="stuweight" class="form-control input-sm" readonly>

        Student Category
        <input name="stucategory" class="form-control input-sm" readonly>
        <input name="stucato" class="form-control input-sm" readonly>

        Allergy ?
        <input name="stuallergy_yes" class="form-control input-sm" readonly>

        Disability ?
        <input name="studisability_yes" class="form-control input-sm" readonly>

        Transport needed ?
        <input name="stutransport" class="form-control input-sm" readonly>

        School Distance (km)
        <input name="stutransport_dist" class="form-control input-sm" readonly>

        Birth Place
        <input name="stubplace" class="form-control input-sm" readonly>

        Mother Tongue
        <input name="stumthtng" class="form-control input-sm" readonly>

        Religion
        <input name="stureligion" class="form-control input-sm" readonly>

        Identity Type
        <input name="stuidentity" class="form-control input-sm" readonly>

        Id Number
        <input name="stuidentitynum" class="form-control input-sm" readonly>

        << Previous
        Next >>
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        Next >>
        << Previous
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        << Previous
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        77777777

        << Previous
        Next >>
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        ID
        Name
        Birthdate
        Class
        Gende
        School Name

        << Previous
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

```

答:
The problem was that attr wasn't properly unsetting the checked property. If you remove your old jQuery library (v1.3.2) you can use the .prop function which handles the toggles correctly (http://api.jquery.com/prop/)</p>

```<code>$(document).ready(function() {
   $("#selectINTI").click(function() {
     $('input:radio[name=app_decision]:nth(0)').prop('checked', true);
   });
   $("#selectINTE").click(function() {
     $('input:radio[name=app_decision]:nth(1)').prop('checked', true);
   });
   $("#selectR").click(function() {
     $('input:radio[name=app_decision]:nth(2)').prop('checked', true);
   });
});
</code>```

Body:
I am in dilemna on how to get this resolved. Basically I am using tab in bootstrap modal and is using button to navigate from one tab to another. I incorporatyed jquery for that. But I also wrote a jquery to allow me to select multiple radio button with same name (using value), But when I incorprated jquery library it seems to stop navigation from happening and when I remove this jquery navigation strrats happening. I believe this happening because jquery for radio button is v1.3.2 while for navigation is v2.1.1 . however I need to use both to fulfil the requirement? please suggest on how to resolve this. Below is the code :

 $(document).ready(function(){
            $("#selectINTI").click(function () {
            $('input:radio[name=app_decision]:nth(0)').attr('checked',true);
            //$('input:radio[name=app_decision]')[0].checked = true;
            });
            $("#selectINTE").click(function () {
            $('input:radio[name=app_decision]:nth(1)').attr('checked',true);
            //$('input:radio[name=app_decision]')[1].checked = true;
            });
            $("#selectR").click(function () {
            $('input:radio[name=app_decision]:nth(2)').attr('checked',true);
            //$('input:radio[name=app_decision]')[2].checked = true;
            });
          });

 $('.btnNext').click(function(){
  $('.nav-tabs > .active').next('li').find('a').trigger('click');
});

  $('.btnPrevious').click(function(){
  $('.nav-tabs > .active').prev('li').find('a').trigger('click');
});

fieldset {
border:2px solid black;
border-radius:10px;
padding:20px;
position:relative;
}
legend {
background: #FF9;
border: solid 1px black;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
padding: 4px;
margin:0px;
}
    .modal .modal-dialog {
    width: 90%;
        }

        <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
        <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>admission_dec</title>
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
        <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <fieldset>
        <legend> Search</legend>

        Academic Year
        <input class="form-control input-sm"  name="acad_period" required>

        Class
        <select name="stuclass" class="form-control" required>
        <option value="">Please select...</option>
        <option value="13">XII</option>
        <option value="12">XI</option>
        <option value="11">X</option>
        <option value="10">IX</option>
        <option value="9">VIII</option>
        <option value="8">VII</option>
        <option value="7">VI</option>
        <option value="6">V</option>
        <option value="5">IV</option>
        <option value="4">III</option>
        <option value="3">II</option>
        <option value="2">I</option>
        <option value="1">KG/Prep</option>
        <option value="Nurs">Nursery</option>
        </select>

        Application Status
        <select name="appstatus" class="form-control" required>
        <option value="">Please select...</option>
        <option value="N">New</option>
        <option value="INTI">Invited for Interview</option>
        <option value="INTE">Invited for Exam</option>
        </select>

        <input name="adm_search" value="Search" class="btn btn-success" type="submit">
        <input name="adm_cancel" value="Cancel" class="btn btn-danger" type="reset">

        </fieldset>

         Result
        Decision

        Student ID
        Name
        App.Status
        App.Date

        <button name="app_intall"  class="btn btn-info btn-md" value="Interview All" id="selectINTI">Interview All</button>
        <button name="app_eall" class="btn btn-info btn-md" value="Exam All" id="selectINTE">Exam All</button>
        <button name="app_rall" class="btn btn-info btn-md" value="Reject All" id="selectR">Reject All</button>

        <button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#myModal">
         View</button>

        <input name="app_decision" value="INTI" type="radio" >Interview

        <input name="app_decision" value="INTE" type="radio">Exam

        <input name="app_decision" value="R" type="radio">Reject

        <button type="button" name="adm_submit"  class="btn btn-success"> Process</button>
        <button type="reset" name="adm_cancel"  class="btn btn-danger"> Cancel</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Student Appilcation Form

Applicant Detail

Additional Details

Father's Detail

Mother's Detail

Guardian's Detail

Sibling's Detail

                        <fieldset>
        <legend>Personal Details</legend>

        Title
        <input class="form-control input-sm" name="stutitle" readonly>

        Gender
        <input class="form-control input-sm" name="stugender" readonly>

        Age(yrs)
        <input class="form-control input-sm" name="stuage" readonly>

        Firstname
        <input class="form-control input-sm" name="stufname" readonly>

        Height(cm)
        <input class="form-control input-sm" name="stuheight" readonly>

        Birthdate
        <input class="form-control input-sm" name="studob" readonly>

        Surname
        <input name="stusname" class="form-control input-sm" readonly>

        Mobile
        <input name="stumobile" class="form-control input-sm" readonly>

        Homephone
        <input name="stuhphone" class="form-control input-sm" readonly>

        Nationality
        <input name="stunatn" class="form-control input-sm" readonly>

        Middlename
        <input name="stumname" class="form-control input-sm" readonly>

        Email Address
        <input size="52" class="form-control input-sm" name="stuemail" readonly>

        </fieldset>

        <fieldset>
        <legend>Address Details</legend>

        Address Line 1
        <input  name="stuadd1" size="40" class="form-control input-sm" readonly>

        Address Line 2
        <input  name="stuadd2" size="40"  class="form-control input-sm" readonly>

        Address Line 3
        <input  name="stuadd3" size="40"  class="form-control input-sm" readonly>

        City
        <input  name="stucity" class="form-control input-sm" readonly>

        State
        <input name="stustate" class="form-control input-sm" readonly>

        Country
        <input  name="stucountry" class="form-control input-sm" readonly>

        Pincode
        <input  name="stupostcode" class="form-control input-sm" readonly>

        </fieldset>

        <fieldset>
        <legend>Application Details</legend>

        Class Applied for
        <input  name="appclass_applied" class="form-control input-sm" readonly>

        Year Applied for
        <input  name="acad_period" class="form-control input-sm" readonly>

        Previous Class
        <input  name="app_prevclass"  size="5" class="form-control input-sm" readonly>

        Year Passed
        <input  name="app_prevyear"  size="5" class="form-control input-sm" readonly>

        Previous CGPA/Percentage
        <input name="app_prevcgpaper"  size="5" class="form-control input-sm" readonly>

        Previous School Name
        <input name="app_prevschlname" type="text" class="form-control input-sm" readonly>

        Previous School Board
        <input name="app_prevboard" type="text" class="form-control input-sm" readonly>
        <input name="app_prevboard_oth" class="form-control input-sm" readonly>

        </fieldset>

                 Next >>
                 <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        Blood Group
        <input name="stublgrp" class="form-control input-sm" readonly>

        Weight(kg)
        <input name="stuweight" class="form-control input-sm" readonly>

        Student Category
        <input name="stucategory" class="form-control input-sm" readonly>
        <input name="stucato" class="form-control input-sm" readonly>

        Allergy ?
        <input name="stuallergy_yes" class="form-control input-sm" readonly>

        Disability ?
        <input name="studisability_yes" class="form-control input-sm" readonly>

        Transport needed ?
        <input name="stutransport" class="form-control input-sm" readonly>

        School Distance (km)
        <input name="stutransport_dist" class="form-control input-sm" readonly>

        Birth Place
        <input name="stubplace" class="form-control input-sm" readonly>

        Mother Tongue
        <input name="stumthtng" class="form-control input-sm" readonly>

        Religion
        <input name="stureligion" class="form-control input-sm" readonly>

        Identity Type
        <input name="stuidentity" class="form-control input-sm" readonly>

        Id Number
        <input name="stuidentitynum" class="form-control input-sm" readonly>

        << Previous
        Next >>
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        Next >>
        << Previous
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        << Previous
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        77777777

        << Previous
        Next >>
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

        ID
        Name
        Birthdate
        Class
        Gende
        School Name

        << Previous
         <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

Body:
The problem was that attr wasn't properly unsetting the checked property. If you remove your old jQuery library (v1.3.2) you can use the .prop function which handles the toggles correctly (http://api.jquery.com/prop/)

$(document).ready(function() {
   $("#selectINTI").click(function() {
     $('input:radio[name=app_decision]:nth(0)').prop('checked', true);
   });
   $("#selectINTE").click(function() {
     $('input:radio[name=app_decision]:nth(1)').prop('checked', true);
   });
   $("#selectR").click(function() {
     $('input:radio[name=app_decision]:nth(2)').prop('checked', true);
   });
});


问:
Using ng-if inside ng-options to filter null results
I'm trying to filter out "null" results from a select dropdown list.
Until now I was using just regular html <select> + <option> with ng-repeat and excluding null result this way:

```<code><option ng-repeat="person in showCase.persons" ng-if="person.profiles">
{{person.profiles}}
</option>
</code>```

This way I could get a list without empty/null 'user profile'.
Now I started using ng-options instead because the list includes arrays with objects,
but I can't get the null results out - ..when I'm using ng-if the whole <select> disappears :

```<code><select ng-model="profile_filter" ng-options="person.profiles for person in persons"
ng-if="person.profiles">
</select>
</code>```

My priority was doing it inline and not in my controller because there's many <select> objects in the page, and some do require the "null" results to show.
I know, it's a very basic question, but still it got me stuck for the last 2 hours.
Thanks.

答: Try with ng-if="person.profiles!=null" to get a boolean value.

Body:
I'm trying to filter out "null" results from a select dropdown list.
Until now I was using just regular html <select> + <option> with ng-repeat and excluding null result this way:

<option ng-repeat="person in showCase.persons" ng-if="person.profiles">
{{person.profiles}}
</option>

This way I could get a list without empty/null 'user profile'.
Now I started using ng-options instead because the list includes arrays with objects,
but I can't get the null results out - ..when I'm using ng-if the whole <select> disappears :

<select ng-model="profile_filter" ng-options="person.profiles for person in persons"
ng-if="person.profiles">
</select>

My priority was doing it inline and not in my controller because there's many <select> objects in the page, and some do require the "null" results to show.
I know, it's a very basic question, but still it got me stuck for the last 2 hours.
Thanks.


问:
Iterate over file and get word index from other file
I need to iterate over all lines in two files (kind of at the same time) and get the index from a word of one of them.

Example:

small_wordlist:

```<code>Book
Woman
Child
</code>```

big_wordlist:

```<code>Book
Man
Dog
Cat
Child
Dinosaur
Woman
</code>```

And so on.
the wanted result would be:

```<code>1
7
5
</code>```

(or every time one less since we start with 0, that doesn't really matter) and save that in another file.

I can't get it to work with sth like this:

```<code>g = open('big_wordlist', 'r')
i = open('index_list', 'w')

with open('small_wordlist', 'r') as h:
for line in h:
    p = h.readline()
    for num, line in enumerate(g):          # num is my found index
            if (line.startswith(p + "\n")): # need that to make sure we only get the correct word and nothing before / after it
                 i.write("%s" % (num) + "\n")
</code>```

So i need to iterate over the small wordlist, get the specific word index from the word found in the big wordlist and write it in my index list.

Now i get "mixing iteration and read methods would lose data" - i would not care about that after i wrote the num into my index list, the p (word at that time) will change (and should) anyway with each new line in small_wordlist.

I have problems when i do my iteration over the small wordlist, when I replace p with "Book" it does work, now I need make it work with a variable that is the word in each line of my small wordlist.

答:
You don't need to process the two files at the same time. Instead, you need to build an index of the first file, and then process the second file looking up words in the index.</p>

```<code>#!python3

small_wordlist = """
    Book
    Woman
    Child
""".strip()

big_wordlist = """
    Book
    Man
    Dog
    Cat
    Child
    Dinosaur
    Woman
""".strip()

import io

# Read the words from the big wordlist into word_index

#with open('big_wordlist.txt') as big:
with io.StringIO(big_wordlist) as big:
    ix = 0
    word_index = {}

    for line in big:
        word = line.strip()
        if word not in word_index:
            word_index[word] = ix
        ix += 1

#with open('small_wordlist.txt') as small:
with io.StringIO(small_wordlist) as small:
    for line in small:
        word = line.strip()
        if word not in word_index:
            print('-1')  # Or print('not found') or raise exception or...
        else:
            print(word_index[word])
</code>```

Body:
I need to iterate over all lines in two files (kind of at the same time) and get the index from a word of one of them.

Example:

small_wordlist:

Book
Woman
Child

big_wordlist:

Book
Man
Dog
Cat
Child
Dinosaur
Woman

And so on.
the wanted result would be:

1
7
5

(or every time one less since we start with 0, that doesn't really matter) and save that in another file.

I can't get it to work with sth like this:

g = open('big_wordlist', 'r')
i = open('index_list', 'w')

with open('small_wordlist', 'r') as h:
for line in h:
    p = h.readline()
    for num, line in enumerate(g):          # num is my found index
            if (line.startswith(p + "\n")): # need that to make sure we only get the correct word and nothing before / after it
                 i.write("%s" % (num) + "\n")

So i need to iterate over the small wordlist, get the specific word index from the word found in the big wordlist and write it in my index list.

Now i get "mixing iteration and read methods would lose data" - i would not care about that after i wrote the num into my index list, the p (word at that time) will change (and should) anyway with each new line in small_wordlist.

I have problems when i do my iteration over the small wordlist, when I replace p with "Book" it does work, now I need make it work with a variable that is the word in each line of my small wordlist.

Body:
You don't need to process the two files at the same time. Instead, you need to build an index of the first file, and then process the second file looking up words in the index.

#!python3

small_wordlist = """
    Book
    Woman
    Child
""".strip()

big_wordlist = """
    Book
    Man
    Dog
    Cat
    Child
    Dinosaur
    Woman
""".strip()

import io

# Read the words from the big wordlist into word_index

#with open('big_wordlist.txt') as big:
with io.StringIO(big_wordlist) as big:
    ix = 0
    word_index = {}

    for line in big:
        word = line.strip()
        if word not in word_index:
            word_index[word] = ix
        ix += 1

#with open('small_wordlist.txt') as small:
with io.StringIO(small_wordlist) as small:
    for line in small:
        word = line.strip()
        if word not in word_index:
            print('-1')  # Or print('not found') or raise exception or...
        else:
            print(word_index[word])


问:
Uploading files with PHP on a linux machine
I'm trying to make some sort of cloud application on a headless raspbian machine.
The testing happens on a wamp-server running on windows8.1. PHP version is 5.6

The code works fine on my testing windows, but I run into issues when running the same code on my linux server. I've narrowed down the issue to the fact that (the linux user behind) my PHP code doesn't have write permissions on the folder where it should store files.

I can think of two ways to solve the issue: either give that php-user permissions, or change the user behind the php code. The last one would be quite interesting if it was possible to change per-script.

So, for my concrete question:

1) Where can I find what user is being used by my PHP code?

2) Can I change what user my PHP code uses, preferably on a per-project basis?

EDIT:

My script was running as root, as is shown by echo get_current_user();. I changed ownership of all files to root:webhosting, which was previously ftpuser:ftpgroup. However, when setting permissions to 770 I get access denied

EDIT2:

When using var_dump(posix_geteuid()); instead of get_current_user();, i get UID 33, which matches user www-data.

SOLUTION:

By looking at the EUID with var_dump(posix_geteuid(); I was able to validate the actual user, which does NOT match the get_current_user();. Changing the directroy and all files in it with sudo chown -R www-data:www-data <root of site> I managed to set the correct permissions.

答:
You're PHP/Apache user is probably www-data. You probably want to run something like this.

```<code>sudo find path/to/project/ -exec chown www-data:root {} \;
</code>```

File permissions may also be a problem. If so, run something like this.

```<code>sudo find path/to/project/ -type d -exec chmod 775 {} \;
sudo find path/to/project/ -type f -exec chmod 664 {} \;
</code>```

Body:
You're PHP/Apache user is probably www-data. You probably want to run something like this.

sudo find path/to/project/ -exec chown www-data:root {} \;

File permissions may also be a problem. If so, run something like this.

sudo find path/to/project/ -type d -exec chmod 775 {} \;
sudo find path/to/project/ -type f -exec chmod 664 {} \;


问:
Getting turbolinks wrapper to work with Ruby on Rails Devise
For my App, I am trying to set up the Turbolinks Mobile wrapper> . I am running into an issue where I can't sign into the App (and thinking the issues is that I need to modify Devise to get it to switch to XHR to work for the mobile).  My sign_in form uses Devise but I can't see the code.

Using:
ruby "2.4.0"
gem "rails", "5.0.2"
gem "turbolinks", "~> 5.0.0.beta"
gem "devise", ">= 4.2.0"
gem "devise-async", git: "https://github.com/mhfs/devise-async", branch: "devise-4.x" # for user authentication

My question is where to I look or what do I need to do to amend DEVISE to have it be able to send the XHR for the turbolinks mobile wrapper?

Right now, it won't sign in and I know (or I am thinking) I need to get DEVISE to switch to XHR but I don't know how.

Suggestions on how to do this?  Or recommendations on reference material?

答:
You need to update your devise initializer to accept ajax requests.

```<code>config.http_authenticatable_on_xhr = false
config.navigational_formats = ["*/*", :html, :json]
</code>```

You will probably need to update your registration and session controllers to respond to json also.

```<code>format.json { render json: resource }
</code>```

Body:
You need to update your devise initializer to accept ajax requests.

config.http_authenticatable_on_xhr = false
config.navigational_formats = ["*/*", :html, :json]

You will probably need to update your registration and session controllers to respond to json also.

format.json { render json: resource }


问:
SQLite + rails - working the database
I ended up in a situation where I have a relatively large table, and I need to add a new column to it. Sounds easy enough? Well, there is a catch - I also need to fill that new column with data based on data already present, but I have no idea how to automate this process.

I have columns 'title' and 'title_de', and new column is 'lang'. New column should contain either 'de' or 'eng' depending on if 'title' is blank or not (blank 'title' means it's 'de', non blank means it's 'eng').

How to tackle this?

答:
You will want to do something like this:

```<code>class AddColumnToItems < ActiveRecord::Migration[5.0]
  def change
    add_column :items, :lang, :string
    ActiveRecord::Base.transaction do
      Item.all.each do |item|
        item.lang = "de"
        item.lang = "eng" unless item.title.blank?
        item.save
      end
    end
  end
end
</code>```

Then:

```<code>rake db:migrate
</code>```

I hope that solves your problem!

Title: SQLite + rails - working the database

Body:
You will want to do something like this:

class AddColumnToItems < ActiveRecord::Migration[5.0]
  def change
    add_column :items, :lang, :string
    ActiveRecord::Base.transaction do
      Item.all.each do |item|
        item.lang = "de"
        item.lang = "eng" unless item.title.blank?
        item.save
      end
    end
  end
end

Then:

rake db:migrate

I hope that solves your problem!


问:
Is reading a file in a view a bad practice?
Assuming a simple blog with a database in which the articles are maintained as:

```<code> CREATE TABLE [Articles](
     [ArticleId] INT IDENTITY(1,1) NOT NULL,
     [ContentURL] NVARCHAR(250) NOT NULL
     ....
 )
</code>```

Would it be a good practice to include article's content in the view through reading the file located at ContentURL as: (To be particular, can be cache the file this way?)

```<code>@model Articles
...
<div class="row">
   <div class="col-md-8 col-xs-12">
       @Html.Raw(File.ReadAllText(Model.ContentURL))
   </div>
</div>
</code>```

Or would it be better to do this in the controller and pass it as ViewBag.RawContent? (Does the [OutputCache] attribute help keep the file in memory?)

On the other hand, how about storing the raw content directly in the database using NVARCHAR(MAX), is this the worst or the best practice?

答:
When answering this question, you have to think about a couple things:

What happens if you can't read all the text?

How often is the information going to change?

How difficult is the proposed solution to manage?

We know that File.ReadAllText() can throw an exception if the file can't be found, or if it is locked, or if you don't have permissions to the file any longer.  We also know that if you have an exception in the View, the user gets the ugly error page.  Neither of those are desirable.

I think it's safe to say that @Html.Raw(File.ReadAllText(Model.ContentURL)) is a bad idea in the View.

You need a way to recover if there does happen to be an exception thrown.

Your other solutions both provide the ability to handle the issues surrounding the first bullet.  They are also both pretty good solutions, so the answer for your project really depends on the answer to the next two bullets.

If your file isn't going to change once you deploy the app, then populating the ViewBag.RawContent is perfectly good.

You you need the ability for someone to edit that file without redeploying anything else, then you might want to use the database.

Body:
Assuming a simple blog with a database in which the articles are maintained as:

 CREATE TABLE [Articles](
     [ArticleId] INT IDENTITY(1,1) NOT NULL,
     [ContentURL] NVARCHAR(250) NOT NULL
     ....
 )

Would it be a good practice to include article's content in the view through reading the file located at ContentURL as: (To be particular, can be cache the file this way?)

@model Articles
...

       @Html.Raw(File.ReadAllText(Model.ContentURL))

Or would it be better to do this in the controller and pass it as ViewBag.RawContent? (Does the [OutputCache] attribute help keep the file in memory?)

On the other hand, how about storing the raw content directly in the database using NVARCHAR(MAX), is this the worst or the best practice?


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
PRINT 3 + 4

The Computer said 7.
And all this was visible on my parents TV. ON A TV!!! Can you imagine that? I was imediately hooked. You could tell a machine what to do and you could see on a TV. Wow.

Backgound: My dads employer bought a small computer (Robotron KC 85/1) for the engineers to get in touch with this technology. They could take it home to play with it at the weekend. So my dad brought it home and all he new about it was how to connect it and how to turn it on. One of his collegues told him the trick with the "PRINT" command and the addition of numbers. He showed me and I was hooked. This was about 1986 when I was 12. I am still hooked for basicly the same reason (telling a machine what to do).

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: EricSchaefer


问:
Get average color(s) of the screen in real time (Mac OS X)
Is it posible to get average color (or more) of the computer screen in real time on a Mac?

For example, if I'm watching this site it will probably be white. I'm trying to make very simple ambient light with Arduino.

答: I'm not a Mac developer, so I may be off the mark here, but I doubt Mac OS X provides a method specifically to get the average color of the screen.  What you could do is take a screenshot and resize it down to one pixel using Core Image, which should efficiently (using hardware acceleration where available) calculate the average.</p>


问:
Search special pattern in string: R
I like to know the number of 0's which are surrounded by 1. But if there are more than one 0 without interrupted by a 1 it count only as one.

```<code>string <- "1101000010101111001110"
</code>```

This is the closest I'm able to do:

```<code>length(gregexpr(pattern ="101",string)[[1]])
</code>```

Expected output:

```<code>5
</code>```

答:
With gregexpr you can use lookahead assertion with perl=True to find overlapping matches:

(?=...) is a lookahead assertion:

(?=...)

A zero-width positive lookahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.

```<code>length(gregexpr("(?=10+1)", string, perl=TRUE)[[1]])
</code>```

Title: Search special pattern in string: R

Body:
I like to know the number of 0's which are surrounded by 1. But if there are more than one 0 without interrupted by a 1 it count only as one.

string <- "1101000010101111001110"

This is the closest I'm able to do:

length(gregexpr(pattern ="101",string)[[1]])

Expected output:

5

Body:
With gregexpr you can use lookahead assertion with perl=True to find overlapping matches:

(?=...) is a lookahead assertion:

(?=...)

A zero-width positive lookahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.

length(gregexpr("(?=10+1)", string, perl=TRUE)[[1]])


问:
Postgres CASE and Range to give a scaled score
I have a table that looks like this:

```<code>table: move_score_total
ID | Move_score_total
1  | 5.7865
2 .| 11.543
3 .| 14.29734
</code>```

and so on....
I'd like to run a query that delivers this (don't care about column order):

```<code>table: move_score_total
ID | scaled_score | Move_score_total
1  | 200          |5.7865
2 .| 80           |11.543
3 .| 20           |14.29734
</code>```

I am new to case and ranges, but I thought this query might be close. Am I? Or am I way off as the error I get is:

```<code>ERROR:  syntax error at or near "numrange"
LINE 3: ...  WHEN move_score_total.move_score_total::numeric numrange[0...

SELECT move_score_total."ID",
CASE move_score_total.move_score_total
   WHEN move_score_total.move_score_total numrange[0,8) THEN 200
   WHEN move_score_total.move_score_total numrange[8,10) THEN 100
   WHEN move_score_total.move_score_total numrange[10,12) THEN 80
   WHEN move_score_total.move_score_total numrange[12,14) THEN 40
   WHEN move_score_total.move_score_total numrange[14,16) THEN 20
   WHEN move_score_total.move_score_total numrange[16,18) THEN 10
   WHEN move_score_total.move_score_total numrange[18,20) THEN 1
ELSE NULL
END AS scaled_score
FROM move_score_total;
</code>```

答:
I would replace the case with this outer join:

```<code>select "ID", scaled_score
from
    move_score_total
    left outer join (values
        (numrange (0,8), 200),
        (numrange (8,10), 100),
        (numrange (10,12), 80),
        (numrange (12,14), 40),
        (numrange (14,16), 20),
        (numrange (16,18), 10),
        (numrange (18,20), 1)
    ) s (r, scaled_score) on move_score_total <@ r
</code>```

Body:
I have a table that looks like this:

table: move_score_total
ID | Move_score_total
1  | 5.7865
2 .| 11.543
3 .| 14.29734

and so on....
I'd like to run a query that delivers this (don't care about column order):

table: move_score_total
ID | scaled_score | Move_score_total
1  | 200          |5.7865
2 .| 80           |11.543
3 .| 20           |14.29734

I am new to case and ranges, but I thought this query might be close. Am I? Or am I way off as the error I get is:

ERROR:  syntax error at or near "numrange"
LINE 3: ...  WHEN move_score_total.move_score_total::numeric numrange[0...

SELECT move_score_total."ID",
CASE move_score_total.move_score_total
   WHEN move_score_total.move_score_total numrange[0,8) THEN 200
   WHEN move_score_total.move_score_total numrange[8,10) THEN 100
   WHEN move_score_total.move_score_total numrange[10,12) THEN 80
   WHEN move_score_total.move_score_total numrange[12,14) THEN 40
   WHEN move_score_total.move_score_total numrange[14,16) THEN 20
   WHEN move_score_total.move_score_total numrange[16,18) THEN 10
   WHEN move_score_total.move_score_total numrange[18,20) THEN 1
ELSE NULL
END AS scaled_score
FROM move_score_total;

Body:
I would replace the case with this outer join:

select "ID", scaled_score
from
    move_score_total
    left outer join (values
        (numrange (0,8), 200),
        (numrange (8,10), 100),
        (numrange (10,12), 80),
        (numrange (12,14), 40),
        (numrange (14,16), 20),
        (numrange (16,18), 10),
        (numrange (18,20), 1)
    ) s (r, scaled_score) on move_score_total <@ r


问:
Is there any method to disable maven version autoincrement while jenkins job builds?
My maven version is increasing in each jenkins job build is there is any method to disable it,any scripts or any maven plugin change for it.

Thanks,
Jose

答:
Jenkins itself does not increment anything: the definition of your job does.

If you are using an old M2+Release+Plugin or a more recent Release+Plugin, they would execute a mvn release:prepare/perform, which by default does increment the version (and also pushes to Nexus if you have configured one)

In your case, Jenkins does increment a variable named BUILD_NUMBER, that you may be using in your job, as in:

```<code>mvn clean install -Dbuild.number=${BUILD_NUMBER}
</code>```

So in the end, it really depends on the exact nature of your Jenkins job.

Body:
Jenkins itself does not increment anything: the definition of your job does.

If you are using an old M2+Release+Plugin or a more recent Release+Plugin, they would execute a mvn release:prepare/perform, which by default does increment the version (and also pushes to Nexus if you have configured one)

In your case, Jenkins does increment a variable named BUILD_NUMBER, that you may be using in your job, as in:

mvn clean install -Dbuild.number=${BUILD_NUMBER}

So in the end, it really depends on the exact nature of your Jenkins job.


问:
Extract values from input fields and store in javascript array
I have a webpage with a few input fields containing a value:

```<code><input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">
</code>```

I need Javascript/jQuery to extract these values and store them in an array like this:

```<code>var myArray = ["Apple", "Pear"];
</code>```

Does anyone know of a way to do this?

Thanks!

答:
You have to loop through the input tags:

var data = [];
var inputs = document.getElementsByTagName('input');
for(var i=0; i< inputs.length; i++)
{
  data.push(inputs[i].value);
}
console.log(data);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear"></code>```

If you use JQuery

    var data = [];
    $('input').each(function(){
      data.push($(this).val());
    });
    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>
<input type="text" id="input_1" value="Apple">
    <input type="text" id="input_2" value="Pear"></code>```

Optimized JQuery:

        var data = [];
        $(":text").each(function(){ //only searches for input type="text"
          data.push($(this).val());
        });
        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>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear"></code>```

UPDATE

I would strongly recommend you to use a common class in all your input elements and then loop through them like $('.the_class') as it is even more optimised.

Body:
I have a webpage with a few input fields containing a value:

<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">

I need Javascript/jQuery to extract these values and store them in an array like this:

var myArray = ["Apple", "Pear"];

Does anyone know of a way to do this?

Thanks!

Body:
You have to loop through the input tags:

var data = [];
var inputs = document.getElementsByTagName('input');
for(var i=0; i< inputs.length; i++)
{
  data.push(inputs[i].value);
}
console.log(data);

<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">

If you use JQuery

    var data = [];
    $('input').each(function(){
      data.push($(this).val());
    });
    console.log(data);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
    <input type="text" id="input_2" value="Pear">

Optimized JQuery:

        var data = [];
        $(":text").each(function(){ //only searches for input type="text"
          data.push($(this).val());
        });
        console.log(data);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">

UPDATE

I would strongly recommend you to use a common class in all your input elements and then loop through them like $('.the_class') as it is even more optimised.


答:
jQuery solution.

var arr = [];
$('input').each(function(){
  arr.push($(this).val());
});
console.log(arr);```
<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>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear"></code>```

Or a pure js solution.

var elems = document.querySelectorAll('input[type="text"]'),
    res = Array.from(elems).map(v => v.value);
    console.log(res);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear"></code>```

Title: Extract values from input fields and store in javascript array

Body:
jQuery solution.

var arr = [];
$('input').each(function(){
  arr.push($(this).val());
});
console.log(arr);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">

Or a pure js solution.

var elems = document.querySelectorAll('input[type="text"]'),
    res = Array.from(elems).map(v => v.value);
    console.log(res);

<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">


问:
Why does Spark SQL turn nullable on for string column even when all values specified?
So for something like this:

```<code>case class RandomClass(stringOne: String, stringTwo: String, numericOne: Int)
val ds = Seq(
  RandomClass("a", null, 1),
  RandomClass("a", "x", 3),
  RandomClass("a", "y", 4),
  RandomClass("a", null, 5)
).toDS()

ds.printSchema()
</code>```

results in

```<code>root
 |-- stringOne: string (nullable = true)
 |-- stringTwo: string (nullable = true)
 |-- numericOne: integer (nullable = false)
</code>```

why would stringOne be nullable? Strangely, numericOne is inferred correctly. I assume I am just missing something about the relationship between Dataset and DataFrame API?

答:
why would stringOne be nullable

Because Scala String is just a Java String and unlike Scala Int can be null. Actual content (presence of null values or lack of it) simply doesn't matter.

See also spark why do columns change to nullable true

Body:
So for something like this:

case class RandomClass(stringOne: String, stringTwo: String, numericOne: Int)
val ds = Seq(
  RandomClass("a", null, 1),
  RandomClass("a", "x", 3),
  RandomClass("a", "y", 4),
  RandomClass("a", null, 5)
).toDS()

ds.printSchema()

results in

root
 |-- stringOne: string (nullable = true)
 |-- stringTwo: string (nullable = true)
 |-- numericOne: integer (nullable = false)

why would stringOne be nullable? Strangely, numericOne is inferred correctly. I assume I am just missing something about the relationship between Dataset and DataFrame API?


问:
Get number before a specified string
Given the string

```<code>RAM Statistics: 5954 / 8174 743=InUse 746=Peak
</code>```

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"
</code>```

But that's returning nothing.

UPDATE:
Per Joshua I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"
</code>```

And both $matches[0] and [1] return everything before the =Peak. So

```<code>Statistics:     5954 /     8174       743=InUse      746!
</code>```

答:
Ok, slightly different approach here, using a RegEx object instead of the -match operator. Since you mentioned inconsistency I have run this twice, once with added garbage text and extra whitespace, and once with only some of the items present.

```<code>$MyRegEx = ([regex]'\b(?<peak>\d+)(?=\=Peak)|(?<ratio>\d+\s*\/\s*\d+)|\b(?<inuse>\d+)(?=\=InUse)')
$String='RAM Statistics: 5954 / 8174 1=somegarbage 743=InUse             746=Peak'
$Results=$MyRegex.matches($String)
Switch($Results){
    {$_.groups['ratio'].success}{"Ratio = " + $_.Groups['ratio'].value}
    {$_.groups['inuse'].success}{"InUse = " + $_.Groups['inuse'].value}
    {$_.groups['peak'].success}{"Peak = " + $_.Groups['peak'].value}
}

$String2 = 'RAM Statistics: 5954 / 8174    746=Peak'
$Results=$MyRegex.matches($String2)
Switch($Results){
    {$_.groups['ratio'].success}{"Ratio = " + $_.Groups['ratio'].value}
    {$_.groups['inuse'].success}{"InUse = " + $_.Groups['inuse'].value}
    {$_.groups['peak'].success}{"Peak = " + $_.Groups['peak'].value}
}
</code>```

That will get you the results of:

```<code>Ratio = 5954 / 8174
InUse = 743
Peak = 746
</code>```

and for the second string:

```<code>Ratio = 5954 / 8174
Peak = 746
</code>```

This is accomplished by using named capture groups, and then evaluating the results looking if that capture group succeeded in the specific grouping. I accomplish that with a Switch.

Title: Get number before a specified string

Body:
Given the string

RAM Statistics: 5954 / 8174 743=InUse 746=Peak

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"

But that's returning nothing.

UPDATE:
Per Joshua I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"

And both $matches[0] and [1] return everything before the =Peak. So

Statistics:     5954 /     8174       743=InUse      746!

Body:
Ok, slightly different approach here, using a RegEx object instead of the -match operator. Since you mentioned inconsistency I have run this twice, once with added garbage text and extra whitespace, and once with only some of the items present.

$MyRegEx = ([regex]'\b(?<peak>\d+)(?=\=Peak)|(?<ratio>\d+\s*\/\s*\d+)|\b(?<inuse>\d+)(?=\=InUse)')
$String='RAM Statistics: 5954 / 8174 1=somegarbage 743=InUse             746=Peak'
$Results=$MyRegex.matches($String)
Switch($Results){
    {$_.groups['ratio'].success}{"Ratio = " + $_.Groups['ratio'].value}
    {$_.groups['inuse'].success}{"InUse = " + $_.Groups['inuse'].value}
    {$_.groups['peak'].success}{"Peak = " + $_.Groups['peak'].value}
}

$String2 = 'RAM Statistics: 5954 / 8174    746=Peak'
$Results=$MyRegex.matches($String2)
Switch($Results){
    {$_.groups['ratio'].success}{"Ratio = " + $_.Groups['ratio'].value}
    {$_.groups['inuse'].success}{"InUse = " + $_.Groups['inuse'].value}
    {$_.groups['peak'].success}{"Peak = " + $_.Groups['peak'].value}
}

That will get you the results of:

Ratio = 5954 / 8174
InUse = 743
Peak = 746

and for the second string:

Ratio = 5954 / 8174
Peak = 746

This is accomplished by using named capture groups, and then evaluating the results looking if that capture group succeeded in the specific grouping. I accomplish that with a Switch.


问:
Python class information from variable
In the following code:

```<code>class species:
    def __init__(self, continent):
        self.continent=continent

giraffe = species("africa")

animal = "giraffe"
</code>```

EDIT: animal is a string

can i retrieve "africa" from var "animal"?

答:
Access the attribute

animal.continent

Title: Python class information from variable

Body:
In the following code:

class species:
    def __init__(self, continent):
        self.continent=continent

giraffe = species("africa")

animal = "giraffe"

EDIT: animal is a string

can i retrieve "africa" from var "animal"?

Body:
Access the attribute

animal.continent


问:
Laravel 5.3 - No break between lines in mail notification?
I send an email out via the toMail channel, which is saved from a text area where I hit enter twice for new line, so it looks like this in the input:

```<code>Line 1

Line 2 with space above and below

Line 3
</code>```

When I use that text in the mail like this:

```<code>return (new MailMessage)->subject('test spacing')
                        ->line($this->text);
</code>```

It looks like this in the email:

```<code>Line 1 Line 2 with space above and below Line 3
</code>```

I changed the relevant section in email.blade.php from:

```<code>@foreach ($introLines as $line)
  {{ $line }}
@endforeach
</code>```

To:

```<code>@foreach ($introLines as $line)
  {!! nl2br(htmlspecialchars($line)) !!}
@endforeach
</code>```

But that still didn't work. In the notifications table in the db, it is saved as:

```<code>Line 1\n\nLine 2 with space above and below\n\nLine 3
</code>```

Any idea how to get the sent email to show the spacing so it's not just one big blob?

UPDATE:

So laravel inserts the notification with \n\n in the notifications table, but it is actually saved in the model table like this:

Which is what is passed to the email, but still not sure how to get those spaces in the email.

答:
specify your email type as text/html. I think laravel does automatically but better to use views I think. The following is working for me.
Another easy way is create view for your mail text and use that like
Create Mailable as follows using view.

```<code>class CompanyCreated extends Mailable
{
    use Queueable, SerializesModels;

    public $company;

    public function __construct(Company $company)
    {
        $this->company = $company;
    }

    public function build()
    {
        return $this->subject("Alert: New Company added")
                ->from("fax@netinkvoice.com", "From1 Name123")
                ->view('super_admin.company-mail')->with(['data' => $this->company]);
    }
}
</code>```

I have created this mailable and working fine, data shows in tabular format. I and its laravel 5.3.

Body:
I send an email out via the toMail channel, which is saved from a text area where I hit enter twice for new line, so it looks like this in the input:

Line 1

Line 2 with space above and below

Line 3

When I use that text in the mail like this:

return (new MailMessage)->subject('test spacing')
                        ->line($this->text);

It looks like this in the email:

Line 1 Line 2 with space above and below Line 3

I changed the relevant section in email.blade.php from:

@foreach ($introLines as $line)
  {{ $line }}
@endforeach

To:

@foreach ($introLines as $line)
  {!! nl2br(htmlspecialchars($line)) !!}
@endforeach

But that still didn't work. In the notifications table in the db, it is saved as:

Line 1\n\nLine 2 with space above and below\n\nLine 3

Any idea how to get the sent email to show the spacing so it's not just one big blob?

UPDATE:

So laravel inserts the notification with \n\n in the notifications table, but it is actually saved in the model table like this:

Which is what is passed to the email, but still not sure how to get those spaces in the email.

Body:
specify your email type as text/html. I think laravel does automatically but better to use views I think. The following is working for me.
Another easy way is create view for your mail text and use that like
Create Mailable as follows using view.

class CompanyCreated extends Mailable
{
    use Queueable, SerializesModels;

    public $company;

    public function __construct(Company $company)
    {
        $this->company = $company;
    }

    public function build()
    {
        return $this->subject("Alert: New Company added")
                ->from("fax@netinkvoice.com", "From1 Name123")
                ->view('super_admin.company-mail')->with(['data' => $this->company]);
    }
}

I have created this mailable and working fine, data shows in tabular format. I and its laravel 5.3.


问:
Function still running after return
I'm adding a colour picker to my Electron app using RobotJS, when the user clicks the button a .click() triggers my function that focuses on an input (hidden opacity: 0; height: 0px; width: 0px;) which acts as a proxy for when the user clicks (.blur()) to fetch the colour at cursor location. It then puts that colour in another input field and returns. However, if the user then click back into the returned input field then clicks out, the .blur() still triggers. Why is this and how can I prevent it?

```<code><input class="clickProxy" style="opacity: 0; height: 0px; width: 0px;" />

$('.color_picker').click(function(){
    getColorAtPointer();
});

function getColorAtPointer(){
    $('input[name="colorSample"]').focus();

    $('input[name="colorSample"]').blur(function(){
        var mouse = robot.getMousePos();
        $('input[name="colorSample"]').val('#'+robot.getPixelColor(mouse.x, mouse.y));
        return;
    });
}
</code>```

Thanks!

答:
You are binding the blur event after the user clicks the color picker. You never unbind it so it would continue to fire every time the user leaves the colorSample element. You have a few options.

The best, in my opinion, is to use .one instead of blur so the event only fires once.

For Example:

```<code>function getColorAtPointer(){
    $('input[name="colorSample"]').focus();

    $('input[name="colorSample"]').one("blur", function(){
        var mouse = robot.getMousePos();
        $('input[name="colorSample"]').val('#'+robot.getPixelColor(mouse.x, mouse.y));
        return;
    });
}
</code>```

Alternatively you could namespace the blur event (e.g. .on("blur.color-picked") then inside of the blur event handler unbind the event (e.g. .off("blur.color-picked")

It is also worth noting that you do not have to use an anonymous function inside of click events, you can pass the function directly

```<code>$('.color_picker').click(getColorAtPointer);
</code>```

Title: Function still running after return

Body:
I'm adding a colour picker to my Electron app using RobotJS, when the user clicks the button a .click() triggers my function that focuses on an input (hidden opacity: 0; height: 0px; width: 0px;) which acts as a proxy for when the user clicks (.blur()) to fetch the colour at cursor location. It then puts that colour in another input field and returns. However, if the user then click back into the returned input field then clicks out, the .blur() still triggers. Why is this and how can I prevent it?

<input class="clickProxy" style="opacity: 0; height: 0px; width: 0px;" />

$('.color_picker').click(function(){
    getColorAtPointer();
});

function getColorAtPointer(){
    $('input[name="colorSample"]').focus();

    $('input[name="colorSample"]').blur(function(){
        var mouse = robot.getMousePos();
        $('input[name="colorSample"]').val('#'+robot.getPixelColor(mouse.x, mouse.y));
        return;
    });
}

Thanks!

Body:
You are binding the blur event after the user clicks the color picker. You never unbind it so it would continue to fire every time the user leaves the colorSample element. You have a few options.

The best, in my opinion, is to use .one instead of blur so the event only fires once.

For Example:

function getColorAtPointer(){
    $('input[name="colorSample"]').focus();

    $('input[name="colorSample"]').one("blur", function(){
        var mouse = robot.getMousePos();
        $('input[name="colorSample"]').val('#'+robot.getPixelColor(mouse.x, mouse.y));
        return;
    });
}

Alternatively you could namespace the blur event (e.g. .on("blur.color-picked") then inside of the blur event handler unbind the event (e.g. .off("blur.color-picked")

It is also worth noting that you do not have to use an anonymous function inside of click events, you can pass the function directly

$('.color_picker').click(getColorAtPointer);


问:
SP.UI.ModalDialog (Please wait message)
I am using an SP.UI.ModalDialog in my code in order to open a modal dialogbox in a sharepoint 2010 application.

Wanted to know how to display the message "please wait while the content loads" while the content is loading instead of showing a blank screen in the modal window (just like sharepoint does).

答:
Remove width and height parameters. I had same problem and removing those solved it.

Here's the function that I use to open modal dialogs:

```<code>function OpenModalDialog(urlToOpen)
{
    var options = {
        url: urlToOpen ,
        allowMaximize: false,
        showClose: true,
        dialogReturnValueCallback: CloseCallback
    };

    SP.UI.ModalDialog.showModalDialog(options);
}
</code>```

Title: SP.UI.ModalDialog (Please wait message)

Body:
Remove width and height parameters. I had same problem and removing those solved it.

Here's the function that I use to open modal dialogs:

function OpenModalDialog(urlToOpen)
{
    var options = {
        url: urlToOpen ,
        allowMaximize: false,
        showClose: true,
        dialogReturnValueCallback: CloseCallback
    };

    SP.UI.ModalDialog.showModalDialog(options);
}


答:
Use document.querySelectorAll and Array#map:

var result = [].map.call(document.querySelectorAll('input'), function (e) {
  return e.value
})

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
   <body>
      <input type="text" id="input_1" value="Apple">
      <input type="text" id="input_2" value="Pear">
   </body>
</html></code>```

Body:
Use document.querySelectorAll and Array#map:

var result = [].map.call(document.querySelectorAll('input'), function (e) {
  return e.value
})

console.log(result)

<html>
   <body>
      <input type="text" id="input_1" value="Apple">
      <input type="text" id="input_2" value="Pear">
   </body>
</html>


问:
Slowcheetah installed but there's no transform option
I have a .NET 4.5 project with MVC 5 and EF 6, in Visual Studio 2013.  I want to have transforms for app.config.

I've installed the SlowCheetah project via NuGet, and (supposedly)[https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5] now I should be able to right-click on App.config and see the option Add Transform.  But I don't.

Does anyone know what are the possible reasons for this?

I've checked that the package is installed in both projects in my solution, restarted, rebuilt, etc.

答:
My conditions:

Visual Studio Professional 2017

SlowCheetah, v 2.5.48 installed in a C# project

When I selected [Right-Click]-->App.config, there was no
Add Transform option

My solution:

Downloaded and ran this:
https://marketplace.visualstudio.com/items?itemName=WillBuikMSFT.SlowCheetah-XMLTransforms

Restarted VS 2017 and [Right-Click]--> App.config displayed the Add Transform option


答:
You can use jQuery map() and get() to return array of values.

var myArray = $('input[type="text"]').map(function() {
  return this.value;
}).get();

console.log(myArray)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear"></code>```

Body:
You can use jQuery map() and get() to return array of values.

var myArray = $('input[type="text"]').map(function() {
  return this.value;
}).get();

console.log(myArray)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="input_1" value="Apple">
<input type="text" id="input_2" value="Pear">


问:
no matches in array in elasticsearch
I am using elasticsearch 5.2.2.

in my index I have data looking like this:

```<code>{
    "_index": "index",
    "_type": "273caf76-ec03-478c-b980-9743180bc863",
    "_id": "eee46e24-f383-4ae7-8930-dc3836e030a5",
    "_score": 3.41408,
    "_source": {
      "Father Name": [
        {
          "id": "some id",
          "value": "Some value test test"
        }
      ],
      "Mother Name": [
        {
          "id": "some id",
          "value": "Another value haha"
        }
      ],
      "Other values": [{ id: "", value: ""}]
    }
}
</code>```

When I am searching with _all, everything works fine and I can find all the results with reasonable scores

```<code>{"query":{"match":{"_all":"value"}},"from":0,"size":20}
</code>```

But that query is searching in all the fields. If I want for instance just to find results in Father Name or in Father Name and Mother Name, then I find nothing.

```<code>{"query":{"match":{"Father Name":"value"}},"from":0,"size":20}
</code>```

My goal is to find in have a search like with _all, but limited to a few fields.

答:
Sam Shen's answer is the way to go if you need to configure which properties to use on a per-query basis.

One alternative is to configure the fields to not be included in the _all query.

For example, this would cause only Father Name to be included in the _all query, by disabling all the fields at the type level, then enabling all of the subfields on Father Name.

```<code>PUT index
{
  "mappings": {
    "type": {
      "include_in_all": false,
      "properties": {
         "Father Name" : {
           "include_in_all": true
         }
      }
    }
}
</code>```

You can set the include_in_all property on any level in the mapping, including subfield properties.

The big drawback here is that this isn't configured on a query-by-query basis, this is configured for all queries attempting to use the _all field.

Title: no matches in array in elasticsearch

Body:
I am using elasticsearch 5.2.2.

in my index I have data looking like this:

{
    "_index": "index",
    "_type": "273caf76-ec03-478c-b980-9743180bc863",
    "_id": "eee46e24-f383-4ae7-8930-dc3836e030a5",
    "_score": 3.41408,
    "_source": {
      "Father Name": [
        {
          "id": "some id",
          "value": "Some value test test"
        }
      ],
      "Mother Name": [
        {
          "id": "some id",
          "value": "Another value haha"
        }
      ],
      "Other values": [{ id: "", value: ""}]
    }
}

When I am searching with _all, everything works fine and I can find all the results with reasonable scores

{"query":{"match":{"_all":"value"}},"from":0,"size":20}

But that query is searching in all the fields. If I want for instance just to find results in Father Name or in Father Name and Mother Name, then I find nothing.

{"query":{"match":{"Father Name":"value"}},"from":0,"size":20}

My goal is to find in have a search like with _all, but limited to a few fields.

Body:
Sam Shen's answer is the way to go if you need to configure which properties to use on a per-query basis.

One alternative is to configure the fields to not be included in the _all query.

For example, this would cause only Father Name to be included in the _all query, by disabling all the fields at the type level, then enabling all of the subfields on Father Name.

PUT index
{
  "mappings": {
    "type": {
      "include_in_all": false,
      "properties": {
         "Father Name" : {
           "include_in_all": true
         }
      }
    }
}

You can set the include_in_all property on any level in the mapping, including subfield properties.

The big drawback here is that this isn't configured on a query-by-query basis, this is configured for all queries attempting to use the _all field.