问:
Call to a member function query() on a non-object error in PDO
This is my sql connection code

```<code>$config['db'] = array('host' => 'localhost', 'username' =>  'root', 'password' => '', 'dbname' => 'reputize');

try
{
    $db = new PDO('mysql:host='.$config['db']['host'].';dbname'.$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    echo "Database connected successfully";
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}
</code>```

and this is the code i am using to fetch data from the table

```<code>$query = $db->query("select * from metaTags where filename='index'");
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $ptitle=$row['MetaTitle'];
    $desc=$row['MetaDisc'];
    $kwords=$row['MetaKwd'];
}
</code>```

but the error keeps on showing

Call to a member function query() on a non-object in C:\xampp\htdocs\template OOP\include\class\websiteClasses.php on line 14

I have tried many solutions here and on other sites as well but of no use.
Please help me out with this problem

答:
You forget to add '=' after dbname.

Your config should look like below

```<code>dbname='.$config['db']['dbname']
</code>```

From your comment, I understand that your '$db' variable must be declared accessible to other functions.  Please check $db has valid database connection before query the database.

I usually use below code for connecting and getting data for my play projects.

```<code>function getDbConnection()
{
  $pdo = null;
  try
  {
    $pdo = new PDO("mysql:host=" . HOST . ";dbname=" . DBNAME,USERNAME,PWD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  }
  catch(PDOException $pe)
  {
    die("Sorry! Could not connect to database " . DBNAME. ": " . $pe->getMessage());
  }
  return $pdo;
}

function getData($qry)
{
  $res = null;
  try
  {
    if(!empty($qry))
    {
      $pdo = getDbConnection();
      if(!empty($pdo))
      {
        $res = $pdo->query($qry);
      }
    }
  }
  catch(PDOException $pe)
  {
    throw $pe;
  }
  return $res;
}
</code>```

Note: The above functions are not robust. But It works.

Body:
This is my sql connection code

$config['db'] = array('host' => 'localhost', 'username' =>  'root', 'password' => '', 'dbname' => 'reputize');

try
{
    $db = new PDO('mysql:host='.$config['db']['host'].';dbname'.$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    echo "Database connected successfully";
}
catch(PDOException $e)
{
    echo $sql . "
" . $e->getMessage();
}

and this is the code i am using to fetch data from the table

$query = $db->query("select * from metaTags where filename='index'");
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $ptitle=$row['MetaTitle'];
    $desc=$row['MetaDisc'];
    $kwords=$row['MetaKwd'];
}

but the error keeps on showing

Call to a member function query() on a non-object in C:\xampp\htdocs\template OOP\include\class\websiteClasses.php on line 14

I have tried many solutions here and on other sites as well but of no use.
Please help me out with this problem

Body:
You forget to add '=' after dbname.

Your config should look like below

dbname='.$config['db']['dbname']

From your comment, I understand that your '$db' variable must be declared accessible to other functions.  Please check $db has valid database connection before query the database.

I usually use below code for connecting and getting data for my play projects.

function getDbConnection()
{
  $pdo = null;
  try
  {
    $pdo = new PDO("mysql:host=" . HOST . ";dbname=" . DBNAME,USERNAME,PWD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  }
  catch(PDOException $pe)
  {
    die("Sorry! Could not connect to database " . DBNAME. ": " . $pe->getMessage());
  }
  return $pdo;
}

function getData($qry)
{
  $res = null;
  try
  {
    if(!empty($qry))
    {
      $pdo = getDbConnection();
      if(!empty($pdo))
      {
        $res = $pdo->query($qry);
      }
    }
  }
  catch(PDOException $pe)
  {
    throw $pe;
  }
  return $res;
}

Note: The above functions are not robust. But It works.


来源: stackexchange

问:
Convert VML graphic to bitmap on the ASP.NET server
I'm using RaphaelJS. The browser renders a chart for me (which is in VML as all my users are on IE). I want the user to be able to save this image and share it normally eg paste into an email, into powerpoint, into a document etc etc.

Problem is not many things can render VML. I can easily get the VML markup describing the image back to the server. All I want to do is convert it to some kind of more universal format eg PNG, BMP, GIFF, whatever which I can then allow the user to download.

I've seen lots of people struggling with this. I would have thought the seeing as VML is Microsoft's proprietary SVG format they might have at least provided facilities within their own languages (C#,VB.net) to convert VML to bitmaps.

Anyone know how?

(Incidentally I can't use PHP - I've seen a lot of people attempting to solve this with a PHP based solution)

Thanks :)

答:
You can use the Internet Explorer ActiveX control and screenshotting techniques to achieve this. See the open source tool IECapt as an example.

You could also evaluate whether a cloud service like Litmus API could be used.

ContentLicense: CC BY-SA 2.5


问:
How can I get current date in Android?
I wrote the following code

```<code>Date d = new Date();
CharSequence s  = DateFormat.format("MMMM d, yyyy ", d.getTime());
</code>```

I want the current date in string format, like

```<code>28-Dec-2011
</code>```

so that I can set it into a TextView.

答:
This is the code i used:</p>

```<code>             Date date = new Date();  // to get the date
             SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
             String formattedDate = df.format(date.getTime());
             text.setText(formattedDate);
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can I get current date in Android?

Body:
I wrote the following code

Date d = new Date();
CharSequence s  = DateFormat.format("MMMM d, yyyy ", d.getTime());

I want the current date in string format, like

28-Dec-2011

so that I can set it into a TextView.

Body:
This is the code i used:

             Date date = new Date();  // to get the date
             SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
             String formattedDate = df.format(date.getTime());
             text.setText(formattedDate);

ContentLicense: CC BY-SA 3.0


问:
Python numpy matrix multiplication with one diagonal matrix
I have two arrays A (4000,4000) of which only the diagonal is filled with data, and B (4000,5), filled with data. Is there a way to multiply (dot) these arrays that is faster than the numpy.dot(a,b) function?

So far I found that (A * B.T).T should be faster (where A is one dimensional (4000,), filled with the diagonal elements), but it turned out to be roughly twice as slow.

is there a faster way to calculate B.dot(A) in the case where A is a diagnal array?

答:
You could simply extract the diagonal elements and then perform broadcasted elementwise multiplication.

Thus, a replacement for B*A would be -

```<code>np.multiply(np.diag(B)[:,None], A)
</code>```

and for A.T*B -

```<code>np.multiply(A.T,np.diag(B))
</code>```

Runtime test -

```<code>In [273]: # Setup
     ...: M,N = 4000,5
     ...: A = np.random.randint(0,9,(M,N)).astype(float)
     ...: B = np.zeros((M,M),dtype=float)
     ...: np.fill_diagonal(B, np.random.randint(11,99,(M)))
     ...: A = np.matrix(A)
     ...: B = np.matrix(B)
     ...:

In [274]: np.allclose(B*A, np.multiply(np.diag(B)[:,None], A))
Out[274]: True

In [275]: %timeit B*A
10 loops, best of 3: 32.1 ms per loop

In [276]: %timeit np.multiply(np.diag(B)[:,None], A)
10000 loops, best of 3: 33 µs per loop

In [282]: np.allclose(A.T*B, np.multiply(A.T,np.diag(B)))
Out[282]: True

In [283]: %timeit A.T*B
10 loops, best of 3: 24.1 ms per loop

In [284]: %timeit np.multiply(A.T,np.diag(B))
10000 loops, best of 3: 36.2 µs per loop
</code>```

Body:
You could simply extract the diagonal elements and then perform broadcasted elementwise multiplication.

Thus, a replacement for B*A would be -

np.multiply(np.diag(B)[:,None], A)

and for A.T*B -

np.multiply(A.T,np.diag(B))

Runtime test -

In [273]: # Setup
     ...: M,N = 4000,5
     ...: A = np.random.randint(0,9,(M,N)).astype(float)
     ...: B = np.zeros((M,M),dtype=float)
     ...: np.fill_diagonal(B, np.random.randint(11,99,(M)))
     ...: A = np.matrix(A)
     ...: B = np.matrix(B)
     ...:

In [274]: np.allclose(B*A, np.multiply(np.diag(B)[:,None], A))
Out[274]: True

In [275]: %timeit B*A
10 loops, best of 3: 32.1 ms per loop

In [276]: %timeit np.multiply(np.diag(B)[:,None], A)
10000 loops, best of 3: 33 µs per loop

In [282]: np.allclose(A.T*B, np.multiply(A.T,np.diag(B)))
Out[282]: True

In [283]: %timeit A.T*B
10 loops, best of 3: 24.1 ms per loop

In [284]: %timeit np.multiply(A.T,np.diag(B))
10000 loops, best of 3: 36.2 µs per loop


问:
JSON data binding issues with jquery datatable
```

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var Jdata = [{"Store":480,"District":62,"Region":8,"Area":10,"City":"SPRINGFIELD","State":"TN","RiskClass":"RISK CLASS 2","AssignedDate":null,"AssignedBy":null,"AssignedConfig":null,"MatchCount":0,"MismatchCount":0,"ConfigModDate":null,"ConfigAppliedDate":null,"ConfigModBy":null},{"Store":590,"District":62,"Region":8,"Area":10,"City":"ASHLAND CITY","State":"TN","RiskClass":"RISK CLASS 0","AssignedDate":null,"AssignedBy":null,"AssignedConfig":null,"MatchCount":0,"MismatchCount":0,"ConfigModDate":null,"ConfigAppliedDate":null,"ConfigModBy":null}]

var tableCatValue = $('#AjaxGrid').dataTable({
                "bDestroy": true,
                "bFilter": true,
                "pageLength": 5,
                "bLengthChange": false,
                "data": Jdata,
                "columns": [

                                    { data: null, render: function (data, type, row) {
                                        return '<div class=" messageName ">' + data.Store + '</div>';
                                    }, width: '20%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '<div class=" messageDesc">' + data.District + '</div>';
                                    }, width: '53%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '<div class=" messageName ct-ml-10">' + data.Region + '</div>';
                                    }, width: '20%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '<div class=" messageName ct-ml-10">' + data.Area + '</div>';
                                    }, width: '20%'
                                }
                        ]
            });</code>```

   Group

   Region

   District

   Store

```
</div>
</div>

