问:
how to call IBM Watson services from javascript
I am implementing a virtual agent using IBM Watson services. My application is developed using Jquery, Angular JS & Java.Currently i am calling the watson services from middle layer that is java. But i want to avoid that and call directly from javascript.When i call from javascript using XML Http request, i am getting CORS error.How to solve this?

Below is my code:

```<code>var username = "uid";
var password = "pwd";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url');
//xhr.withCredentials = true;
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type, application/json, Authorization");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader('Access-Control-Allow-Credentials', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
xhr.setRequestHeader('Content-Type', undefined);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + " " + password));
xhr.send('"query":"hi"');
</code>```

答: You might also want to look at some of the Watson SDK's available on GitHub.</p>

Body:
I am implementing a virtual agent using IBM Watson services. My application is developed using Jquery, Angular JS & Java.Currently i am calling the watson services from middle layer that is java. But i want to avoid that and call directly from javascript.When i call from javascript using XML Http request, i am getting CORS error.How to solve this?

Below is my code:

var username = "uid";
var password = "pwd";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url');
//xhr.withCredentials = true;
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type, application/json, Authorization");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader('Access-Control-Allow-Credentials', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
xhr.setRequestHeader('Content-Type', undefined);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + " " + password));
xhr.send('"query":"hi"');


来源: stackexchange

问:
PHPMailer does not return error but only sends 6 emails instead of 24
My PHPMailer seems to work, but loops through the mailer only 6 times instead of 24 times. if loop used without mailer, it does return 24 addresses. I'm connected to an internal network with access from outside. can anyone clear up what is going on. ($link -> close()) is done at a later stage. also the 24 emails sent two 2 different email accounts(for testing purposes), both receive 3 emails from this phpMailer. found many posts regarding phpMailer, I haven't encountered this one so far. </p>

```<code>        if ($result = $link->query("SELECT Adres FROM Emails")) {
            //Alle variabelen voor de mail
            $mail = new PHPMailer;
            //$mail->SMTPDebug = 3;                               // Enable verbose debug output
            $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->SMTPKeepAlive = true;
            $mail->Host = 'smtp-mail.outlook.com';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = '**********@outlook.com';                 // SMTP username
            $mail->Password = '**********';                           // SMTP password
            $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 587;                                    // TCP port to connect to
            $mail->setFrom('**********@outlook.com');
            $mail->isHTML(true);                                  // Set email format to HTML
            $mail->Subject = 'APP';
            $mail->Body    = 'is this working??';
            $mail->AltBody = 'is this working??';
            while($row = mysqli_fetch_row($result)) {
                $variable = $row[0];
                $mail->addAddress($variable);

                if(!$mail->send()) {
                    echo 'Message could not be sent.';
                    echo 'Mailer Error: ' . $mail->ErrorInfo;
                } else {
                    echo 'Message has been sent';
                }
                $mail->ClearAllRecipients( );
            }
            $result->close();
        }
</code>```

答:
You're not checking that addAddress succeeds, for example if the email addresses are invalid. If you set SMTPDebug = 2, you can watch the SMTP conversation.

Check addresses like this:

```<code>$variable = $row[0];
if (!$mail->addAddress($variable)) {
  echo "skipping invalid address $variable";
  continue;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My PHPMailer seems to work, but loops through the mailer only 6 times instead of 24 times. if loop used without mailer, it does return 24 addresses. I'm connected to an internal network with access from outside. can anyone clear up what is going on. ($link -> close()) is done at a later stage. also the 24 emails sent two 2 different email accounts(for testing purposes), both receive 3 emails from this phpMailer. found many posts regarding phpMailer, I haven't encountered this one so far.

        if ($result = $link->query("SELECT Adres FROM Emails")) {
            //Alle variabelen voor de mail
            $mail = new PHPMailer;
            //$mail->SMTPDebug = 3;                               // Enable verbose debug output
            $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->SMTPKeepAlive = true;
            $mail->Host = 'smtp-mail.outlook.com';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = '**********@outlook.com';                 // SMTP username
            $mail->Password = '**********';                           // SMTP password
            $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 587;                                    // TCP port to connect to
            $mail->setFrom('**********@outlook.com');
            $mail->isHTML(true);                                  // Set email format to HTML
            $mail->Subject = 'APP';
            $mail->Body    = 'is this working??';
            $mail->AltBody = 'is this working??';
            while($row = mysqli_fetch_row($result)) {
                $variable = $row[0];
                $mail->addAddress($variable);

                if(!$mail->send()) {
                    echo 'Message could not be sent.';
                    echo 'Mailer Error: ' . $mail->ErrorInfo;
                } else {
                    echo 'Message has been sent';
                }
                $mail->ClearAllRecipients( );
            }
            $result->close();
        }

Body:
You're not checking that addAddress succeeds, for example if the email addresses are invalid. If you set SMTPDebug = 2, you can watch the SMTP conversation.

Check addresses like this:

$variable = $row[0];
if (!$mail->addAddress($variable)) {
  echo "skipping invalid address $variable";
  continue;
}


问:
angularjs routing with slash
In the following AngularJS/Ui-router example I have a nav leading to 2 state:

```<code><body ng-app='myApp'>
    <a ui-sref="home">Home</a>
    <a ui-sref="news">News</a>
    <ui-view></ui-view>
</body>

