问:
Append table data from controller in blade through ajax
My table is designed for the controller, I want to append this table to the table in the blade of laravel.

This is my table in controller:

```<code>        $subLaws='';
          $n=1;
          foreach($sublaw as $sLaw)
          {
             $govt_no='';
             $eventType='';
             $status='Inactive';
             $url=url('admin/sublawmaster/'.$sLaw->id);
             $lmsid=$sLaw->lms_id;
             $view_url=url('admin/sublawmaster/view/' .$sLaw->id);
             if($sLaw->status=='1'){$status='Active';}
             $subLaws .= '<tr class="odd">
                          <td></td>
                          <td><a href="'.$view_url.'">'.$lmsid.'</a></td>
                          <td>'.$sLaw->sub_law_name.'</td>
                          <td>'.$eventType.'</td>
                          <td><span class="label label-success
 btn_status">'.$status.'</span></td>
           $n++;
    }
           return json_encode($subLaws);
</code>```

this is my ajax code:

```<code>$.ajax({
                type: 'GET',
                dataType: "json",
                data: {law_id:id},
                url: "{{ URL::to('admin/postlawid/') }}",
                success: function (data) {

                }
            });
</code>```

this is my table in blade file:

```<code><table class="table table-striped table-bordered table-hover" id="sublawmasterdata">
<thead>
            <tr id="header">
            <th align="center" width="80" style="text-align:center;">S NO</th>
                 <th>LMS ID</th>
                 <th>LMS Name</th>
                 <th>LMS Type</th>
                 <th>Status</th>
                 <th>Action</th>
             </tr>
             </thead>
             <tbody>

             </tbody>
            </table>
</code>```

I have a dropdown when the value is selected from this dropdown the table in the controller should get appended to the table in blade file.
how should I append the table in the controller to the table in blade file?

答:
In your controller need to make change as given below

```<code>return json_encode(['table_html' => $subLaws]);
</code>```

Use following ajax code to append rows dynamically

```<code>$.ajax({
      type: 'GET',
      dataType: "json",
      data: {law_id:id},
      url: "{{ your route to controller function }}",
      success: function (data) {
          ("#sublawmasterdata tbody").innerHtml(data.table_html); }
      }
});
</code>```

Body:
My table is designed for the controller, I want to append this table to the table in the blade of laravel.

This is my table in controller:

        $subLaws='';
          $n=1;
          foreach($sublaw as $sLaw)
          {
             $govt_no='';
             $eventType='';
             $status='Inactive';
             $url=url('admin/sublawmaster/'.$sLaw->id);
             $lmsid=$sLaw->lms_id;
             $view_url=url('admin/sublawmaster/view/' .$sLaw->id);
             if($sLaw->status=='1'){$status='Active';}
             $subLaws .= '

                          '.$lmsid.'
                          '.$sLaw->sub_law_name.'
                          '.$eventType.'
                          '.$status.'
           $n++;
    }
           return json_encode($subLaws);

this is my ajax code:

$.ajax({
                type: 'GET',
                dataType: "json",
                data: {law_id:id},
                url: "{{ URL::to('admin/postlawid/') }}",
                success: function (data) {

                }
            });

this is my table in blade file:

            S NO
                 LMS ID
                 LMS Name
                 LMS Type
                 Status
                 Action

I have a dropdown when the value is selected from this dropdown the table in the controller should get appended to the table in blade file.
how should I append the table in the controller to the table in blade file?

Body:
In your controller need to make change as given below

return json_encode(['table_html' => $subLaws]);

Use following ajax code to append rows dynamically

$.ajax({
      type: 'GET',
      dataType: "json",
      data: {law_id:id},
      url: "{{ your route to controller function }}",
      success: function (data) {
          ("#sublawmasterdata tbody").innerHtml(data.table_html); }
      }
});


来源: stackexchange

问:
Intel Xdk backend implementation
I have been studying about Intel XDK about how to program for cross platforms, for now I'm that much clear that we can program the interface using HtML,css and Js but don't know How to implement the backend code!!! (whether using js or php) ?</p>

答:
Intel xdk stops their support, we can only work with the last release.

For the above question, you can add HTML file for the UI design and add its backend file as javascript file and add the javascript file in HTML.

ContentLicense: CC BY-SA 3.0

Title: Intel Xdk backend implementation


问:
Calling an Excel sheet in VBScript
I have the following code:

```<code>Option Explicit
Randomize
Dim a, song, album
a = Int((Rnd*195)+1)
song = "B" & a
album = "A" & a

Dim objApp, objWbs, objWorkbook, objSheet

Set objApp = CreateObject("Excel.Application")
Set objWbs = objApp.WorkBooks
objApp.Visible = False
Set objWorkbook = objWbs.Open("C:\Users\Name\Documents\Music.xlsx")
Set objSheet = objWorkbook.Sheets("Sheet1")

song = objSheet.Range(song).Value
album = objSheet.Range(album).Value

objWorkbook.Close False
objWbs.Close
objApp.Quit

Set objSheet = Nothing
Set objWorkbook = Nothing
Set objWbs = Nothing
Set objApp = Nothing

MsgBox("Album name: " & album & vbNewLine & "Song name: " & song)
</code>```

It prints two random cells between row 1 and row 195 from the Excel sheet "Music". One of them - the one in column A - represents the album, and the other represents the song. The problem is that it takes quite a long time to return the results, about 20 seconds.

I was wondering whether there was a more efficient method I could use to get the results more quickly.

答:
Cheran, I disagree with the answers here.

I just ran your script on my 5 year old laptop, and got the answer in about 2 seconds.  Whether an instance of Excel was already open made no difference in run time.

(I created a test Music.xlsx spreadsheet by entering "A1" in cell A1, and "B1" in cell B1, and dragged those cells down to row 195 to get a nice set of unique sample data).

Why don't you make Excel visible when it runs, so that you can see for yourself what is going on?

You might see, for example, that Excel takes one second to open, and the Excel Add-ins you have are taking the other fifteen seconds to initialize.  It's also possible that your machine and/or hard drive is slow and does indeed take 20 seconds to run this.  Who knows...

To get some insight, please make objApp.Visible = True and rerun.

You might also comment out the final eight lines, except for the MsgBox line so that your Excel file stays open after script is done, so that you might see other clues.

Other observations:
1) Your method of opening Excel with CreateObject from a .vbs script seems to be the most reliable/accepted method of automating Excel.

2) It's not stated here HOW you are running the .vbs script (command line vs. double-click from Explorer).  Your script is running, but be aware that using cscript.exe to run the .vbs is also common when people try to automate this.

3) I'm not used to seeing an external vbs interact with the data inside Excel...I'm used to having vbs open Excel.xlsm, then letting a Macro do the number crunching.  But, Macros bring an entirely different set of headaches.  I'm not saying your method is good or bad...just not used to that approach.

Good luck!

Title: Calling an Excel sheet in VBScript

Body:
I have the following code:

Option Explicit
Randomize
Dim a, song, album
a = Int((Rnd*195)+1)
song = "B" & a
album = "A" & a

Dim objApp, objWbs, objWorkbook, objSheet

Set objApp = CreateObject("Excel.Application")
Set objWbs = objApp.WorkBooks
objApp.Visible = False
Set objWorkbook = objWbs.Open("C:\Users\Name\Documents\Music.xlsx")
Set objSheet = objWorkbook.Sheets("Sheet1")

song = objSheet.Range(song).Value
album = objSheet.Range(album).Value

objWorkbook.Close False
objWbs.Close
objApp.Quit

Set objSheet = Nothing
Set objWorkbook = Nothing
Set objWbs = Nothing
Set objApp = Nothing

MsgBox("Album name: " & album & vbNewLine & "Song name: " & song)

It prints two random cells between row 1 and row 195 from the Excel sheet "Music". One of them - the one in column A - represents the album, and the other represents the song. The problem is that it takes quite a long time to return the results, about 20 seconds.

I was wondering whether there was a more efficient method I could use to get the results more quickly.


问:
Why is that my $wpdb->delete value is FALSE, And won't execute properly?
I'm going to delete a row in a table using the $wpdb object

here's my code:

```<code>function delete_variation($variation_ID){
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = 'wp-posts';
    $wpdb->delete( $table_name , $where);
}
</code>```

every arguments are fine, I've got results.. But the

```<code>$wpdb->delete( $table_name , $where);
</code>```

returned FALSE and won't execute?

no errors has been found, everything seems okay, just that it returned FALSE.

Thanks!

答:
Two mistakes i found in your code is

declare global $wpdb.

check for the proper prefix for the table name i.e : wp_posts use  $wpdb->prefix.'posts'

Body:
I'm going to delete a row in a table using the $wpdb object

here's my code:

function delete_variation($variation_ID){
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = 'wp-posts';
    $wpdb->delete( $table_name , $where);
}

every arguments are fine, I've got results.. But the

$wpdb->delete( $table_name , $where);

returned FALSE and won't execute?