```

答:
Problem1: First load jquery and then load dataTable.

Problem2: You have not included dataTable.css (To style table)

var Jdata = [{"Store":480,"District":62,"Region":8,"Area":10,"City":"SPRINGFIELD","State":"TN","RiskClass":"RISK CLASS 2","AssignedDate":null,"AssignedBy":null,"AssignedConfig":null,"MatchCount":0,"MismatchCount":0,"ConfigModDate":null,"ConfigAppliedDate":null,"ConfigModBy":null},{"Store":590,"District":62,"Region":8,"Area":10,"City":"ASHLAND CITY","State":"TN","RiskClass":"RISK CLASS 0","AssignedDate":null,"AssignedBy":null,"AssignedConfig":null,"MatchCount":0,"MismatchCount":0,"ConfigModDate":null,"ConfigAppliedDate":null,"ConfigModBy":null}];

var tableCatValue = $('#AjaxGrid').dataTable({
                "bDestroy": true,
                "bFilter": true,
                "pageLength": 5,
                "bLengthChange": false,
                "data": Jdata,
                "columns": [

                                    { data: null, render: function (data, type, row) {
                                        return '
' + data.Store + '
';
                                    }, width: '20%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '
' + data.District + '
';
                                    }, width: '53%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '
' + data.Region + '
';
                                    }, width: '20%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '
' + data.Area + '
';
                                    }, width: '20%'
                                }
                        ]
            });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<table id="AjaxGrid">
<thead>
 <tr>
  <th>
   <b>Group</b>
  </th>
  <th>
   <b>Region</b>
  </th>
  <th>
   <b>District</b>
  </th>
  <th>
   <b>Store</b>
  </th>
 </tr>
</thead>
<tbody>
</tbody>
</table></code>```

Body:
var Jdata = [{"Store":480,"District":62,"Region":8,"Area":10,"City":"SPRINGFIELD","State":"TN","RiskClass":"RISK CLASS 2","AssignedDate":null,"AssignedBy":null,"AssignedConfig":null,"MatchCount":0,"MismatchCount":0,"ConfigModDate":null,"ConfigAppliedDate":null,"ConfigModBy":null},{"Store":590,"District":62,"Region":8,"Area":10,"City":"ASHLAND CITY","State":"TN","RiskClass":"RISK CLASS 0","AssignedDate":null,"AssignedBy":null,"AssignedConfig":null,"MatchCount":0,"MismatchCount":0,"ConfigModDate":null,"ConfigAppliedDate":null,"ConfigModBy":null}]

var tableCatValue = $('#AjaxGrid').dataTable({
                "bDestroy": true,
                "bFilter": true,
                "pageLength": 5,
                "bLengthChange": false,
                "data": Jdata,
                "columns": [

                                    { data: null, render: function (data, type, row) {
                                        return '
' + data.Store + '
';
                                    }, width: '20%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '
' + data.District + '
';
                                    }, width: '53%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '
' + data.Region + '
';
                                    }, width: '20%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '
' + data.Area + '
';
                                    }, width: '20%'
                                }
                        ]
            });

   Group

   Region

   District

   Store

Body:
Problem1: First load jquery and then load dataTable.

Problem2: You have not included dataTable.css (To style table)

var Jdata = [{"Store":480,"District":62,"Region":8,"Area":10,"City":"SPRINGFIELD","State":"TN","RiskClass":"RISK CLASS 2","AssignedDate":null,"AssignedBy":null,"AssignedConfig":null,"MatchCount":0,"MismatchCount":0,"ConfigModDate":null,"ConfigAppliedDate":null,"ConfigModBy":null},{"Store":590,"District":62,"Region":8,"Area":10,"City":"ASHLAND CITY","State":"TN","RiskClass":"RISK CLASS 0","AssignedDate":null,"AssignedBy":null,"AssignedConfig":null,"MatchCount":0,"MismatchCount":0,"ConfigModDate":null,"ConfigAppliedDate":null,"ConfigModBy":null}];

var tableCatValue = $('#AjaxGrid').dataTable({
                "bDestroy": true,
                "bFilter": true,
                "pageLength": 5,
                "bLengthChange": false,
                "data": Jdata,
                "columns": [

                                    { data: null, render: function (data, type, row) {
                                        return '<div class=" messageName ">' + data.Store + '</div>';
                                    }, width: '20%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '<div class=" messageDesc">' + data.District + '</div>';
                                    }, width: '53%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '<div class=" messageName ct-ml-10">' + data.Region + '</div>';
                                    }, width: '20%'
                                },
                                    { data: null, render: function (data, type, row) {
                                        return '<div class=" messageName ct-ml-10">' + data.Area + '</div>';
                                    }, width: '20%'
                                }
                        ]
            });

<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<table id="AjaxGrid">
<thead>
 <tr>
  <th>
   <b>Group</b>
  </th>
  <th>
   <b>Region</b>
  </th>
  <th>
   <b>District</b>
  </th>
  <th>
   <b>Store</b>
  </th>
 </tr>
</thead>
<tbody>
</tbody>
</table>


问:
jQuery - Calculate sum of two numbers inside one td and display inside new td?
Hello Stackoverflowers,

I have this code:

```<code>    <table class="table">
        <tbody>
            <tr>
                <td><a href="#">New thing</a></td>
                <td>2017/06/04 08:00</td>
                <td><a href="#">One Thing</a><span>Another thing</span></td>
                <td class="random">R</td>
                <td><a href="#">12-11      </a></td>
            </tr>
            <tr>
                <td><a href="#">New thing</a></td>
                <td>2017/06/04 08:00</td>
                <td><a href="#">One Thing</a><span>Another thing</span></td>
                <td class="random">R</td>
                <td><a href="#">22-23      </a></td>
            </tr>
        </tbody>
    </table>
</code>```

In the result I want to use jQuery to get a sum of numbers inside last table TD and display it into new TD. Like in the following code:

```<code><table class="table">
    <tbody>
        <tr>
            <td><a href="#">New thing</a></td>
            <td>2017/06/04 08:00</td>
            <td><a href="#">One Thing</a><span>Another thing</span></td>
            <td class="random">R</td>
            <td><a href="#">12-11      </a></td>
            <td>[ 23 ]</td>
        </tr>
        <tr>
            <td><a href="#">New thing</a></td>
            <td>2017/06/04 08:00</td>
            <td><a href="#">One Thing</a><span>Another thing</span></td>
            <td class="random">R</td>
            <td><a href="#">22-23      </a></td>
            <td>[ 45 ]</td>
        </tr>
    </tbody>
</table>
</code>```

thank you in advance.

答:
find the last children('td:last') .

split string with split(-)

And use with parseFloat() for convert the string to number