app.config(function($stateProvider){
  $stateProvider.state('home', {
    url : '/home',
    template: '<h1>Home page</h1>'
  });

  $stateProvider.state('news', {
    url : '/news',
    template: '<h1>News page</h1>'
  });
});
</code>```

Yeah, everything works fine in general as you already know. Hitting the news link will call the news state and so on.

BUT, suppose your user goes into the browser navigator and writes:

WEBSITEURL/news/ by adding a slash / at the end!

OH NOOOO! It won't redirect to WEBSITEURL/news

Why /news works and /news/ doesn't work?

In general, why /uri works and /uri/ doesn't work?

That's not logical at all. What is a good solution to get out of this?!

答:
Add a new rule for your ui-router configuration:

```<code>$urlRouterProvider.rule(function($injector, $location) {
    var path = $location.path();
    if(path[path.length-1] === '/';) {
       var newPath = path.substr(0, path.length - 1);
       return newPath
    }

});
</code>```

So, your code becomes,

```<code>app.config(function($stateProvider){

    $urlRouterProvider.rule(function($injector, $location) {
        var path = $location.path();
        if(path[path.length-1] === '/';) {
          var newPath = path.substr(0, path.length - 1);
          return newPath
        }

    });

    $stateProvider.state('home', {
      url : '/home',
      template: '<h1>Home page</h1>'
    });

    $stateProvider.state('news', {
      url : '/news',
      template: '<h1>News page</h1>'
    });
});
</code>```

Title: angularjs routing with slash

Body:
In the following AngularJS/Ui-router example I have a nav leading to 2 state:

    Home
    News
    <ui-view></ui-view>

app.config(function($stateProvider){
  $stateProvider.state('home', {
    url : '/home',
    template: '
Home page
'
  });

  $stateProvider.state('news', {
    url : '/news',
    template: '
News page
'
  });
});

Yeah, everything works fine in general as you already know. Hitting the news link will call the news state and so on.

BUT, suppose your user goes into the browser navigator and writes:

WEBSITEURL/news/ by adding a slash / at the end!

OH NOOOO! It won't redirect to WEBSITEURL/news

Why /news works and /news/ doesn't work?

In general, why /uri works and /uri/ doesn't work?

That's not logical at all. What is a good solution to get out of this?!

Body:
Add a new rule for your ui-router configuration:

$urlRouterProvider.rule(function($injector, $location) {
    var path = $location.path();
    if(path[path.length-1] === '/';) {
       var newPath = path.substr(0, path.length - 1);
       return newPath
    }

});

So, your code becomes,

app.config(function($stateProvider){

    $urlRouterProvider.rule(function($injector, $location) {
        var path = $location.path();
        if(path[path.length-1] === '/';) {
          var newPath = path.substr(0, path.length - 1);
          return newPath
        }

    });

    $stateProvider.state('home', {
      url : '/home',
      template: '<h1>Home page</h1>'
    });

    $stateProvider.state('news', {
      url : '/news',
      template: '<h1>News page</h1>'
    });
});

ContentLicense: CC BY-SA 4.0


问:
Print records in horizontal columns
How can I print information like this in Crystal Reports?

答:
In general, Crystal reports is not very well configured to handle information displayed horizontally. There are some exceptions to this, but the gist is that the report is evaluated top to bottom. So any solution you can get to work will have to be out of the box (and probably a lot of extra work.)

If you want 3 columns, you could rig something up that displays information in your section like this by use of formulas or subreports.

PREVIOUS(your_field_here) | your_field_here | NEXT(your_field_here)

You would then want to set the supression logic for that entire section as RecordCount Mod 3 = 2 to prevent data from repeating.

Title: Print records in horizontal columns


问:
How to remove blanks/NA's from dataframe and shift the values up
I have a huge dataframe which has values and blanks/NA's in it. I want to remove the blanks from the dataframe and move the next values up in the column. Consider below sample dataframe.

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5,4))
df.iloc[1,2] = np.NaN
df.iloc[0,1] = np.NaN
df.iloc[2,1] = np.NaN
df.iloc[2,0] = np.NaN
df

       0           1           2         3
0   1.857476      NaN      -0.462941   -0.600606
1   0.000267   -0.540645    NaN        0.492480
2   NaN           NaN      -0.803889   0.527973
3   0.566922    0.036393   -1.584926   2.278294
4   -0.243182   -0.221294   1.403478   1.574097
</code>```

I want my output to be as below

```<code>       0             1             2           3
0   1.857476    -0.540645     -0.462941   -0.600606
1   0.000267     0.036393     -0.803889    0.492480
2   0.566922    -0.221294     -1.584926    0.527973
3   -0.243182                  1.403478    2.278294
4                                          1.574097
</code>```

I want the NaN to be removed and the next value to move up. df.shift was not helpful. I tried with multiple loops and if statements and achieved the desired result but is there any better way to get it done.

Body:
I have a huge dataframe which has values and blanks/NA's in it. I want to remove the blanks from the dataframe and move the next values up in the column. Consider below sample dataframe.

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5,4))
df.iloc[1,2] = np.NaN
df.iloc[0,1] = np.NaN
df.iloc[2,1] = np.NaN
df.iloc[2,0] = np.NaN
df

       0           1           2         3
0   1.857476      NaN      -0.462941   -0.600606
1   0.000267   -0.540645    NaN        0.492480
2   NaN           NaN      -0.803889   0.527973
3   0.566922    0.036393   -1.584926   2.278294
4   -0.243182   -0.221294   1.403478   1.574097

I want my output to be as below

       0             1             2           3
0   1.857476    -0.540645     -0.462941   -0.600606
1   0.000267     0.036393     -0.803889    0.492480
2   0.566922    -0.221294     -1.584926    0.527973
3   -0.243182                  1.403478    2.278294
4                                          1.574097

I want the NaN to be removed and the next value to move up. df.shift was not helpful. I tried with multiple loops and if statements and achieved the desired result but is there any better way to get it done.

Body:
You can use apply with dropna:

np.random.seed(100)
df = pd.DataFrame(np.random.randn(5,4))
df.iloc[1,2] = np.NaN
df.iloc[0,1] = np.NaN
df.iloc[2,1] = np.NaN
df.iloc[2,0] = np.NaN
print (df)
          0         1         2         3
0 -1.749765       NaN  1.153036 -0.252436
1  0.981321  0.514219       NaN -1.070043
2       NaN       NaN -0.458027  0.435163
3 -0.583595  0.816847  0.672721 -0.104411
4 -0.531280  1.029733 -0.438136 -1.118318

df1 = df.apply(lambda x: pd.Series(x.dropna().values))
print (df1)
          0         1         2         3
0 -1.749765  0.514219  1.153036 -0.252436
1  0.981321  0.816847 -0.458027 -1.070043
2 -0.583595  1.029733  0.672721  0.435163
3 -0.531280       NaN -0.438136 -0.104411
4       NaN       NaN       NaN -1.118318

And then if need replace to empty space, what create mixed values - strings with numeric - some functions can be broken:

df1 = df.apply(lambda x: pd.Series(x.dropna().values)).fillna('')
print (df1)
          0         1         2         3
0  -1.74977  0.514219   1.15304 -0.252436
1  0.981321  0.816847 -0.458027 -1.070043
2 -0.583595   1.02973  0.672721  0.435163
3  -0.53128           -0.438136 -0.104411
4                               -1.118318


问:
"hadoop namenode -format" formats wrong directory
I'm trying to install Hadoop 1.1.2.21 on CentOS 6.3

I've configured dfs.name.dir in /etc/hadoop/conf/hdfs-site.xml file

```<code><name>dfs.name.dir</name>
<value>/mnt/ext/hadoop/hdfs/namenode</value>
</code>```

But when I run "hadoop namenode -format" command, it formats /tmp/hadoop-hadoop/dfs/name instead.

What am I missing?

答:
I ran into this problem and solved it. So updating this answer.
Make sure your environment variable HADOOP_CONF_DIR points to the directory where it can find all you xml files for used for configuration. It solved it for me.

Body:
I'm trying to install Hadoop 1.1.2.21 on CentOS 6.3

I've configured dfs.name.dir in /etc/hadoop/conf/hdfs-site.xml file

<name>dfs.name.dir</name>
<value>/mnt/ext/hadoop/hdfs/namenode</value>

But when I run "hadoop namenode -format" command, it formats /tmp/hadoop-hadoop/dfs/name instead.