no errors has been found, everything seems okay, just that it returned FALSE.

Thanks!


问:
Android Radio Button Group, why I need this?
Why i need to add if (null != rb && checkedId > -1), if I remove the code, the program still work. What's the benefit of this line of code?

```<code>radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) group.findViewById(checkedId);
            if (null != rb && checkedId > -1) {

                switch (rb.getId()){

                    case R.id.radioFast:
                        mAnimOption = FAST;
                        break;

                    case R.id.radioSlow:
                        mAnimOption = SLOW;
                        break;

                    case R.id.radioNone:
                        mAnimOption = NONE;
                        break;

                }
                // End switch block

                mEditor.putInt("anim option", mAnimOption);

            }

        }
    });
</code>```

答:
```<code>if (null != rb && checkedId > -1)
</code>```

it is used to avoid crashes, so thar whenever NULL is invoked or user checkedId is NULL it throws error, and avoid unwanted crashes.

As per Developer, we should make code in this way no crashes are appearing during run of APP.

Body:
Why i need to add if (null != rb && checkedId > -1), if I remove the code, the program still work. What's the benefit of this line of code?

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) group.findViewById(checkedId);
            if (null != rb && checkedId > -1) {

                switch (rb.getId()){

                    case R.id.radioFast:
                        mAnimOption = FAST;
                        break;

                    case R.id.radioSlow:
                        mAnimOption = SLOW;
                        break;

                    case R.id.radioNone:
                        mAnimOption = NONE;
                        break;

                }
                // End switch block

                mEditor.putInt("anim option", mAnimOption);

            }

        }
    });

Body:
if (null != rb && checkedId > -1)

it is used to avoid crashes, so thar whenever NULL is invoked or user checkedId is NULL it throws error, and avoid unwanted crashes.

As per Developer, we should make code in this way no crashes are appearing during run of APP.


问:
Python Convert string to dict
I have a string :

```<code>'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'
</code>```

and would like to convert it to

```<code>{
  "tomatoes" : "5" ,
  "livestock" :"{"cow" : "5" , "sheep" :"2" }"
}
</code>```

Any ideas ?

答:
Here is my answer:

```<code>dict_str = '{tomatoes: 5, livestock: {cow: 5, sheep: 2}}'

def dict_from_str(dict_str):

    while True:

        try:
            dict_ = eval(dict_str)
        except NameError as e:
            key = e.message.split("'")[1]
            dict_str = dict_str.replace(key, "'{}'".format(key))
        else:
            return dict_

print dict_from_str(dict_str)
</code>```

My strategy is to convert the dictionary str to a dict by eval. However, I first have to deal with the fact that your dictionary keys are not enclosed in quotes. I do that by evaluating it anyway and catching the error. From the error message, I extract the key that was interpreted as an unknown variable, and enclose it with quotes.

Title: Python Convert string to dict

Body:
I have a string :

'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'

and would like to convert it to

{
  "tomatoes" : "5" ,
  "livestock" :"{"cow" : "5" , "sheep" :"2" }"
}

Any ideas ?

Body:
Here is my answer:

dict_str = '{tomatoes: 5, livestock: {cow: 5, sheep: 2}}'

def dict_from_str(dict_str):

    while True:

        try:
            dict_ = eval(dict_str)
        except NameError as e:
            key = e.message.split("'")[1]
            dict_str = dict_str.replace(key, "'{}'".format(key))
        else:
            return dict_

print dict_from_str(dict_str)

My strategy is to convert the dictionary str to a dict by eval. However, I first have to deal with the fact that your dictionary keys are not enclosed in quotes. I do that by evaluating it anyway and catching the error. From the error message, I extract the key that was interpreted as an unknown variable, and enclose it with quotes.


问:
Error Stream was not readble
I wrote the code below and I got an error (Stream was not readble) while execute this line SR = New StreamReader(FS) why and how to fix it