$('table tr').each(function(){
var a =$(this).children('td:last').text().trim().split('-')
$(this).append(''+(parseFloat(a[0])+parseFloat(a[1]))+'	')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,tr,td{
border:1px solid;
}</code>```

                New thing
                2017/06/04 08:00
                One ThingAnother thing
                R
                12-11

                New thing
                2017/06/04 08:00
                One ThingAnother thing
                R
                22-23

```

Body:
Hello Stackoverflowers,

I have this code:

                New thing
                2017/06/04 08:00
                One ThingAnother thing
                R
                12-11

                New thing
                2017/06/04 08:00
                One ThingAnother thing
                R
                22-23

In the result I want to use jQuery to get a sum of numbers inside last table TD and display it into new TD. Like in the following code:

            New thing
            2017/06/04 08:00
            One ThingAnother thing
            R
            12-11
            [ 23 ]

            New thing
            2017/06/04 08:00
            One ThingAnother thing
            R
            22-23
            [ 45 ]

thank you in advance.

Body:
find the last children('td:last') .

split string with split(-)

And use with parseFloat() for convert the string to number

$('table tr').each(function(){
var a =$(this).children('td:last').text().trim().split('-')
$(this).append('<td>'+(parseFloat(a[0])+parseFloat(a[1]))+'</td>')
})

table,tr,td{
border:1px solid;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table class="table">
        <tbody>
            <tr>
                <td><a href="#">New thing</a></td>
                <td>2017/06/04 08:00</td>
                <td><a href="#">One Thing</a><span>Another thing</span></td>
                <td class="random">R</td>
                <td><a href="#">12-11      </a></td>
            </tr>
            <tr>
                <td><a href="#">New thing</a></td>
                <td>2017/06/04 08:00</td>
                <td><a href="#">One Thing</a><span>Another thing</span></td>
                <td class="random">R</td>
                <td><a href="#">22-23</a></td>
            </tr>
        </tbody>
    </table>


问:
android retrofit post logout request giving error 406 Not Acceptable : User is not logged in. ...on postman api works fine

I am using retrofit2 to logout in App but everytime it gives error406
  : Not Acceptable : User is not logged in. . i am using retrofit custom
  header authentication . Here is my Code :

logout code

public void logout()

{
Log.v("checkTokenbefore",Constants.token);

```<code>  OkHttpClient httpClient1 = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
      @Override
      public Response intercept(Interceptor.Chain chain) throws IOException {
          Request original = chain.request();
            Log.v("checkLogin",Constants.token+Constants.username+Constants.password) ;
          // Request customization: add request headers
          Request.Builder requestBuilder = original.newBuilder()
                  .addHeader("Accept-Language","application/json").addHeader("content-type", "application/x-www-form-urlencoded")
                  .addHeader("API_KEY", "a5XSE8XCdsY6hAoCNojYBQ")

                  .addHeader("X-CSRF-Token",Constants.token)

                  ;

          Request request = requestBuilder.method(original.method(),original.body()).build();
          return chain.proceed(request);
      }
  }).build();

  Retrofit retrofit1 = new Retrofit.Builder()
          .baseUrl(Constants.API_BASE_URL)
          .client(httpClient1)

          .addConverterFactory(GsonConverterFactory.create())
          .build();

  ApiInterface restAPI1 = retrofit1.create(ApiInterface.class);

  Call<Logout> callLogout = restAPI1.userLogout(Constants.token,Constants.username,Constants.password);
  callLogout.enqueue(new Callback<Logout>() {
      @Override
      public void onResponse(Call<Logout> call, retrofit2.Response<Logout> response) {
          Log.v("responseLogout",response.code()+"code"+response.errorBody().toString()+response.message()) ;
      }

      @Override
      public void onFailure(Call<Logout> call, Throwable t) {

      }
  });
</code>```

}

While Following is the code for login which works fine :

```<code> public void loginQuestin(){

    //checkValidation ();
/*
    ApiInterface apiService =
            ApiClient.create(ApiInterface.class) ;*/
    ApiInterface restAPI = retrofit.create(ApiInterface.class);

    Call<UserAgain> call = restAPI.userLogin(mEmailAddress.getText().toString().trim(),
            mPassword.getText().toString().trim());
    call.enqueue(new Callback<UserAgain>() {
      @Override
      public void onResponse(Call<UserAgain> call, Response<UserAgain> response) {
        Log.v("check",response.code()+"login"+response.body().getToken()) ;
         //response.body().getU
          Constants.username = mEmailAddress.getText().toString().trim() ;
          Constants.password =  mPassword.getText().toString().trim() ;

          if (response.code()==200) {
            Log.v("checkAgain",response.code()+"login") ;
           Constants.token = response.body().getToken() ;
            startActivity(new Intent(LoginActivity.this, NavigationDrawerActivity.class));
          }
      }

      @Override
      public void onFailure(Call<UserAgain> call, Throwable t) {
        Log.v("check","failed");
        t.printStackTrace();
      }
    });
  }
</code>```

//API/Http client for login api call

```<code>public class ApiClient {

   public static OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder() .addHeader("Accept-Language","application/json")
                    .addHeader("content-type", "application/x-www-form-urlencoded").addHeader("API_KEY", "a5XSE8XCdsY6hAoCNojYBQ")

                    ;

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    }).build();

    public static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.API_BASE_URL)
            .client(httpClient)

            .addConverterFactory(GsonConverterFactory.create())
            .build();
   public static ApiInterface restAPI = retrofit.create(ApiInterface.class);
}
</code>```

API Interface class

```<code>@POST("token")
Call<Token> getToken();

@FormUrlEncoded
@POST("login")
Call<UserAgain> userLogin(@Field("username") String param1, @Field("password") String param2);

@FormUrlEncoded
@POST("logout")
Call<Logout> userLogout(@Field("username") String param1 , @Field("password") String param2);
</code>```

Login APi works fine give a response code of 200 OK . The major issue is encountered when working with added dynamic customn header on logout api (client xsrf token )

Reference :
  https://futurestud.io/tutorials/retrofit-add-custom-request-header
  api formats :

User Authentication/Login

Purpose: - User Login Rest URL: - /api/v1/people/login
  Method:-POST Headers:  Accept-Language: application/json API_KEY:
  a5XSE8XCdsY6hAoCNojYBQ Content-Type: application/x-www-form-urlencoded
  X-CSRF-Token:

User Logout

Purpose: - User Logout Rest URL: - /api/v1/people/logout
  Method:-POST Headers:  Accept-Language: application/json API_KEY:
  a5XSE8XCdsY6hAoCNojYBQ Content-Type: application/x-www-form-urlencoded
  X-CSRF-Token:     Parameters in body:   username:  e.g
  service@test.com password:   e.g. 123456

答:
Use Interceptors for adding dynamic Header.

```<code>httpClient.addInterceptor((Interceptor.Chain chain) -> {
            Request originalRequest = chain.request();
</code>```

set OAuth token

```<code>Request.Builder newRequest = originalRequest.newBuilder();

newRequest.header("Authorization", accessToken).method(originalRequest.method(), originalRequest.body());

originalRequest = newRequest.build();
chain.proceed(originalRequest);
</code>```

repeat request with new token

```<code>Response response = chain.proceed(originalRequest); //perform request, here original request will be executed

  if (response.code() == 401) {
            //if unauthorized
            //perform all 401 in sync blocks

      }
      return chain.proceed(newRequest.build());
});
</code>```

Body:
I am using retrofit2 to logout in App but everytime it gives error406
  : Not Acceptable : User is not logged in. . i am using retrofit custom
  header authentication . Here is my Code :

logout code

public void logout()

{
Log.v("checkTokenbefore",Constants.token);

  OkHttpClient httpClient1 = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
      @Override
      public Response intercept(Interceptor.Chain chain) throws IOException {
          Request original = chain.request();
            Log.v("checkLogin",Constants.token+Constants.username+Constants.password) ;
          // Request customization: add request headers
          Request.Builder requestBuilder = original.newBuilder()
                  .addHeader("Accept-Language","application/json").addHeader("content-type", "application/x-www-form-urlencoded")
                  .addHeader("API_KEY", "a5XSE8XCdsY6hAoCNojYBQ")

                  .addHeader("X-CSRF-Token",Constants.token)

                  ;

          Request request = requestBuilder.method(original.method(),original.body()).build();
          return chain.proceed(request);
      }
  }).build();

  Retrofit retrofit1 = new Retrofit.Builder()
          .baseUrl(Constants.API_BASE_URL)
          .client(httpClient1)

          .addConverterFactory(GsonConverterFactory.create())
          .build();

  ApiInterface restAPI1 = retrofit1.create(ApiInterface.class);

  Call<Logout> callLogout = restAPI1.userLogout(Constants.token,Constants.username,Constants.password);
  callLogout.enqueue(new Callback<Logout>() {
      @Override
      public void onResponse(Call<Logout> call, retrofit2.Response<Logout> response) {
          Log.v("responseLogout",response.code()+"code"+response.errorBody().toString()+response.message()) ;
      }

      @Override
      public void onFailure(Call<Logout> call, Throwable t) {

      }
  });

}

While Following is the code for login which works fine :

 public void loginQuestin(){

    //checkValidation ();
/*
    ApiInterface apiService =
            ApiClient.create(ApiInterface.class) ;*/
    ApiInterface restAPI = retrofit.create(ApiInterface.class);

    Call<UserAgain> call = restAPI.userLogin(mEmailAddress.getText().toString().trim(),
            mPassword.getText().toString().trim());
    call.enqueue(new Callback<UserAgain>() {
      @Override
      public void onResponse(Call<UserAgain> call, Response<UserAgain> response) {
        Log.v("check",response.code()+"login"+response.body().getToken()) ;
         //response.body().getU
          Constants.username = mEmailAddress.getText().toString().trim() ;
          Constants.password =  mPassword.getText().toString().trim() ;

          if (response.code()==200) {
            Log.v("checkAgain",response.code()+"login") ;
           Constants.token = response.body().getToken() ;
            startActivity(new Intent(LoginActivity.this, NavigationDrawerActivity.class));
          }
      }

      @Override
      public void onFailure(Call<UserAgain> call, Throwable t) {
        Log.v("check","failed");
        t.printStackTrace();
      }
    });
  }

//API/Http client for login api call

public class ApiClient {

   public static OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder() .addHeader("Accept-Language","application/json")
                    .addHeader("content-type", "application/x-www-form-urlencoded").addHeader("API_KEY", "a5XSE8XCdsY6hAoCNojYBQ")

                    ;

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    }).build();

    public static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.API_BASE_URL)
            .client(httpClient)

            .addConverterFactory(GsonConverterFactory.create())
            .build();
   public static ApiInterface restAPI = retrofit.create(ApiInterface.class);
}

API Interface class

@POST("token")
Call<Token> getToken();

@FormUrlEncoded
@POST("login")
Call<UserAgain> userLogin(@Field("username") String param1, @Field("password") String param2);

@FormUrlEncoded
@POST("logout")
Call<Logout> userLogout(@Field("username") String param1 , @Field("password") String param2);

Login APi works fine give a response code of 200 OK . The major issue is encountered when working with added dynamic customn header on logout api (client xsrf token )

Reference :
  https://futurestud.io/tutorials/retrofit-add-custom-request-header
  api formats :

User Authentication/Login

Purpose: - User Login Rest URL: - /api/v1/people/login
  Method:-POST Headers:  Accept-Language: application/json API_KEY:
  a5XSE8XCdsY6hAoCNojYBQ Content-Type: application/x-www-form-urlencoded
  X-CSRF-Token:

User Logout

Purpose: - User Logout Rest URL: - /api/v1/people/logout
  Method:-POST Headers:  Accept-Language: application/json API_KEY:
  a5XSE8XCdsY6hAoCNojYBQ Content-Type: application/x-www-form-urlencoded
  X-CSRF-Token:     Parameters in body:   username:  e.g
  service@test.com password:   e.g. 123456

Body:
Use Interceptors for adding dynamic Header.

httpClient.addInterceptor((Interceptor.Chain chain) -> {
            Request originalRequest = chain.request();

set OAuth token

Request.Builder newRequest = originalRequest.newBuilder();

newRequest.header("Authorization", accessToken).method(originalRequest.method(), originalRequest.body());

originalRequest = newRequest.build();
chain.proceed(originalRequest);

repeat request with new token

Response response = chain.proceed(originalRequest); //perform request, here original request will be executed

  if (response.code() == 401) {
            //if unauthorized
            //perform all 401 in sync blocks

      }
      return chain.proceed(newRequest.build());
});


问:
PHP -- usort is modifying contents of objects in array, how do I prevent this?
I am using usort with a user comparison function to sort an array of objects.  After running usort on an array of these objects, I've found that some of the values of the objects have changed along with their position in the array.  What am I missing?  I don't believe there are any side effects in my user comparison function.  Does usort deconstruct/reconstruct objects some how?

Here is the the user comparison function I'm using:

```<code>private function SortArrayOfSegments($segments){
    foreach($segments as $segment){
        echo '```';
        var_dump($segment);
    }
    usort($segments, "AirObject::CompareSegments");
    foreach($segments as $segment){
        var_dump($segment);
        echo '```';
     }
    return $segments;
}

public static function CompareSegments($a, $b){
    $interval = date_diff(date_create($a->StartDateTime->GetString()),
                date_create($b->StartDateTime->GetString()));
    if($interval->invert == 1){
        return 1;
    }else if($interval->y == 0 && $interval->m == 0  && $interval->d == 0
    && $interval->i == 0 && $interval->s == 0 && $interval->h == 0){
        return 0;
    }else if($interval->invert == 0){
        return -1;
    }
}
</code>```

The objects I'm using look like this :

```<code>object(AirSegment)#14 (12) {
      ["StartDateTime"]=>
      object(VDateTime)#27 (4) {
        ["date"]=>
        string(10) "2010-12-07"
        ["time"]=>
        string(8) "09:23:21"
        ["timezone"]=>
        string(0) ""
        ["utc_offset"]=>
        string(0) ""
      }
      ["EndDateTime"]=>
      object(VDateTime)#23 (4) {
        ["date"]=>
        string(10) "2010-12-07"
        ["time"]=>
        string(8) "13:23:21"
        ["timezone"]=>
        string(0) ""
        ["utc_offset"]=>
        string(0) ""
      }
      ["start_airport_code"]=>
      string(3) "SFO"
      ["start_city_name"]=>
      string(13) "San Francisco"
      ["end_airport_code"]=>
      string(3) "STL"
      ["end_city_name"]=>
      string(8) "St Louis"
      ["operating_airline"]=>
      string(15) "United Airlines"
      ["operating_flight_number"]=>
      string(3) "335"
      ["duration"]=>
      float(NAN)
      ["required_properties":protected]=>
      array(9) {
        ["StartDateTime"]=>
        bool(false)
        ["EndDateTime"]=>
        bool(false)
        ["start_airport_code"]=>
        bool(false)
        ["end_airport_code"]=>
        bool(false)
        ["operating_airline"]=>
        bool(false)
        ["operating_flight_number"]=>
        bool(false)
        ["start_city_name"]=>
        bool(false)
        ["end_city_name"]=>
        bool(false)
        ["service_class"]=>
        bool(true)
      }
      ["service_class"]=>
      string(5) "Coach"
      ["trip_id"]=>
      string(4) "1621"
    }