What am I missing?


问:
How to set the width of <h:outputText> of JSF2.0?
The code:

```<code><div>
  <h:outputText value="DelivertyType: " style="width:135px"/>
  <h:inputText value="#{newConsign.consign.faId}" style="width:135px"/>
</div>
</code>```

The style="width:135px" for h:outputText doesn't work.

答:
The outputText will generate the a span like this :

```<code><span style="width: 135px;">DelivertyType:</span>
</code>```

The "width" attribute cannot be applied on in-line elements like SPAN. (can only be applied to block-style elements).

Try wrapping the outputText in a div, and apply the styling on the DIV.

ContentLicense: CC BY-SA 2.5

Body:
The code:

  <h:outputText value="DelivertyType: " style="width:135px"/>
  <h:inputText value="#{newConsign.consign.faId}" style="width:135px"/>

The style="width:135px" for h:outputText doesn't work.

Body:
The outputText will generate the a span like this :

<span style="width: 135px;">DelivertyType:</span>

The "width" attribute cannot be applied on in-line elements like SPAN. (can only be applied to block-style elements).

Try wrapping the outputText in a div, and apply the styling on the DIV.


问:
Embed Website in Unity 3D
is there a way to embed a website in Unity 3D?
It must be a website instead of a local site.
I would like to display some live charts, using Grafana, and display them on button click.

The app will be used on iOS.

Thanks

答: After a short search I found this In-App Web Browser in the asset store. It will cost you 5$, but it seems to do what you want and it will save you the time and effort to figure out how to make something like that yourself. It works on both iOS and Android.</p>

Title: Embed Website in Unity 3D


问:
PHP: Get name of the class the current function was defined in
In PHP I'd like to find out in a function in which class this function was defined in, even if it was inherited by another class.

Let me give you an example:

```<code>class cParent {
   function getDefinedInClassName() {
      return function_I_am_looking_for();
   }
}

class cChild1 extends cParent {
}

class cChild2 extends cParent {
   function getDefinedInClassName() {
      return parent::getDefinedInClassName();
   }
}

$objParent = new cParent();
$objParent->getDefinedInClassName(); // should return 'cParent'

$objChild1 = new cChild1();
$objChild1->getDefinedInClassName(); // should return 'cParent'

$objChild2 = new cChild2();
$objChild2->getDefinedInClassName(); // should return 'cChild2'
</code>```

EDIT:

Just realized I had an error in the code. I have corrected it. Now it shows the actual problem. Sorry for the mistake!

答:
http://php.net/manual/function.get-class.php I think you should try this function.

```<code>get_class($this)
</code>```

will return the name of the current class.

Body:
In PHP I'd like to find out in a function in which class this function was defined in, even if it was inherited by another class.

Let me give you an example:

class cParent {
   function getDefinedInClassName() {
      return function_I_am_looking_for();
   }
}

class cChild1 extends cParent {
}

class cChild2 extends cParent {
   function getDefinedInClassName() {
      return parent::getDefinedInClassName();
   }
}

$objParent = new cParent();
$objParent->getDefinedInClassName(); // should return 'cParent'

$objChild1 = new cChild1();
$objChild1->getDefinedInClassName(); // should return 'cParent'

$objChild2 = new cChild2();
$objChild2->getDefinedInClassName(); // should return 'cChild2'

EDIT:

Just realized I had an error in the code. I have corrected it. Now it shows the actual problem. Sorry for the mistake!

Body:
http://php.net/manual/function.get-class.php I think you should try this function.

get_class($this)

will return the name of the current class.


问:
How to print all session variables currently set?
Without having to call each session variable by name, is there a way to display the content of all the session variables currently set?</p>

答:
this worked for me:-

<?php echo '```' . print_r($_SESSION, TRUE) . '```'; ?>

thanks for sharing code...

```<code>Array
(
    [__ci_last_regenerate] => 1490879962

    [user_id] => 3

    [designation_name] => Admin
    [region_name] => admin
    [territory_name] => admin
    [designation_id] => 2
    [region_id] => 1
    [territory_id] => 1
    [employee_user_id] => mosin11
)
</code>```

Body:
this worked for me:-

<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>

thanks for sharing code...

Array
(
    [__ci_last_regenerate] => 1490879962

    [user_id] => 3

    [designation_name] => Admin
    [region_name] => admin
    [territory_name] => admin
    [designation_id] => 2
    [region_id] => 1
    [territory_id] => 1
    [employee_user_id] => mosin11
)


问:
The return of my inner func callback isn't waited
I don't really know how to name the question so, you're welcome to edit it.

This is my function :

```<code>public static KeyValuePair<bool, string> IsAuthenticated(Token token)
    {
        List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>();
        parameters.Add(new KeyValuePair<string, string>("token", token.ToString()));
        parameters.Add(new KeyValuePair<string, string>("creation_date", token.Creation_date));

        //MESSAGE
        if (!Plugin.Connectivity.CrossConnectivity.Current.IsConnected)
            return (new KeyValuePair<bool, string>(false, "No connectivity."));

        else
        {
            HttpHandler.Post(HttpHandler.ApiAddresses.ISAUTHENTICATED, parameters, (object response, bool isOk) =>
            {
                if (isOk)
                {
                    return (new KeyValuePair<bool, string>(isOk, ""));
                }
                else
                {
                    return (new KeyValuePair<bool, string>(isOk, (response as Exception).Message));
                }
            });
        }

        return (new KeyValuePair<bool, string>(false, "isAuthenticated() didn't worked.."));
    }
</code>```

So, basically, I would like to avoid the last return, but if I do, then I have a warning -> All code path doesn't return a value blablabla

But my real problem is that, I would like my delegate func (or whatever you call it) to return the final value.

This is the HttpHandle.Post() function :

```<code>public static async void Post(string url, List<KeyValuePair<string, string>> parameters, Func<object, bool, KeyValuePair<bool, string>> callback)
    {
        try
        {
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();
            httpClient.BaseAddress = new Uri(url);
            var content = new FormUrlEncodedContent(parameters);
            HttpResponseMessage response = await httpClient.PostAsync(url, content);
            callback(await response.Content.ReadAsStringAsync() as object, true);
        }
        catch (Exception e)
        {
            callback(e as object, false);
        }
    }
</code>```

Because each time, I only reach the "isAuthenticated() didn't worked.." return.. Maybe I don't understand something or I'm just totally wrong, please explain to me..

Thank for any help !

答:
I think Post should return a Task<KeyValuePair<...>> rather than void. Then you can either make IsAuthenticated async as well and await the results from Post (which should just be returning whatever callback returns) or you may be able to get away with calling Result or Wait on it but be aware that this is a frequent source of deadlocks - it's better, if possible, to push async all the way up the call stack.

So, Post would be:

```<code>public static async Task<KeyValuePair<bool, string>> Post(string url, List<KeyValuePair<string, string>> parameters, Func<object, bool, KeyValuePair<bool, string>> callback)
    {
        try
        {
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();
            httpClient.BaseAddress = new Uri(url);
            var content = new FormUrlEncodedContent(parameters);
            HttpResponseMessage response = await httpClient.PostAsync(url, content);
            return callback(await response.Content.ReadAsStringAsync() as object, true);
        }
        catch (Exception e)
        {
            return callback(e as object, false);
        }
    }
</code>```

The problem with async void is that it will complete its work at some future point in time and it doesn't give you any means of tracking that and knowing when it has been done. That's why it's usually best avoided outside of event handlers.

Body:
I don't really know how to name the question so, you're welcome to edit it.

This is my function :

public static KeyValuePair<bool, string> IsAuthenticated(Token token)
    {
        List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>();
        parameters.Add(new KeyValuePair<string, string>("token", token.ToString()));
        parameters.Add(new KeyValuePair<string, string>("creation_date", token.Creation_date));

        //MESSAGE
        if (!Plugin.Connectivity.CrossConnectivity.Current.IsConnected)
            return (new KeyValuePair<bool, string>(false, "No connectivity."));

        else
        {
            HttpHandler.Post(HttpHandler.ApiAddresses.ISAUTHENTICATED, parameters, (object response, bool isOk) =>
            {
                if (isOk)
                {
                    return (new KeyValuePair<bool, string>(isOk, ""));
                }
                else
                {
                    return (new KeyValuePair<bool, string>(isOk, (response as Exception).Message));
                }
            });
        }

        return (new KeyValuePair<bool, string>(false, "isAuthenticated() didn't worked.."));
    }

So, basically, I would like to avoid the last return, but if I do, then I have a warning -> All code path doesn't return a value blablabla

But my real problem is that, I would like my delegate func (or whatever you call it) to return the final value.

This is the HttpHandle.Post() function :

public static async void Post(string url, List<KeyValuePair<string, string>> parameters, Func<object, bool, KeyValuePair<bool, string>> callback)
    {
        try
        {
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();
            httpClient.BaseAddress = new Uri(url);
            var content = new FormUrlEncodedContent(parameters);
            HttpResponseMessage response = await httpClient.PostAsync(url, content);
            callback(await response.Content.ReadAsStringAsync() as object, true);
        }
        catch (Exception e)
        {
            callback(e as object, false);
        }
    }

Because each time, I only reach the "isAuthenticated() didn't worked.." return.. Maybe I don't understand something or I'm just totally wrong, please explain to me..

Thank for any help !

Body:
I think Post should return a Task<KeyValuePair<...>> rather than void. Then you can either make IsAuthenticated async as well and await the results from Post (which should just be returning whatever callback returns) or you may be able to get away with calling Result or Wait on it but be aware that this is a frequent source of deadlocks - it's better, if possible, to push async all the way up the call stack.

So, Post would be:

public static async Task<KeyValuePair<bool, string>> Post(string url, List<KeyValuePair<string, string>> parameters, Func<object, bool, KeyValuePair<bool, string>> callback)
    {
        try
        {
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage();
            httpClient.BaseAddress = new Uri(url);
            var content = new FormUrlEncodedContent(parameters);
            HttpResponseMessage response = await httpClient.PostAsync(url, content);
            return callback(await response.Content.ReadAsStringAsync() as object, true);
        }
        catch (Exception e)
        {
            return callback(e as object, false);
        }
    }

The problem with async void is that it will complete its work at some future point in time and it doesn't give you any means of tracking that and knowing when it has been done. That's why it's usually best avoided outside of event handlers.


问:
How to send values to another method
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

```<code>private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}
</code>```

答:
Use constructor in AsyncTask

```<code>private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {

    String mLat;
    String mLng;
    public GetDirecoes(String lat, String lng){
        mLat = lat;
        mLng = lng;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
}
</code>```

and pass the value

```<code>new GetDirecoes(latRepr,LngRepr).execute();
</code>```

Title: How to send values to another method

Body:
I have these strings latRepr and LngRepr and I want to send them to the getDirecoes method. The GetDirecoes class is a AsyncTask.

This is how I start the method:

new GetDirecoes().execute();

So, how do I send those strings to here:

private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {}

Body:
Use constructor in AsyncTask

private class GetDirecoes extends AsyncTask<Void, Void, Void> implements Serializable {

