问:
sentence extraction from 'so dump' using pandas
I am supposed to work with the stack-overflow dump as a part of my project. Now, being a novice programmer I am facing problems with doing the following task with the Pandas library.

I have a .csv file that looks like:

```<code>Id,ParentId,CreationDate,Score,Body,OwnerUserId,LastEditorUserId,LastEditDate,LastActivityDate,CommentCount,FLAG
127,126,01-08-08 16:13,51,"This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called).",35,35,01-08-08 16:32,01-08-08 16:32,2,
152,146,01-08-08 17:33,28,"The funny thing is i wrote a php media gallery for all my music 2 days ago. I had a similar problem.  Im using http://musicplayer.sourceforge.net/ for the player. and the playlis are built via php.  all music request go there a script called xfer.php?file=WHATEVER

$filename = base64_url_decode($_REQUEST['file']);
header(""Cache-Control: public"");
header(""Content-Description: File Transfer"");
header('Content-disposition: attachment; filename='.basename($filename));
header(""Content-Transfer-Encoding: binary"");
header('Content-Length: '. filesize($filename));

//  Put either file counting code here. either a db or static files

//

readfile($filename);  //and spit the user the file

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_,', '+/='));
}

And when you call files use something like

function base64_url_encode($input) {
     return strtr(base64_encode($input), '+/=', '-_,');
}

http://us.php.net/manual/en/function.base64-encode.php

If you are using some javascript or a flash player (JW player for example) that requires the actual link to be an mp3 file or whatever, you can append the text ""&type=.mp3"" so the final linke becomes something like ""www.example.com/xfer.php?file=34842ffjfjxfh&type=.mp3"". That way it looks like it ends with an mp3 extension without affecting the file link.
",146637,30,10-08-08 12:16,10-08-08 12:16,4,
</code>```

I wish to obtain another .csv file which should look like:

```<code>Id,ParentId,CreationDate,Score,Body,OwnerUserId,LastEditorUserId,LastEditDate,LastActivityDate,CommentCount,FLAG
127,126,2008-08-01 16:13:48,51,"This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called).",35,35.0,2008-08-01 16:32:17,2008-08-01 16:32:17,2,
152,146,2008-08-01 17:33:59,28,"The funny thing is i wrote a php media gallery for all my music 2 days ago.",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"I had a similar problem.",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"Im using /musicplayer.sourceforge/ for the player. and the playlis are built via php. all music request go there a script called xfer.php?file=WHATEVER ",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"$filename = base64_url_decode($_REQUEST['file']); header(""Cache-Control: public""); header(""Content-Description: File Transfer""); header('Content-disposition: attachment; filename='.basename($filename)); header(""Content-Transfer-Encoding: binary""); header('Content-Length: '. filesize($filename)); //  Put either file counting code here. either a db or static files // readfile($filename);  //and spit the user the file function base64_url_decode($input) {    return base64_decode(strtr($input, '-_,', '+/='));}",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"And when you call files use something like function base64_url_encode($input) {     return strtr(base64_encode($input), '+/=', '-_,');}",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"http://us.php.net/manual/en/function.base64-encode.php",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"If you are using some javascript or a flash player (JW player for example) that requires the actual link to be an mp3 file or whatever, you can append the text ""&type=.mp3"" so the final linke becomes something like ""example/xfer.php?file=34842ffjfjxfh&type=.mp3"".",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"That way it looks like it ends with an mp3 extension without affecting the file link. ",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
</code>```

答:
After cleaning the input csv file using the re and lxml, the following code did the job (using nltk)

```<code>sentences = []
for row in df.itertuples():
for sentence in nltk.sent_tokenize(row[10]):
sentences.append((row[1], sentence, row[11]))
new_df = pd.DataFrame(sentences, columns=['POSTID', 'SENTENCE', 'FLAG'])
</code>```

This snippet found online....some tweaking was necessary ofcourse.

Body:
I am supposed to work with the stack-overflow dump as a part of my project. Now, being a novice programmer I am facing problems with doing the following task with the Pandas library.

I have a .csv file that looks like:

Id,ParentId,CreationDate,Score,Body,OwnerUserId,LastEditorUserId,LastEditDate,LastActivityDate,CommentCount,FLAG
127,126,01-08-08 16:13,51,"This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called).",35,35,01-08-08 16:32,01-08-08 16:32,2,
152,146,01-08-08 17:33,28,"The funny thing is i wrote a php media gallery for all my music 2 days ago. I had a similar problem.  Im using http://musicplayer.sourceforge.net/ for the player. and the playlis are built via php.  all music request go there a script called xfer.php?file=WHATEVER

$filename = base64_url_decode($_REQUEST['file']);
header(""Cache-Control: public"");
header(""Content-Description: File Transfer"");
header('Content-disposition: attachment; filename='.basename($filename));
header(""Content-Transfer-Encoding: binary"");
header('Content-Length: '. filesize($filename));

//  Put either file counting code here. either a db or static files

//

readfile($filename);  //and spit the user the file

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_,', '+/='));
}

And when you call files use something like

function base64_url_encode($input) {
     return strtr(base64_encode($input), '+/=', '-_,');
}

http://us.php.net/manual/en/function.base64-encode.php

If you are using some javascript or a flash player (JW player for example) that requires the actual link to be an mp3 file or whatever, you can append the text ""&type=.mp3"" so the final linke becomes something like ""www.example.com/xfer.php?file=34842ffjfjxfh&type=.mp3"". That way it looks like it ends with an mp3 extension without affecting the file link.
",146637,30,10-08-08 12:16,10-08-08 12:16,4,

I wish to obtain another .csv file which should look like:

Id,ParentId,CreationDate,Score,Body,OwnerUserId,LastEditorUserId,LastEditDate,LastActivityDate,CommentCount,FLAG
127,126,2008-08-01 16:13:48,51,"This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called).",35,35.0,2008-08-01 16:32:17,2008-08-01 16:32:17,2,
152,146,2008-08-01 17:33:59,28,"The funny thing is i wrote a php media gallery for all my music 2 days ago.",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"I had a similar problem.",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"Im using /musicplayer.sourceforge/ for the player. and the playlis are built via php. all music request go there a script called xfer.php?file=WHATEVER ",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"$filename = base64_url_decode($_REQUEST['file']); header(""Cache-Control: public""); header(""Content-Description: File Transfer""); header('Content-disposition: attachment; filename='.basename($filename)); header(""Content-Transfer-Encoding: binary""); header('Content-Length: '. filesize($filename)); //  Put either file counting code here. either a db or static files // readfile($filename);  //and spit the user the file function base64_url_decode($input) {    return base64_decode(strtr($input, '-_,', '+/='));}",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"And when you call files use something like function base64_url_encode($input) {     return strtr(base64_encode($input), '+/=', '-_,');}",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"http://us.php.net/manual/en/function.base64-encode.php",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"If you are using some javascript or a flash player (JW player for example) that requires the actual link to be an mp3 file or whatever, you can append the text ""&type=.mp3"" so the final linke becomes something like ""example/xfer.php?file=34842ffjfjxfh&type=.mp3"".",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,
152,146,2008-08-01 17:33:59,28,"That way it looks like it ends with an mp3 extension without affecting the file link. ",146637,30.0,2008-08-10 12:16:40,2008-08-10 12:16:40,4,

Body:
After cleaning the input csv file using the re and lxml, the following code did the job (using nltk)

sentences = []
for row in df.itertuples():
for sentence in nltk.sent_tokenize(row[10]):
sentences.append((row[1], sentence, row[11]))
new_df = pd.DataFrame(sentences, columns=['POSTID', 'SENTENCE', 'FLAG'])

This snippet found online....some tweaking was necessary ofcourse.


来源: stackexchange

问:
Megaparsec: Unable to parse recursive arithmetic string
I'm working on a small parser using Megaparsec and trying to parse arithmetic.

```<code>-- Arithmetic expressions
data Aexp = N Num
            | V Var
            | Mult Aexp Aexp
            | Add Aexp Aexp
            | Sub Aexp Aexp
             deriving (Show, Eq, Read)

arithParser :: Parser Aexp
arithParser = V <$> strParser
            <|> N <$> numParser
            <|> Mult <$> arithParser <* tok "*" <*> arithParser
--boolParser :: Parser Bexp

strParser :: Parser Var
strParser = tok "\"" *> some (noneOf ("\n\r\"=[]{},:")) <* tok "\""

numParser :: Parser Num
numParser = (some (oneOf ['0' .. '9']) >>= return . read) <* whitespace
</code>```

If I run the command Parse arithParser "5*5" "5*5" it just returns Right (N 5), where it should return Mult(N 5) (N 5). Because of the precedence in the arithParser. But if I change the order then it seems to go into an infinite loop and crash.

Not sure what I'm doing wrong here, any help would be appreciated.

答:
The types are lying to you: when you define a recursive parser p, you're not actually allowed to use p itself wherever you want! You need to munch part of the input first in order to guarantee that you are making progress. Otherwise Haskell will indeed happily go into an infinite loop.