</code>```

The property that is changing is the duration property.  Before usort is run, every object has a valid float value.  After usort, two of them are NaN.

RESOLUTION:

date_diff has side effects -- at least in my build of PHP.  Removing it fixed the issues entirely.

```<code>public static function CompareSegments($a, $b){
    $adate = new DateTime($a->StartDateTime->GetString());
    $bdate = new DateTime($b->StartDateTime->GetString());
    $lessThan = $adate < $bdate;
    $equal = $adate == $bdate;
    $greaterThan = $adate > $bdate;

    if($lessThan){
        return -1;
    }else if($equal){
        return 0;
    }else{
        return 1;
    }
}
</code>```

答: What do the objects look like before you apply the usort method, or indeed any method? Without knowing the original state of the objects it is difficult to be conclusive, but NaN is the erroneous result produced by the function passed to usort.</p>

Body:
I am using usort with a user comparison function to sort an array of objects.  After running usort on an array of these objects, I've found that some of the values of the objects have changed along with their position in the array.  What am I missing?  I don't believe there are any side effects in my user comparison function.  Does usort deconstruct/reconstruct objects some how?

Here is the the user comparison function I'm using:

private function SortArrayOfSegments($segments){
    foreach($segments as $segment){
        echo '
';
        var_dump($segment);
    }
    usort($segments, "AirObject::CompareSegments");
    foreach($segments as $segment){
        var_dump($segment);
        echo '
';
     }
    return $segments;
}

public static function CompareSegments($a, $b){
    $interval = date_diff(date_create($a->StartDateTime->GetString()),
                date_create($b->StartDateTime->GetString()));
    if($interval->invert == 1){
        return 1;
    }else if($interval->y == 0 && $interval->m == 0  && $interval->d == 0
    && $interval->i == 0 && $interval->s == 0 && $interval->h == 0){
        return 0;
    }else if($interval->invert == 0){
        return -1;
    }
}

The objects I'm using look like this :

object(AirSegment)#14 (12) {
      ["StartDateTime"]=>
      object(VDateTime)#27 (4) {
        ["date"]=>
        string(10) "2010-12-07"
        ["time"]=>
        string(8) "09:23:21"
        ["timezone"]=>
        string(0) ""
        ["utc_offset"]=>
        string(0) ""
      }
      ["EndDateTime"]=>
      object(VDateTime)#23 (4) {
        ["date"]=>
        string(10) "2010-12-07"
        ["time"]=>
        string(8) "13:23:21"
        ["timezone"]=>
        string(0) ""
        ["utc_offset"]=>
        string(0) ""
      }
      ["start_airport_code"]=>
      string(3) "SFO"
      ["start_city_name"]=>
      string(13) "San Francisco"
      ["end_airport_code"]=>
      string(3) "STL"
      ["end_city_name"]=>
      string(8) "St Louis"
      ["operating_airline"]=>
      string(15) "United Airlines"
      ["operating_flight_number"]=>
      string(3) "335"
      ["duration"]=>
      float(NAN)
      ["required_properties":protected]=>
      array(9) {
        ["StartDateTime"]=>
        bool(false)
        ["EndDateTime"]=>
        bool(false)
        ["start_airport_code"]=>
        bool(false)
        ["end_airport_code"]=>
        bool(false)
        ["operating_airline"]=>
        bool(false)
        ["operating_flight_number"]=>
        bool(false)
        ["start_city_name"]=>
        bool(false)
        ["end_city_name"]=>
        bool(false)
        ["service_class"]=>
        bool(true)
      }
      ["service_class"]=>
      string(5) "Coach"
      ["trip_id"]=>
      string(4) "1621"
    }

The property that is changing is the duration property.  Before usort is run, every object has a valid float value.  After usort, two of them are NaN.

RESOLUTION:

date_diff has side effects -- at least in my build of PHP.  Removing it fixed the issues entirely.

public static function CompareSegments($a, $b){
    $adate = new DateTime($a->StartDateTime->GetString());
    $bdate = new DateTime($b->StartDateTime->GetString());
    $lessThan = $adate < $bdate;
    $equal = $adate == $bdate;
    $greaterThan = $adate > $bdate;

    if($lessThan){
        return -1;
    }else if($equal){
        return 0;
    }else{
        return 1;
    }
}


问:
Android open new activity when click link from textview(autolink)
I have a view display textview and enable autolink.

```<code><TextView
   android:id="@+id/txt_contents"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="30dp"
   android:textColor="@color/txt_code_itemlist"
   android:autoLink="web"
   android:textSize="22sp" />
</code>```

Now, when I click link from textview it's will open browser. But I want to find way to open new activity when I click same link.

答:
that work perfect :

```<code>    tvoublie.setPaintFlags(tvoublie.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
            Linkify.addLinks(tvoublie, Linkify.ALL);
            tvoublie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i("LoginActivity", "Sign Up Activity activated.");
                    // this is where you should start the new Activity
                   Intent intent = new Intent(CurrentActivity.this,YourNewActivity.class);
                   startActivity(intent);

                }
            });
</code>```

this to open o browser with url :

```<code>register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(Uri.parse("https://www.google.com"));
                startActivity(intent);
            }
        });
</code>```

Body:
I have a view display textview and enable autolink.

<TextView
   android:id="@+id/txt_contents"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="30dp"
   android:textColor="@color/txt_code_itemlist"
   android:autoLink="web"
   android:textSize="22sp" />

Now, when I click link from textview it's will open browser. But I want to find way to open new activity when I click same link.

Body:
that work perfect :

    tvoublie.setPaintFlags(tvoublie.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
            Linkify.addLinks(tvoublie, Linkify.ALL);
            tvoublie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i("LoginActivity", "Sign Up Activity activated.");
                    // this is where you should start the new Activity
                   Intent intent = new Intent(CurrentActivity.this,YourNewActivity.class);
                   startActivity(intent);

                }
            });

this to open o browser with url :

register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(Uri.parse("https://www.google.com"));
                startActivity(intent);
            }
        });


问:
NameError: name 'urlpatterns' is not defined
I'm trying to show an image using "ImageField"

```<code>from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

settings.py:

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    )
MEDIA_ROOT = ''
MEDIA_URL = "/media/"
</code>```

答:
try this:</p>

```<code>from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
</code>```

Body:
I'm trying to show an image using "ImageField"

from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py:

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    )
MEDIA_ROOT = ''
MEDIA_URL = "/media/"

Body:
try this:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()


问:
Why Angular Material is responive and AngualJS Material isn't?
I'm trying to choose a framework for an application of mine and I stumbled across
Angular Material and AngularJS Material I understand that both are from Google (correct me if I'm wrong) but basically are both doing more or less the same, rendering components in a HTML page, what I don't get (and google around is not very efficent due to confusion on similar name) why Angular material is not responsive and AngularJS Material is? Wich one I should choose in order to make my app responsive? Or..how would I get an Angular Material app respnsive?</p>

答:
Just because the website documenting the library is not responsive it does not mean the library itself is not responsive either. In fact, both are responsive, but obviously whether your app is going to be responsive or not, that depends mainly on you, not just the library.

As to which one you should choose, that should be your main question. AngularJS Material is for AngularJS (v1.x) and Angular Material is for Angular (v2+).

I agree with you that the naming is confusing, but you should not concern yourself with that. Pick a framework first, not the library. Picking a library first would be like choosing a paint, going home and wondering which rooms you can paint with that color. It might be the case that the paint is very universal and can by applied to all your walls in all your rooms. But it might be the case that the color is very specific and it would not look good in either of your rooms.


问:
How to schedule PHP script on Job Finish (from CLI)
I am processing a big .gz file using PHP (transfering data from gz to mysql)
it takes about 10 minutes per .gz file.
I have a lot of .gz file to be processed.

After PHP is finished with one file I have to manually change the PHP script to select another .gz file and then run the script again manually.

I want it to be automatically run the next job to process the next file.
the gz file is named as 1, 2 ,3, 4, 5 ...
I can simply make a loop to be something like this ( process file 1 - 5):

```<code>for ($i = 1 ; $i >= 5; $i++)
{
    $file = gzfile($i.'.gz')
    ...gz content processing...
}
</code>```

However, since the gz file is really big, I cannot do that, because if I use this loop, PHP will run multiple big gz files as single script job. (takes a lot of memory)

What I want to do is after PHP is finished with one job I want a new job to process the next file.

maybe its going to be something like this:

```<code>    $file = gzfile($_GET['filename'].'.gz')
    ...gz content processing...
</code>```

Thank You

答:
You should call the PHP script with argument, from a shell script. Here's the doc how to use command-line parameters in PHP http://php.net/manual/en/features.commandline.php

Or, I can't try it now, but you may give a chance to unset($file) after processing the gzip.

```<code>for ($i = 1 ; $i >= 5; $i++)
{
    $file = gzfile($i.'.gz')
    ...gz content processing...
    unset($file);
}
</code>```

Body:
I am processing a big .gz file using PHP (transfering data from gz to mysql)
it takes about 10 minutes per .gz file.
I have a lot of .gz file to be processed.

After PHP is finished with one file I have to manually change the PHP script to select another .gz file and then run the script again manually.

I want it to be automatically run the next job to process the next file.
the gz file is named as 1, 2 ,3, 4, 5 ...
I can simply make a loop to be something like this ( process file 1 - 5):

for ($i = 1 ; $i >= 5; $i++)
{
    $file = gzfile($i.'.gz')
    ...gz content processing...
}

However, since the gz file is really big, I cannot do that, because if I use this loop, PHP will run multiple big gz files as single script job. (takes a lot of memory)

What I want to do is after PHP is finished with one job I want a new job to process the next file.

maybe its going to be something like this:

    $file = gzfile($_GET['filename'].'.gz')
    ...gz content processing...

Thank You

Body:
You should call the PHP script with argument, from a shell script. Here's the doc how to use command-line parameters in PHP http://php.net/manual/en/features.commandline.php

Or, I can't try it now, but you may give a chance to unset($file) after processing the gzip.

for ($i = 1 ; $i >= 5; $i++)
{
    $file = gzfile($i.'.gz')
    ...gz content processing...
    unset($file);
}


问:
Django Apply Model Foreign Key Default Value to Existing Record
Thank you very much for taking your time.

Previously, I posted this question, How to Get Unread Posts for Users.

The problem was: I cannot filter out which article one user has not read while this article has already been read by another user.

I figured out why I cannot do that---- because I have data that I wrote into the database without using Django although I set the reading default for each post to False---- there is simply no record.

Then, I manually set one article to unread to a user in the Admin, everything works, because now in the database there is one record stating that this certain article has not been read by this user.

The problem now is:

How do I set "unread" for every existing article that I have in the database for all existing users?

And how can articles stay unread for every new user unless the new user actually read it?

For your convenience, I copied the codes to here.

My model:

```<code>class Posts(models.Model):
 title = models.CharField(max_length=255)
 content_url = models.URLField(unique=True)
 content = models.CharField(max_length=255)
 post_date = models.DateField(default="2999-12-12")