    String mLat;
    String mLng;
    public GetDirecoes(String lat, String lng){
        mLat = lat;
        mLng = lng;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
}

and pass the value

new GetDirecoes(latRepr,LngRepr).execute();


问:
Class 'Inline\PDF\PDF' not found in laravel using wemersonjanuario/laravelpdf package
I am trying to use this package -> http://packalyst.com/packages/package/wemersonjanuario/laravelpdf

I have installed and configured as per the website and also I had used this package couple of times which worked following the same procedure.

But now its giving the error Class 'Inline\PDF\PDF' not found

Not sure whats the mistake.

Can someone please help me sort this issue.

Below is the sample code

Composer.json file

```<code>"h4cc/wkhtmltopdf-i386": "0.12.3",
"wemersonjanuario/laravelpdf": "1.0.*"
</code>```

app.php file

```<code>'providers' => [
        //  other providers
        Inline\LaravelPDF\PDFServiceProvider::class
    ],

'aliases' => [
        // other aliases
        'PDF' => Inline\LaravelPDF\PDFFacade::class,

    ],
</code>```

In config/laravelpdf.php file

```<code><?php
return [
    'executable' => base_path().'/vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386'
];
</code>```

PHP Pdf code

```<code>use Inline\LaravelPDF\PDFFacade as PDF;

class SummaryHelper
{
   public function getReport($date)
   {
      // Some code
      $data = [ ];   // some data in it

      $pdf_obj = PDF::loadView('vendor/daily-report', $data);
   }
}
</code>```

Github issue link

答:
Sorry for this.

I have changed the namespace to Novanti instead of Inline.

Please switch to 1.1.* version and change alias and provider namespaces to Novanti.

I have also updated the README.md to better document this.

Let me know if this works.

Thank you for reporting.

Body:
I am trying to use this package -> http://packalyst.com/packages/package/wemersonjanuario/laravelpdf

I have installed and configured as per the website and also I had used this package couple of times which worked following the same procedure.

But now its giving the error Class 'Inline\PDF\PDF' not found

Not sure whats the mistake.

Can someone please help me sort this issue.

Below is the sample code

Composer.json file

"h4cc/wkhtmltopdf-i386": "0.12.3",
"wemersonjanuario/laravelpdf": "1.0.*"

app.php file

'providers' => [
        //  other providers
        Inline\LaravelPDF\PDFServiceProvider::class
    ],

'aliases' => [
        // other aliases
        'PDF' => Inline\LaravelPDF\PDFFacade::class,

    ],

In config/laravelpdf.php file

<?php
return [
    'executable' => base_path().'/vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386'
];

PHP Pdf code

use Inline\LaravelPDF\PDFFacade as PDF;

class SummaryHelper
{
   public function getReport($date)
   {
      // Some code
      $data = [ ];   // some data in it

      $pdf_obj = PDF::loadView('vendor/daily-report', $data);
   }
}

Github issue link


问:
Mysql(GroupBy) alternative for Postgresql?
I am using laravel with mysql..

I have query something like this..

```<code>$mix = Ergebnisse::where(function($q) use($result) {
    foreach ($result as $item) {
         $q->orWhere(function($q) use($item) {
             $q->where('temperatur', $item->temperatur)
               ->where('zeit', $item->zeit);
        });
    }
})->groupBy('katogorie_id')->get();
</code>```

on my localhost it is working fine as i am using mysql there.
but i deployed the project on Heroku with Postgresql.

I got an error..

```<code>SQLSTATE[42803]: Grouping error: 7 ERROR: column "ergebnisse.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from "ergebnisse" where (("temperatur" = $1 and "ze...
^ (SQL: select * from "ergebnisse" where (("temperatur" = 85 and "zeit" = 35) or ("temperatur" = 85 and "zeit" = 30)) group by "katogorie_id")
</code>```

after further searching i came to know that GroupBy is not compatible with postgre. is there any other way of doing that? thanks

答:
Thankyou all of you who helped me.i solved it by this

```<code> ->distinct()->get(['katogorie_id']);
</code>```

full query-

```<code>$result=Ergebnisse::where('name_id', $nam)->where('geometrie_id', $geo)->orWhere('name_id', $nam2)->orWhere('geometrie_id', $geo2)->get();

          $mix = Ergebnisse::where(function($q) use($result) {
        foreach ($result as $item) {
             $q->orWhere(function($q) use($item) {
                 $q->where('temperatur', $item->temperatur)
                   ->where('zeit', $item->zeit);
            });
        }
    })->distinct()->get(['katogorie_id']);
</code>```

Body:
I am using laravel with mysql..

I have query something like this..

$mix = Ergebnisse::where(function($q) use($result) {
    foreach ($result as $item) {
         $q->orWhere(function($q) use($item) {
             $q->where('temperatur', $item->temperatur)
               ->where('zeit', $item->zeit);
        });
    }
})->groupBy('katogorie_id')->get();

on my localhost it is working fine as i am using mysql there.
but i deployed the project on Heroku with Postgresql.

I got an error..

SQLSTATE[42803]: Grouping error: 7 ERROR: column "ergebnisse.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select * from "ergebnisse" where (("temperatur" = $1 and "ze...
^ (SQL: select * from "ergebnisse" where (("temperatur" = 85 and "zeit" = 35) or ("temperatur" = 85 and "zeit" = 30)) group by "katogorie_id")

after further searching i came to know that GroupBy is not compatible with postgre. is there any other way of doing that? thanks

Body:
Thankyou all of you who helped me.i solved it by this

 ->distinct()->get(['katogorie_id']);

full query-

$result=Ergebnisse::where('name_id', $nam)->where('geometrie_id', $geo)->orWhere('name_id', $nam2)->orWhere('geometrie_id', $geo2)->get();