This problem typically gets solved by defining different "tiers" of expressions and only allowing either "simpler" ones or parentheses-wrapped "more complex" ones in left recursive positions (because matching an open parentheses does force you to make your way through part of the input string).

E.g. the grammar for your expressions would be turned into (from simplest to most complex):

```<code><Literal> ::= [0-9]+
<Var>     ::= [a-zA-Z]+
<Base>    ::= '(' <Expr> ')' | <Var> | <Literal>
<Factor>  ::= <Base> | <Base> '*' <Factor>
<Expr>    ::= <Factor> | <Factor> '+' <Expr> | <Factor> '-' <Expr>
</code>```

This is where a total language shines: because the types have to be completely honest when it comes to termination, it becomes literally impossible to write these badly behaved left recursive parsers. The typechecker tells you that you have to find another way of recognizing the terms of your language.

For instance the fixpoint combinator fix I use in my total parser combinators library doesn't have type (a -> a) -> a but rather (ignoring the funny brackets) (□ a → a) → a which precisely prevents you from using the recursive call before you've made some progress. You can still write a parser for Expr but the typechecker is here to warn you when you're making an illegal move.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a small parser using Megaparsec and trying to parse arithmetic.

-- Arithmetic expressions
data Aexp = N Num
            | V Var
            | Mult Aexp Aexp
            | Add Aexp Aexp
            | Sub Aexp Aexp
             deriving (Show, Eq, Read)

arithParser :: Parser Aexp
arithParser = V <$> strParser
            <|> N <$> numParser
            <|> Mult <$> arithParser <* tok "*" <*> arithParser
--boolParser :: Parser Bexp

strParser :: Parser Var
strParser = tok "\"" *> some (noneOf ("\n\r\"=[]{},:")) <* tok "\""

numParser :: Parser Num
numParser = (some (oneOf ['0' .. '9']) >>= return . read) <* whitespace

If I run the command Parse arithParser "5*5" "5*5" it just returns Right (N 5), where it should return Mult(N 5) (N 5). Because of the precedence in the arithParser. But if I change the order then it seems to go into an infinite loop and crash.

Not sure what I'm doing wrong here, any help would be appreciated.

Body:
The types are lying to you: when you define a recursive parser p, you're not actually allowed to use p itself wherever you want! You need to munch part of the input first in order to guarantee that you are making progress. Otherwise Haskell will indeed happily go into an infinite loop.

This problem typically gets solved by defining different "tiers" of expressions and only allowing either "simpler" ones or parentheses-wrapped "more complex" ones in left recursive positions (because matching an open parentheses does force you to make your way through part of the input string).

E.g. the grammar for your expressions would be turned into (from simplest to most complex):

<Literal> ::= [0-9]+
<Var>     ::= [a-zA-Z]+
<Base>    ::= '(' <Expr> ')' | <Var> | <Literal>
<Factor>  ::= <Base> | <Base> '*' <Factor>
<Expr>    ::= <Factor> | <Factor> '+' <Expr> | <Factor> '-' <Expr>

This is where a total language shines: because the types have to be completely honest when it comes to termination, it becomes literally impossible to write these badly behaved left recursive parsers. The typechecker tells you that you have to find another way of recognizing the terms of your language.

For instance the fixpoint combinator fix I use in my total parser combinators library doesn't have type (a -> a) -> a but rather (ignoring the funny brackets) (□ a → a) → a which precisely prevents you from using the recursive call before you've made some progress. You can still write a parser for Expr but the typechecker is here to warn you when you're making an illegal move.

ContentLicense: CC BY-SA 3.0


问:
Firebase Topic Messaging always return InvalidRegistration error when push notifications in ASP.NET
I am developing an Asp.NET MVC application. In my application, I need to push notifications to Android Devices using Firebase. This is the consequence of this question - https://stackoverflow.com/questions/40416654/unable-to-push-firebase-notifications-to-multiple-devices-using-webclient-in-asp I asked.

After I searched for solutions, I realized that I should use Topic Messaging of Firebase - https://firebase.google.com/docs/cloud-messaging/android/topic-messaging. But when I use topic messaging and push from server, it always return Error=InvalidRegistration error.

I subscribe to a topic in Android like this

```<code>FirebaseMessaging.getInstance().subscribeToTopic("newsTopic");
</code>```

Then I push like this in asp.net

```<code>public string PushNotifications()
        {
            using (var client = new WebClient())
            {
                client.Headers.Add(string.Format("Authorization:key={0}", Utils.FirebaseServerKey)); //get from firebase
                var values = new NameValueCollection();

                values["to"] = "/topics/newsTopic";
                values["data.message"] = "This is the test FCM test message";
                var response = client.UploadValues("https://fcm.googleapis.com/fcm/send", values);
                string responseString = Encoding.Default.GetString(response);
                if (!string.IsNullOrEmpty(responseString))
                {
                    return responseString;
                }
                else
                {
                    return "Something went wrong";
                }
            }
        }
</code>```

But when I push, it returns this Error=InvalidRegistration.

Update

I tried replacing

```<code>values["to"] = "/topics/newsTopic";
</code>```

with this

```<code>values["condition"] = "'newsTopic' in topics";
</code>```

It returns, Error=MissingRegistration

答: I could reproduce the problem(Error=MissingRegistration) when I did not include "Content-Type=application/json" header. Can you try adding the Content-Type header?</p>

Body:
I am developing an Asp.NET MVC application. In my application, I need to push notifications to Android Devices using Firebase. This is the consequence of this question - https://stackoverflow.com/questions/40416654/unable-to-push-firebase-notifications-to-multiple-devices-using-webclient-in-asp I asked.

After I searched for solutions, I realized that I should use Topic Messaging of Firebase - https://firebase.google.com/docs/cloud-messaging/android/topic-messaging. But when I use topic messaging and push from server, it always return Error=InvalidRegistration error.

I subscribe to a topic in Android like this

FirebaseMessaging.getInstance().subscribeToTopic("newsTopic");

Then I push like this in asp.net

public string PushNotifications()
        {
            using (var client = new WebClient())
            {
                client.Headers.Add(string.Format("Authorization:key={0}", Utils.FirebaseServerKey)); //get from firebase
                var values = new NameValueCollection();

                values["to"] = "/topics/newsTopic";
                values["data.message"] = "This is the test FCM test message";
                var response = client.UploadValues("https://fcm.googleapis.com/fcm/send", values);
                string responseString = Encoding.Default.GetString(response);
                if (!string.IsNullOrEmpty(responseString))
                {
                    return responseString;
                }
                else
                {
                    return "Something went wrong";
                }
            }
        }

But when I push, it returns this Error=InvalidRegistration.

Update

I tried replacing

values["to"] = "/topics/newsTopic";

with this

values["condition"] = "'newsTopic' in topics";

It returns, Error=MissingRegistration


问:
Razor MVC numeric format for textbox
I have a textbox, in that i insert a number, the code are the following,

```<code>     @Html.TextBox("Semana1", "", new { @type = "number", @placeholder = "Ingrese Proyección", @maxlength = "15"   })
</code>```

this textbox display a number 12356

I need that the textbox display a number with the format 123.456

thanks for your help.

答:
You can use a step with your input. Add the below as an example.</p>

```<code>@type = "number", @step = "0.01", @size = "6",
</code>```

Title: Razor MVC numeric format for textbox

Body:
I have a textbox, in that i insert a number, the code are the following,

     @Html.TextBox("Semana1", "", new { @type = "number", @placeholder = "Ingrese Proyección", @maxlength = "15"   })

this textbox display a number 12356

I need that the textbox display a number with the format 123.456

thanks for your help.

Body:
You can use a step with your input. Add the below as an example.

@type = "number", @step = "0.01", @size = "6",


问:
How Scalable is the Google Vision API?
I have an IOS app where users can upload images.
I want to run all these images through Google's Vision API.
Could someone please let me know how realistic this idea is?

Let's say that I want to run 1000 images through their API.
How much would this cost me?

In the question title, I used the word scalable because I'm worried that using this service would be really expensive.

This is mainly a question about how much it costs to get Google to scan each an image.

Thanks!

答:
It really depends what you want as a result, but in general, the first 1000 images are free per month. After that it is $1.50 per 1000 images per activity in a month (a few things are more expensive).

So if you wanted to get what labels are in an image (broadly speaking - what is the primary thing this is a picture of, which it sounds like you want), the first 1000 images in a month are free, and the next 1000 would be $1.50. Another 1000 (for a total of 3000) would be another $1.50 for a total of $3 for the 3000.

If, however, you wanted to both get what labels are in an image and if there is any explicit content in the image (Safe Search detection), the first 1000 images would be free, but the next 1000 would be $3.00 ($1.50 for the label detection, and $1.50 for the safe search detection).

See Google Cloud Vision API Pricing for the different types of operations available and the price for each.

Title: How Scalable is the Google Vision API?