</code>```

Another

```<code>class readstatus(models.Model):
 reading_status = models.BooleanField(default=False)
 user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
 article = models.ForeignKey(Posts, on_delete=models.CASCADE)
 created = models.DateTimeField(auto_now_add=True)
</code>```

My View:

```<code>class DailyReading(ListView):

 template_name = 'reading.html'
 context_object_name = "data"
 paginate_by = 20
 def get_queryset(self):

    if self.kwargs['status'] == "read":
        queryset = piaoyou.objects.filter(readstatus__reading_status=True,readstatus__user=self.request.user)
        return queryset
    else:
        queryset= Posts.objects.filter(readstatus__reading_status=False,readstatus__user=self.request.user)
        return queryset
</code>```

My Template:

```<code>    {% for info in data %}
                <quoteblock>
                    <ul>
                        <li><a href="{{ info.get_absolute_url }}">{{ info.title }}
                            <footnote></footnote>
                        </a>{{ info.post_date }}</li>

                        <footnote>{{ info.get_abstract_content }}</footnote>
                    </ul>
                </quoteblock>

       {% endfor %}
</code>```

答:
OMG, I just figured out how to do this.

For an article that has been read by the requesting user, we can just pass queryset = Post.objects.filter(readstatus__reading_status=True, readstatus__user=self.request.user)

For an article that has not been read by the requesting user yet, we can pass Posts.objects.all() into the template.

Then in the template:

We need {% if instance.readstatus_set.all %} this line to make things work. Assume there is no data about whether this requesting user has read the article, the instance should not have readstatus_set.all, which means the user has not read the article yet. Once checking this if condition, we can carry out to check other conditions in the loop.

Body:
Thank you very much for taking your time.

Previously, I posted this question, How to Get Unread Posts for Users.

The problem was: I cannot filter out which article one user has not read while this article has already been read by another user.

I figured out why I cannot do that---- because I have data that I wrote into the database without using Django although I set the reading default for each post to False---- there is simply no record.

Then, I manually set one article to unread to a user in the Admin, everything works, because now in the database there is one record stating that this certain article has not been read by this user.

The problem now is:

How do I set "unread" for every existing article that I have in the database for all existing users?

And how can articles stay unread for every new user unless the new user actually read it?

For your convenience, I copied the codes to here.

My model:

class Posts(models.Model):
 title = models.CharField(max_length=255)
 content_url = models.URLField(unique=True)
 content = models.CharField(max_length=255)
 post_date = models.DateField(default="2999-12-12")

Another

class readstatus(models.Model):
 reading_status = models.BooleanField(default=False)
 user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
 article = models.ForeignKey(Posts, on_delete=models.CASCADE)
 created = models.DateTimeField(auto_now_add=True)

My View:

class DailyReading(ListView):

 template_name = 'reading.html'
 context_object_name = "data"
 paginate_by = 20
 def get_queryset(self):

    if self.kwargs['status'] == "read":
        queryset = piaoyou.objects.filter(readstatus__reading_status=True,readstatus__user=self.request.user)
        return queryset
    else:
        queryset= Posts.objects.filter(readstatus__reading_status=False,readstatus__user=self.request.user)
        return queryset

My Template:

    {% for info in data %}
                <quoteblock>

{{ info.title }}
                            <footnote></footnote>
                        {{ info.post_date }}

                        <footnote>{{ info.get_abstract_content }}</footnote>

                </quoteblock>

       {% endfor %}


问:
Add multiple documents to envelope using c# sdk using Docusign API
I have a template in Docusign that I need to send to joe@acme.com

However Joe is responsible for managing 10 clients and instead of me sending Joe 10 separate envelopes for him to sign I want to send Joe 1 envelope with 10 documents and Joe needs to sign all 10 document in the envelope. The documents are identical except for the different data filled in the text field of the template

I am using the C# SDK provided by Docusign and I can send one document in an envelope using EnvelopeDefinition class and TemplateRole class but am lost as to how to create 10 documents in an envelope

The following recipe does it but it is in python and uses the REST API with which I am not sure how to translate to the C# SDK equivalent
https://www.docusign.com/developer-center/recipes/send-multiple-docs

答:
There is the property Documents in the class EnvelopeDefinition, where you can add multiply documents.

I use the REST API Explorer from DocuSign when I want to check how to implement a feature.

```<code>            enDef = new EnvelopeDefinition();
            doc = new Document();

            doc.DocumentBase64 = System.Convert.ToBase64String(System.IO.File.ReadAllBytes(filename));
            doc.Name = DocName;
            doc.DocumentId = "1"; // increment this

            enDef.Documents = new List<Document>();
            enDef.Documents.Add(doc);
</code>```

Added

For multiply template roles also exists a property called TemplateRoles in the EnvelopeDefinition. There you can add more than one.

```<code>            tempRole = new TemplateRole();
            tempRole.Name = Rolename;

            enDef.TemplateRoles = new List<TemplateRole>();
            enDef.TemplateRoles.Add(tempRole);`
</code>```

Body:
There is the property Documents in the class EnvelopeDefinition, where you can add multiply documents.

I use the REST API Explorer from DocuSign when I want to check how to implement a feature.

            enDef = new EnvelopeDefinition();
            doc = new Document();

            doc.DocumentBase64 = System.Convert.ToBase64String(System.IO.File.ReadAllBytes(filename));
            doc.Name = DocName;
            doc.DocumentId = "1"; // increment this

            enDef.Documents = new List<Document>();
            enDef.Documents.Add(doc);

Added

For multiply template roles also exists a property called TemplateRoles in the EnvelopeDefinition. There you can add more than one.

            tempRole = new TemplateRole();
            tempRole.Name = Rolename;

            enDef.TemplateRoles = new List<TemplateRole>();
            enDef.TemplateRoles.Add(tempRole);`


问:
Img won't centre align - email
Having an issue getting an image at the top of an email to center align. I believe it is to do with a piece of code that makes the image vanish when the browser is greater than 520px. Though I need this code for the rest of email. How can I create an exception so this particular image remains central?

```<code>.mobile {
    display: none !important;
    font-size 0 !important;
    max-height: 0 !important;
    line-height: 0 !important;
    margin: 0 !important;
    mso-hide: all !important;
    overflow: hidden !important;
}
.mobile img {
    max-height: 0 !important;
    width: 0 !important;
}

@media only screen and (max-width: 520px) {
    *[class=hide] {
        display: none !important;
    }
    [class=mobile] {
        display: block !important;
        max-height: none !important;
        margin: 0px !important;
        overflow: visible !important;
    }
    *[class=mobile] img {
        display: block !important;
        width: 100% !important;
        height: auto !important;
        max-height: none !important;
        max-width: 100% !important;
    }
}
</code>```

.

```<code><td class="mobile" style="font-size: 0; mso-hide: all; width:120px; height:24px;"><div align="center"><a href="~PROBE(201)~"><img border="0" height="24" width="120" src="images/MH-logo.png" /></a></div></td>
</code>```

答:
the "align" is deprecated in HTML5 and might not be supported in the browser/email.

Try this in your div

EDIT:

Sorry, I should have looked  closer.

Most likely the reason is the lack of complete HTML for the TD tag.

```<code><table style="width:100%"><tr>
<td class="mobile" style="font-size: 0; mso-hide: all; width:120px; height:24px;"><div align="center"><a href="~PROBE(201)~"><img border="0" height="24" width="120" src="images/MH-logo.png" /></a></div></td>
</tr></table>
</code>```

ALSO

I commented out everything that does not make sense

```<code><style>
.mobile {
/*  display: none !important;   Do Display, No image */
    font-size 0 !important;
/*  max-height: 0 !important;  */
/*  line-height: 0 !important; */
    margin: 0 !important;
/*  mso-hide: all !important;  not CSS , this is Microsoft Office code */
    overflow: hidden !important;
}

.mobile img {
 /*   max-height: 0 !important;   no height, No image */
 /*   width: 0 !important;   no width, no image   */
}

@media only screen and (max-width: 520px) {
    *[class=hide] {
        display: none !important;
    }
    [class=mobile] {
/*      display: block !important; */
/*      max-height: none !important; */
        margin: 0px !important;
        overflow: visible !important;
    }
 *[class=mobile] img {
       display: block !important;
/*      width: 100% !important; */
/*      height: auto !important; */
/*      max-height: none !important;  */
        max-width: 100% !important;
    }
}
</style>