          $mix = Ergebnisse::where(function($q) use($result) {
        foreach ($result as $item) {
             $q->orWhere(function($q) use($item) {
                 $q->where('temperatur', $item->temperatur)
                   ->where('zeit', $item->zeit);
            });
        }
    })->distinct()->get(['katogorie_id']);


问:
Center a column using Twitter Bootstrap
How do I center a div of one column size within the container (12 columns) in Twitter Bootstrap 3?

.centered {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body class="container">
  <div class="col-lg-1 col-offset-6 centered">
    <img data-src="holder.js/100x100" alt="" />
  </div>
</body></code>```

I want a div, with a class .centered to be centered within the container. I may use a row if there are multiple divs, but for now I just want a div with the size of one column centered within the container (12 columns).

I am also not sure the above approach is good enough as the intention is not to offset the div by half. I do not need free spaces outside the div and the contents of the div shrink in proportion. I want to empty space outside the div to be evenly distributed (shrink till the container width is equal to one column).

答:
We can achieve this by using the table layout mechanism:

The mechanism is:

Wrap all columns in one div.

Make that div as a table with a fixed layout.

Make each column as a table cell.

Use vertical-align property to control content position.

The sample demo is here

Title: Center a column using Twitter Bootstrap

Body:
How do I center a div of one column size within the container (12 columns) in Twitter Bootstrap 3?

.centered {
  background-color: red;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

I want a div, with a class .centered to be centered within the container. I may use a row if there are multiple divs, but for now I just want a div with the size of one column centered within the container (12 columns).

I am also not sure the above approach is good enough as the intention is not to offset the div by half. I do not need free spaces outside the div and the contents of the div shrink in proportion. I want to empty space outside the div to be evenly distributed (shrink till the container width is equal to one column).


问:
Div background-color change upon drop-down
I knew javaScript but I'm not used to it as I'm more focus on creating UI design. So decided to take up some short courses and then I've encountered this problem. There should be dropdown which consist of 4 items to choose: red, blue, green, yellow. If a user choose a color let's say yellow, the div box underneath will become yellow. I used Bootstrap for this by the way.

My code goes something like this ` Dropdown 1

```<code><ul class="dropdown-menu">
    <li id="red"><a href="#">Red</a>
    </li>
    <li><a href="#">Blue</a>
    </li>
    <li><a href="#">Green</a>
    </li>
    <li><a href="#">Yellow</a>
    </li>
</ul>
</code>```

`
Full code resides here
http://jsfiddle.net/0c4dbr9t/7/

答:
Please let me know if this is what you needed..

html

```<code><div class="btn-group"> <a class="btn " href="#">Dropdown 1</a>
 <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>

    <ul id="dd" class="dropdown-menu">
       <li><a href="#">Red</a>
        </li>
        <li><a href="#">Blue</a>
        </li>
        <li><a href="#">Green</a>
        </li>
        <li><a href="#">Yellow</a>
        </li>
    </ul>
</div>

<div id ="box"><div>
</code>```

css

```<code>#box {
margin-top: 20px;
background-color: #000;
padding: 50px;
}
</code>```

js

```<code>var ul = document.getElementById('dd');
ul.addEventListener("click", changeColor, false);

function changeColor (e) {
  if(e.target.nodeName == "A") {
       document.getElementById("box").style.background =e.target.innerHTML;
    }

}
</code>```

Body:
I knew javaScript but I'm not used to it as I'm more focus on creating UI design. So decided to take up some short courses and then I've encountered this problem. There should be dropdown which consist of 4 items to choose: red, blue, green, yellow. If a user choose a color let's say yellow, the div box underneath will become yellow. I used Bootstrap for this by the way.

My code goes something like this ` Dropdown 1

Red

Blue

Green

Yellow

`
Full code resides here
http://jsfiddle.net/0c4dbr9t/7/

Body:
Please let me know if this is what you needed..

html

<div class="btn-group"> <a class="btn " href="#">Dropdown 1</a>
 <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>

    <ul id="dd" class="dropdown-menu">
       <li><a href="#">Red</a>
        </li>
        <li><a href="#">Blue</a>
        </li>
        <li><a href="#">Green</a>
        </li>
        <li><a href="#">Yellow</a>
        </li>
    </ul>
</div>

<div id ="box"><div>

css

#box {
margin-top: 20px;
background-color: #000;
padding: 50px;
}

js

var ul = document.getElementById('dd');
ul.addEventListener("click", changeColor, false);

function changeColor (e) {
  if(e.target.nodeName == "A") {
       document.getElementById("box").style.background =e.target.innerHTML;
    }

}


问:
HTTP ERROR 503 Service unavailable in Jetty server
Everytime I try to run a simple jetty server on netbeans i am facing this error, please note previously it was working fine, now all of a sudden it is giving me this error, has there been any updates? Am i missing something. please note this is web.xml code</p>

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/Fc_jetty</Set>
</Configure>
</code>```

答: Solved by myself after a lot of trial and error,finally got the cause that was the netbeans plugin compatible issue with the jetty server on downgrading the server to 9.2 the problem is gone, if someone is facing similar kind of issue please try this it will be solved</p>

Body:
Everytime I try to run a simple jetty server on netbeans i am facing this error, please note previously it was working fine, now all of a sudden it is giving me this error, has there been any updates? Am i missing something. please note this is web.xml code

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/Fc_jetty</Set>
</Configure>


问:
Is it possible to change the read-only/read-write status of a docker mount at runtime?
I have a dockerized application that uses the filesystem to store lots of state. The application code is contained in the docker image

I am considering a update strategy which involves sharing the volume between two containers, but making sure that at most one container at a time can write to that filesystem.

The workflow would be:

start container A with /data mounted rw

start container B with /data mounted ro, and a newer version of the application

stop serving requests to container A

for container A, make the /data mount read-only

for container B, make the /data mount read-write

start serving requests to container B

答:
You can re-mount your volume from inside the container, in the rw mode, like that:

```<code>mount -o remount,rw /mnt/data
</code>```

The catch is that mount syscall is not allowed inside the Docker containers by default so that you would have to run it in a privileged mode:

```<code>docker run --privileged ...
</code>```

or enable the SYS_ADMIN capability

SYS_ADMIN Perform a range of system administration operations.

```<code>docker run --cap-add=SYS_ADMIN --security-opt apparmor:unconfined
</code>```

(note that I have had to also add --security-opt apparmor:unconfined, to make this work on Ubuntu).

Also, remounting the rw volume back to ro might be tricky, as some process(es) might have already opened some files inside it for writing , in which case the remount will fail with is busy error message.

But my guess is that you can just restart the container instead (as it would be the one running an old version of the app).

Body:
You can re-mount your volume from inside the container, in the rw mode, like that:

mount -o remount,rw /mnt/data

The catch is that mount syscall is not allowed inside the Docker containers by default so that you would have to run it in a privileged mode:

docker run --privileged ...

or enable the SYS_ADMIN capability

SYS_ADMIN Perform a range of system administration operations.

docker run --cap-add=SYS_ADMIN --security-opt apparmor:unconfined

(note that I have had to also add --security-opt apparmor:unconfined, to make this work on Ubuntu).

Also, remounting the rw volume back to ro might be tricky, as some process(es) might have already opened some files inside it for writing , in which case the remount will fail with is busy error message.

But my guess is that you can just restart the container instead (as it would be the one running an old version of the app).


问:
Finding two values in a column and calculating difference of adjacent cells
I’ve two columns as follows.

```<code>A              B            C
1   1/9/2016  12:57:48 PM       Text A
2   1/9/2016 1:04:48 PM     Text A
3   1/9/2016 1:05:04 PM     Text A
4   1/9/2016 1:05:14 PM     Text A
5   1/9/2016 1:05:15 PM     Text B      A5 – A1
6   1/9/2016 1:05:38 PM     Text A
7   1/11/2016 9:57:12 AM        Text A
8   1/15/2016 10:42:55 AM       Text A
9   1/15/2016 10:45:21 AM       Text B      A9 – A6
10  1/15/2016 10:58:12 AM       Text A
</code>```

Query:
I need the difference of Cell: A5 & Cell: A1 in the cell C5, A9 – A6 in C9 and so on..
So basically, we have to look at the Column B for a change in the text value – and subtract the corresponding  column A values. Hope my explanation of the problem is understandable. If not – do let me know. I can help to understand in a better way if possible.

答:
Could you use one more column? if so the solution may look like this:

let D be additional column

in D1 put formula: =A1

in D2 put formula: =IF(B1="Text B", A2, D1)

drag down formula from D2

in C2 put formula: =IF(B2="Text B", A2-D1, "")

drag down formula from C2

Body:
I’ve two columns as follows.

A              B            C
1   1/9/2016  12:57:48 PM       Text A
2   1/9/2016 1:04:48 PM     Text A
3   1/9/2016 1:05:04 PM     Text A
4   1/9/2016 1:05:14 PM     Text A
5   1/9/2016 1:05:15 PM     Text B      A5 – A1
6   1/9/2016 1:05:38 PM     Text A
7   1/11/2016 9:57:12 AM        Text A
8   1/15/2016 10:42:55 AM       Text A
9   1/15/2016 10:45:21 AM       Text B      A9 – A6
10  1/15/2016 10:58:12 AM       Text A

Query:
I need the difference of Cell: A5 & Cell: A1 in the cell C5, A9 – A6 in C9 and so on..
So basically, we have to look at the Column B for a change in the text value – and subtract the corresponding  column A values. Hope my explanation of the problem is understandable. If not – do let me know. I can help to understand in a better way if possible.


问:
Controlling Class Visibility in Java
My project has currently following package structure.

Here I have added a package name utils and defined all utility classes related to this module inside it. Those have been used by other packages (i.e. impl, internal), and because of that I have made classes and methods in util package public.

Because, it is public, not only classes in this module, classes in other modules can also access this and when I am coding using my IDE they are shown as coding suggestions.

I went through few research papers which describe how this can reduce the usability of the API and give a bad experience to developers who involve in the development [ref1, ref2].

I understand that java does not allow me to make classes inside util accessible to impl and internal packages and not to others.

Is it correct to put my utility classes to a package 'util'? Or should I put all classes that communicate with each other to the same package?

答:
You are correct, something marked public becomes usable in any other package. In contrast to other languages, Java doesn't provide any control beyond that.

A simple workaround: it might be helpful to have one special package containing those public things that should be available to your external users.

Meaning: create something like com.whatever.product.api - and instruct your users that they are fine to use everything from there - but nothing else.

In other words: you make all those things public that you need to public; but you collect those things in a special place that you allow to be used by others.

It is worth mentioning though that Java9 will introduce the concept of modules, those allow you to define which of your packages should be public to users of your module. In that sense, java 9 modules allow you to distinguish between "internal" and "external" public.

Title: Controlling Class Visibility in Java


问:
php preg_replace remove the last new line character?
I have following string in my database and i want to remove the "\r\n" at the end of the string, i tried number of times but all failed

for example, see below

```<code><?php

$text = 'Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue\r\n';

echo $essay = preg_replace("/(\\r\\n)$/", ' ', $text);
echo preg_replace("/\=\r\n$/", " ", $text);
</code>```

I am testing this with

http://phptester.net/

but unable to get expected output as below

```<code>$text = 'Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue';
</code>```

答:
So First you need to change single ' to dobule quote string "

```<code>$text = "Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue\r\n";
</code>```

then use

```<code>echo $essay  = preg_replace('/\\r+\\n/', '', $text);
</code>```

Body:
I have following string in my database and i want to remove the "\r\n" at the end of the string, i tried number of times but all failed

for example, see below

<?php

$text = 'Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue\r\n';

echo $essay = preg_replace("/(\\r\\n)$/", ' ', $text);
echo preg_replace("/\=\r\n$/", " ", $text);

I am testing this with

http://phptester.net/

but unable to get expected output as below

$text = 'Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue';

Body:
So First you need to change single ' to dobule quote string "

$text = "Am a 44 year old divorced lady with two adult sons. Having been single for 15years and dedicating my life to my two boys, am ready now to find love and companionship with a loving caring honest man with humane values\r\n\r\nThough 44 I look much younger. Look forward to meeting a like minded honest man and share the rest of our  journey of life together with mutual understanding and complement each other.       \r\n\r\nWill be happy to forward a photograph after initial dialogue\r\n";

then use

echo $essay  = preg_replace('/\\r+\\n/', '', $text);


问:
Naming conventions for "number of foos" variables
Let's suppose that I need to store the number of foo objects in a variable.

Not being a native English speaker, I always wonder what's the best (= short and immediately clear) name for that var.

foo_num? num_foo? no_foo? foo_no? or something else?

The full name should be number_of_foos, but it's a bit verbose.

What's your favorite and why?

答:
I personally would go for total_foos or totalFoos depending on the language standard. It represents better that the value is a final total and not just a running count.

It also makes more sense to say "I have 3 total foos" rather than "I have a 3 count of foos".

Overall, it's not a huge deal but I always use total over count!


问:
Dropbox and pyinotify
I just got an iPad and I foolishly got the TexTouch application. Foolishly, because due to Apple regulation, TexTouch can't compile Tex. It syncs the .tex file to a computer using Dropbox. On the distant computer, it gets caught by another program that compiles the .tex file to PDF and sends it back. But (surprise!) that distant program in Windows and Mac only. And I'm on Linux. So I thought, why not use inotify? To make things a bit simpler, I actually used pyinotify so I wouldn't have to deal with tons of compilation. BUT when Dropbox drops a file, here are, in pyinotify vernacular, the events that happen. (Obviously, "first doc.tex" is the name of the file I'm syncing.)