问:
Reading text file from same folder
Im working on this word game in C#, but now I want to get every word that I will use from text file, just not sure how to do it. My problem is about if I send my program to my friend, I still want program to read words from text file, line by line. I tried to include text into resource files but im not sure if this is the right way, Im lost...</p>

答: You can add it to the resources if it's something that is never going to change (on your friend's end), or you can set the file to "copy always" in your project so that it copies the file into the bin. This should then get packaged along with your executable when you publish it.

Title: Reading text file from same folder


问:
Why doesn't my negative margin work in IE7?
I have two stacked divs, where I want the content from the top div to flow over onto the bottom div.  Using a negative bottom margin on the content wrapper, I was able to achieve this in all browsers except IE 7, where instead of flowing over the bottom div, the content gets cut-off/overlapped by it.

I'm looking for an explanation of what exactly is happening here, and potential fixes.

Complete HTML example:

```<code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Negative Margin Test</title>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssreset/reset-min.css">

<style type="text/css">

.container {
 width: 800px;
 background: none;
 position:relative;
}
.container-mid{
 background:#F00;/**/
 border:dashed thick #090;
 width:100%;
}
.container-bottom{
 background:#FF0;/**/
 border:dashed thick #090;
 width:100%;
 height: 200px;
}
.container-inner{
 width:100%;
 margin:0 auto;
 margin-bottom:-200px;/**/

}

</style>

</head>

<body>

<div class="container">

    <div class="container-mid">

        <div class="container-inner">

            <div class="content">

                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>
                <br />
                <br />
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>
                <br />
                <br />
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>

            </div><!-- end .content -->

        </div><!-- end .container-inner -->

    </div><!-- end .container-mid -->

    <div class="container-bottom"></div>

  <!-- end .container --></div>

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

In IE8: (Results same with Chrome/FFox/etc...)

In IE 7: (Tested with IE8->Developer Tools->IE7 Mode)

As you can see, overflowing content gets overlapped by the yellow div.

See my live example

答:
You will probably have to explicitly set the overflow CSS property.  IE 7 has a number of defaults that are different than most browsers.  See: http://www.w3schools.com/css/pr_pos_overflow.asp

Try:

```<code>.container-inner{
    width:100%;
    margin:0 auto;
    margin-bottom:-200px;/**/
    overflow: visible;/**/
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have two stacked divs, where I want the content from the top div to flow over onto the bottom div.  Using a negative bottom margin on the content wrapper, I was able to achieve this in all browsers except IE 7, where instead of flowing over the bottom div, the content gets cut-off/overlapped by it.

I'm looking for an explanation of what exactly is happening here, and potential fixes.

Complete HTML example:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Negative Margin Test</title>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssreset/reset-min.css">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

In IE8: (Results same with Chrome/FFox/etc...)

In IE 7: (Tested with IE8->Developer Tools->IE7 Mode)

As you can see, overflowing content gets overlapped by the yellow div.

See my live example

Body:
You will probably have to explicitly set the overflow CSS property.  IE 7 has a number of defaults that are different than most browsers.  See: http://www.w3schools.com/css/pr_pos_overflow.asp

Try:

.container-inner{
    width:100%;
    margin:0 auto;
    margin-bottom:-200px;/**/
    overflow: visible;/**/
}


问:
How to dedupe an excel file based on multiple conditions in python?
I have an Excel file (attached here). I have to dedupe it against two or more duplicate ids.
Criteria for deduping is based on multiple factors.

Id

Type

Time

Now, the process I follow manually to dedupe is:

I sort id in Ascending order.

I set Attribute for every id starting with t as tid.

I put xid for every [id] in id column. I sometimes leave a blank for one id if there are duplicate [id](if dates are same for two consecutive [id]).

For every duplicate id, I first check Type if it is Tea or Coffee. If one is coffee and other is tea we will always prefer coffee and set the attribute as "No" for tea. We can get more than 2 duplicates, so, we have to set "No" for all the tea for same IDs. If we get two coffee and one tea for same IDs then we will keep the latest one based on time.

If the duplicate ids have the same type then we will look at dates and set the attribute as "No" for older dates. If dates are same then we will keep one and set Attribute as "No" for others. The IDs can be more than two but the process will be same.

What I want to do is:

Set attribute as tid for IDs starting with t.

Set attribute as xid for IDs having [].

Set No in attribute if two or more IDs are duplicate based on certain conditions:

Coffee should be preferred over tea. If we have tea and coffee in
type for duplicate ids, we put No in attribute against every tea for
every duplicate ID.

In case we have one tea and two or more coffee for every duplicate ID
then we will set No against remaining coffees based on the time(IDs
with older timestamps should be No.)

If we have the same Type for every duplicate ID then whichever ID is
latest according to time should be kept and for all others attributes
should be No.

If we have same dates and same types for all duplicate IDs then we
will just randomly set No against all except one.

Note:

Duplicate one, two and three are there for us to easily just filter out based on color and then dedupe.They based on Excel formulas: (Duplicate 1=(=IF(B2=B3,1,""), Duplicate2=(=IF(C1=1,1,""), Duplicate3=(=IF(SUM(C2:D2) >=1,1,""))

We can't delete rows.

I can't figure out any code for this and this is the blocker for me in a key automation process.

There are No/xid/tid in the attribute column in attached file for reference.

Important Question:
 - Is it even possible or feasible to do with python?

答:
I dont't know if I get your question right thus I will provide a few different ways.

If you want to remove all rows which contain the same values for id,Type  and Time this could be done with:

```<code>frame=pd.read_excel(io=r"D:\xxxxxx\test.xlsx")
df=pd.DataFrame(frame)
drop_dup=df.drop_duplicates(subset=("id","Type","Time"))
print(drop_dup)
</code>```

which yields:

```<code>              id  Duplicate 1  Duplicate 2  Total Duplicates  \
0            121349100          NaN          NaN               NaN
1            121350610          NaN          NaN               NaN
2            124426041          NaN          NaN               NaN
3            124436734          NaN          NaN               NaN
4            124451775          1.0          NaN               1.0
5            124451775          1.0          1.0               1.0
7            124463136          NaN          NaN               NaN
8            124463568          NaN          NaN               NaN
9            124469946          NaN          NaN               NaN
10           124474373          NaN          NaN               NaN

....
                  Time    Type Attribute
0  2017-04-19 18:08:00     Tea       NaN
1  2017-04-19 18:08:00     Tea       NaN
2  2017-05-05 12:21:00     Tea       NaN
3  2017-04-25 15:20:00  Coffee       NaN
4  2017-04-05 21:04:00  Coffee        No
5  2017-06-05 07:38:00     Tea        No
7  2017-06-05 05:40:00  Coffee       NaN
8  2017-09-04 23:12:00     Tea       NaN
9  2017-04-24 07:48:00     Tea       NaN
10 2017-07-05 23:39:00  Coffee       NaN
....
[77 rows x 7 columns]
</code>```

This means there are 7 rows which have exactly the same Type, id and Time.
If you want to drop rows which are exactly the same (all columns are incorporated) this will yield the desired result:

```<code>df=df.drop_duplicates()
</code>```

Furthermore:

```<code>dup=df.duplicated(subset=("id","Type","Time"))
</code>```

returns a True/False array which indicates if rows are duplicates or not

```<code>0     False
1     False
2     False
3     False
4     False
5     False
6      True
7     False
</code>```

If you want to know which single values of your DataFrame are duplicates use:

```<code>dupl_val=df.apply(pd.Series.duplicated,axis=1)

       id  Duplicate 1  Duplicate 2  Total Duplicates   Time   Type  Attribute
0   False        False        False             False  False  False      False
1   False        False        False             False  False  False      False
2   False        False        False             False  False  False      False
3   False        False        False             False  False  False      False
4   False        False        False              True  False  False      False
5   False        False         True              True  False  False      False
6   False        False        False              True  False  False      False
</code>```

The reason for calling pd.Series.duplicated is that this method is applied to the axis 1 of the DataFrame which means to each single DataFrame column. A DataFrame column is a Pandas Series object.

If you don't want to delete the rows but just indicate which values are duplicates use:

```<code>dupl_val=df.apply(pd.Series.duplicated,axis=1)
df=df.where(~dupl_val,"duplicate")
print(df)

                    id Duplicate 1 Duplicate 2 Total Duplicates  \
0            121349100         NaN         NaN              NaN
1            121350610         NaN         NaN              NaN
2            124426041         NaN         NaN              NaN
3            124436734         NaN         NaN              NaN
4            124451775           1         NaN        duplicate
5            124451775           1   duplicate        duplicate
6            124451775         NaN           1        duplicate

                  Time    Type Attribute
0  2017-04-19 18:08:00     Tea       NaN
1  2017-04-19 18:08:00     Tea       NaN
2  2017-05-05 12:21:00     Tea       NaN
3  2017-04-25 15:20:00  Coffee       NaN
4  2017-04-05 21:04:00  Coffee        No
5  2017-06-05 07:38:00     Tea        No
6  2017-04-05 21:04:00  Coffee       NaN
</code>```

EDIT:
If you just want to set the Attribute column to a special value (I have chosen "duplicate") if "id","Type","Time" values within a row are duplicates of another row and don't want to change the values of the remaining columns, this code should deliver the desired result:

```<code>frame=pd.read_excel(io=r"D:\xxxxx\test.xlsx")
df=pd.DataFrame(frame)

dup=df.duplicated(subset=("id","Type","Time"))

duplicate="duplicate"

for i in range(len(dup)):
    if dup[i]==True:
        df.loc[i,"Attribute"]=duplicate

print(df)

                    id  Duplicate 1  Duplicate 2  Total Duplicates  \
0            121349100          NaN          NaN               NaN
1            121350610          NaN          NaN               NaN
2            124426041          NaN          NaN               NaN
3            124436734          NaN          NaN               NaN
4            124451775          1.0          NaN               1.0
5            124451775          1.0          1.0               1.0
6            124451775          NaN          1.0               1.0
7            124463136          NaN          NaN               NaN
                  Time    Type  Attribute
0  2017-04-19 18:08:00     Tea        NaN
1  2017-04-19 18:08:00     Tea        NaN
2  2017-05-05 12:21:00     Tea        NaN
3  2017-04-25 15:20:00  Coffee        NaN
4  2017-04-05 21:04:00  Coffee         No
5  2017-06-05 07:38:00     Tea         No
6  2017-04-05 21:04:00  Coffee  duplicate
7  2017-06-05 05:40:00  Coffee        NaN

[85 rows x 7 columns]
</code>```

You can see, that row 6 (= row 8 in the original excel file) contains the first duplicate. In this case this is a duplicate of row number 6 in the excel file.

EDIT 2

In my second edit the code now will mark ALL duplicates (also the first) as "duplicates". Also the code does no longer seach for all three columns (id,Time,Type) but either for (id and Time) OR (id and Type) OR (Time and Type). Thus all combinations of these three coumns

```<code>dup=[df.duplicated(subset=(i),keep=False) for i in [("id","Type"),("id","Time"),("Time","Type")]]
duplicate="duplicate"

for i in range(len(dup)):
    for j in range(len(dup[i])):
        if dup[i][j]==True:
            df.loc[j,"Attribute"]=duplicate

print(df)
</code>```

|

```<code>       id  Duplicate 1  Duplicate 2  Total Duplicates  \
0            121349100          NaN          NaN               NaN
1            121350610          NaN          NaN               NaN
2            124426041          NaN          NaN               NaN
3            124436734          NaN          NaN               NaN
4            124451775          1.0          NaN               1.0
5            124451775          1.0          1.0               1.0
6            124451775          NaN          1.0               1.0
              Time    Type  Attribute
0  2017-04-19 18:08:00     Tea  duplicate
1  2017-04-19 18:08:00     Tea  duplicate
2  2017-05-05 12:21:00     Tea        NaN
3  2017-04-25 15:20:00  Coffee        NaN
4  2017-04-05 21:04:00  Coffee  duplicate
5  2017-06-05 07:38:00     Tea         No
6  2017-04-05 21:04:00  Coffee  duplicate
</code>```

For more inforations about this functions read: drop_duplicates, duplicated for both, Series and DataFrames (the main difference is that for Series, the functions are applied to single values and for DataFrames they are applied to rows respectively to rows of specified columns)

Body:
I dont't know if I get your question right thus I will provide a few different ways.

If you want to remove all rows which contain the same values for id,Type  and Time this could be done with:

frame=pd.read_excel(io=r"D:\xxxxxx\test.xlsx")
df=pd.DataFrame(frame)
drop_dup=df.drop_duplicates(subset=("id","Type","Time"))
print(drop_dup)

which yields:

              id  Duplicate 1  Duplicate 2  Total Duplicates  \
0            121349100          NaN          NaN               NaN
1            121350610          NaN          NaN               NaN
2            124426041          NaN          NaN               NaN
3            124436734          NaN          NaN               NaN
4            124451775          1.0          NaN               1.0
5            124451775          1.0          1.0               1.0
7            124463136          NaN          NaN               NaN
8            124463568          NaN          NaN               NaN
9            124469946          NaN          NaN               NaN
10           124474373          NaN          NaN               NaN

....
                  Time    Type Attribute
0  2017-04-19 18:08:00     Tea       NaN
1  2017-04-19 18:08:00     Tea       NaN
2  2017-05-05 12:21:00     Tea       NaN
3  2017-04-25 15:20:00  Coffee       NaN
4  2017-04-05 21:04:00  Coffee        No
5  2017-06-05 07:38:00     Tea        No
7  2017-06-05 05:40:00  Coffee       NaN
8  2017-09-04 23:12:00     Tea       NaN
9  2017-04-24 07:48:00     Tea       NaN
10 2017-07-05 23:39:00  Coffee       NaN
....
[77 rows x 7 columns]

This means there are 7 rows which have exactly the same Type, id and Time.
If you want to drop rows which are exactly the same (all columns are incorporated) this will yield the desired result:

df=df.drop_duplicates()

Furthermore:

dup=df.duplicated(subset=("id","Type","Time"))

returns a True/False array which indicates if rows are duplicates or not

0     False
1     False
2     False
3     False
4     False
5     False
6      True
7     False

If you want to know which single values of your DataFrame are duplicates use:

dupl_val=df.apply(pd.Series.duplicated,axis=1)

       id  Duplicate 1  Duplicate 2  Total Duplicates   Time   Type  Attribute
0   False        False        False             False  False  False      False
1   False        False        False             False  False  False      False
2   False        False        False             False  False  False      False
3   False        False        False             False  False  False      False
4   False        False        False              True  False  False      False
5   False        False         True              True  False  False      False
6   False        False        False              True  False  False      False

The reason for calling pd.Series.duplicated is that this method is applied to the axis 1 of the DataFrame which means to each single DataFrame column. A DataFrame column is a Pandas Series object.

If you don't want to delete the rows but just indicate which values are duplicates use:

dupl_val=df.apply(pd.Series.duplicated,axis=1)
df=df.where(~dupl_val,"duplicate")
print(df)

                    id Duplicate 1 Duplicate 2 Total Duplicates  \
0            121349100         NaN         NaN              NaN
1            121350610         NaN         NaN              NaN
2            124426041         NaN         NaN              NaN
3            124436734         NaN         NaN              NaN
4            124451775           1         NaN        duplicate
5            124451775           1   duplicate        duplicate
6            124451775         NaN           1        duplicate

                  Time    Type Attribute
0  2017-04-19 18:08:00     Tea       NaN
1  2017-04-19 18:08:00     Tea       NaN
2  2017-05-05 12:21:00     Tea       NaN
3  2017-04-25 15:20:00  Coffee       NaN
4  2017-04-05 21:04:00  Coffee        No
5  2017-06-05 07:38:00     Tea        No
6  2017-04-05 21:04:00  Coffee       NaN

EDIT:
If you just want to set the Attribute column to a special value (I have chosen "duplicate") if "id","Type","Time" values within a row are duplicates of another row and don't want to change the values of the remaining columns, this code should deliver the desired result:

frame=pd.read_excel(io=r"D:\xxxxx\test.xlsx")
df=pd.DataFrame(frame)

dup=df.duplicated(subset=("id","Type","Time"))

duplicate="duplicate"

for i in range(len(dup)):
    if dup[i]==True:
        df.loc[i,"Attribute"]=duplicate

print(df)

                    id  Duplicate 1  Duplicate 2  Total Duplicates  \
0            121349100          NaN          NaN               NaN
1            121350610          NaN          NaN               NaN
2            124426041          NaN          NaN               NaN
3            124436734          NaN          NaN               NaN
4            124451775          1.0          NaN               1.0
5            124451775          1.0          1.0               1.0
6            124451775          NaN          1.0               1.0
7            124463136          NaN          NaN               NaN
                  Time    Type  Attribute
0  2017-04-19 18:08:00     Tea        NaN
1  2017-04-19 18:08:00     Tea        NaN
2  2017-05-05 12:21:00     Tea        NaN
3  2017-04-25 15:20:00  Coffee        NaN
4  2017-04-05 21:04:00  Coffee         No
5  2017-06-05 07:38:00     Tea         No
6  2017-04-05 21:04:00  Coffee  duplicate
7  2017-06-05 05:40:00  Coffee        NaN

[85 rows x 7 columns]

You can see, that row 6 (= row 8 in the original excel file) contains the first duplicate. In this case this is a duplicate of row number 6 in the excel file.

EDIT 2

In my second edit the code now will mark ALL duplicates (also the first) as "duplicates". Also the code does no longer seach for all three columns (id,Time,Type) but either for (id and Time) OR (id and Type) OR (Time and Type). Thus all combinations of these three coumns

dup=[df.duplicated(subset=(i),keep=False) for i in [("id","Type"),("id","Time"),("Time","Type")]]
duplicate="duplicate"

for i in range(len(dup)):
    for j in range(len(dup[i])):
        if dup[i][j]==True:
            df.loc[j,"Attribute"]=duplicate

print(df)

|

       id  Duplicate 1  Duplicate 2  Total Duplicates  \
0            121349100          NaN          NaN               NaN
1            121350610          NaN          NaN               NaN
2            124426041          NaN          NaN               NaN
3            124436734          NaN          NaN               NaN
4            124451775          1.0          NaN               1.0
5            124451775          1.0          1.0               1.0
6            124451775          NaN          1.0               1.0
              Time    Type  Attribute
0  2017-04-19 18:08:00     Tea  duplicate
1  2017-04-19 18:08:00     Tea  duplicate
2  2017-05-05 12:21:00     Tea        NaN
3  2017-04-25 15:20:00  Coffee        NaN
4  2017-04-05 21:04:00  Coffee  duplicate
5  2017-06-05 07:38:00     Tea         No
6  2017-04-05 21:04:00  Coffee  duplicate

For more inforations about this functions read: drop_duplicates, duplicated for both, Series and DataFrames (the main difference is that for Series, the functions are applied to single values and for DataFrames they are applied to rows respectively to rows of specified columns)


答:
Using the comments on the post, I found that the first 1000 monthly requests are free, and the next million cost $1.50 per 1000 requests (for label recognition, which is what I wanted)

There is different pricing for different features.

@SLaks pointed me to the following helpful link https://cloud.google.com/vision/docs/pricing

Thanks for your help guys!

Title: How Scalable is the Google Vision API?

Body:
I have an IOS app where users can upload images.
I want to run all these images through Google's Vision API.
Could someone please let me know how realistic this idea is?

Let's say that I want to run 1000 images through their API.
How much would this cost me?

In the question title, I used the word scalable because I'm worried that using this service would be really expensive.

This is mainly a question about how much it costs to get Google to scan each an image.

Thanks!


问:
SOCKS 5 Server - BND.PORT & BND.ADDR
In C++ (I didn't include code because this is more of a protocol understanding matter) I am creating a SOCKS5 server and had a few questions because the client terminates the connection after I send it the approved message. In the RFC it says BND.ADDR and BND.PORT are used for:   RFC 1928

o  BND.ADDR       server bound address

o BND.PORT       server bound
  port in network octet order`

In the reply to a CONNECT, BND.PORT contains the port number that the
  server assigned to connect to the target host, while BND.ADDR

  contains the associated IP address.

Here are my questions,

What is BND.PORT and what should I specify for it?.

What does it mean by "server assigned to connect to the target host" Is target host the "Client"?

I've read the RFC front to back like 5 times and I have yet to understand it, can someone go into more detail about the BND.PORT and what it means?

I was sniffing around in Wireshark and I found that BND.PORT was different for each request made. (I am not sure what port to enter because everything I tried resulted in Proxifer (The socks client) says "The server gave an unexpected replay - Connection terminated"

Wireshark connection hex-dump from an actual SOCKS5 server (not mine):

答:
Just to make sure we're on the same page... This is the relationship between client, server and host. Notice that the client and host can't talk to each other directly.

CLIENT <-> SERVER <-> HOST

What does it mean by "server assigned to connect to the target host" Is target host the "Client"?

No. The "host" is the device the client is trying to connect to via the SOCKS5 server. The "client" is on the other side of the SOCKS5 server, furthest away from the host.

What is BND.PORT and what should I specify for it?.

BND.PORT is the source port of packets leaving the SOCKS5 server, bound for a host. You have no control over what port the server chooses. Think about it. Where does a host see packets coming from? It certainly isn't the client. From the perspective of the host, packets are all coming from the server, it doesn't know about the client. Additionally the BND.ADDR is the IP of the server.

What I've said is true under the condition that CONNECT is being used. I have no experience with BIND or UDP ASSOCIATE yet.

Title: SOCKS 5 Server - BND.PORT & BND.ADDR


答:
You can pass the path to your file using the command line:

e.g. application.exe ##path##

https://stackoverflow.com/a/12998434/1384539

then

```<code>class Program
{
    static void Main(string[] args)
    {
        using (StreamReader reader = new StreamReader(args[0]))
        {
            while (true)
            {
                string line = reader.ReadLine();
                if (line == null)
                {
                    break;
                }
                Console.WriteLine(line); // Use line.
            }
        }
    }
}
</code>```

Title: Reading text file from same folder

Body: Im working on this word game in C#, but now I want to get every word that I will use from text file, just not sure how to do it. My problem is about if I send my program to my friend, I still want program to read words from text file, line by line. I tried to include text into resource files but im not sure if this is the right way, Im lost...

Body:
You can pass the path to your file using the command line:

e.g. application.exe ##path##

https://stackoverflow.com/a/12998434/1384539

then

class Program
{
    static void Main(string[] args)
    {
        using (StreamReader reader = new StreamReader(args[0]))
        {
            while (true)
            {
                string line = reader.ReadLine();
                if (line == null)
                {
                    break;
                }
                Console.WriteLine(line); // Use line.
            }
        }
    }
}


问:
"Call to undefined function sqlsrv_connect()" when trying to connect to Azure DB from PHP
I'm trying to connect from php to Azure DB by

```<code>$connectionInfo = array("UID" => "xxx@xxx", "pwd" => "xxx", "Database" => "xxx");
$serverName = "tcp:xxx.database.windows.net,1433";
$conn = sqlsrv_connect($serverName, $connectionInfo);
</code>```

But it gives me

Fatal error: Call to undefined function sqlsrv_connect() in C:\wamp\www...\index.php on line 19

答: I added this dll to the ext/ folder then added extension=php_sqlsrv.dll to the php.ini in the php7/ folder.

Body:
I'm trying to connect from php to Azure DB by

$connectionInfo = array("UID" => "xxx@xxx", "pwd" => "xxx", "Database" => "xxx");
$serverName = "tcp:xxx.database.windows.net,1433";
$conn = sqlsrv_connect($serverName, $connectionInfo);

But it gives me

Fatal error: Call to undefined function sqlsrv_connect() in C:\wamp\www...\index.php on line 19


问:
Date range question
If I have 2 dates, 21/05/2010 and 23/05/2010, how can I find out if 22/05/2006 7:16 AM exists in between them?

I am using the following code to calculate the min/max date and will then SELECT ALL records in the table that are clear to update them.

```<code>    $today = date('l');

    if($today == 'Wednesday'){
        $min = date('d/m/Y', strtotime('0 days'));
        $max = date('d/m/Y', strtotime('+6 days'));
    }else if($today == 'Thursday'){
        $min = date('d/m/Y', strtotime('-1 days'));
        $max = date('d/m/Y', strtotime('+5 days'));
    }else if($today == 'Friday'){
        $min = date('d/m/Y', strtotime('-2 days'));
        $max = date('d/m/Y', strtotime('+4 days'));
    }else if($today == 'Saturday'){
        $min = date('d/m/Y', strtotime('-3 days'));
        $max = date('d/m/Y', strtotime('+3 days'));
    }else if($today == 'Sunday'){
        $min = date('d/m/Y', strtotime('-4 days'));
        $max = date('d/m/Y', strtotime('+2 days'));
    }else if($today == 'Monday'){
        $min = date('d/m/Y', strtotime('-5 days'));
        $max = date('d/m/Y', strtotime('+1 days'));
    }else if($today == 'Tuesday'){
        $min = date('d/m/Y', strtotime('-6 days'));
        $max = date('d/m/Y', strtotime('0 days'));
    }
</code>```

答:
DateTime::diff

Create a DateTime::diff between 21/05/2010 and 22/05/2006 7:16 AM, as well as a DateTime::diff between  23/05/2010 and 22/05/2006 7:16 AM.

Then check that the first DateTime::diff is > 0, and the second is < 0

Update : used Datetime::createFromFormat, which is a php5.3 method

Update2 : Tested code sample. Produces expected output.

```<code><?php
$datetime_lower = DateTime::createFromFormat('d/m/Y', '21/05/2010');
$datetime_upper = DateTime::createFromFormat('d/m/Y', '23/05/2010');
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', '22/05/2006 7:16 AM');

var_dump($datetime_lower < $datetime_compare);
var_dump($datetime_upper > $datetime_compare);

if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
    echo " + date is between";
} else {
    echo " date is not between";
}
</code>```

Also, there is a procedural date_diff function

Title: Date range question

Body:
If I have 2 dates, 21/05/2010 and 23/05/2010, how can I find out if 22/05/2006 7:16 AM exists in between them?

I am using the following code to calculate the min/max date and will then SELECT ALL records in the table that are clear to update them.

    $today = date('l');

    if($today == 'Wednesday'){
        $min = date('d/m/Y', strtotime('0 days'));
        $max = date('d/m/Y', strtotime('+6 days'));
    }else if($today == 'Thursday'){
        $min = date('d/m/Y', strtotime('-1 days'));
        $max = date('d/m/Y', strtotime('+5 days'));
    }else if($today == 'Friday'){
        $min = date('d/m/Y', strtotime('-2 days'));
        $max = date('d/m/Y', strtotime('+4 days'));
    }else if($today == 'Saturday'){
        $min = date('d/m/Y', strtotime('-3 days'));
        $max = date('d/m/Y', strtotime('+3 days'));
    }else if($today == 'Sunday'){
        $min = date('d/m/Y', strtotime('-4 days'));
        $max = date('d/m/Y', strtotime('+2 days'));
    }else if($today == 'Monday'){
        $min = date('d/m/Y', strtotime('-5 days'));
        $max = date('d/m/Y', strtotime('+1 days'));
    }else if($today == 'Tuesday'){
        $min = date('d/m/Y', strtotime('-6 days'));
        $max = date('d/m/Y', strtotime('0 days'));
    }

Body:
DateTime::diff

Create a DateTime::diff between 21/05/2010 and 22/05/2006 7:16 AM, as well as a DateTime::diff between  23/05/2010 and 22/05/2006 7:16 AM.

Then check that the first DateTime::diff is > 0, and the second is < 0

Update : used Datetime::createFromFormat, which is a php5.3 method

Update2 : Tested code sample. Produces expected output.

<?php
$datetime_lower = DateTime::createFromFormat('d/m/Y', '21/05/2010');
$datetime_upper = DateTime::createFromFormat('d/m/Y', '23/05/2010');
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', '22/05/2006 7:16 AM');

var_dump($datetime_lower < $datetime_compare);
var_dump($datetime_upper > $datetime_compare);

if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
    echo " + date is between";
} else {
    echo " date is not between";
}

Also, there is a procedural date_diff function


问:
Why is Okio more efficient than BufferedInputStream and BufferedOutputStream?
I tried to find out why OkHttp uses Okio but not BufferedInputStream and BufferedOutputStream to buffer data.
I used following code to verify：

```<code>private String targetPath = Environment.getExternalStorageDirectory()
        + File.separator + "performance.dat";

private InputStream getInputStream() {
    try {
        File targetFile = new File(targetPath);

        if (targetFile.exists()) {
            targetFile.delete();
        }

        targetFile.createNewFile();
        return new FileInputStream("/sdcard/file.zip");
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

public void bufferedIO(View view) {
    new Thread() {

        @Override
        public void run() {
            InputStream inputStream = getInputStream();

            if (inputStream == null) {
                return;
            }

            long start = System.currentTimeMillis();

            inputStream = new BufferedInputStream(inputStream, 8192);
            File targetFile = new File(targetPath);
            BufferedOutputStream fileOutputStream = null;

            try {
                fileOutputStream = new BufferedOutputStream(new FileOutputStream(targetFile, true), 8192);
                byte[] buffer = new byte[4096];

                int count;
                while ((count = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, count);
                }

                fileOutputStream.flush();
                Log.i("performance", "BufferedInputStream and BufferedOutputStream: " + (System.currentTimeMillis() - start) + "ms");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }.start();
}

public void okio(View view) {
    new Thread() {

        @Override
        public void run() {
            InputStream inputStream = getInputStream();

            if (inputStream == null) {
                return;
            }

            long start = System.currentTimeMillis();

            File targetFile = new File(targetPath);
            Source bufferSource = Okio.buffer(Okio.source(inputStream));
            BufferedSink bufferSink = null;

            try {
                bufferSink = Okio.buffer(Okio.sink(targetFile));

                while ((bufferSource.read(bufferSink.buffer(), 4096)) != -1) {
                    bufferSink.emitCompleteSegments();
                }
                bufferSink.flush();

                Log.i("performance", "okio: " + (System.currentTimeMillis() - start) + "ms");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bufferSource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (bufferSink != null) {
                    try {
                        bufferSink.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }.start();
}
</code>```

I called bufferedIO() 5 times, the results are:

```<code>357ms
299ms
311ms
324ms
331ms
</code>```

I called okio() 5 times, the results are:

```<code>524ms
661ms
555ms
525ms
573ms
</code>```

According to the results, BufferedInputStream and BufferedOutputStream are more efficient than Okio. Is there anything wrong with my verification?

答:
I ran this benchmark on my desktop and my results were very inconsistent. I think the benchmark is ultimately measuring filesystem performance more than the I/O library.

I took out the extra indirection in the Okio benchmark, starting with a Source rather than the intermediate FileInputStream. I also removed the page-by-page loop which isn’t necessary for Okio: you can just call writeAll() to copy an entire source to a sink:

```<code>public void okio() throws IOException {
  long start = System.currentTimeMillis();

  File targetFile = new File(targetPath);
  targetFile.delete();

  try (BufferedSink sink = Okio.buffer(Okio.sink(targetFile));
      Source bufferSource = Okio.source(new File(sourcePath))) {
    sink.writeAll(bufferSource);
    System.out.println("okio: " + (System.currentTimeMillis() - start) + "ms");
  }
}
</code>```

My results were wildly inconsistent due to file system performance - individual runs varied by more than 200%.

```<code>okio:  67ms   java.io: 106ms
okio:  98ms   java.io: 106ms
okio: 108ms   java.io: 110ms
okio: 121ms   java.io: 113ms
okio: 125ms   java.io: 116ms
okio: 131ms   java.io: 118ms
okio: 143ms   java.io: 143ms
okio: 154ms   java.io: 145ms
okio: 191ms   java.io: 146ms
okio: 217ms   java.io: 239ms
</code>```

Overall Okio was more efficient here, but that might just be luck. A better benchmark would isolate the unreliable filesystem I/O. If you’d like to try that, I’m interested in the results!

Body:
I tried to find out why OkHttp uses Okio but not BufferedInputStream and BufferedOutputStream to buffer data.
I used following code to verify：

private String targetPath = Environment.getExternalStorageDirectory()
        + File.separator + "performance.dat";

private InputStream getInputStream() {
    try {
        File targetFile = new File(targetPath);

        if (targetFile.exists()) {
            targetFile.delete();
        }

        targetFile.createNewFile();
        return new FileInputStream("/sdcard/file.zip");
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

public void bufferedIO(View view) {
    new Thread() {

        @Override
        public void run() {
            InputStream inputStream = getInputStream();

            if (inputStream == null) {
                return;
            }

            long start = System.currentTimeMillis();

            inputStream = new BufferedInputStream(inputStream, 8192);
            File targetFile = new File(targetPath);
            BufferedOutputStream fileOutputStream = null;

            try {
                fileOutputStream = new BufferedOutputStream(new FileOutputStream(targetFile, true), 8192);
                byte[] buffer = new byte[4096];

                int count;
                while ((count = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, count);
                }

                fileOutputStream.flush();
                Log.i("performance", "BufferedInputStream and BufferedOutputStream: " + (System.currentTimeMillis() - start) + "ms");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }.start();
}

public void okio(View view) {
    new Thread() {

        @Override
        public void run() {
            InputStream inputStream = getInputStream();

            if (inputStream == null) {
                return;
            }

            long start = System.currentTimeMillis();

            File targetFile = new File(targetPath);
            Source bufferSource = Okio.buffer(Okio.source(inputStream));
            BufferedSink bufferSink = null;

            try {
                bufferSink = Okio.buffer(Okio.sink(targetFile));

                while ((bufferSource.read(bufferSink.buffer(), 4096)) != -1) {
                    bufferSink.emitCompleteSegments();
                }
                bufferSink.flush();

                Log.i("performance", "okio: " + (System.currentTimeMillis() - start) + "ms");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bufferSource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (bufferSink != null) {
                    try {
                        bufferSink.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }.start();
}

I called bufferedIO() 5 times, the results are:

357ms
299ms
311ms
324ms
331ms

I called okio() 5 times, the results are:

524ms
661ms
555ms
525ms
573ms

According to the results, BufferedInputStream and BufferedOutputStream are more efficient than Okio. Is there anything wrong with my verification?

Body:
I ran this benchmark on my desktop and my results were very inconsistent. I think the benchmark is ultimately measuring filesystem performance more than the I/O library.

I took out the extra indirection in the Okio benchmark, starting with a Source rather than the intermediate FileInputStream. I also removed the page-by-page loop which isn’t necessary for Okio: you can just call writeAll() to copy an entire source to a sink:

public void okio() throws IOException {
  long start = System.currentTimeMillis();

  File targetFile = new File(targetPath);
  targetFile.delete();

  try (BufferedSink sink = Okio.buffer(Okio.sink(targetFile));
      Source bufferSource = Okio.source(new File(sourcePath))) {
    sink.writeAll(bufferSource);
    System.out.println("okio: " + (System.currentTimeMillis() - start) + "ms");
  }
}

My results were wildly inconsistent due to file system performance - individual runs varied by more than 200%.

okio:  67ms   java.io: 106ms
okio:  98ms   java.io: 106ms
okio: 108ms   java.io: 110ms
okio: 121ms   java.io: 113ms
okio: 125ms   java.io: 116ms
okio: 131ms   java.io: 118ms
okio: 143ms   java.io: 143ms
okio: 154ms   java.io: 145ms
okio: 191ms   java.io: 146ms
okio: 217ms   java.io: 239ms

Overall Okio was more efficient here, but that might just be luck. A better benchmark would isolate the unreliable filesystem I/O. If you’d like to try that, I’m interested in the results!


问:
Method is missing or has incorrect signature
I am making a simple app in which context view changes and then a toast message is displayed as input given by user. I don't understand why the app keeps on crashing when changing the context view.

Also Android studio gives this warning:

Method "Toaster" is missing in "FirstActivity" or has incorrect signature.

Here is my code:

activity_me_clicked.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/welcome"
        android:textSize="36sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:paddingLeft="7dp"
        android:paddingRight="7dp"
        android:text="@string/intro"
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:baselineAligned="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <EditText
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="7dp"
                android:layout_marginEnd="7dp"
                android:layout_marginTop="10dp"
                android:ems="10"
                android:hint="Name"
                android:inputType="textPersonName"
                tools:ignore="HardcodedText" />

            <Button
                android:id="@+id/named"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:paddingBottom="10dp"
                android:paddingTop="10dp"
                android:onClick="MainProcess"
                android:text="@string/done" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal"
            tools:ignore="UselessLeaf"></LinearLayout>

    </LinearLayout>

</LinearLayout>
</code>```

FirstActivity.Java:

```<code>package com.example.nautatvanavlakha.abcd;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class FirstActivity extends AppCompatActivity {
    public static String owner_string;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_clicked);
    }

    public void MainProcess(View view) {

        final String TAG="DEBUG";
        Log.d(TAG,"At least process started");

        EditText owner = (EditText) findViewById(R.id.name);
        owner_string = owner.getText().toString();
        Log.d(TAG,"owner name stored");

        TextView textView = (TextView) findViewById(R.id.welcome);
        textView.setText("Hi " + owner_string + ".");
        Log.d(TAG,"owner name is set");

        setContentView(R.layout.activity_main_screen);
        Log.d(TAG,"content shown");
    }
}
</code>```

activity_main_screen.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/welcome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/what_would_you_like_me_to_do_today"
        android:textSize="18sp" />

    <Button
        android:id="@+id/Cam"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/camera" />

    <Button
        android:id="@+id/Mus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/music" />

    <Button
        android:id="@+id/QR"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/scanQR" />

    <EditText
        android:id="@+id/toastText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/order"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/toaster"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:onClick="toaster"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/toast"
        android:layout_marginEnd="100dp"
        android:layout_gravity="center"/>

</LinearLayout>
</code>```

MainScreen.java:

```<code>package com.example.nautatvanavlakha.abcd;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
    }

    public void toaster(View view){

        EditText toast = (EditText)findViewById(R.id.toastText);
        String final_toast = toast.getText().toString();
        Toast.makeText(getApplicationContext(), final_toast, Toast.LENGTH_SHORT).show();
    }

}
</code>```

EDIT: As suggested, I moved the toaser function to FirstActivity.Java and deleted the MainScreen.java file as it becomes pointless to keep it. But the major problem is when I press the button (id named) the app keeps stopping.

EDIT2: I found that setContentView(R.layout.activity_main_screen) in FirstActivity.Java needs to be above this code

```<code>    TextView textView = (TextView) findViewById(R.id.welcome);
    textView.setText("Hi " + owner_string + ".");
    Log.d(TAG,"owner name is set");
</code>```

so that Activity has access to all the layout components. Thanks solved :)

答:
You replaced the content view in the first activity with a layout that include the onClick attribute,  but you have no public void toaster(View view) method there.

So, either don't use setContentView a second time, or implement that method on both Activities.

The recommended  way to replace the view is Fragments, by the way

Body:
I am making a simple app in which context view changes and then a toast message is displayed as input given by user. I don't understand why the app keeps on crashing when changing the context view.

Also Android studio gives this warning:

Method "Toaster" is missing in "FirstActivity" or has incorrect signature.

Here is my code:

activity_me_clicked.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/welcome"
        android:textSize="36sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:paddingLeft="7dp"
        android:paddingRight="7dp"
        android:text="@string/intro"
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:baselineAligned="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <EditText
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="7dp"
                android:layout_marginEnd="7dp"
                android:layout_marginTop="10dp"
                android:ems="10"
                android:hint="Name"
                android:inputType="textPersonName"
                tools:ignore="HardcodedText" />

            <Button
                android:id="@+id/named"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:paddingBottom="10dp"
                android:paddingTop="10dp"
                android:onClick="MainProcess"
                android:text="@string/done" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal"
            tools:ignore="UselessLeaf"></LinearLayout>

    </LinearLayout>

</LinearLayout>

FirstActivity.Java:

package com.example.nautatvanavlakha.abcd;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class FirstActivity extends AppCompatActivity {
    public static String owner_string;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_clicked);
    }

    public void MainProcess(View view) {

        final String TAG="DEBUG";
        Log.d(TAG,"At least process started");

        EditText owner = (EditText) findViewById(R.id.name);
        owner_string = owner.getText().toString();
        Log.d(TAG,"owner name stored");

        TextView textView = (TextView) findViewById(R.id.welcome);
        textView.setText("Hi " + owner_string + ".");
        Log.d(TAG,"owner name is set");

        setContentView(R.layout.activity_main_screen);
        Log.d(TAG,"content shown");
    }
}

activity_main_screen.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/welcome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/what_would_you_like_me_to_do_today"
        android:textSize="18sp" />

    <Button
        android:id="@+id/Cam"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/camera" />

    <Button
        android:id="@+id/Mus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/music" />

    <Button
        android:id="@+id/QR"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/scanQR" />

    <EditText
        android:id="@+id/toastText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/order"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/toaster"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:onClick="toaster"
        android:padding="0dp"
        android:paddingTop="15dp"
        android:text="@string/toast"
        android:layout_marginEnd="100dp"
        android:layout_gravity="center"/>

</LinearLayout>

MainScreen.java:

package com.example.nautatvanavlakha.abcd;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
    }

    public void toaster(View view){

        EditText toast = (EditText)findViewById(R.id.toastText);
        String final_toast = toast.getText().toString();
        Toast.makeText(getApplicationContext(), final_toast, Toast.LENGTH_SHORT).show();
    }

}

EDIT: As suggested, I moved the toaser function to FirstActivity.Java and deleted the MainScreen.java file as it becomes pointless to keep it. But the major problem is when I press the button (id named) the app keeps stopping.

EDIT2: I found that setContentView(R.layout.activity_main_screen) in FirstActivity.Java needs to be above this code

    TextView textView = (TextView) findViewById(R.id.welcome);
    textView.setText("Hi " + owner_string + ".");
    Log.d(TAG,"owner name is set");

so that Activity has access to all the layout components. Thanks solved :)


问:
How do I use a .lib with the "Visual C++ for linux" plugin?
I'm using the Visual C++ for Linux plugin. I can run a basic Hello world without problems. My actual project uses a .lib. It compiles fine but I get an error during linking (this is copied from Visual Studio's output pane):

```<code>ClCompile:
  Starting remote build
  Compiling sources:
  Invoking g++
  g++ -c -x c++ /home/devbox/projects/LinuxProgServ/LinuxProgServ/main.cpp -I /home/devbox/projects/LinuxProgServ/include/libuv -I /home/devbox/projects/LinuxProgServ/../include/lubuntu -I "/home/devbox/projects/LinuxProgServ/../include/lubuntu/x86_64-linux-gnu" -g2 -gdwarf-2 -o "/home/devbox/projects/LinuxProgServ/obj/x64/Debug/main.o" -Wall -Wswitch -W"no-deprecated-declarations" -W"empty-body" -Wconversion -W"return-type" -Wparentheses -W"no-format" -Wuninitialized -W"unreachable-code" -W"unused-function" -W"unused-value" -W"unused-variable" -O0 -fno-strict-aliasing -fno-omit-frame-pointer -fthreadsafe-statics -fexceptions -frtti -std=c++11
  main.cpp
  Done compiling '/home/devbox/projects/LinuxProgServ/LinuxProgServ/main.cpp'
Link:
  Linking objects
  Invoking ld
  g++ -o "/home/devbox/projects/LinuxProgServ/bin/x64/Debug/LinuxProgServ.out" -Wl,--no-undefined /home/devbox/projects/LinuxProgServ/obj/x64/Debug/main.o -llibuv.lib
  /usr/bin/ld: cannot find -llibuv.lib
  collect2: error: ld returned 1 exit status
</code>```

libuv.lib is specified in Project Properties>Linker>Input>Library Dependencies. I tried the following without success:

Copy the lib to /home/devbox/projects/lib and add that directory to

the linker command with -L, both using Visual Studio's additional

library folder field and directly in the Additional command line

options field. This results in the same final command.

Copy the lib to the output directory and set it to be copied

Add the local Windows path to Visual Studio's additional library folders

Add the linux path from #1 to Visual Studio's additional library folders

Try with another library

I made the same project but for Windows just to be sure and it works.

Am I missing something? Obviously I could just run the commands myself or use any variant of *make but that's not the point.

答:
When you pass a library to g++ with -l, g++ helpfully prefixes the name you give with lib then looks for a file of that name with a .so or .a extension on the library search path. By convention, shared libraries (dlls) have the .so extension and static libraries the .a extension.

The route of least resistance would be to build your library with the .a extension, i.e. libuv.a then specify it to the VCLinux project library dependencies as uv. And specify the library search path with -L, as you do in your step 1.

Alternatively, you can put the full path of the library on the g++ link command line, without -l prefix, i.e. /home/devbox/projects/lib/libuv.lib and g++ will use it in the same way it uses other object files. Set via Linker/All Options/Additional Options.

Update: on reflection, this second approach won't work. Although g++ (gcc) will accept the library as an input when specified with its fully qualified path, the library must appear after the program object files for references to be resolved. Unfortunately there is no control over positioning of Additional Options in VCLinux which always puts them at the front of the parameter list on the g++ command line, i.e. before the object file(s). :(

And, at the risk of stating the obvious, the library must be built on Linux with g++ and be located on a path visible to g++ when linking your program.

Body:
I'm using the Visual C++ for Linux plugin. I can run a basic Hello world without problems. My actual project uses a .lib. It compiles fine but I get an error during linking (this is copied from Visual Studio's output pane):

ClCompile:
  Starting remote build
  Compiling sources:
  Invoking g++
  g++ -c -x c++ /home/devbox/projects/LinuxProgServ/LinuxProgServ/main.cpp -I /home/devbox/projects/LinuxProgServ/include/libuv -I /home/devbox/projects/LinuxProgServ/../include/lubuntu -I "/home/devbox/projects/LinuxProgServ/../include/lubuntu/x86_64-linux-gnu" -g2 -gdwarf-2 -o "/home/devbox/projects/LinuxProgServ/obj/x64/Debug/main.o" -Wall -Wswitch -W"no-deprecated-declarations" -W"empty-body" -Wconversion -W"return-type" -Wparentheses -W"no-format" -Wuninitialized -W"unreachable-code" -W"unused-function" -W"unused-value" -W"unused-variable" -O0 -fno-strict-aliasing -fno-omit-frame-pointer -fthreadsafe-statics -fexceptions -frtti -std=c++11
  main.cpp
  Done compiling '/home/devbox/projects/LinuxProgServ/LinuxProgServ/main.cpp'
Link:
  Linking objects
  Invoking ld
  g++ -o "/home/devbox/projects/LinuxProgServ/bin/x64/Debug/LinuxProgServ.out" -Wl,--no-undefined /home/devbox/projects/LinuxProgServ/obj/x64/Debug/main.o -llibuv.lib
  /usr/bin/ld: cannot find -llibuv.lib
  collect2: error: ld returned 1 exit status

libuv.lib is specified in Project Properties>Linker>Input>Library Dependencies. I tried the following without success:

Copy the lib to /home/devbox/projects/lib and add that directory to

the linker command with -L, both using Visual Studio's additional

library folder field and directly in the Additional command line

options field. This results in the same final command.

Copy the lib to the output directory and set it to be copied

Add the local Windows path to Visual Studio's additional library folders

Add the linux path from #1 to Visual Studio's additional library folders

Try with another library

I made the same project but for Windows just to be sure and it works.

Am I missing something? Obviously I could just run the commands myself or use any variant of *make but that's not the point.


问:
Structural type to mirror a Java static method
Given a third party Java library with the call

```<code>public static Bar Foo()
</code>```

Can I define a structural type to represent this? The following doesn't type match, as it doesn't capture the static nature.

```<code>val fooBar: { def Foo: Bar }
</code>```

Of course, I can always wrap this call in something else & that's what I'll do if necessary. But, is there a syntax that will define a type for this method?

答:
Scala doesn't have static so you can't define it. There are object that behave like static but they are not exactly the same.

You may keep trying but you will inevitably end up with Object is not a value error.

Body:
Given a third party Java library with the call

public static Bar Foo()

Can I define a structural type to represent this? The following doesn't type match, as it doesn't capture the static nature.

val fooBar: { def Foo: Bar }

Of course, I can always wrap this call in something else & that's what I'll do if necessary. But, is there a syntax that will define a type for this method?


问:
Add a text file in a jar file using powershell
Has anyone tried to add a text file to a jar file within a jar file using powershell?

For example, I need to add a sample.txt file inside a jar file that is inside a jar file.

Is there a creative way to do that in Powershell?

答:
You can just do:

jar -u file.jar file.txt


问:
Use of unassigned local variable after going through a list
```<code>List <State> states = JsonConvert.DeserializeObject <List<State>> (json);

State state;
foreach(State i in states) {
if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) {
    state = i;
    }
else {}
}

try {
    btnApprove.Visible = state.Actions.Approved.NextStateID != null ? true : false;
    btnApprove.Text = state.Actions.Approved.Title.ToString();
}
catch (Exception ex) {
    btnApprove.Visible = false;
}
</code>```

"state" in "state.Actions.Approved.NextStateID != null ? true : false;" is giving the "use of unassigned local variable" even though it assigned.

答:
The state variable would be unassigned if:

the states list is empty, or

the condition if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) is false for all states in the list.

You need to initialize the state variable to null (or better yet a valid state value) to avoid the compiler warning.

Body:
List <State> states = JsonConvert.DeserializeObject <List<State>> (json);

State state;
foreach(State i in states) {
if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) {
    state = i;
    }
else {}
}

try {
    btnApprove.Visible = state.Actions.Approved.NextStateID != null ? true : false;
    btnApprove.Text = state.Actions.Approved.Title.ToString();
}
catch (Exception ex) {
    btnApprove.Visible = false;
}

"state" in "state.Actions.Approved.NextStateID != null ? true : false;" is giving the "use of unassigned local variable" even though it assigned.


问:
How to get message info by ID [Telegram API]
I'm writing bot for telegram to gather some stats from group chat. I need to get info about every message (from the beginning of chat). I know how can i do it, but it's a quite bad idea. I can use forwardMessage method, but i need second acc for it and i'm getting timeouted when i'm sending messages too fast (for one hour), so it's a bit long way to collect stats for conversation that has over 2 million messages ;s I tried to set limit on 10 messages per second but i'm still getting timeouted, so idk how it works.
There must be other way to get JUST message info by id without forwarding it ;v I can't find it in API.</p>

答:
There has no API to do this at this time, you can suggest this idea to @BotSupport, before them added this feature, I am doing same thing like you.

According to Bot FAQ, Telegram API rate limit 1/s pre chat, and global limit is 30/s.


问:
Google Gantt chart with milliseconds scale, instead of seconds scale
I am creating a Gantt chart representing computer processes instead of human processes, so the scale is at the millisecond level.

https://developers.google.com/chart/interactive/docs/gallery/ganttchart

Does anyone know if it's possible to create a Google Gantt Chart representing the millisecond scale?

What I am thinking of doing is just multiplying all my values by 1000 and then mapping them to seconds, but the problem with that is that the chart will then by labeled as seconds, which is kinda annoying.

答:
This is trickier than I thought. Not sure if this will help anyone, please follow closely.

Say we have a timestamp to the milliseconds like so: 1499211060169.

To scale from milliseconds to seconds, you cannot just multiply a unix timestamp by 1000 (obviously). What you need to do, is take the seconds from the timestamp, and store that as foo, (effectively taking the floor of timestamp at the seconds place, and dropping any milliseconds). Separately, take the milliseconds from the timestamp, and multiply by 1000, store that as bar. To get your scaled value, sum foo and bar.

So that looks like:

```<code>original value: 1499211063169
seconds value:  1499211063000
milliseconds: 169
milliseconds scaled: 169000

scaled value: 169000 + 1499211063000 => 1499211232000
</code>```

It makes sense that the last 3 digits are 000, when you think about it.
Because we need to scale this thing to the second, because whatever system we are using is not granular to the millisecond.

Body:
This is trickier than I thought. Not sure if this will help anyone, please follow closely.

Say we have a timestamp to the milliseconds like so: 1499211060169.

To scale from milliseconds to seconds, you cannot just multiply a unix timestamp by 1000 (obviously). What you need to do, is take the seconds from the timestamp, and store that as foo, (effectively taking the floor of timestamp at the seconds place, and dropping any milliseconds). Separately, take the milliseconds from the timestamp, and multiply by 1000, store that as bar. To get your scaled value, sum foo and bar.

So that looks like:

original value: 1499211063169
seconds value:  1499211063000
milliseconds: 169
milliseconds scaled: 169000

scaled value: 169000 + 1499211063000 => 1499211232000

It makes sense that the last 3 digits are 000, when you think about it.
Because we need to scale this thing to the second, because whatever system we are using is not granular to the millisecond.