<table style="width:100%"><tr>
<td class="mobile" style="font-size: 0; XXXXmso-hide: all; width:120px; height:24px;"><div align="center"><a href="~PROBE(201)~"><img border="0" height="24" width="120" src="images/MH-logo.png" /></a></div></td>
</tr>
</table>
</code>```

Title: Img won't centre align - email

Body:
Having an issue getting an image at the top of an email to center align. I believe it is to do with a piece of code that makes the image vanish when the browser is greater than 520px. Though I need this code for the rest of email. How can I create an exception so this particular image remains central?

.mobile {
    display: none !important;
    font-size 0 !important;
    max-height: 0 !important;
    line-height: 0 !important;
    margin: 0 !important;
    mso-hide: all !important;
    overflow: hidden !important;
}
.mobile img {
    max-height: 0 !important;
    width: 0 !important;
}

@media only screen and (max-width: 520px) {
    *[class=hide] {
        display: none !important;
    }
    [class=mobile] {
        display: block !important;
        max-height: none !important;
        margin: 0px !important;
        overflow: visible !important;
    }
    *[class=mobile] img {
        display: block !important;
        width: 100% !important;
        height: auto !important;
        max-height: none !important;
        max-width: 100% !important;
    }
}

.

Body:
the "align" is deprecated in HTML5 and might not be supported in the browser/email.

Try this in your div

<div style="text-align:center">

EDIT:

Sorry, I should have looked  closer.

Most likely the reason is the lack of complete HTML for the TD tag.

<table style="width:100%"><tr>
<td class="mobile" style="font-size: 0; mso-hide: all; width:120px; height:24px;"><div align="center"><a href="~PROBE(201)~"><img border="0" height="24" width="120" src="images/MH-logo.png" /></a></div></td>
</tr></table>

ALSO

I commented out everything that does not make sense

<style>
.mobile {
/*  display: none !important;   Do Display, No image */
    font-size 0 !important;
/*  max-height: 0 !important;  */
/*  line-height: 0 !important; */
    margin: 0 !important;
/*  mso-hide: all !important;  not CSS , this is Microsoft Office code */
    overflow: hidden !important;
}

.mobile img {
 /*   max-height: 0 !important;   no height, No image */
 /*   width: 0 !important;   no width, no image   */
}

@media only screen and (max-width: 520px) {
    *[class=hide] {
        display: none !important;
    }
    [class=mobile] {
/*      display: block !important; */
/*      max-height: none !important; */
        margin: 0px !important;
        overflow: visible !important;
    }
 *[class=mobile] img {
       display: block !important;
/*      width: 100% !important; */
/*      height: auto !important; */
/*      max-height: none !important;  */
        max-width: 100% !important;
    }
}
</style>

<table style="width:100%"><tr>
<td class="mobile" style="font-size: 0; XXXXmso-hide: all; width:120px; height:24px;"><div align="center"><a href="~PROBE(201)~"><img border="0" height="24" width="120" src="images/MH-logo.png" /></a></div></td>
</tr>
</table>


问:
Wkhtmltopdf conversion
My html to pdf conversion using wkhtmlpdf working fine without the

答:
The way I handle this is as follows--

```<code><?php
// create some HTML content
    $html = '<!DOCTYPE html><html><head>
    <style>
        body {
            margin:     0;
            padding:    0;
        }
        ...
    </style></head><body>
    <!-- Your body content -->
    </body></html>';

$options = array(
                "no-outline",
                "binary"                    => "/usr/local/bin/wkhtmltopdf",
                "margin-top"                => ".25in",
                "margin-right"              => ".25in",
                "margin-bottom"             => ".55in",
                "margin-left"               => ".25in",
                "zoom"                      => 1
            );

$footer = '<!DOCTYPE html><html><head></head><body>...</body></html>';

$page_options = array('footer-html' => $footer);
$pdf->addPage($html, $page_options);

$pdf->saveAs('MY_PDF_NAME.pdf');
</code>```

Hope this helps!

Best,

-Rush

Title: Wkhtmltopdf conversion

Body:
The way I handle this is as follows--

<?php
// create some HTML content
    $html = '<!DOCTYPE html><html><head>
    <style>
        body {
            margin:     0;
            padding:    0;
        }
        ...
    </style></head><body>
    <!-- Your body content -->
    </body></html>';

$options = array(
                "no-outline",
                "binary"                    => "/usr/local/bin/wkhtmltopdf",
                "margin-top"                => ".25in",
                "margin-right"              => ".25in",
                "margin-bottom"             => ".55in",
                "margin-left"               => ".25in",
                "zoom"                      => 1
            );

$footer = '<!DOCTYPE html><html><head></head><body>...</body></html>';

$page_options = array('footer-html' => $footer);
$pdf->addPage($html, $page_options);

$pdf->saveAs('MY_PDF_NAME.pdf');

Hope this helps!

Best,

-Rush


问:
Make opied values from not visible list visible [Sharepoint 2013]
I have a list A with various columns. One of them is a lookup from another list B.

List A:

```
Name | Option copied | Option lookup
```

The read permissions for list B are on item level. Reason is that for the 'new entry' form of list A, only options 1-3 should be selectable. (However, there are other options 4-6 to be set only by a small group of people.)

List B:

```
Option | Read Permission
-------|----------------
1      | all
2      | all
3      | all
4      | some
5      | some
6      | some
```

Now I want to show all entries of list A. Not only those with option 1-3 but also with option 4-6.

List A:

```
Name | Option copied | Option lookup from B
-----|---------------|---------------------
A    | 1             | 1
B    | 2             | 2
C    | 5             | 5
```

Therefore, I created a workflow to copy the lookup value to another column in list A (works fine).

Problem is: Only entries with options 1-3 are shown.

List A:

```
Name | Option copied | Option lookup from B
-----|---------------|---------------------
A    | 1             | 1
B    | 2             | 2
```

So the question is:

How can I still have the read permissions on list B, but show all entries (including the copied lookup from list B) in list A?

答:
Seems to be not possible, due to permissions inheritance or so.

I gave up and implemented another solution. :-(

Why are you down-voting the question?

Body:
I have a list A with various columns. One of them is a lookup from another list B.

List A:

Name | Option copied | Option lookup

The read permissions for list B are on item level. Reason is that for the 'new entry' form of list A, only options 1-3 should be selectable. (However, there are other options 4-6 to be set only by a small group of people.)

List B:

Option | Read Permission
-------|----------------
1      | all
2      | all
3      | all
4      | some
5      | some
6      | some

Now I want to show all entries of list A. Not only those with option 1-3 but also with option 4-6.

List A:

Name | Option copied | Option lookup from B
-----|---------------|---------------------
A    | 1             | 1
B    | 2             | 2
C    | 5             | 5

Therefore, I created a workflow to copy the lookup value to another column in list A (works fine).

Problem is: Only entries with options 1-3 are shown.

List A:

Name | Option copied | Option lookup from B
-----|---------------|---------------------
A    | 1             | 1
B    | 2             | 2

So the question is:

How can I still have the read permissions on list B, but show all entries (including the copied lookup from list B) in list A?


问:
Specific topics on Tensorflow for CNN
I have a mini project for my new course in Tensorflow for this semester with random topics. Since I have some background on Convolution Neuron Network, I intend to use it for my project. My computer can only run CPU version of TensorFlow.

However, as a new bee, I realize that there are a lot of topics such that MNIST, CIFAR-10, etc, thus I don't know which suitable topic I should pick out from them. I only have two weeks left. It would be great if the topic is not too complicated but too not easy for study because it matchs my intermediate level.

In your experience, could you give me some advice about the specific topic I should do for my project?

Moreover, it would be better if in this topic I can provide my own data to test my training, because my professor said that it is a plus point to get A grade in my project.

Thanks in advance,

答:
I think that to answer this question you need to properly evaluate the marking criteria for your project. However, I can give you a brief overview of what you've just mentioned.

MNIST: MNIST is a Optical Character Recognition task for individual numbers 0-9 in images size 28px square. This is considered the "Hello World" of CNNs. It's pretty basic and might be too simplistic for your requirements. Hard to gauge without more information. Nonetheless, this will run pretty quickly with CPU Tensorflow and the online tutorial is pretty good.

CIFAR-10: CIFAR is a much bigger dataset of objects and vehicles. The image sizes are 32px square so individual image processing isn't too bad. But the dataset is very large and your CPU might struggle with it. It takes a long time to train. You could try training on a reduced dataset but I don't know how that would go. Again, depends on your course requirements.

Flowers-Poets: There is the Tensorflow for Poets re-training example which might not be suitable for your course, you could use the flowers dataset to build your own model.

Build-your-own-model: You could use tf.Layers to build your own network and experiment with it. tf.Layers is pretty easy to use. Alternatively you could look at the new Estimators API that will automate a lot of the training processes for you. There are a number of tutorials (of varying quality) on the Tensorflow website.

I hope that helps give you a run-down of what's out there. Other datasets to look at are PASCAL VOC and imageNet (however they are huge!). Models to look at experimenting with may include VGG-16 and AlexNet.

Title: Specific topics on Tensorflow for CNN


问:
Run tIme 1004 error in VBA for dynamic formula pasting
Want to place the given formula in 5 cells

```<code>'////j and p have been declared before as Double
For j = 5 To 9
p=j*4

Worksheets("Sheet1").Activate
Sheets("Sheet1").Cells(j, 5 + (3 * n) + 1 ).Select
ActiveCell.FormulaR1C1 = "=IFERROR(IF(ROW(RC[p])<255,""DATA N/A"",INDIRECT(ADDRESS(ROW(RC[p])-250,COLUMN(RC[p]),,,))/RC[p]-1),""DATA N/A"")"

Next j
</code>```

There is a Run Time 1004 error in the ActiveCell.... line . I am unable to debug the error. Someone please help.

答:
You don't actually want the string 'p' to appear in your formula. I've no idea if your formula is valid btw.</p>

```<code>Sub x()

Dim j As Long, p As Long, n As Long

For j = 5 To 9
    p = j * 4
    Worksheets("Sheet1").Cells(j, 5 + (3 * n) + 1).FormulaR1C1 = "=IFERROR(IF(ROW(RC[" & p & "])<255,""DATA N/A"",INDIRECT(ADDRESS(ROW(RC[" & p & "])-250,COLUMN(RC[" & p & "]),,,))/RC[" & p & "]-1),""DATA N/A"")"
Next j