the code :

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FS As FileStream
    Dim SR As StreamReader
    Dim SW As StreamWriter
    Dim FS_Out As FileStream
    FS = New FileStream("C:\Temp\My Picture.JPG", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
    SR = New StreamReader(FS)
    FS_Out = New FileStream("C:\Temp\My Picture Out.JPG", FileMode.Create, FileAccess.ReadWrite)
    SW = New StreamWriter(FS_Out)

    Dim alltext As String
    FS.Seek(0, SeekOrigin.Begin)
    alltext = SR.ReadToEnd()

    'SW.Write (Buffer)

    SR.Close()
    FS.Close()

End Sub
</code>```

答: You open FS with only the "write" flag, then try to read from it. Personally I always use File.OpenRead, File.OpenWrite, etc - much easier and clearer.

ContentLicense: CC BY-SA 2.5

Title: Error Stream was not readble

Body:
I wrote the code below and I got an error (Stream was not readble) while execute this line SR = New StreamReader(FS) why and how to fix it

the code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FS As FileStream
    Dim SR As StreamReader
    Dim SW As StreamWriter
    Dim FS_Out As FileStream
    FS = New FileStream("C:\Temp\My Picture.JPG", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
    SR = New StreamReader(FS)
    FS_Out = New FileStream("C:\Temp\My Picture Out.JPG", FileMode.Create, FileAccess.ReadWrite)
    SW = New StreamWriter(FS_Out)

    Dim alltext As String
    FS.Seek(0, SeekOrigin.Begin)
    alltext = SR.ReadToEnd()

    'SW.Write (Buffer)

    SR.Close()
    FS.Close()

End Sub


问:
How to get all column values from csv using pandas
I have a table in .csv which contains some random messages:

```<code>id,msg
2,start
1,bot
1,run
2,san
</code>```

I want to get only rows which match certain condition. I managed to do that, but I want to get all cell values of column - msg which match condition.

My code:

```<code>df = pd.read_csv('msgs.csv')

# if id==2 and msg contains letter 'a'
p = df[(df['id'] == 2) & (df['msg'].str.contains('a'))]
print(p)

for row in p:
    print(p.iloc[0]['msg'])
</code>```

When I print(p) my result (which is good) is:

```<code>           id msg
1          2  start
5          2    san
</code>```

And I want to have output like this :

```<code>start
san
</code>```

But when I try to do it with iloc I get only first cell value:

```<code>start
start
</code>```

Probably the solution is easy but I don't know how to get it. Thanks in advance.

答:
You can always do this:</p>

```<code>for x in p['msg'].values:
    print(x)
</code>```

Body:
I have a table in .csv which contains some random messages:

id,msg
2,start
1,bot
1,run
2,san

I want to get only rows which match certain condition. I managed to do that, but I want to get all cell values of column - msg which match condition.

My code:

df = pd.read_csv('msgs.csv')

# if id==2 and msg contains letter 'a'
p = df[(df['id'] == 2) & (df['msg'].str.contains('a'))]
print(p)

for row in p:
    print(p.iloc[0]['msg'])

When I print(p) my result (which is good) is:

           id msg
1          2  start
5          2    san

And I want to have output like this :

start
san

But when I try to do it with iloc I get only first cell value:

start
start

Probably the solution is easy but I don't know how to get it. Thanks in advance.

Body:
You can always do this:

for x in p['msg'].values:
    print(x)


问:
how to store private key securely in application in android?
i want to store a private key securely in my application. I read a lot of SO question but failed to find proper answer?

Sharedpreference is the way to store securely but rooted phone can easily find it.

Can any one tell me how to store securely a key = "The real world" in android app?

Thanks

答:
You can securely store it in Shared Preference by encrypting it. Then use KeyStore to also secure the key for decrypting.

There's no way to 100% secure a data on android but you can make it harder for a hacker to get it. (like encryptions).

KeyStore: https://www.androidauthority.com/use-android-keystore-store-passwords-sensitive-information-623779/


问:
Pip only install cpu tensorflow of tensorflow 0.11
I previously installed tensorflow-gpu v 0.12 which worked fine, but for a code of a colleague I need v0.11. So I uninstalled tensorflow and tensorflow-gpu 0.12 and I tried to install v 0.11 with:

```<code>pip install https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl
</code>```

It successfully installs tensorflow, but not the gpu version, even though in the link above I took the gpu and not cpu version. Apparently, it doesn't matter if I choose cpu or gpu, it always only installs the cpu version.

Any idea how to fix this problem?

答:
Thaks for @user8289596 answer the following command was useful for my case and i have successfully installed tensorflow 0.11

pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc0-cp27-none-linux_x86_64.whl

Note: I am using anaconda with python 2.7 and linux

Body:
I previously installed tensorflow-gpu v 0.12 which worked fine, but for a code of a colleague I need v0.11. So I uninstalled tensorflow and tensorflow-gpu 0.12 and I tried to install v 0.11 with:

pip install https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl

It successfully installs tensorflow, but not the gpu version, even though in the link above I took the gpu and not cpu version. Apparently, it doesn't matter if I choose cpu or gpu, it always only installs the cpu version.

Any idea how to fix this problem?


问:
Error message for immediate attribute
See the following code:

```<code><h:form>
   <table>
     <tr>
     <td>
       <h:inputText id="name" value="#{jsfBean.name }" required="true" immediate="true"/>
      <h:message for="name"/>
    </td>
 </tr>
     <tr>
        <td>
      <h:inputText id="number" value="#{jsfBean.number }" required="true" />
      <h:message for="number"/>
    </td>
 </tr>
 <tr>
    <td>
         <h:commandButton id="submit" value="Submit" action="#{jsfBean.submit }" immediate="true"/>
 </td>
 </tr>
     </table>
    </h:form>
</code>```

When I am submitting the form without typing the values, It should validate and throw error for first text box. But, its not happening. What could be the problem?

答:
Its working for me

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

faces-config.xml

```<code><?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="2.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">

</faces-config>
</code>```

index.xhtml

```<code><?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form>

            <h:inputText value="#{myBean.val}" required="true" immediate="true"/>
            <h:commandButton action="#{myBean.submit}" immediate="true"/>

        </h:form>
    </h:body>
</html>
</code>```

libraries

```<code>  <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.0.2-b10</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.0.2-b10</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
    </dependencies>
</code>```

Title: Error message for immediate attribute

Body:
See the following code:

<h:form>

       <h:inputText id="name" value="#{jsfBean.name }" required="true" immediate="true"/>
      <h:message for="name"/>

      <h:inputText id="number" value="#{jsfBean.number }" required="true" />
      <h:message for="number"/>

         <h:commandButton id="submit" value="Submit" action="#{jsfBean.submit }" immediate="true"/>

    </h:form>

When I am submitting the form without typing the values, It should validate and throw error for first text box. But, its not happening. What could be the problem?

Body:
Its working for me

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="2.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">

</faces-config>

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form>

            <h:inputText value="#{myBean.val}" required="true" immediate="true"/>
            <h:commandButton action="#{myBean.submit}" immediate="true"/>

        </h:form>
    </h:body>
</html>

libraries

  <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.0.2-b10</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.0.2-b10</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
    </dependencies>


问:
Impala streaming over JDBC is really slow
I have run several large queries using impala-shell and found the performance to be satisfactory. These queries typically write 100k-1m rows to disk. However, when I run the very same queries programmatically using JDBC, the results take much, much longer to write to disk. For example, a query which takes five minutes from impala-shell takes up to thirty minutes over JDBC.

I have tried both the Hive and Cloudera JDBC drivers but get similarly bad performance. I have tried various fetch sizes but it has not made any difference. Is Impala streaming over JDBC fundamentally slow or could I do something else to speed up the streaming?

This is on CDH 5.9.1.

答: This turned out to be a client-side issue. I was using curl to test a web application which was making the Impala queries. Switching from curl to a client written in Scala code removed the latency.</p>


问:
How to query for a primary key in oracle 11g
Does anybody know how to query for a primary key of a table in Oracle 11g? I saw a similar question for SQL Server, but I've had no luck from trying the answers on that thread.

Thanks!

答:
```<code>SELECT cols.table_name
  ||' - '
  ||cols.column_name primary_key
FROM all_constraints cons,
  all_cons_columns cols,
  user_tables ut
WHERE cons.constraint_type = 'P'
AND cons.constraint_name   = cols.constraint_name
AND cons.owner             = cols.owner
AND cols.table_name        = ut.table_name
ORDER BY cols.table_name;
</code>```

ContentLicense: CC BY-SA 4.0


问:
Pandas sklearn one-hot encoding dataframe or numpy?
How can I transform a pandas data frame to sklearn one-hot-encoded (dataframe / numpy array) where some columns do not require encoding?

```<code>mydf = pd.DataFrame({'Target':[0,1,0,0,1, 1,1],
                   'GroupFoo':[1,1,2,2,3,1,2],
                    'GroupBar':[2,1,1,0,3,1,2],
                    'GroupBar2':[2,1,1,0,3,1,2],
                    'SomeOtherShouldBeUnaffected':[2,1,1,0,3,1,2]})
columnsToEncode = ['GroupFoo', 'GroupBar']
</code>```

Is an already label encoded data frame and I would like to only encode the columns marked by columnsToEncode?

My problem is that I am unsure if a pd.Dataframe or the numpy array representation are better and how to re-merge the encoded part with the other one.

My attempts so far:

```<code>myEncoder = OneHotEncoder(sparse=False, handle_unknown='ignore')
myEncoder.fit(X_train)
df = pd.concat([
         df[~columnsToEncode], # select all other / numeric
        # select category to one-hot encode
         pd.Dataframe(encoder.transform(X_train[columnsToEncode]))#.toarray() # not sure what this is for
        ], axis=1).reindex_axis(X_train.columns, axis=1)
</code>```

Notice: I am aware of Pandas: Get Dummies / http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html but that does not play well in a train / test split where I require such an encoding per fold.

答:
I believe that this update to the initial answer is even better in order t perform dummy coding
    import logging</p>

```<code>import pandas as pd
from sklearn.base import TransformerMixin

log = logging.getLogger(__name__)

class CategoricalDummyCoder(TransformerMixin):
    """Identifies categorical columns by dtype of object and dummy codes them. Optionally a pandas.DataFrame
    can be returned where categories are of pandas.Category dtype and not binarized for better coding strategies
    than dummy coding."""

    def __init__(self, only_categoricals=False):
        self.categorical_variables = []
        self.categories_per_column = {}
        self.only_categoricals = only_categoricals

    def fit(self, X, y):
        self.categorical_variables = list(X.select_dtypes(include=['object']).columns)
        logging.debug(f'identified the following categorical variables: {self.categorical_variables}')

        for col in self.categorical_variables:
            self.categories_per_column[col] = X[col].astype('category').cat.categories
        logging.debug('fitted categories')
        return self

    def transform(self, X):
        for col in self.categorical_variables:
            logging.debug(f'transforming cat col: {col}')
            X[col] = pd.Categorical(X[col], categories=self.categories_per_column[col])
            if self.only_categoricals:
                X[col] = X[col].cat.codes
        if not self.only_categoricals:
            return pd.get_dummies(X, sparse=True)
        else:
            return X
</code>```

Body:
How can I transform a pandas data frame to sklearn one-hot-encoded (dataframe / numpy array) where some columns do not require encoding?

mydf = pd.DataFrame({'Target':[0,1,0,0,1, 1,1],
                   'GroupFoo':[1,1,2,2,3,1,2],
                    'GroupBar':[2,1,1,0,3,1,2],
                    'GroupBar2':[2,1,1,0,3,1,2],
                    'SomeOtherShouldBeUnaffected':[2,1,1,0,3,1,2]})
columnsToEncode = ['GroupFoo', 'GroupBar']

Is an already label encoded data frame and I would like to only encode the columns marked by columnsToEncode?

My problem is that I am unsure if a pd.Dataframe or the numpy array representation are better and how to re-merge the encoded part with the other one.

My attempts so far:

myEncoder = OneHotEncoder(sparse=False, handle_unknown='ignore')
myEncoder.fit(X_train)
df = pd.concat([
         df[~columnsToEncode], # select all other / numeric
        # select category to one-hot encode
         pd.Dataframe(encoder.transform(X_train[columnsToEncode]))#.toarray() # not sure what this is for
        ], axis=1).reindex_axis(X_train.columns, axis=1)

Notice: I am aware of Pandas: Get Dummies / http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html but that does not play well in a train / test split where I require such an encoding per fold.

Body:
I believe that this update to the initial answer is even better in order t perform dummy coding
    import logging

import pandas as pd
from sklearn.base import TransformerMixin

log = logging.getLogger(__name__)

class CategoricalDummyCoder(TransformerMixin):
    """Identifies categorical columns by dtype of object and dummy codes them. Optionally a pandas.DataFrame
    can be returned where categories are of pandas.Category dtype and not binarized for better coding strategies
    than dummy coding."""

    def __init__(self, only_categoricals=False):
        self.categorical_variables = []
        self.categories_per_column = {}
        self.only_categoricals = only_categoricals

    def fit(self, X, y):
        self.categorical_variables = list(X.select_dtypes(include=['object']).columns)
        logging.debug(f'identified the following categorical variables: {self.categorical_variables}')

        for col in self.categorical_variables:
            self.categories_per_column[col] = X[col].astype('category').cat.categories
        logging.debug('fitted categories')
        return self

    def transform(self, X):
        for col in self.categorical_variables:
            logging.debug(f'transforming cat col: {col}')
            X[col] = pd.Categorical(X[col], categories=self.categories_per_column[col])
            if self.only_categoricals:
                X[col] = X[col].cat.codes
        if not self.only_categoricals:
            return pd.get_dummies(X, sparse=True)
        else:
            return X


问:
how do we make user to enter the correct login of the website in android
How do we make a user to enter the correct login of the website in android

I am using shared preferences but it saves only when I enter the values locally.

I am making an app which signs up/ register me on the real website.

But I cannot do it.

Please help me on this

答:
If you want to communicate with your own portal / website with your app and want user login from remote server you already have configured. you should use web service like REST etc you can find extensive details here consuming REST services in android application

and you also can maintain to avoid user re login and switch it to main activity (where user reaches after login/signup) by checking login state of user on your portal / website and switch between activities with accordance


答: Because its immediate=true. Immediate fields skip the validation step. I think you have to validate this field manually.</p>

Title: Error message for immediate attribute


问:
Including only .gitignore, .bashrc, .vimrc, .vim/ in a Git repo
I thought I was pretty good with .gitignore files until just now.  I'm trying to include only the following files in a Git repo:

.gitignore

.bashrc

.vimrc

.vim/ (everything in this directory)

I have read several other answers on StackOverflow (How do I ignore files in a directory in Git?, Git ignore sub folders and Is there a way to tell git to only include certain files instead of ignoring certain files?).  But, I can't seem to get my .gitignore file right.  Here's what I have in my .gitignore file presently:

```<code>*
.*
!.gitignore
!.bashrc*
!.vimrc
!.vim/
</code>```

After I run git init; git add .; git status the repo contains:

```<code>$ git init; git add .; git status
Initialized empty Git repository in /home/username/.git/
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   .bashrc
    new file:   .gitignore
    new file:   .vimrc
</code>```

I've tried variations on the last line of my .gitignore file, but to no avail.  Can anyone spot my mistake?

EDIT

I'm trying to find a solution which modifies only the .gitignore file.

答:
You need to ignore files only (* ignores files and folder)

```<code>**
.**
</code>```

Then you can whitelist folders and their files:

```<code>!.vim/
!.vim/**
</code>```

Double-check what .gitignore rule applies with:

```<code>git check-ignore -v .vim/afile
</code>```

What you want is for check-ignore to return nothing.

Body:
I thought I was pretty good with .gitignore files until just now.  I'm trying to include only the following files in a Git repo:

.gitignore

.bashrc

.vimrc

.vim/ (everything in this directory)

I have read several other answers on StackOverflow (How do I ignore files in a directory in Git?, Git ignore sub folders and Is there a way to tell git to only include certain files instead of ignoring certain files?).  But, I can't seem to get my .gitignore file right.  Here's what I have in my .gitignore file presently:

*
.*
!.gitignore
!.bashrc*
!.vimrc
!.vim/

After I run git init; git add .; git status the repo contains:

$ git init; git add .; git status
Initialized empty Git repository in /home/username/.git/
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   .bashrc
    new file:   .gitignore
    new file:   .vimrc

I've tried variations on the last line of my .gitignore file, but to no avail.  Can anyone spot my mistake?

EDIT

I'm trying to find a solution which modifies only the .gitignore file.

Body:
You need to ignore files only (* ignores files and folder)

**
.**

Then you can whitelist folders and their files:

!.vim/
!.vim/**

Double-check what .gitignore rule applies with:

git check-ignore -v .vim/afile

What you want is for check-ignore to return nothing.


问:
String Swap Before and After Comma
I have the table below

```<code>AdviserName
-----------
Tearle, Michael Hearn
Hearn Tearle, Michael
Van Der Welden, Luke
Welden, Luke Van Der
Brennan, Sony G
G Brennan, Sony
Rhammasamysundaran, Vishnu Brahma Kuma
Brahma Kuma Rhammasamysundaran, Vishnu
</code>```

Basically I need to re-arrange so it become FirstName MiddleName LastName. For example Michael Hearn Tearle or Sony G Brennan or Luke Van Der Welden.

I used below syntax but somehow it doesn't like if the middle name is before the comma like Hearn Tearle, Michael.

```<code>If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (AdviserName varchar(max))

insert into #tempX (AdviserName)
values ('Tearle, Michael Hearn'),('Hearn Tearle, Michael'),('Van Der Welden, Luke'),('Welden, Luke Van Der'),('Brennan, Sony G'),('G Brennan, Sony'),('Rhammasamysundaran, Vishnu Brahma Kuma '), ('Brahma Kuma Rhammasamysundaran, Vishnu ')

--select * from #tempX

select substring(advisername, charindex(',', replace(advisername, ' ', '')) + 1, len(advisername))+' '+ left(advisername, charindex(',', advisername) -1) as AdviserName from #tempX
</code>```

Below is the result.

```<code>AdviserName
--------------------------------------
 Michael Hearn Tearle
, Michael Hearn Tearle
n, Luke Van Der Welden
 Luke Van Der Welden
 Sony G Brennan
, Sony G Brennan
 Vishnu Brahma Kuma  Rhammasamysundaran
n, Vishnu  Brahma Kuma Rhammasamysundaran
</code>```

How do you make a query to cater both middle name before comma and after comma?

I'm using SQL Server 2012.

Thanks all.

答:
```<code>;with d as
(select AdviserName, charindex(',',AdviserName) as comma from #tempX)
select
ltrim(rtrim(substring(advisername,comma+1,100)))+' '+ltrim(rtrim(left(advisername,comma-1)))
from d
</code>```

Title: String Swap Before and After Comma

Body:
I have the table below

AdviserName
-----------
Tearle, Michael Hearn
Hearn Tearle, Michael
Van Der Welden, Luke
Welden, Luke Van Der
Brennan, Sony G
G Brennan, Sony
Rhammasamysundaran, Vishnu Brahma Kuma
Brahma Kuma Rhammasamysundaran, Vishnu

Basically I need to re-arrange so it become FirstName MiddleName LastName. For example Michael Hearn Tearle or Sony G Brennan or Luke Van Der Welden.

I used below syntax but somehow it doesn't like if the middle name is before the comma like Hearn Tearle, Michael.

If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (AdviserName varchar(max))

insert into #tempX (AdviserName)
values ('Tearle, Michael Hearn'),('Hearn Tearle, Michael'),('Van Der Welden, Luke'),('Welden, Luke Van Der'),('Brennan, Sony G'),('G Brennan, Sony'),('Rhammasamysundaran, Vishnu Brahma Kuma '), ('Brahma Kuma Rhammasamysundaran, Vishnu ')

--select * from #tempX

select substring(advisername, charindex(',', replace(advisername, ' ', '')) + 1, len(advisername))+' '+ left(advisername, charindex(',', advisername) -1) as AdviserName from #tempX

Below is the result.

AdviserName
--------------------------------------
 Michael Hearn Tearle
, Michael Hearn Tearle
n, Luke Van Der Welden
 Luke Van Der Welden
 Sony G Brennan
, Sony G Brennan
 Vishnu Brahma Kuma  Rhammasamysundaran
n, Vishnu  Brahma Kuma Rhammasamysundaran

How do you make a query to cater both middle name before comma and after comma?

I'm using SQL Server 2012.

Thanks all.


问:
Use array of a component in another component in angular2
I have an array declared public like :

```<code>public arr: Array<any> = []
</code>```

in AddUserComponent which stores the name of users.

i need this array to be used in another component AddTopicComponent to display the user's names as a dropdown.

How do i use this array values in AddTopicComponent ? these two components are not parent-child component.

答:
Below example has both parent to child binding and child to parent binding.

Parent to child binding is done by property binding where master string is passed to child component by the custom property named childToMaster using @Input.

Child to parent binding is done by event binding using @Output. See childToMaster event.

Working demo

Parent component

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  //passing values from parent to child
  master : String="send from parent";

  //Getting value from child
  childToParent(name){
    this.master=name;
  }

}
</code>```

Parent Template

```<code><div>
  <span>Master to Child </span><input type="textbox" [(ngModel)]='master'>
</div>

<app-child [childToMaster]=master (childToParent)="childToParent($event)">

</app-child>
</code>```

Child Component with template

```<code>import { Component, Input, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <input type="textbox" [(ngModel)]='masterName'>
    <button (click)="sendToParent(masterName)" >sendToParent</button>
    <div>{{masterName}}</div>
  `
})
export class AppChildComponent {
  //getting value from parent to child
  @Input('childToMaster') masterName: string;

  @Output() childToParent = new EventEmitter<String>();

  sendToParent(name){
    //alert("hello");
    this.childToParent.emit(name);
  }
}
</code>```

Body:
I have an array declared public like :

public arr: Array<any> = []

in AddUserComponent which stores the name of users.

i need this array to be used in another component AddTopicComponent to display the user's names as a dropdown.

How do i use this array values in AddTopicComponent ? these two components are not parent-child component.

Body:
Below example has both parent to child binding and child to parent binding.

Parent to child binding is done by property binding where master string is passed to child component by the custom property named childToMaster using @Input.

Child to parent binding is done by event binding using @Output. See childToMaster event.

Working demo

Parent component

import { Component, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  //passing values from parent to child
  master : String="send from parent";

  //Getting value from child
  childToParent(name){
    this.master=name;
  }

}

Parent Template

<div>
  <span>Master to Child </span><input type="textbox" [(ngModel)]='master'>
</div>

<app-child [childToMaster]=master (childToParent)="childToParent($event)">

</app-child>

Child Component with template

import { Component, Input, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <input type="textbox" [(ngModel)]='masterName'>
    <button (click)="sendToParent(masterName)" >sendToParent</button>
    <div>{{masterName}}</div>
  `
})
export class AppChildComponent {
  //getting value from parent to child
  @Input('childToMaster') masterName: string;

  @Output() childToParent = new EventEmitter<String>();

  sendToParent(name){
    //alert("hello");
    this.childToParent.emit(name);
  }
}


问:
PHP Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect
Error

Warning: odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect in E:\DEP\Prog\PHP6\starcraft\starcraft\personnage_traitement.php on line 61
  [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.

SQL query when using the Ajouter action (ADD in english)

```<code>$nom =$_POST["nom"];
$faction = $_POST["faction"];
$age = $_POST["age"];
$race = $_POST["race"];
$description = $_POST["description"];
$fichier = $_POST["image"];

if ($_POST["action"] == "Ajouter") {

  $sql="Insert into personnage (nom,  faction, race, age, description, image) values ('$nom', $faction, $race, $age,'$description', '$fichier')";

  odbc_exec($odbc, $sql) or die(odbc_error($odbc));
</code>```

My code

```<code><fieldset>
    <legend>New hero</legend>
                    <label for="nom">Nom : </label><input type="text"     name="nom" id="nom" size="40" required><br>
                    <label for="age">Âge : </label><input type="number" name="age" id="age" size="40" required><br>
                    <label for="race">Race : </label><select name="race" id="race" size="1" >
                        <?php
                        $sql2 = "SELECT NomRace FROM Race;";
                        $resultat2 = odbc_exec($odbc, $sql2) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat2, 0);

                        while (odbc_fetch_row($resultat2)) {

                            $idS = odbc_result($resultat2, "IDRace");

                            $race = utf8_encode(odbc_result($resultat2, "NomRace"));

                            echo "<OPTION VALUE=\"$idS\">$race</OPTION>";
                        }
                        ?>
                    </select> <a href="race.php">Édition des races</a><br>
                    <label for="faction">Faction : </label><select name="faction" id="faction" size="1" >
                        <?php

                        $sql3 = "SELECT NomFaction FROM Faction;";
                        $resultat3 = odbc_exec($odbc, $sql3) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat3, 0);

                        while (odbc_fetch_row($resultat3)) {

                            $idS = odbc_result($resultat3, "IDFaction");

                            $faction = utf8_encode(odbc_result($resultat3, "NomFaction"));

                            echo "<OPTION VALUE=\"$idS\">$faction</OPTION>";
                        }
                        ?>
                    </select> <a href="faction.php">Édition des factions</a><br>
                    <label for="description">Description : </label><input type="text" name="description" id="description" size="40" required>
                    <br>
                    <br>
                    <input type="hidden" name="MAX_FILE_SIZE" value="100000">
                    <label for="fichier">Fichier d'image : </label>
                    <input type="file" onchange="readURL(this);" name="fichier" id="fichier">
                    <img alt="Image" id="preview" title="image" src="#" />
                    <br>
                    <br>
                    <input type="submit" name="action" value="Ajouter">
                </fieldset>
</code>```

答:
this is a sample code, before this you can make your if-else block

```<code>if(condition)
{

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');"

}
</code>```

Body:
Error

Warning: odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect in E:\DEP\Prog\PHP6\starcraft\starcraft\personnage_traitement.php on line 61
  [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.

SQL query when using the Ajouter action (ADD in english)

$nom =$_POST["nom"];
$faction = $_POST["faction"];
$age = $_POST["age"];
$race = $_POST["race"];
$description = $_POST["description"];
$fichier = $_POST["image"];

if ($_POST["action"] == "Ajouter") {

  $sql="Insert into personnage (nom,  faction, race, age, description, image) values ('$nom', $faction, $race, $age,'$description', '$fichier')";

  odbc_exec($odbc, $sql) or die(odbc_error($odbc));

My code

<fieldset>
    <legend>New hero</legend>
                    Nom : <input type="text"     name="nom" id="nom" size="40" required>

                    Âge : <input type="number" name="age" id="age" size="40" required>

                    Race : <select name="race" id="race" size="1" >
                        <?php
                        $sql2 = "SELECT NomRace FROM Race;";
                        $resultat2 = odbc_exec($odbc, $sql2) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat2, 0);

                        while (odbc_fetch_row($resultat2)) {

                            $idS = odbc_result($resultat2, "IDRace");

                            $race = utf8_encode(odbc_result($resultat2, "NomRace"));

                            echo "<OPTION VALUE=\"$idS\">$race</OPTION>";
                        }
                        ?>
                    </select> Édition des races

                    Faction : <select name="faction" id="faction" size="1" >
                        <?php

                        $sql3 = "SELECT NomFaction FROM Faction;";
                        $resultat3 = odbc_exec($odbc, $sql3) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat3, 0);

                        while (odbc_fetch_row($resultat3)) {

                            $idS = odbc_result($resultat3, "IDFaction");

                            $faction = utf8_encode(odbc_result($resultat3, "NomFaction"));

                            echo "<OPTION VALUE=\"$idS\">$faction</OPTION>";
                        }
                        ?>
                    </select> Édition des factions

                    Description : <input type="text" name="description" id="description" size="40" required>

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000">
                    Fichier d'image :
                    <input type="file" onchange="readURL(this);" name="fichier" id="fichier">

                    <input type="submit" name="action" value="Ajouter">
                </fieldset>

Body:
this is a sample code, before this you can make your if-else block

if(condition)
{

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');"

}


问:
Grails Hibernate Session Troubles - failed to lazily initialize a collection
Error:

```<code>Error 500: null
Servlet:
URI:
Exception Message: failed to lazily initialize a collection of role: Student.lockers, no session or session was closed
Caused by: Error executing tag <g:render>: Error executing tag <g:link>: failed to lazily initialize a collection of role: com.itzik.User.carts, no session or session was closed at grails-app/views/shared/_navigation.gsp:18 at grails-app/views/layouts/home.gsp:26
</code>```

So I have a Student (with many Lockers). Now when a student logs in the security service handles putting them into the session. Then my main controller checks to see if they have an active locker. If not it creates one for them. Now for some reason it's choking on the Student –> Locker relationship.

答:
You have several options:

use fetch=FetchType.EAGER - if the collection is not likely to contain too many objects, that in turn have other collections in them, this is the easiest option - you just fetch them from the database together with their owner

use OpenSessionInView - this would require some configuration time, but you might ultimately need it, even if not for this particular case. I can't tell you exactly how to configure OSIV in grails though.

use Hibernate.initialize(collection) before the session is closed (and before the transaction is committed) - this is manual, and pollutes the code, so less preferable

Body:
Error:

Error 500: null
Servlet:
URI:
Exception Message: failed to lazily initialize a collection of role: Student.lockers, no session or session was closed
Caused by: Error executing tag <g:render>: Error executing tag <g:link>: failed to lazily initialize a collection of role: com.itzik.User.carts, no session or session was closed at grails-app/views/shared/_navigation.gsp:18 at grails-app/views/layouts/home.gsp:26

So I have a Student (with many Lockers). Now when a student logs in the security service handles putting them into the session. Then my main controller checks to see if they have an active locker. If not it creates one for them. Now for some reason it's choking on the Student –> Locker relationship.


问:
what are the ways to get texts on image without using "position:absolute"?
Is it the only way to get texts on images?
    position:absolute;
    top:0; (at 0 or wherever the image is..)

Is there any other way to accomplish this ?

答:
Depending on the html layout, there are other options. Use background image as  toast said in comment. Also can use a negative margin. Like this example:

.myimage{
  background:red;
  display:block;
  margin-bottom: -50px;
}

.mytext{
  color:white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red block" width="100" height="100" class="myimage" />
<div class="mytext">
[SOME TEXT]
</div></code>```

Body:
Depending on the html layout, there are other options. Use background image as  toast said in comment. Also can use a negative margin. Like this example:

.myimage{
  background:red;
  display:block;
  margin-bottom: -50px;
}

.mytext{
  color:white;
}

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red block" width="100" height="100" class="myimage" />
<div class="mytext">
[SOME TEXT]
</div>


问:
Split the numbers with dashes and parentheses (input type with numbers only)
How could I set my input type with parentheses and dashes splitting in numbers?

```<code>Number : <input type="text" name="quantity" id="quantity" />
           <span id="errmsg"></span>

$("#quantity").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    //display error message
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
           return false;
}
 });
</code>```

example input type

答:
Happy Coding :)

// Used to format phone number and add placeholder and max-length
function phoneFormatter() {
 $(' input[type="text"]').attr({ placeholder : '(___) ___-____' });
  $('input[tabindex="111"]').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length == 7) {
      number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
    } else if (number.length == 10) {
      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");

    }
    $(this).val(number)
    $('input[type="text"]').attr({ maxLength : 10 });

  });
};

$(phoneFormatter);```
<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" name="input_111[]" value="" tabindex="111"></code>```

Body:
How could I set my input type with parentheses and dashes splitting in numbers?

Number : <input type="text" name="quantity" id="quantity" />

$("#quantity").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    //display error message
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
           return false;
}
 });

example input type

Body:
Happy Coding :)

// Used to format phone number and add placeholder and max-length
function phoneFormatter() {
 $(' input[type="text"]').attr({ placeholder : '(___) ___-____' });
  $('input[tabindex="111"]').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length == 7) {
      number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
    } else if (number.length == 10) {
      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");

    }
    $(this).val(number)
    $('input[type="text"]').attr({ maxLength : 10 });

  });
};

$(phoneFormatter);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input_111[]" value="" tabindex="111">


问:
Reversing Characters within a List using a loop
This is my code I have come up with trying to reverse these strings

```<code>presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)
</code>```

As of now, it only prints the list backwards like this:

```<code>John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington
</code>```

I need it to output the list like:

```<code>notgnihsaW egroeG
smadA nhoJ
</code>```

and so on

答:
Beauty of Recursion :

```<code>presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

def reverse_list(list_1):
    for item in list_1:
        def reverse(word):
            if len(word)==0:
                return word
            else:
                return reverse(word[1:]) + word[0]
        print(reverse(item))
print(reverse_list(presidents))
</code>```

output:

```<code> notgnihsaW egroeG
 smadA nhoJ
 nosreffeJ samohT
 nosidaM semaJ
 eornoM semaJ
 smadA ycniuQ nhoJ
</code>```

Body:
This is my code I have come up with trying to reverse these strings

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)

As of now, it only prints the list backwards like this:

John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington

I need it to output the list like:

notgnihsaW egroeG
smadA nhoJ

and so on

Body:
Beauty of Recursion :

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

def reverse_list(list_1):
    for item in list_1:
        def reverse(word):
            if len(word)==0:
                return word
            else:
                return reverse(word[1:]) + word[0]
        print(reverse(item))
print(reverse_list(presidents))

output:

 notgnihsaW egroeG
 smadA nhoJ
 nosreffeJ samohT
 nosidaM semaJ
 eornoM semaJ
 smadA ycniuQ nhoJ


问:
Using 3rd party UI component in Xcode
I'm trying to use a button from third party library for my iOS app.

I already put AYVibrantButton in my Podfile, and used pod install. I would expect it to appear somewhere in the identity inspector, but it's nowhere to be found. Searching for AYVibrantButton in Xcode's Help search bar doesn't bring up anything either

Thanks in advance

答:
because if you check in interface file, AYVibrantButton is subclass of UIControl, to assign it to your button that must be subclass of UIButton.
You can try changing it to UiButton (you may need to unlock the file to make changes, check the license before making changes)</p>

Title: Using 3rd party UI component in Xcode


问:
Getting custom parameter for D2L LTI launch
We are trying to include user's id as part of LTI launch payload in D2L.

This is what we are getting as the user_id field:

```<code>{
    "user_id": "0d45101e-230a-4c06-9008-0024a52038fc_1914"
}
</code>```

We only want the last DB id field portion. In the attempt to include it as a separate custom parameter, we found that there's doesn't seem to be a very good way to do that, other than checkbox options for allowed params. Is there a way to achieve that?

Creating new custom link seems to have the option to provide the custom parameter. But looks like there are mostly for hard-coded values and can't seem to find template form to provide dynamic values there.

Otherwise, only another fallback option for us is to parse this id and get the last part as our desired identifier, which is our last choice.

Any help/suggestions are appreciated. Thanks!

答:
Your assumptions are correct, this cant be done. the system user ID is not sent with the LTI request, other than in the user_id field as you already know.
Custom parameters are indeed hard-coded and cant be used to send dynamic/per user data. This has been asked before with no answer How to Assign Dynamic Values to Custom Parameters in D2L Basic LTI

Splitting the user_id field on the underscore to extract the system user ID is the only option.

Body:
We are trying to include user's id as part of LTI launch payload in D2L.

This is what we are getting as the user_id field:

{
    "user_id": "0d45101e-230a-4c06-9008-0024a52038fc_1914"
}

We only want the last DB id field portion. In the attempt to include it as a separate custom parameter, we found that there's doesn't seem to be a very good way to do that, other than checkbox options for allowed params. Is there a way to achieve that?

Creating new custom link seems to have the option to provide the custom parameter. But looks like there are mostly for hard-coded values and can't seem to find template form to provide dynamic values there.

Otherwise, only another fallback option for us is to parse this id and get the last part as our desired identifier, which is our last choice.

Any help/suggestions are appreciated. Thanks!


问:
Visual Studio Team Services Build yml npm test not recognized
I'm trying to run an npm install and test on Visual Studio Team Services Build (configuring the build using YAML). I have the following definition.

** updated **

```<code>
queue:
  name: Hosted VS2017
  demands: npm</p>

<p>steps:
- task: NodeTool@0
  inputs:
    versionSpec: "8.x"</p>

<ul>
<li><p>task: Npm@1
inputs:
command: "custom"
verbose: "false"
customCommand: "install @angular/cli -g"</p></li>
<li><p>task: Npm@1
inputs:
verbose: "false"</p></li>
<li><p>task: CmdLine@1
inputs:
filename: "ng"
arguments: "test --watch=false --single-run=true --reporters=junit,progress"</p></li>
<li><p>task: PublishTestResults@2
inputs:
testResultsFiles: "**\test.xml"
testRunTitle: "Jasmine Tests"</p></li>
</ul>

<p>```

The install runs fine, but I get an error on the test step:

 85% chunk id optimization               86% hashing 87% module assets processing  88% chunk assets processing 89% additional chunk assets processing                          90% recording 91% additional asset processing    92% chunk asset optimization       94% asset optimization           95% emitting

2017-12-06T06:21:34.7643927Z ##[error]Process completed with exit code 1.
2017-12-06T06:21:34.7682485Z ##[section]Finishing: Run  Tests

I'm using puppeteer to workaround lack of chrome to run the tests.

答:
Using this code instead:

```<code>queue: Hosted VS2017
steps:
- script: echo installing packages
- task: Npm@1
  displayName: npm install
  inputs:
    command: install
- task: Npm@1
  displayName: npm test
  inputs:
    command: custom
    customCommand: run test
</code>```

BTW, you need add @angular/cli dependency in package.json to install angular cli during running npm install command.

Body:
I'm trying to run an npm install and test on Visual Studio Team Services Build (configuring the build using YAML). I have the following definition.

** updated **

queue:
  name: Hosted VS2017
  demands: npm

steps:
- task: NodeTool@0
  inputs:
    versionSpec: "8.x"

task: Npm@1
inputs:
command: "custom"
verbose: "false"
customCommand: "install @angular/cli -g"

task: Npm@1
inputs:
verbose: "false"

task: CmdLine@1
inputs:
filename: "ng"
arguments: "test --watch=false --single-run=true --reporters=junit,progress"

task: PublishTestResults@2
inputs:
testResultsFiles: "**\test.xml"
testRunTitle: "Jasmine Tests"

The install runs fine, but I get an error on the test step:

 85% chunk id optimization               86% hashing 87% module assets processing  88% chunk assets processing 89% additional chunk assets processing                          90% recording 91% additional asset processing    92% chunk asset optimization       94% asset optimization           95% emitting

2017-12-06T06:21:34.7643927Z ##[error]Process completed with exit code 1.
2017-12-06T06:21:34.7682485Z ##[section]Finishing: Run  Tests

I'm using puppeteer to workaround lack of chrome to run the tests.

Body:
Using this code instead:

queue: Hosted VS2017
steps:
- script: echo installing packages
- task: Npm@1
  displayName: npm install
  inputs:
    command: install
- task: Npm@1
  displayName: npm test
  inputs:
    command: custom
    customCommand: run test

BTW, you need add @angular/cli dependency in package.json to install angular cli during running npm install command.


问:
filter function in ng options repetitive call issue
I have a dropdown in an ng-repeat which stores id of the item in ng-model

```<code><tr ng-repeat="bill in billItems track by $index">
</code>```

And, I have a filter in my ng-options that iterates over a list like this:-

```<code><td>
    <select ng-model="bill.itemId"  ng-required="true"
        ng-options="item.itemId as item.itemName for item in itemRates |
                    exclude: bill.itemId: billItems">

        <option value="">Select Here</option>
    </select>
</td>
</code>```

And an add button that adds the same dropdown below, but does not show the option already selected in the above dropdown for the next one.
In a way, very similar to this fiddle.
(Also see the exclude function written in the app.js file)
http://plnkr.co/edit/zJnExGHQ9hJznoF4TyZI?p=preview

The above helps me to disable select option in the next dropdown I add.

Barring a few tweaks, the code written in the above filter function is very similar to mine.

However, the issue I am facing is that it keeps getting repeatedly called, even though I just open the state (html page) containing the dropdown(s).

Have verified this by using a console.log("In exclude function()") statement in the same.

Another problem, supposedly due to this is that the sequence in which I add billItems in my dropdown(s) shuffles at random, when the page is saved and I open it again.

For instance, I have added around 5 billItems in the dropdown, say sequentially from billItem1, billItem2, and so on till billItem5.

When I persist this data (I have a save button) in the billItems array, got to a different state ,  and again return to this state (Using the edit button) and check the billItems array, the sequence has been changed.

I can see the sequence like this billItem2, billItem1, billItem3, billItem4, billItem5 in that order in the array now.

Again, when I do this entire thing again, the sequence again shuffles. How exactly do I prevent this ?

I expect the result to be in the same sequence as I have added the dropdowns one after another.

How can it be achieved ?

答:
However, the issue I am facing is that it keeps getting repeatedly called, even though I just open the state (html page) containing the dropdown(s).

In AngularJS, every filter is called at least once during each digest cycle. Opening a dropdown triggers a digest cycle so all filters are called at least once each time.

When I persist this data (I have a save button) in the billItems array, got to a different state , and again return to this state (Using the edit button) and check the billItems array, the sequence has been changed.

It's hard to say why this is happening. This is most likely not an issue with your code but rather with the backend API which is returning the data. For example, SQL Server does not guarantee the order of results unless you explicitly add an ORDER BY clause to the SELECT statement. Does the displayed order differ from the order which is returned by the API?

Body:
I have a dropdown in an ng-repeat which stores id of the item in ng-model

And, I have a filter in my ng-options that iterates over a list like this:-

    <select ng-model="bill.itemId"  ng-required="true"
        ng-options="item.itemId as item.itemName for item in itemRates |
                    exclude: bill.itemId: billItems">

        <option value="">Select Here</option>
    </select>

And an add button that adds the same dropdown below, but does not show the option already selected in the above dropdown for the next one.
In a way, very similar to this fiddle.
(Also see the exclude function written in the app.js file)
http://plnkr.co/edit/zJnExGHQ9hJznoF4TyZI?p=preview

The above helps me to disable select option in the next dropdown I add.

Barring a few tweaks, the code written in the above filter function is very similar to mine.

However, the issue I am facing is that it keeps getting repeatedly called, even though I just open the state (html page) containing the dropdown(s).

Have verified this by using a console.log("In exclude function()") statement in the same.

Another problem, supposedly due to this is that the sequence in which I add billItems in my dropdown(s) shuffles at random, when the page is saved and I open it again.

For instance, I have added around 5 billItems in the dropdown, say sequentially from billItem1, billItem2, and so on till billItem5.

When I persist this data (I have a save button) in the billItems array, got to a different state ,  and again return to this state (Using the edit button) and check the billItems array, the sequence has been changed.

I can see the sequence like this billItem2, billItem1, billItem3, billItem4, billItem5 in that order in the array now.

Again, when I do this entire thing again, the sequence again shuffles. How exactly do I prevent this ?

I expect the result to be in the same sequence as I have added the dropdowns one after another.

How can it be achieved ?


问:
Change the color of the input line in the alert Dialog
I need to change the color of the edit text line, in the alert dialog, I'm trying everything, and I'm not working.

```<code>public void alertaComentario()
    {
        AlertDialog.Builder comentario = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
        comentario.setMessage("Escreva uma resenha curta");
        final EditText input = new EditText(getActivity());
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        comentario.setView(input);

        comentario.setPositiveButton("Enviar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "A sociedade agradece seu comentário", Toast.LENGTH_SHORT).show();
            }
        });
        comentario.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        comentario.show();
    }
</code>```

alert dialog

答:
in your Alert Dialog xml update EditText with this line:

```<code> android:backgroundTint="#ffffff"
</code>```

Body:
I need to change the color of the edit text line, in the alert dialog, I'm trying everything, and I'm not working.

public void alertaComentario()
    {
        AlertDialog.Builder comentario = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
        comentario.setMessage("Escreva uma resenha curta");
        final EditText input = new EditText(getActivity());
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        comentario.setView(input);

        comentario.setPositiveButton("Enviar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "A sociedade agradece seu comentário", Toast.LENGTH_SHORT).show();
            }
        });
        comentario.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        comentario.show();
    }

alert dialog

Body:
in your Alert Dialog xml update EditText with this line:

 android:backgroundTint="#ffffff"


问:
How to Implement A Recommendation System?
I've Collective Intelligence book, but I'm not sure how it can be apply in practical.

Let say I have a PHP website with mySQL database. User can insert articles with title and content in the database. For the sake of simplicity, we just compare the title.

How to Make Coffee?

15 Things About Coffee.

The Big Question.

How to Sharpen A Pencil?

Guy Getting Hit in Balls

We open 'How to Make Coffee?' article and because there are similarity in words with the second and fourth title, they will be displayed in Related Article section.

How can I implement this using PHP and mySQL? It's ok if I have to use Python. Thanks in advance.

答:
This can be simply achieved by using wildcards in SQL queries. If you have larger texts and the wildcard seems to be unable to capture the middle part of text then check if the substring of one matches the other. I hope this helps.
BTW, your question title asks about implementing recommendation system and the question description just asks about matching a field among database records. Recommendation system is a broad topic and comes with many interesting algorithms (e.g, Collaborative filtering, content-based method, matrix factorization, neural networks, etc.). Please feel free to explore these advanced topics if your project is to that scale.</p>


答:
If you are looking for alternate rows where ign=0 then below script will help you to get desire result :</p>

```<code>WITH CTE AS(
   SELECT Device_Code,
          ign,
          Event_DateTime,
          ROW_NUMBER() OVER (PARTITION BY ign ORDER BY Device_Code) RN
   FROM TableName
)
SELECT Device_Code,
          ign,
          Event_DateTime
FROM CTE
WHERE RN % 2 = 1
</code>```

Title: Select alternate column having IGN=0 from the following table using CTE in SQL Server

Body:
Device_Code ign Event_DateTime
-------------------------------
5909    0   49:32.0
5909    0   19:32.0
5909    0   49:32.0
5909    0   18:42.0
5909    1   17:42.0
5909    1   16:42.0
5909    1   16:32.0
5909    1   16:27.0
5909    1   16:22.0
5909    1   15:47.0
5909    1   15:42.0
5909    1   15:24.0
5909    1   15:12.0
5909    1   14:52.0
5909    1   13:53.0
5909    1   13:02.0
5909    1   12:02.0
5909    1   11:18.0
5909    1   11:13.0
5909    1   11:02.0
5909    1   10:02.0
5909    1   09:02.0
5909    1   08:02.0
5909    1   07:31.0
5909    1   07:02.0
5909    1   06:29.0
5909    1   06:24.0
5909    0   06:02.0
5909    1   05:02.0

Body:
If you are looking for alternate rows where ign=0 then below script will help you to get desire result :

WITH CTE AS(
   SELECT Device_Code,
          ign,
          Event_DateTime,
          ROW_NUMBER() OVER (PARTITION BY ign ORDER BY Device_Code) RN
   FROM TableName
)
SELECT Device_Code,
          ign,
          Event_DateTime
FROM CTE
WHERE RN % 2 = 1


问:
Paper trail gem makes fields with the name version unusable
I have a table named clients backed by an AR model Client. This is the structure of clients table:

```<code>clients
  - id <serial primary key>
  - name <varchar(255)>
  - version <varchar(255)>
</code>```

I have added versioning to it using the paper trail gem. However, when I update or create the record, the column version does not update. And when I do Client.first.version it gives me nil value even though all my records in the table have a version column that is not null or empty. I suspect this is because of paper trail gem. When I switch my project's branch to a version that does not use the gem, I am able to get non-nil value of version.

Is there any workaround to fix this issue?

答:
Sure, there is. Problem is, version is the default association name in paper_trail, thus calling the association on client rather than fetching it's attribute.
You can change your model as:

```<code>class Client < ActiveRecord::Base
  has_paper_trail version: :paper_version, versions: :paper_versions
end

c = Client.first
c.version #=> row field
c.paper_versions #=> previous versions.
</code>```

Edit: Just found that it is also documented in paper_trail here - https://github.com/airblade/paper_trail#6-extensibility

Body:
I have a table named clients backed by an AR model Client. This is the structure of clients table:

clients
  - id <serial primary key>
  - name <varchar(255)>
  - version <varchar(255)>

I have added versioning to it using the paper trail gem. However, when I update or create the record, the column version does not update. And when I do Client.first.version it gives me nil value even though all my records in the table have a version column that is not null or empty. I suspect this is because of paper trail gem. When I switch my project's branch to a version that does not use the gem, I am able to get non-nil value of version.

Is there any workaround to fix this issue?

Body:
Sure, there is. Problem is, version is the default association name in paper_trail, thus calling the association on client rather than fetching it's attribute.
You can change your model as:

class Client < ActiveRecord::Base
  has_paper_trail version: :paper_version, versions: :paper_versions
end

c = Client.first
c.version #=> row field
c.paper_versions #=> previous versions.

Edit: Just found that it is also documented in paper_trail here - https://github.com/airblade/paper_trail#6-extensibility


问:
javax.mail.MessagingException Is throwing when I try to connect via IMAP to Gmail
Trying to connect to gmail via IMAP connection, catch javax.mail.MessagingException

```<code>public static StringBuffer getEmailByBody(String username, String password, String containsMsg) throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imap.ssl.enable", "true");

    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    try {
        store.connect("imap.gmail.com", username , password);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new Exception("Fail in connection" + ex.getMessage());
    }

    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);

    Message[] messages = null;
    boolean isMailFound = false;
    Message confirmationMAil = null;

    // Search for mail MAX 10 runs
    for (int i = 0; i < 10; i++) {
        messages = folder.search(new BodyTerm(containsMsg), folder.getMessages());
        for(Message message : messages){
            if (!message.isSet(Flags.Flag.SEEN)) {
                confirmationMAil = message;
                isMailFound = true;
                break;
            }
        }
        // wait for 3 seconds if message is not found
        if (!isMailFound) {
            Thread.sleep(3000);
        }
    }

    // Search latests for unread mail
    for(Message message : messages){
        if (!message.isSet(Flags.Flag.SEEN)) {
            confirmationMAil = message;
            isMailFound = true;
            break;
        }
    }

    // Test fails if no unread mail was found from God
    if (!isMailFound) {
        throw new Exception("Could not find email");

        // Read the content of mail and launch registration URL
    } else {
        String line;
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                confirmationMAil.getInputStream()));
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer;
    }
}
</code>```

Stack Trace:

javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
    nested exception is:
      javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
      at javax.mail.Service.connect(Service.java:364)
      at javax.mail.Service.connect(Service.java:245)
      at insynctive.utils.MailManager.getEmailByBody(MailManager.java:39)
      at insynctive.utils.MailManager.getVerificationCode(MailManager.java:106)
      at insynctive.pages.insynctive.TwoFAPage.sendViaPrimaryEmail(TwoFAPage.java:49)
      at insynctive.tests.PersonFileTest.loginWith2FAEmail(PersonFileTest.java:148)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:483)
      at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
      at org.testng.internal.Invoker.invokeMethod(Invoker.java:659)
      at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:845)
      at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1153)
      at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
      at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
      at org.testng.TestRunner.privateRun(TestRunner.java:771)
      at org.testng.TestRunner.run(TestRunner.java:621)
      at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
      at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
      at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
      at org.testng.SuiteRunner.run(SuiteRunner.java:259)
      at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
      at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
      at org.testng.TestNG.runSuitesSequentially(TestNG.java:1199)
      at org.testng.TestNG.runSuitesLocally(TestNG.java:1124)
      at org.testng.TestNG.run(TestNG.java:1032)
      at insynctive.runnable.RunnableTest.run(RunnableTest.java:36)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
      at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917)
      at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301)
      at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295)
      at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1369)
      at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156)
      at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925)
      at sun.security.ssl.Handshaker.process_record(Handshaker.java:860)
      at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
      at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
      at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
      at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
      at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
      at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
      at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
      at com.sun.mail.iap.Protocol.(Protocol.java:116)
      at com.sun.mail.imap.protocol.IMAPProtocol.(IMAPProtocol.java:115)
      at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:685)
      at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636)
      ... 29 more
  Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
      at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
      at sun.security.validator.Validator.validate(Validator.java:260)
      at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
      at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)

Main:

```<code>public static void main(String[] args) throws Exception {
        MailManager.getEmailByBody("asd@gmail.com", "password", "Hello");
}
</code>```

答:
Try adding this before you call Session class:</p>

```<code> System.setProperty("javax.net.ssl.trustStore", path to your cacerts file in your Java folder, inside your hard disk);
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
        Properties prop = new Properties();
        prop.setProperty("mail.pop3.starttls.enable", "false");
        prop.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.pop3.socketFactory.fallback", "false");
        prop.setProperty("mail.pop3.port", port);
        prop.setProperty("mail.pop3.socketFactory.port", port);
        prop.setProperty("mail.imap.ssl.trust", "*");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.socketFactory", sf);
</code>```

Body:
Trying to connect to gmail via IMAP connection, catch javax.mail.MessagingException

public static StringBuffer getEmailByBody(String username, String password, String containsMsg) throws Exception {
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imap.ssl.enable", "true");

    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    try {
        store.connect("imap.gmail.com", username , password);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new Exception("Fail in connection" + ex.getMessage());
    }

    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);

    Message[] messages = null;
    boolean isMailFound = false;
    Message confirmationMAil = null;

    // Search for mail MAX 10 runs
    for (int i = 0; i < 10; i++) {
        messages = folder.search(new BodyTerm(containsMsg), folder.getMessages());
        for(Message message : messages){
            if (!message.isSet(Flags.Flag.SEEN)) {
                confirmationMAil = message;
                isMailFound = true;
                break;
            }
        }
        // wait for 3 seconds if message is not found
        if (!isMailFound) {
            Thread.sleep(3000);
        }
    }

    // Search latests for unread mail
    for(Message message : messages){
        if (!message.isSet(Flags.Flag.SEEN)) {
            confirmationMAil = message;
            isMailFound = true;
            break;
        }
    }

    // Test fails if no unread mail was found from God
    if (!isMailFound) {
        throw new Exception("Could not find email");

        // Read the content of mail and launch registration URL
    } else {
        String line;
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                confirmationMAil.getInputStream()));
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer;
    }
}

Stack Trace:

javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
    nested exception is:
      javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
      at javax.mail.Service.connect(Service.java:364)
      at javax.mail.Service.connect(Service.java:245)
      at insynctive.utils.MailManager.getEmailByBody(MailManager.java:39)
      at insynctive.utils.MailManager.getVerificationCode(MailManager.java:106)
      at insynctive.pages.insynctive.TwoFAPage.sendViaPrimaryEmail(TwoFAPage.java:49)
      at insynctive.tests.PersonFileTest.loginWith2FAEmail(PersonFileTest.java:148)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:483)
      at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
      at org.testng.internal.Invoker.invokeMethod(Invoker.java:659)
      at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:845)
      at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1153)
      at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
      at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
      at org.testng.TestRunner.privateRun(TestRunner.java:771)
      at org.testng.TestRunner.run(TestRunner.java:621)
      at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
      at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
      at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
      at org.testng.SuiteRunner.run(SuiteRunner.java:259)
      at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
      at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
      at org.testng.TestNG.runSuitesSequentially(TestNG.java:1199)
      at org.testng.TestNG.runSuitesLocally(TestNG.java:1124)
      at org.testng.TestNG.run(TestNG.java:1032)
      at insynctive.runnable.RunnableTest.run(RunnableTest.java:36)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
      at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917)
      at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301)
      at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295)
      at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1369)
      at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156)
      at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925)
      at sun.security.ssl.Handshaker.process_record(Handshaker.java:860)
      at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
      at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
      at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
      at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
      at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
      at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
      at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
      at com.sun.mail.iap.Protocol.(Protocol.java:116)
      at com.sun.mail.imap.protocol.IMAPProtocol.(IMAPProtocol.java:115)
      at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:685)
      at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636)
      ... 29 more
  Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
      at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
      at sun.security.validator.Validator.validate(Validator.java:260)
      at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
      at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)

Main:

public static void main(String[] args) throws Exception {
        MailManager.getEmailByBody("asd@gmail.com", "password", "Hello");
}

Body:
Try adding this before you call Session class:

 System.setProperty("javax.net.ssl.trustStore", path to your cacerts file in your Java folder, inside your hard disk);
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
        Properties prop = new Properties();
        prop.setProperty("mail.pop3.starttls.enable", "false");
        prop.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.pop3.socketFactory.fallback", "false");
        prop.setProperty("mail.pop3.port", port);
        prop.setProperty("mail.pop3.socketFactory.port", port);
        prop.setProperty("mail.imap.ssl.trust", "*");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.socketFactory", sf);


问:
Hardware JPEG decompression / Win32
I know that most graphics hardware uses MPEG hardware decompression. I would like to use the hardware to decompress JPEG images. Does anyone know of a book or link to any information about using this functionality, or can tell me anything about it?

Also, I am willing to convert the images into a "video" if I can obtain hardware decompression of each frame. Would this be more viable?

答:
Video decompression hardware is special purpose.  It takes a video stream that is encoded to a specific standard.  You will generally not be able to decode JPEG using MPEG decoding hardware.

Another software option is to use the Intel Integrated Performance Primitives.  These are optimized to take advantage of SSE instructions on Intel processors.

As @6502 notes if you convert your JPEG images to a video format (e.g. h.264) there are many ways to use hardware accelerated playback (e.g. DirectShow under Windows).  You can do this conversion manually with most video editing software.

Title: Hardware JPEG decompression / Win32