```<code>event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event cookie=151401 dir=False mask=0x40 maskname=IN_MOVED_FROM name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event cookie=151402 dir=False mask=0x80 maskname=IN_MOVED_TO name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x4 maskname=IN_ATTRIB name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
</code>```

What can I make of that? The only events that appear to be unique are the IN_MOVE_FROM and IN_MOVE_TO events. But it looks like a BAD idea to monitor those. Is there a way to detect an event that is initiated by Dropbox? Should I use something other than inotify or pyinotify?

答:
I got a script working that watches for IN_MOVED_TO. Whenever Dropbox drops a new file, it is triggered. You should use IN_MOVED_TO.</p>

```<code><Event cookie=63896 dir=False mask=0x80 maskname=IN_MOVED_TO name=test.zip path=/home/bpotter/Dropbox/Apps/Backup pathname=/home/bpotter/Dropbox/Apps/Backup/test.zip wd=1 >
</code>```

Title: Dropbox and pyinotify

Body:
I just got an iPad and I foolishly got the TexTouch application. Foolishly, because due to Apple regulation, TexTouch can't compile Tex. It syncs the .tex file to a computer using Dropbox. On the distant computer, it gets caught by another program that compiles the .tex file to PDF and sends it back. But (surprise!) that distant program in Windows and Mac only. And I'm on Linux. So I thought, why not use inotify? To make things a bit simpler, I actually used pyinotify so I wouldn't have to deal with tons of compilation. BUT when Dropbox drops a file, here are, in pyinotify vernacular, the events that happen. (Obviously, "first doc.tex" is the name of the file I'm syncing.)

event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event cookie=151401 dir=False mask=0x40 maskname=IN_MOVED_FROM name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event cookie=151402 dir=False mask=0x80 maskname=IN_MOVED_TO name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x4 maskname=IN_ATTRIB name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x20 maskname=IN_OPEN name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x1 maskname=IN_ACCESS name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >
event: <Event dir=False mask=0x10 maskname=IN_CLOSE_NOWRITE name=first doc.tex path=/home/eje211/Dropbox/TexTouch pathname=/home/eje211/Dropbox/TexTouch/first doc.tex wd=1 >

What can I make of that? The only events that appear to be unique are the IN_MOVE_FROM and IN_MOVE_TO events. But it looks like a BAD idea to monitor those. Is there a way to detect an event that is initiated by Dropbox? Should I use something other than inotify or pyinotify?

Body:
I got a script working that watches for IN_MOVED_TO. Whenever Dropbox drops a new file, it is triggered. You should use IN_MOVED_TO.

<Event cookie=63896 dir=False mask=0x80 maskname=IN_MOVED_TO name=test.zip path=/home/bpotter/Dropbox/Apps/Backup pathname=/home/bpotter/Dropbox/Apps/Backup/test.zip wd=1 >


问:
How to carry the value of checkbox to a php page and output an .xls file?
I am trying to download the contents from mysql db on checkbox selection and button click in excel format. The program is working. But the problem is that I'm only getting one value instead of the entire row. An error on excel file shows undefined index on the line of query.