End Sub
</code>```

Body:
Want to place the given formula in 5 cells

'////j and p have been declared before as Double
For j = 5 To 9
p=j*4

Worksheets("Sheet1").Activate
Sheets("Sheet1").Cells(j, 5 + (3 * n) + 1 ).Select
ActiveCell.FormulaR1C1 = "=IFERROR(IF(ROW(RC[p])<255,""DATA N/A"",INDIRECT(ADDRESS(ROW(RC[p])-250,COLUMN(RC[p]),,,))/RC[p]-1),""DATA N/A"")"

Next j

There is a Run Time 1004 error in the ActiveCell.... line . I am unable to debug the error. Someone please help.

Body:
You don't actually want the string 'p' to appear in your formula. I've no idea if your formula is valid btw.

Sub x()

Dim j As Long, p As Long, n As Long

For j = 5 To 9
    p = j * 4
    Worksheets("Sheet1").Cells(j, 5 + (3 * n) + 1).FormulaR1C1 = "=IFERROR(IF(ROW(RC[" & p & "])<255,""DATA N/A"",INDIRECT(ADDRESS(ROW(RC[" & p & "])-250,COLUMN(RC[" & p & "]),,,))/RC[" & p & "]-1),""DATA N/A"")"
Next j

End Sub


问:
PhpStorm - cURL is not working
I am using PhpStorm's built-in PHP server for testing my website. I need cURL support. In my php.ini I have uncommented extension=php_curl.dll, and I have installed cURL onto my computer (it works from the command line). I have also restarted PhpStorm, and still, it says that any of the curl functions (curl_init, curl_version, etc.) are undefined.

After some research I have ended up running phpinfo(). cURL is not shown on the list of extensions.

Under the interpreter configuration (Settings > Languages > PHP > CLI Interpreter > ...) I even clicked the "open php.ini in the editor" button, to make sure they were the same. When it opened php.ini in the editor (PhpStorm) the line was uncommented too, so PhpStorm is referencing the correct file.

Why isn't cURL working on PhpStorm?

答:
I have also restarted PhpStorm, and still, it says that any of the curl functions (curl_init, curl_version, etc.) are undefined.

PhpStorm should be able to recognize those functions despite the curl.dll availability in php.ini file. Could you please attach a screenshot illustrating the issue in IDE?

I have ended up running phpinfo(). cURL is not shown on the list of extensions.

Did you restart Web Server after uncommenting the line in php.ini?

Could you please also share a link you're using to access phpinfo (e.g. localhost:63349/index.php)?

Title: PhpStorm - cURL is not working


问:
Send a mail to Admin with a BO link to specific customer in Prestashop 1.6
In Prestashop 1.6, from a FrontController, I have to send a mail to the administrator of the Shop.

This part works well but I got problems to include a link to the administration page of a specific customer.

The only thing I miss is the name of the administration directory. I would be able to parse and concatenate the PS_ADMIN_DIR constant but it is not available from the FrontController.

I'm kinda stuck here.

Here is the code :

```<code>$admin_customer_link =
    _PS_BASE_URL_
    .__PS_BASE_URI__
    /* Missing the Administration directory name here */
    .$this->context->link->getAdminLink('AdminCustomers', false)
    ."&id_customer=".(int)$customer->id."&viewcustomer";
</code>```

The output I got :

```<code>http://127.0.0.1:8080/prestashop/index.php?controller=AdminCustomers&id_customer=2&viewcustomer
</code>```

The output I need :

```<code>http://127.0.0.1:8080/prestashop/administration/index.php?controller=AdminCustomers&id_customer=2&viewcustomer
</code>```

Any help will be appreciated.

答:
There is no (standard) way to know the administration folder from a front controller, otherwise all the security will flushed down the toilet :).

What you can do is to retrieve the administration folder from the module 'configuration' or when you install it, and save it somewhere, at the moment I suggest into the database but maybe there is a more safely mode.

Something like:

```<code>public function install()
{
    // your stuff
    $current_dir = $_SERVER['PHP_SELF']; // this give you the current dir (administration folder included)
    $administration_folder = /* Clean your string with a string replace or preg */
    Configuration::updateValue('PS_MYMOD_ADMIN_DIR', $administration_folder);
    return true;
}
</code>```

Then in your front controller retrieve it by:

```<code>$adminfolder = Configuration::get('PS_MYMOD_ADMIN_DIR');
</code>```

However I hope you know that you're creating a security breach through e-mail...

Hope it helps

Body:
In Prestashop 1.6, from a FrontController, I have to send a mail to the administrator of the Shop.

This part works well but I got problems to include a link to the administration page of a specific customer.

The only thing I miss is the name of the administration directory. I would be able to parse and concatenate the PS_ADMIN_DIR constant but it is not available from the FrontController.

I'm kinda stuck here.

Here is the code :

$admin_customer_link =
    _PS_BASE_URL_
    .__PS_BASE_URI__
    /* Missing the Administration directory name here */
    .$this->context->link->getAdminLink('AdminCustomers', false)
    ."&id_customer=".(int)$customer->id."&viewcustomer";

The output I got :

http://127.0.0.1:8080/prestashop/index.php?controller=AdminCustomers&id_customer=2&viewcustomer

The output I need :

http://127.0.0.1:8080/prestashop/administration/index.php?controller=AdminCustomers&id_customer=2&viewcustomer

Any help will be appreciated.

Body:
There is no (standard) way to know the administration folder from a front controller, otherwise all the security will flushed down the toilet :).

What you can do is to retrieve the administration folder from the module 'configuration' or when you install it, and save it somewhere, at the moment I suggest into the database but maybe there is a more safely mode.

Something like:

public function install()
{
    // your stuff
    $current_dir = $_SERVER['PHP_SELF']; // this give you the current dir (administration folder included)
    $administration_folder = /* Clean your string with a string replace or preg */
    Configuration::updateValue('PS_MYMOD_ADMIN_DIR', $administration_folder);
    return true;
}

Then in your front controller retrieve it by:

$adminfolder = Configuration::get('PS_MYMOD_ADMIN_DIR');

However I hope you know that you're creating a security breach through e-mail...

Hope it helps


问:
Passe data in bundle to the activity of the gallery
I had this code, without the bundle it works very well, but when I add the bundle in the intent, in my onActivityResult I don't found this id_q in data, I found just the path of the chosen picture.

```<code>Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putInt("id_q", q.getId());
        intent.putExtras(b);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);
</code>```

this is onActivityResult :

```<code>public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_IMAGE)
                onSelectFromGalleryResult(data);
</code>```

and in onSelectFromGalleryResult(data) I had this :

```<code>       if (data != null && data.getExtras() != null) {
            Bundle b = data.getExtras();
            int id_q = b.getInt("id_q");}
</code>```

答:
Try this.

There is no need of a Bundle here.

```<code>Intent intent = new Intent();
intent.putIntExtra("id_q", q.getId());
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);
</code>```

and in onActivityResult

```<code>int id_q = data.getIntExtra("id_q");
</code>```

Body:
I had this code, without the bundle it works very well, but when I add the bundle in the intent, in my onActivityResult I don't found this id_q in data, I found just the path of the chosen picture.

Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putInt("id_q", q.getId());
        intent.putExtras(b);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);

this is onActivityResult :

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_IMAGE)
                onSelectFromGalleryResult(data);

and in onSelectFromGalleryResult(data) I had this :

       if (data != null && data.getExtras() != null) {
            Bundle b = data.getExtras();
            int id_q = b.getInt("id_q");}

Body:
Try this.

There is no need of a Bundle here.

Intent intent = new Intent();
intent.putIntExtra("id_q", q.getId());
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);

and in onActivityResult

int id_q = data.getIntExtra("id_q");


问:
How to cat a binary file on a loop
I need to read a file and store on another file. For that I use cat, the problem is that the file to read is binary, doesnt contain EOF, so on this code:

```<code>for i in $(seq 0 100)
do
  cat < /dev/ttyO5 > $FILE # I'm reading from a serial port, yes
done
</code>```

Cat does never stop, how could I stop it so it goes on the next iteration and so on?

Thanks!

答: Put the cat in the background.  Add another loop that checks the file size every minute or so. (Whatever you think is a reasonable time.)  If the file has not grown in that time, kill the cat with kill -9 $!.

Title: How to cat a binary file on a loop

Body:
I need to read a file and store on another file. For that I use cat, the problem is that the file to read is binary, doesnt contain EOF, so on this code:

for i in $(seq 0 100)
do
  cat < /dev/ttyO5 > $FILE # I'm reading from a serial port, yes
done

Cat does never stop, how could I stop it so it goes on the next iteration and so on?

Thanks!


问:
How to avoid elements in split function to be saved in an array?
I'm trying to use split() method in javascript and the elements that are split are saved as an array which I don't want to be done.

I want  the elements to be saved as values in an object.

```<code>var string = "as1234,as5678,as6789";
var result = {}
result.values = string.split(',');
</code>```

Output that I'm getting is below :

```<code>  result{
values : ["as1234","as5678","as6789"]
}
</code>```

Output that I want is :

```<code>result{
values : "as1234","as5678","as6789"
}
</code>```

答:
Assuming, you want a string with the values padded by quote, you could split the string and stringify every element of the array and join it together to a string.

var string = "as1234,as5678,as6789",
    result = {};

result.values = string.split(',').map(a => JSON.stringify(a)).join(',');
console.log(result);```
</div>
</div>
</p>

<hr>

<p>Or if the pattern is consistent, you can use a regex to get the groups and parse string accordingly.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var string = "as1234,as5678,as6789",
    result = {};

result.values = string.replace(/([a-z0-9]+)/g,"\"$1\"")
console.log(result);</code>```

Body:
I'm trying to use split() method in javascript and the elements that are split are saved as an array which I don't want to be done.

I want  the elements to be saved as values in an object.

var string = "as1234,as5678,as6789";
var result = {}
result.values = string.split(',');

Output that I'm getting is below :

  result{
values : ["as1234","as5678","as6789"]
}

Output that I want is :

result{
values : "as1234","as5678","as6789"
}

Body:
Assuming, you want a string with the values padded by quote, you could split the string and stringify every element of the array and join it together to a string.

var string = "as1234,as5678,as6789",
    result = {};

result.values = string.split(',').map(a => JSON.stringify(a)).join(',');
console.log(result);

Or if the pattern is consistent, you can use a regex to get the groups and parse string accordingly.

var string = "as1234,as5678,as6789",
    result = {};

result.values = string.replace(/([a-z0-9]+)/g,"\"$1\"")
console.log(result);


问:
Regex Contains in the XML element
How can I use "contains" in the regex ("Contains" or "%like%")?

I have a regex to match the XML node with exact text:

```<code><([\w]+)[^>]*>sample<\/\1>
</code>```

It yields the exact Node name, but I want to apply the regex like in C# and SQL (%LIKE%).

Text:

```<code>    <Part>this is sample part</Part>
    <Remarks>this is sample remark</Remarks>
    <Notes>this is sample notes</Notes>
    <Desc>sample</Desc>
</code>```

Expected regex result should return all the above nodes, but currently it returns only the last node.

I created a sample here to test.

答:
You may use XDocument to parse XML like this:

```<code>var s = @"<?xml version=""1.0""?>
  <root>
    <Part>this is sample part</Part>
    <Remarks>this is sample remark</Remarks>
    <Notes>this is sample notes</Notes>
    <Desc>sample</Desc>
  </root>";
var document = XDocument.Parse(s);
var names = document.Descendants()
               .Elements()
               .Where(x => x.Value.Contains("sample")) // all nodes with text having sample
               .Select(a => a.Name.LocalName); // return the local names of the nodes