```<code>    <form action="connect.php" method="POST">

     <table class= "table table-condensed table-striped">

     <thead>
     <tr class="warning">
     <th></th>
     <th>Delivery No.</th>
     <th>Invoice Number</th>
     <th>Bill Date</th>
     <th>Customer</th>
     <th>Quantity</th>
     <th>Brand</th>

     </tr>

     </thead>

     <?php while ($row = mysql_fetch_array($filter_result)){ ?>
                      <tr>

<td class="border-right" align="center"><input type="checkbox" name="check[]" id="check[]" value= "<?php echo $row['Delivery_no']; ?>" /></td>
<td><?php echo $row['Delivery_no'];?></td>
<td><?php echo $row['Invoice_no'];?></td>
<td><?php echo $row['Bill_date'];?></td>
<td><?php echo $row['Bill_to_party'];?></td>
<td><?php echo $row['Quantity'];?></td>
<td><?php echo $row['Brand']; } ?></td>
                        </tr>

     </table>
     <br>

     <input type= "submit" name="submit" id="submit" value="submit" class="btn btn-primary button-loading">

     </form>
</code>```

PHP CODE

```<code>if (is_array($_REQUEST['check']) and count($_REQUEST['check']) > 0)
{
    $checks = implode(array_map('intval', $_REQUEST['check']));

    $sql = "Select * from $DB_TBLName WHERE Delivery_no IN ($checks)" ;
    echo $sql;
    $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
    if(isset($_POST['submit'])){
       if(!empty($_POST['check'])) {
          // Loop to store and display values of individual checked checkbox.
          foreach($_POST['check'] as $selected) {
             echo $selected ;
          }
       }
    }
    $sep = "\t";
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
       echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
       $schema_insert = "";
       for($j=0; $j<mysql_num_fields($result);$j++) {
          if(!isset($row[$j]))
             $schema_insert .= "NULL".$sep;
          elseif ($row[$j] != "")
             $schema_insert .= "$row[$j]".$sep;
          else
             $schema_insert .= "".$sep;
       }
       $schema_insert = str_replace($sep."$", "", $schema_insert);
       $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
       $schema_insert .= "\t";
       print(trim($schema_insert));
       print "\n";
    }
    $file_ending = "xls";
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
}
</code>```

答:
I tried to keep my code as much close to your code. but please note that using mysql functions is not recommended and removed from php 7 . also the code is vulnerable to SQL injection attacks.

as I told you in the comments just loop throw the selected rows and do to them what you have done with the first row in the previous version of your code.

```<code>$finalOutput = ""; // <-- my edit
if(isset($_POST['submit'])){
    if(!empty($_POST['check'])) {
        // Loop to store and display values of individual checked checkbox.
        $sep = "\t";
        foreach($_POST['check'] as $selected) {
            $sql = "Select * from $DB_TBLName WHERE Delivery_no = '$selected' " ;
            $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
            for ($i = 0; $i < mysql_num_fields($result); $i++) {
                //echo mysql_field_name($result,$i) . "\t";
            }
            //print("\n");
            $schema_insert = "";
            while($row = mysql_fetch_row($result))
            {
                for($j=0; $j<mysql_num_fields($result);$j++)
                {
                    if(!isset($row[$j]))
                        $schema_insert .= "NULL".$sep;
                    elseif ($row[$j] != "")
                        $schema_insert .= "$row[$j]".$sep;
                    else
                        $schema_insert .= "".$sep;
                }
                $schema_insert = str_replace($sep."$", "", $schema_insert);
                $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
                $schema_insert .= "\t";
                $schema_insert = trim($schema_insert);
                $schema_insert.= "\n";
            }
        }
        $finalOutput .= $schema_insert; // <-- my edit (edited)
    }
}

$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
die($finalOutput);
</code>```

Body:
I am trying to download the contents from mysql db on checkbox selection and button click in excel format. The program is working. But the problem is that I'm only getting one value instead of the entire row. An error on excel file shows undefined index on the line of query.

    <form action="connect.php" method="POST">

     Delivery No.
     Invoice Number
     Bill Date
     Customer
     Quantity
     Brand

     <?php while ($row = mysql_fetch_array($filter_result)){ ?>

<input type="checkbox" name="check[]" id="check[]" value= "<?php echo $row['Delivery_no']; ?>" />
<?php echo $row['Delivery_no'];?>
<?php echo $row['Invoice_no'];?>
<?php echo $row['Bill_date'];?>
<?php echo $row['Bill_to_party'];?>
<?php echo $row['Quantity'];?>
<?php echo $row['Brand']; } ?>

     <input type= "submit" name="submit" id="submit" value="submit" class="btn btn-primary button-loading">

     </form>

PHP CODE

if (is_array($_REQUEST['check']) and count($_REQUEST['check']) > 0)
{
    $checks = implode(array_map('intval', $_REQUEST['check']));

    $sql = "Select * from $DB_TBLName WHERE Delivery_no IN ($checks)" ;
    echo $sql;
    $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:
" . mysql_error(). "
" . mysql_errno());
    if(isset($_POST['submit'])){
       if(!empty($_POST['check'])) {
          // Loop to store and display values of individual checked checkbox.
          foreach($_POST['check'] as $selected) {
             echo $selected ;
          }
       }
    }
    $sep = "\t";
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
       echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
       $schema_insert = "";
       for($j=0; $j<mysql_num_fields($result);$j++) {
          if(!isset($row[$j]))
             $schema_insert .= "NULL".$sep;
          elseif ($row[$j] != "")
             $schema_insert .= "$row[$j]".$sep;
          else
             $schema_insert .= "".$sep;
       }
       $schema_insert = str_replace($sep."$", "", $schema_insert);
       $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
       $schema_insert .= "\t";
       print(trim($schema_insert));
       print "\n";
    }
    $file_ending = "xls";
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
}

Body:
I tried to keep my code as much close to your code. but please note that using mysql functions is not recommended and removed from php 7 . also the code is vulnerable to SQL injection attacks.

as I told you in the comments just loop throw the selected rows and do to them what you have done with the first row in the previous version of your code.

$finalOutput = ""; // <-- my edit
if(isset($_POST['submit'])){
    if(!empty($_POST['check'])) {
        // Loop to store and display values of individual checked checkbox.
        $sep = "\t";
        foreach($_POST['check'] as $selected) {
            $sql = "Select * from $DB_TBLName WHERE Delivery_no = '$selected' " ;
            $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
            for ($i = 0; $i < mysql_num_fields($result); $i++) {
                //echo mysql_field_name($result,$i) . "\t";
            }
            //print("\n");
            $schema_insert = "";
            while($row = mysql_fetch_row($result))
            {
                for($j=0; $j<mysql_num_fields($result);$j++)
                {
                    if(!isset($row[$j]))
                        $schema_insert .= "NULL".$sep;
                    elseif ($row[$j] != "")
                        $schema_insert .= "$row[$j]".$sep;
                    else
                        $schema_insert .= "".$sep;
                }
                $schema_insert = str_replace($sep."$", "", $schema_insert);
                $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
                $schema_insert .= "\t";
                $schema_insert = trim($schema_insert);
                $schema_insert.= "\n";
            }
        }
        $finalOutput .= $schema_insert; // <-- my edit (edited)
    }
}

$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
die($finalOutput);