Console.WriteLine(string.Join("\n", names));
</code>```

It prints:

The same can be achieved with an XPath:

```<code>var names2 = document.Root.XPathSelectElements("//*[contains(text(), \"sample\")]");
var results = names2.Select(x => x.Name.LocalName));
</code>```

To fall back to regex in case the XML is not valid, use

```<code><(?:\w+:)?(\w+)[^<]*>[^<]*?sample[^<]*</(?:\w+:)?\1>
</code>```

See the regex demo. Note the (?:\w+:)? matches arbitrary namespace in the open and close tag nodes. [^<] matches any char but <, so it won't overflow to the next node.

Title: Regex Contains in the XML element

Body:
How can I use "contains" in the regex ("Contains" or "%like%")?

I have a regex to match the XML node with exact text:

<([\w]+)[^>]*>sample<\/\1>

It yields the exact Node name, but I want to apply the regex like in C# and SQL (%LIKE%).

Text:

    <Part>this is sample part</Part>
    <Remarks>this is sample remark</Remarks>
    <Notes>this is sample notes</Notes>
    <Desc>sample</Desc>

Expected regex result should return all the above nodes, but currently it returns only the last node.

I created a sample here to test.

Body:
You may use XDocument to parse XML like this:

var s = @"<?xml version=""1.0""?>
  <root>
    <Part>this is sample part</Part>
    <Remarks>this is sample remark</Remarks>
    <Notes>this is sample notes</Notes>
    <Desc>sample</Desc>
  </root>";
var document = XDocument.Parse(s);
var names = document.Descendants()
               .Elements()
               .Where(x => x.Value.Contains("sample")) // all nodes with text having sample
               .Select(a => a.Name.LocalName); // return the local names of the nodes
Console.WriteLine(string.Join("\n", names));

It prints:

The same can be achieved with an XPath:

var names2 = document.Root.XPathSelectElements("//*[contains(text(), \"sample\")]");
var results = names2.Select(x => x.Name.LocalName));

To fall back to regex in case the XML is not valid, use

<(?:\w+:)?(\w+)[^<]*>[^<]*?sample[^<]*</(?:\w+:)?\1>

See the regex demo. Note the (?:\w+:)? matches arbitrary namespace in the open and close tag nodes. [^<] matches any char but <, so it won't overflow to the next node.


问:
Spoon.batch file not launching software
I downloaded Pentaho Data Integration (or Kettle) to my Windows 10 machine from the sourceforge link on the Pentaho Community website. After unzipping the files I followed the instructions on the community website for launching the software, quoted here:

After unzipping the downloaded file, you can launch Spoon by navigating to the folder /data-integration and double clicking Spoon.bat

My OS doesn't recognize any .bat file in the specified folder, but a Windows Batch File of the same name is in the folder, and it has the same size (4 KB) which the Spoon.bat file is meant to have, so I believe it is the same file referred to in the instructions.

Opening this file seems to execute the batch instruction in a command prompt window which immediatey disappears. No other effect is observed; in particular, no software is launched.

I googled and found that a common cause for issues of this kind is not having the a 64-bit version of java installed. So I installed a 64-bit version of the java runtime environment from this link and followed the approach described in this forum post for putting links to the java executables in the path that pentaho expects.

This had no effect, even after I restarted my computer.

Is there a simpler way to get this software working that I don't know about, or a step that I've missed here? Any help would be greatly appreciated!

答: Does your batch-file contain a space in the name? For me that was causing a launch problem.</p>

Title: Spoon.batch file not launching software


问:
Can someone explain this about paging in operating system?

Frequently, on a 32-bit CPU, each page-table entry is 4 bytes long,
  but that size can vary as well. A 32-bit entry can point to one of
  2^32 physical page frames. If frame size is 4 KB (2^12), then a system
  with 4-byte entries can address 2^44 bytes (or 16 TB) of physical
  memory. We should note here that the size of physical memory in a
  paged memory system is different from the maximum logical size of a
  process.

How does paging make logical memory space more than physical memory space? Isn't total number of frames in 32-bit CPU equal to  2^(32-12)=2^20 number of frames rather than 2^32 number of frames? If so, isn't a system with 4-byte entry capable of addressing (2^20)*(2^12) bytes of memory?

答:
That text isn't very clear admittedly.  I'll try to clear it out.

When translating a virtual address into a physical one, a fixed number of lower bits don't get translated:

```<code>+---------------------+----------+
|    High bits        | Low bits |
+---------------------+----------+
         |                  |
         |                  |
         V                  |
   [Page tables]            |
         |                  |
         |                  |
         V                  V
+---------------------+----------+
|        Physical address        |
+---------------------+----------+
</code>```

The lower bits number is tied to the page size: if we assume 4KiB pages then the lower 12 bits are fixed and not translated.

We also assume that the virtual address space is 32 bits.

If a page table entry is 32-bit long it can give 32 bits to use as the high part of the physical address.

Thus we have 20 (32 - 12) bits in input and 32 bits in output when looking up the page tables.

With the additional 12 bits from the fixed part this gives 32 + 12 = 44 bits of physical address.

An updated figure:

```<code>        <---------- 32 bits ----------->
        <---- 20 bit -------> <- 12 b ->
       +---------------------+----------+
       |    High bits        | Low bits |
       +---------------------+----------+
               |                  |
               | 20 bit           |
               V                  |
         [Page tables]            |
               |                  |
               | 32 bit           |
               V                  V
+----------------------------+----------+
|           Physical address            |
+----------------------------+----------+
 <-------- 32 bits ---------> <- 12 b ->
 <------------- 44 bits --------------->
</code>```

This is not a true 44-bit addressing however, pointers are still 32-bit.

Application can only access 4GiB of memory directly, but the OS can map an
application to the first 4GiB, another to the second 4GiB and so on.

This is similar to how PAE works on x86.

The assumption that all of a page table entry is used to give the higher bits of the physical address is untrue.

Some of the bits are used to set the attribute of the frame: cache-ability, access right, mapping status and so on.

The higher bits of the physical address are called page frames.

The number of page frames is determined by the structure of a page table entry, not by the size of the virtual address space (nor of the physical address space).

If a page table entry has 50-bit for the frame number then there are 250 frames.

The lower part of the physical address is called page offset and it is determined by the page size (or frame size, they are equal by design).

Body:
That text isn't very clear admittedly.  I'll try to clear it out.

When translating a virtual address into a physical one, a fixed number of lower bits don't get translated:

+---------------------+----------+
|    High bits        | Low bits |
+---------------------+----------+
         |                  |
         |                  |
         V                  |
   [Page tables]            |
         |                  |
         |                  |
         V                  V
+---------------------+----------+
|        Physical address        |
+---------------------+----------+

The lower bits number is tied to the page size: if we assume 4KiB pages then the lower 12 bits are fixed and not translated.

We also assume that the virtual address space is 32 bits.

If a page table entry is 32-bit long it can give 32 bits to use as the high part of the physical address.

Thus we have 20 (32 - 12) bits in input and 32 bits in output when looking up the page tables.

With the additional 12 bits from the fixed part this gives 32 + 12 = 44 bits of physical address.

An updated figure:

        <---------- 32 bits ----------->
        <---- 20 bit -------> <- 12 b ->
       +---------------------+----------+
       |    High bits        | Low bits |
       +---------------------+----------+
               |                  |
               | 20 bit           |
               V                  |
         [Page tables]            |
               |                  |
               | 32 bit           |
               V                  V
+----------------------------+----------+
|           Physical address            |
+----------------------------+----------+
 <-------- 32 bits ---------> <- 12 b ->
 <------------- 44 bits --------------->

This is not a true 44-bit addressing however, pointers are still 32-bit.

Application can only access 4GiB of memory directly, but the OS can map an
application to the first 4GiB, another to the second 4GiB and so on.

This is similar to how PAE works on x86.

The assumption that all of a page table entry is used to give the higher bits of the physical address is untrue.

Some of the bits are used to set the attribute of the frame: cache-ability, access right, mapping status and so on.

The higher bits of the physical address are called page frames.

The number of page frames is determined by the structure of a page table entry, not by the size of the virtual address space (nor of the physical address space).

If a page table entry has 50-bit for the frame number then there are 250 frames.

The lower part of the physical address is called page offset and it is determined by the page size (or frame size, they are equal by design).


问:
Hard Question: How to access ffmpeg_php getFrame in Imagick without convert to GD?
I have thousands of movie clips need to be process in Imagick frame-by-frame. I'm currently obtain the frames using ffmpeg-php and process each frame by Imagick. The Imagick can not (at least I don't know how) access the frame directly so I have to convert the frames to GD and capture it into binary string. This is slow for thousands of clips with over million frames. How can I access / convert the frame from ffmpeg getFrame in Imagick? Or other quick / dirty ways for such conversion? Thanks in advance!</p>

```<code>$movie = new ffmpeg_movie('any.avi', 0);

 $im = new Imagick();

 ob_start();

 imagejpeg($movie->getFrame($i)->toGDImage());

 $im->readImageBlob(ob_get_contents());

 ob_end_clean();

// do Imagick process....

 echo $im_im;
</code>```

答:
Not that hard with Imagick delegates, see:

```<code><?php

$im = new imagick();
$im->newPseudoImage( 200, 200, "ffmpeg:test1.mpg[40]" );
$im->setImageFormat( "png" );

header( "Content-Type: image/png" );
echo $im;

?>
</code>```

And the full link

http://valokuva.org/?p=13

Hope it helps.

OwnerDisplayName: babyromeo

Body:
I have thousands of movie clips need to be process in Imagick frame-by-frame. I'm currently obtain the frames using ffmpeg-php and process each frame by Imagick. The Imagick can not (at least I don't know how) access the frame directly so I have to convert the frames to GD and capture it into binary string. This is slow for thousands of clips with over million frames. How can I access / convert the frame from ffmpeg getFrame in Imagick? Or other quick / dirty ways for such conversion? Thanks in advance!

$movie = new ffmpeg_movie('any.avi', 0);

 $im = new Imagick();

 ob_start();

 imagejpeg($movie->getFrame($i)->toGDImage());

 $im->readImageBlob(ob_get_contents());

 ob_end_clean();

// do Imagick process....

 echo $im_im;

Body:
Not that hard with Imagick delegates, see:

<?php

$im = new imagick();
$im->newPseudoImage( 200, 200, "ffmpeg:test1.mpg[40]" );
$im->setImageFormat( "png" );

header( "Content-Type: image/png" );
echo $im;

?>

And the full link

http://valokuva.org/?p=13

Hope it helps.