How to use the getline command in c++?

Question: I'm trying to turn a cout command into a getline command in c++.
This is my code that I'm trying to changes....
for (int count=0; count < numberOfEmployees; count++)
    {
        cout << "Name: ";
        cin >> employees[count].name;

        cout << "Title: ";
        cin >> employees[count].title;

        cout << "SSNum: ";
        cin >> employees[count].SSNum;

        cout << "Salary: ";
        cin >> employees[count].Salary;

        cout << "Withholding Exemptions: ";
        cin >> employees[count].Withholding_Exemptions;
    }

I'm trying to change this line: cin >> employees[count].name; and this line: cin >> employees[count].title; into getlines. Can anyone help?
Thanks
Comment: `getline(cin, employees[count].name)`?
Comment: @R.MartinhoFernandes: That's not enough, the whitespace remaining after the previous input will terminate the line immediately.  Let's close as dupe; this has been explained before.
Comment: @Ben Oh. I don't think I ever mixed line-based input with "regular" input, as I never ran into that. You're right, that's probably what's "not working" here.
Comment: possible duplicate of [Need help with getline()](http://stackoverflow.com/questions/1744665/need-help-with-getline) and http://stackoverflow.com/questions/2039918/stdgetline-does-not-work-inside-a-for-loop and http://stackoverflow.com/questions/4067256/how-do-i-stop-program-from-skipping-over-getline and http://stackoverflow.com/questions/5739937/using-getlinecin-s-after-cin
Answer: Flushing Problems with cin.getline() in C++
When you want to remove extraneous characters from an input stream in C++, it's usually because you mixed formatted and unformatted input methods. The formatted method would leave a newline in the stream and the unformatted method would consume it and terminate successfully, but fail completely to do what you wanted.
    #include <iostream>
 int main() {
std::cout<<"Enter the letter A: ";
 std::cin.get();
std::cout<<"Enter the letter B: ";
  std::cin.get();
std::cout<<"Too late, you can't type anymore\n";
 }

Often this question stems from another question, which is how to pause a program before it terminates. Using cin.get() works only when there are no characters left in the stream. The instant you throw a cin>> foo; in the code, suddenly the solution fails. You need to clear out any leftover characters from the stream before it'll work again.
So how do you fix the problem? The good news is that unless you want to get picky, it's as simple as a loop:
 C++ Syntax (Toggle Plain Text)
    #include <istream>
 void ignore_line ( std::istream& in ) {
  char ch;
        while ( in.get ( ch ) && ch != '\n' );
 }

This loop simply reads characters until end-of-file or a newline is read. It's generally assumed that interactive input in C++ is line-oriented and you're guaranteed to have a clean buffer after reading a newline. While that's not true (input doesn't have to be line-oriented), it's wide spread enough that we can assume it for the purposes of this thread.
So what's wrong with this approach? Nothing. In fact, this is about as good as it gets unless you want to dig down and fix the subtle problems. But before we look at the problems, here's an alternative solution that does the same thing in a different way:
    #include <ios>
    #include <istream>
    #include <limits>
void ignore_line ( std::istream& in ) {
in.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
 }

The ignore member function of std::istream will read and discard up to N characters or until a delimiter. In the above example, N is represented by the largest value of the streamsize data type, and the delimiter is a newline. It works equally well with just a large value (80 is common): C++ Syntax (Toggle Plain Text) in.ignore ( 80, '\n' ); However, the streamsize data type is more likely to be an accurate representation of the size of the buffer that the stream is using, and it's more likely to work all of the time. This is the solution that I recommend.
So what's wrong with this? There are two notable problems. The first is easy to fix, and it stems from the fact that istream isn't very flexible. istream is actually a typedef for basic_istream. If you want a wide stream to work with ignore_line, you're SOL with istream. So the trick is to use basic_istream<> instead:
    #include <ios>
    #include <istream>
    #include <limits>
template <typename CharT>
void ignore_line ( std::basic_istream<CharT>& in ) {
  in.ignore ( std::numeric_limits<std::streamsize>::max(), in.widen ( '\n' ) );
}

Now ignore_line is a template function that will derive the type of characters that the stream contains from the first argument. You can pass any stream that derives from or specializes basic_istream, and the problem is gone. Instead of just '\n', it's a good idea to use widen on the literal so that it will be properly converted to a wider type if necessary. Nice and easy.
The second problem is harder. Much harder. It's harder because standard iostreams seem to block your way at every turn with lack of portability or undesired features. In fact, it's impossible to completely fix the problem. The problem is that the behavior is different depending on the contents of the stream. For example:
    #include <iostream>
    #include <ios>
    #include <istream>
    #include <limits>
 template <typename CharT>
void ignore_line ( std::basic_istream<CharT>& in ) {
  in.ignore ( std::numeric_limits<std::streamsize>::max(), in.widen ( '\n' ) );
 }
 int main() {
 std::cout<<"First input: ";
  std::cin.get();
 std::cout<<"Clearing cin.\n";
  std::cin.clear();
ignore_line ( std::cin );
  std::cout<<"All done.\n";
}

Run this program three times:
Input: "asdf" Output: The program finishes without any more input from you.
Input: Just hit Enter Output: The program waits for you to hit Enter one more time.
Input: Signal EOF Output: The program waits for you to hit Enter one more time.
The problem is that the stream is empty. If you hit Enter immediately, a newline is placed on the stream and consumed by cin.get. Likewise with signaling EOF. At that point there's nothing left in the stream and cin.ignore stops everything until you type more characters. This is because cin.ignore is a blocking read. If there's nothing to read, it waits.
What we'd like it to do is not block for any of those three cases. The good news is that the iostream library supports some possible solutions. The bad news is that these are dead ends. Here are two common ones:
The sync member function The istream class supports a member function called sync. Why it has such a function is under debate, because nobody can agree on what it should be doing. Even Bjarne Stroustrup himself incorrectly stated that it discards all characters in the stream:
  #include <iostream>
 int main() {
std::cout<<"First input: ";
 std::cin.get();
std::cout<<"Clearing cin.\n";
 std::cin.clear();
std::cin.sync();
std::cout<<"All done.\n";
}

When this works, it works beautifully. The bad news is that the C++ standard doesn't require sync to do anything like discarding extraneous characters. This solution is non-portable.
The in_avail member function The next step is to look at the in_avail member function of istream's stream buffer. At first glance it looks like this member function will tell you how many characters are in the stream, and if it returns 0, you can refrain from calling ignore:
  #include <iostream>
    #include <ios>
    #include <istream>
    #include <limits>
 template <typename CharT>
void ignore_line ( std::basic_istream<CharT>& in ) {
   if ( in.rdbuf()->in_avail() > 0 )
        in.ignore ( std::numeric_limits<std::streamsize>::max(), in.widen ( '\n' ) );
 }
 int main() {
  std::cout<<"First input: ";
  std::cin.get();
std::cout<<"Clearing cin.\n";
  std::cin.clear();
 ignore_line ( std::cin );
  std::cout<<"All done.\n";
 }

As with sync, when this works, it works great. But once again, the standard raises a wall by saying that in_avail isn't required to give you an accurate representation of the characters in the stream. In fact, some popular implementations have a strictly conforming in_avail that always returns 0. Not very useful. Now we have to get creative.
The putback member function
 #include <iostream>
    #include <ios>
    #include <istream>
    #include <limits>
  template <typename CharT>
 void ignore_line
 ( std::basic_istream<CharT>& in ) {
  if ( !in.putback ( in.widen ( '\n' ) ) )
        in.ignore ( std::numeric_limits<std::streamsize>::max(), in.widen ( '\n' ) );   else
        in.ignore(); }
int main()
{   std::cout<<"First input: ";
std::cin.get();
std::cout<<"Clearing cin.\n";
  std::cin.clear();
 ignore_line ( std::cin );
 std::cout<<"All done.\n";
 }

This looks very promising because at first glance, it seems that you can attempt to push back a newline. If the operation fails, the last read character wasn't a newline and you're free to call ignore without blocking. If the operation succeeds, the newline is back and you can remove it with a single character ignore.
Sadly, it doesn't work. putback isn't not required to do any of this predictably, which raises the question of why it's even available.
But putback actually takes us close to a solution that seems plausible enough to work most of the time. Instead of relying on putback to fail or not, we can guarantee that the last read character is put back by using the sungetc member function of the stream's buffer. The trick is to unget the last character, then read it again and test it against a newline:
  #include <iostream>
    #include <ios>
    #include <istream>
    #include <limits>
 template <typename CharT>
 void ignore_line ( std::basic_istream<CharT>& in ) {
  if ( in.rdbuf()->sungetc() != std::char_traits<CharT>::eof()
        && in.get() != in.widen ( '\n' ) )   {
        in.ignore ( std::numeric_limits<std::streamsize>::max(), in.widen ( '\n' ) );
 }
}
int main() {
std::cout<<"First input: ";
 std::cin.get();
std::cout<<"Clearing cin.\n";
std::cin.clear();
ignore_line ( std::cin );
std::cout<<"All done.\n";
 }

The reason we use sungetc instead of istream's unget is because unget returns the stream, but sungetc returns either the character that was pushed back, or EOF. This way we can tell if the function failed or not more easily.
If sungetc fails, one of the following will be true:
1) The stream is in an error state. 2) There are no characters to unget. 3) The stream doesn't support ungetting characters.
If sungetc succeeds, there will always be a character to read and test against the newline. If that character matches a newline, then the last read character was also a newline and we don't need to call ignore. If the character doesn't match, then a full line hasn't been read and we can safely call ignore without blocking.
If the stream is in an error state, that's something the calling code has to deal with. If there are no characters to unget, then that's precisely what this solution is designed to properly handle. But, if the stream doesn't support ungetting characters, that's an issue. The ignore_line function will always fail to discard characters, so for those implementations that don't support ungetting characters, we can add a flag that forces an ignore. It's sometimes useful to know how many characters were ignored as well, so let's add that too and we have the final solution:
   #include <ios>
    #include <istream>
    #include <limits>
template <typename CharT>
std::streamsize ignore_line (   std::basic_istream<CharT>& in, bool always_discard = false ) {
  std::streamsize nread = 0;
        if ( always_discard || ( in.rdbuf()->sungetc() != std::char_traits<CharT>::eof()
        && in.get() != in.widen ( '\n' ) ) )
 {
        // The stream is good, and we haven't
        // read a full line yet, so clear it out
        in.ignore ( std::numeric_limits<std::streamsize>::max(), in.widen ( '\n' ) );
        nread = in.gcount();   }
        return nread;
}

Just for good measure, I'll also include a manipulator that calls ignore_line and also a manipulator that uses ignore_line to pause the program. That way the unwashed masses can stop using system ( "PAUSE" ); and getch();:
  class ignoreline {
  bool _always_discard;
   mutable std::streamsize _nread;
public:
 ignoreline ( bool always_discard = false )
        : _always_discard ( always_discard ), _nread ( 0 )   {}
        std::streamsize gcount() const { return _nread;
 }
        template <typename CharT>
 friend std::basic_istream<CharT>& operator>> (        std::basic_istream<CharT>& in, const ignoreline& manip )
 {
        manip._nread = ignore_line ( in, manip._always_discard );
        return in;
 }
};
 class pause {
  ignoreline _ignore;
public:
pause ( bool always_discard = false )        : _ignore ( always_discard )   {}
        std::streamsize gcount()
const { return _ignore.gcount();
}
        template <typename CharT>
  friend std::basic_istream<CharT>& operator>> (        std::basic_istream<CharT>& in, const pause& manip )
{
        if ( !( in>> manip._ignore ) )
          in.clear();

        std::cout<<"Press Enter to continue . . .";

        return in.ignore();
 }
};

Now all three cases behave identically:
     int main()
{   std::cout<<"First input: ";
  std::cin.get();
std::cout<<"Clearing cin.\n";
 std::cin>> ignoreline();
 std::cout<<"All done.\n";
 std::cin>> pause();
 }

And the moral of the story is: It's never as simple as it seems, writing portable code that does what you want is extremely difficult, and the iostream library is a huge mess.
NOTE: If you are a beginner forget everything and just understand there is a flushing problem and use cin
Comment: Thank you for this answer! It is ridiculous that an everyday problem like this has such a complicated solution.
Comment: NOTE: If u r beginner forget everything about cin.getline and just understand there is a flushing problem and use cin
Answer: Taking a look at the getline prototype, you'll see that you need two things:

An istream object
A string to for the result
(optionally) the "new line" delimiter (default is '\n'.

In your case, it seems that the delimiter might be the default: '\n'; if not, you can specify what character separates each value (maybe it's a space ' ' or something). The cin stream would be you istream object, and each of the properties of employees[count] will serve as the second parameter. In summary, getline(cin, employees[count].name); should do the trick.
Answer: You can use getline function that takes input stream as first argument. It's prototype looks like this: basic_istream<...>& getline(basic_istream<...>& _Istr, basic_string<...>& _Str)
But then you have to think about that you are dealing with std::string and parse it as a type that you actually need (char*, int, whatever):
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//...

for (int count=0; count < numberOfEmployees; count++)
{
    string name, title, sSSnum, sSalary, s;

    cout << "Name: ";
    getline(cin, name);
    employees[count].name = name.c_str();

    cout << "Title: ";
    getline(cin, title);
    employees[count].title = name.c_str();

    cout << "SSNum: ";
    getline(cin, sSSnum);
    istringstream is(sSSnum);
    is >> employees[count].SSNum;

    cout << "Salary: ";
    getline(cin, sSalary);
    is.clear();
    is.str(sSalary);
    is >> employees[count].Salary;
    //...
}

Answer: for (int count=0; count < numberOfEmployees; count++)
    {
        cout << "Name: ";
       cin.getline (employees[count].name,100);

        cout << "Title: ";
        cin.getline (employees[count].title,100);

        cout << "SSNum: ";
       //error cin.getline (employees[count].SSNum);
       cin>>employees[count].SSNum;

        cout << "Salary: ";
        // error cin.getline( employees[count].Salary);
        cin>>employees[count].Salary;

        cout << "Withholding Exemptions: ";
       //error cin.getline (employees[count].Withholding_Exemptions);
       cin>>employees[count]..Withholding_Exemptions;
    }

Answer: istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
Get line from stream
Extracts characters from the input sequence and stores them as a c-string into the array beginning at s.
Characters are extracted until either (n - 1) characters have been extracted or the delimiting character is found (which is delim if this parameter is specified, or '\n' otherwise). The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation.
If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it. If you don't want this character to be extracted, you can use member get instead.
The ending null character that signals the end of a c-string is automatically appended to s after the data extracted.
The number of characters read by this function can be obtained by calling to the member function gcount.
A global function with the same name exists in header . This global function provides a similar behavior, but with standard C++ string objects instead of c-strings: see getline (string).
Parameters
s
A pointer to an array of characters where the string is stored as a c-string.
n
Maximum number of characters to store (including the terminating null character).
This is an integer value of type streamsize.
If the function stops reading because this size is reached, the failbit internal flag is set.
delim
The delimiting character. The operation of extracting successive characters is stopped when this character is read. This parameter is optional, if not specified the function considers '\n' (a newline character) to be the delimiting character.
Return Value
The function returns *this.
MSDN EXAMPLE:
// istream getline
#include <iostream>
using namespace std;

int main () {
  char name[256], title[256];

  cout << "Enter your name: ";
  cin.getline (name,256);

  cout << "Enter your favourite movie: ";
  cin.getline (title,256);

  cout << name << "'s favourite movie is " << title;

  return 0;
}

And for your situation with structure object, u have to use the objectname.datamember to access objects data:
for (int count=0; count < numberOfEmployees; count++)
    {
        cout << "Name: ";
       cin.getline (employees[count].name,100);

        cout << "Title: ";
        cin.getline (employees[count].title,100);

        cout << "SSNum: ";
        cin.getline (employees[count].SSNum);

        cout << "Salary: ";
        cin.getline( employees[count].Salary);

        cout << "Withholding Exemptions: ";
       cin.getline (employees[count].Withholding_Exemptions);
    }

Comment: When I do that for the name and title, the program starts, but it displays "Name" and "Title" at the same time and only records the title. WHat wrong?
Comment: its the Flushing problem. If u really wanna know read through the answer!!
Comment: better use cin so that u can leave out thinking of getting the input in the required formats

How to use the getline command in c++?


Discrete Random Variable; Finding Probability of X=Y

Question: Let $X$ be a discrete random variable uniformly distributed on the integers $1,...,n$ and $Y$ on the integers $1,...,m$. Where $0 < n ≤ m$ are integers. Assume $X$ and $Y$ are independent.
What is the probability $X = Y$?
 I know how to the majority of the set up, the only thing I don't get is let's say $k$ is the number that $X = k = Y$.  What is $\Pr(X=k)$ and $\Pr(Y=k)$?  We would need these to for the computation but I am not sure how to get these.
Comment: You are confusing the discrete uniform distribution with the continuous uniform distribution. See https://en.wikipedia.org/wiki/Discrete_uniform_distribution .
Comment: It is mentioned that the random variables are 'uniformly' distributed implying that $X$ assumes all values from $1$ to $n$ with equal probability. Similarly for $Y$ on $1$ to $m$. Can you now figure out those probabilities?
Comment: Would it be $\frac{1}{n-1}$ and $\frac{1}{m-1}$ for X and Y?
Comment: It would be $1/n$ and $1/m$ for $X$ and $Y$ respectively since there are $n$ and $m$ elements in the sets respectively.
Comment: A uniform disturbution is $\frac{1}{b-a} where a < x <b so wouldn't it be  1 < x < n?
Comment: @LeanderTilstedKristensen is correct. Another way to see this is as follows. There are $n$ possible values that $X$ can take, all with equal probability. Since their sum has to be $1$, the probability of each of them as to be $1/n$ and not $1/(n-1)$.
Answer: For all $i \in \{1,\dots, n\}$ and $j \in \{1,\dots, m\}$ we have $P(X=i,Y=j) = \frac{1}{nm}$ and therefore
$$P(X=Y) = \sum_{i=1}^n P(X=i,Y=i) = \sum_{i=1}^n \frac{1}{nm} = \frac{1}{m}$$


Xml Serialization - Render as

Question: I am using the XmlSerializer and have the following property in a class
public string Data { get; set; }

which I need to be output exactly like so since There's a parser at client expecting like this
<Data></Date>

When the value is null
How would I go about achieving this?
Right Now I am getting like
<Data/>

Answer: Just use XMLElementAttribute
[XmlElement(ElementName = "Data")]
public string Data { get; set; }

Comment: You can ommit the `ElemenName` within the attribute as by default the properties name itself is written.

Xml Serialization - Render as


Problema com jQuery scrollTop() no chrome

Question: Fala pessoal.
Estou com o seguinte problema, tenho um código que identifica quando ocorreu um scroll da página para poder subir o meu menu lateral ao ser realizado um scroll. Funciona no IE e no FireFox porém não funciona no Chrome.
Segue o exemplo de código.

Com isso obtive os seguintes resultados.
Firefox e IE =

scrolled $(body).scrollTop() = 270
scrolled $(document).scrollTop() = 0
scrolled $(window).scrollTop() = 0
scrolled $('html').scrollTop() = 0
scrolled $('html, body').scrollTop() = 0
scrolled $('html, body', document).scrollTop() = 0

Chrome =

scrolled $(body).scrollTop() = 0
scrolled $(document).scrollTop() = 0
scrolled $(window).scrollTop() = 0
scrolled $('html').scrollTop() = 0
scrolled $('html, body').scrollTop() = 0
scrolled $('html, body', document).scrollTop() = 0

Alguém sabe o porque disso ou se existe outra maneira de conseguir esse mesmo resultado sem usar o scrollTop ?
Solução
Galera, após explorar um pouco mais e analisar as sugestões cheguei na seguinte solução.

Desisti do uso do scrollTop() pois estava apresentando um comportamento muito instável o que não é bom para aplicação.
Valeu a todos!
Comment: Veja se aqui te ajuda. http://pt.stackoverflow.com/questions/47462/fazer-else-em-jquery-para-controlar-scrolltop/47593#47593
Comment: tente utilizando a propriedade nativa `window.scrollY`, além disso o correto é atribuir o evento `scroll` ao elemento `window`
Comment: @Sanção a propriedade `window.scrollY` também fica retornando `0`.
Comment: Valeu galera. Com base nas sugestões e respostas cheguei a uma solução possível que coloquei no corpo da pergunta para ajudar outras pessoas.
Answer: Galera, após explorar um pouco mais e analisar as sugestões cheguei na seguinte solução.

Desisti do uso do scrollTop() pois estava apresentando um comportamento muito instável o que não é bom para aplicação.


Solving: $\int_{-\infty}^{+\infty}e^{-2i\pi xy-\pi x^2/r^2}dx$

Question: I would like to solve:$$\int_{-\infty}^{+\infty}e^{-2i\pi xy-\pi x^2/r^2}dx$$
Where $i$ is the imaginary unit, and $y,r$ are constants.
I've used Wolfram to get $re^{-\pi r^2 y ^2}$. Any way of solving it step-by-step?
Comment: By following his solution I get the answer $re^{-r^2x^2/(2\pi)}$, with $\beta=\pi /r^2$ in his $G_{\beta}(\omega)$. Which is not the answer I have. Or perhaps I'm doing something wrong?
Comment: Nevermind I found it: http://mathworld.wolfram.com/FourierTransformGaussian.html Thank you it helped a lot
Answer: Call this function $f(y)$ so $f(0)=r$ from the usual Gaussian integral. We need only show $f'(y)=-2\pi r^2 y f(y)$. Integrating by parts, $$f'(y)=-2\pi i\int_\mathbb{R}x\exp(-2\pi ixy-\frac{\pi x^2}{r^2})dx=-2\pi r^2y\int_\mathbb{R}\exp(-2\pi ixy-\frac{\pi x^2}{r^2})dx.$$
Comment: what do you mean by "Call this function" $f(y)$? You mean the whole integral? And y is a constant. Are you making it a variable?
Comment: @Maximus That's exactly what I'm doing.
Comment: I understand that part but why is it only necessary to show that "$f'(y)=-2\pi r^2 y f(y)$" I am confused how this gives the original solution.
Comment: Because the desired result is the unique solution to that differential equation satisfying $f(0)=r$.
Comment: Ah I see, I found a simpler answer which is what you are saying as well: http://mathworld.wolfram.com/FourierTransformGaussian.html


PHP Twitter API search/tweets GET tweets from last hour ONLY

Question: Hi I have been looking around on the internet and haven't been able to find a solution yet. I want to only get the tweets from the past hour which have a certain hashtag.
I am pulling the tweets in with that hashtag but I dont know how to only get the ones from the past hour.
Here is some example data:

As you can see there is a created_at date there but I dont know how to use this to get the ones from the past hour. I think this would be the only way that I would be able to do it.
The best way I can think of doing it is converting that date into a UNIX timestamp and then checking if it was tweets in the last hour. But there is a lot of data to go through and this doesnt seem like a very good solution but its all I cant think of.
If that is the only solution there is, would some given me an example on how to convert that date to a UNIX timestamp in PHP. If you have a different solution I would love to see a detailed example :) Thanks
You may also find this link useful https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
Answer: I couldn't find an alternative solution neither so I coded it. The WINDOW constant defines the time interval to 1 hour. Hope it helps!
<?php
//Access token & access token secret
define("TOKEN", 'XXXXXXXXXXXXXXXX'); //Access token
define("TOKEN_SECRET", 'XXXXXXXXXXXXXXXX'); //Access token secret
//Consumer API keys
define("CONSUMER_KEY", 'XXXXXXXXXXXXXXXX'); //API key
define("CONSUMER_SECRET", 'XXXXXXXXXXXXXXXX'); //API secret key

$method='GET';
$host='api.twitter.com';
$path='/1.1/search/tweets.json'; //API call path
$url="https://$host$path";
//Query parameters
$query = array(
    'q' => 'wordtosearch',          /* Word to search */
    'count' => '100',               /* Specifies a maximum number of tweets you want to get back, up to 100. As you have 100 API calls per hour only, you want to max it */
    'result_type' => 'recent',      /* Return only the most recent results in the response */
    'include_entities' => 'false'   /* Saving unnecessary data */
);
//time window in hours
define("WINDOW", 1);

//Authentication
$oauth = array(
    'oauth_consumer_key' => CONSUMER_KEY,
    'oauth_token' => TOKEN,
    'oauth_nonce' => (string)mt_rand(), //A stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);
//Used in Twitter's demo
function add_quotes($str) { return '"'.$str.'"'; }

//Searchs Twitter for a word and get a couple of results
function twitter_search($query, $oauth, $url){
    global $method;

    $arr=array_merge($oauth, $query); //Combine the values THEN sort
    asort($arr); //Secondary sort (value)
    ksort($arr); //Primary sort (key)
    $querystring=http_build_query($arr,'','&');
    //Mash everything together for the text to hash
    $base_string=$method."&".rawurlencode($url)."&".rawurlencode($querystring);
    //Same with the key
    $key=rawurlencode(CONSUMER_SECRET)."&".rawurlencode(TOKEN_SECRET);
    //Generate the hash
    $signature=rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
    //This time we're using a normal GET query, and we're only encoding the query params (without the oauth params)
    $url=str_replace("&","&",$url."?".http_build_query($query));
    $oauth['oauth_signature'] = $signature; //Don't want to abandon all that work!
    ksort($oauth); //Probably not necessary, but twitter's demo does it
    $oauth=array_map("add_quotes", $oauth); //Also not necessary, but twitter's demo does this too
    //This is the full value of the Authorization line
    $auth="OAuth ".urldecode(http_build_query($oauth, '', ', '));
    //If you're doing post, you need to skip the GET building above and instead supply query parameters to CURLOPT_POSTFIELDS
    $options=array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                      //CURLOPT_POSTFIELDS => $postfields,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);
    //Query Twitter API
    $feed=curl_init();
    curl_setopt_array($feed, $options);
    $json=curl_exec($feed);
    curl_close($feed);
    //Return decoded response
    return json_decode($json);
};

//Initializing
$done = false;      //Loop flag
$countCalls=0;      //Api Calls
$countTweets=0;     //Tweets fetched
$intervalTweets=0;  //Tweets in the last WINDOW hour
$twitter_data = new stdClass();
$now=new DateTime(date('D M j H:i:s O Y')); //Current search time

//Fetching starts
do{
    $twitter_data = twitter_search($query,$oauth,$url);
    $countCalls+=1;
    //Partial results, updating the total amount of tweets fetched
    $countTweets += count($twitter_data->statuses);
    //Searching for tweets inside the time window
    foreach($twitter_data->statuses as $tweet){
        $time=new DateTime($tweet->created_at);
        $interval = $time->diff($now);
        $days=$interval->format('%a');
        $hours=$interval->h;
        $mins=$interval->i;
        $secs=$interval->s;
        $diff=$days*24 + $hours + $mins/60 + $secs/3600;
        if($diff<WINDOW){
            $intervalTweets+=1;
        }else{
            $done = true;
            break;
        }
    }
    //If not all the tweets have been fetched, then redo...
    if(!$done && isset($twitter_data->search_metadata->next_results)){
        //Parsing information for max_id in tweets fetched
        $string="?max_id=";
        $parse=explode("&",$twitter_data->search_metadata->next_results);
        $maxID=substr($parse[0],strpos($parse[0],$string)+strlen($string));
        $query['max_id'] = -1+$maxID; //Returns results with an ID less than (that is, older than) or equal to the specified ID, to avoid getting the same last tweet
        //Twitter will be queried again, this time with the addition of 'max_id'
    }else{
        $done = true;
    }
}while(!$done);

//If all the tweets have been fetched, then we are done
echo "
query: ".urldecode($query['q'])."
";
echo "
tweets fetched: ".$countTweets."
";
echo "
API calls: ".$countCalls."
";
echo "
tweets in the last ".WINDOW." hour: ".$intervalTweets."
";
?>


Migrating from libvirt + iptables to libvirt + nftables

Question: I'm about to migrate a Debian Stretch host using qemu-kvm to Debian Buster.
I've seen people complaining on the Internet about issues due to nftables becoming default in place of iptables and libvirt using iptables rules. Rules automatically written by libvirt are not understood by nftables.
I can move back to iptables after the upgrade if needed:
# update-alternatives --set iptables /usr/sbin/iptables-legacy
# update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy
# update-alternatives --set arptables /usr/sbin/arptables-legacy
# update-alternatives --set ebtables /usr/sbin/ebtables-legacy

Would that be enough to get my system running?

From the docs and this GH comment firewalld support was added in libvirt 5.1.0. And it is unclear to me whether the minimal firewalld version required for the whole thing to work is 0.6.0 or 0.7.0.
Here are the versions shipped by Debian:
firewalld

stretch 0.4.4.2-1
buster 0.6.3-5
bullseye 0.7.2-1

libvirt-daemon

stretch 3.0.0-4+deb9u4
buster 5.0.0-4
bullseye 5.6.0-2

So I guess things should be fine in bullseye. Except for the existing rules.
Is the following plan the way to go?

Migrate to Buster and stick to iptables using the update-alternatives trick above.
When Bullseye is out, migrate and stick to iptables for now.
Translate rules manually and migrate to nftables later.

Edit:
/etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# Local network
auto eth0
iface eth0 inet manual

auto br0
iface br0 inet static
    bridge_ports eth0
    bridge_maxwait 0
    address 192.168.10.27
    netmask 255.255.255.0
    gateway 192.168.10.1
    dns-nameservers 192.168.10.8 192.168.1.9 126.96.36.199
    dns-domain my_domain.local
    dns-search my_domain.local

# External network
auto eth1
iface eth1 inet manual

auto br1
iface br1 inet manual
    bridge_ports eth1
    bridge_maxwait 0

Comment: @A.B You're right about firewalld, I'm not using it. I got mislead by the phrasing "libvirt 5.1.0 has native integration with firewalld and as such works well with the nftables backend." in https://github.com/firewalld/firewalld/issues/397#issuecomment-518264850. This could be a wrong lead.
Comment: @A.B are you implying that I'm overthinking it and it should work fine out of the box? I didn't find much posts about such issues, so maybe they only affect corner cases.
Comment: Thaks @A.B. We setup a bridge in the host. The host had two network interfaces, one on the local network, the other one directly connected to the outside world. The host is only accessible internally, but the guest VMs inside are accessible from the Internet but not from the local network. I added the network config file to the question. We didn't do anything related to firewalling. And I don't think we did anything specific about firewall rules when configuring virtual machines.
Comment: Are there any iptables rules automatically created by libvirt? Where would they be? How can I check they work with nftables (or nftables + compat layer, this iss a bit blurry to me)? Is the compatibility be maintained temporarily? Do I need to convert some rules on the long run?
Comment: @JamesYoungman I just dit the Stretch -> Buster upgrade. I checked that iptables point to iptables-nft and firewalld is not installed. My old VM seem to work fine. I haven't tried to create a new VM yet. I don't know what a virtual network is so it is possible that I'm just not affected by the issue you posted above and by all those things I read on the Internet back then that made me fear the upgrade could get me into trouble.
Comment: How did you get on?   AFAICT, libvirt appears to be incompatible with systems that directly use nftables (but not firewalld): https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=994127    But if instead you do choose to use firewalld, you get a different problem: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=942368
Comment: @JamesYoungman Well I still haven't updated yet... I was willing to do it soon, blind update, fingers crossed and see how it goes, eventually using update-alternatives for legacy compatibility. Thanks for the links, I'll look into them.
Answer: The strategy I have taken on this is to migrate the filtering rules used for VMs from nftables to libvirt's nwfilter rules.   The effect of this is that libvirt manages iptables filters.   In effect this is a downgrade from nftables to iptables, but my hope is that libvirt will support a later migration to nftables.
Documentation here: https://libvirt.org/formatnwfilter.html
Comment: Since I've never creted a rule and I've only ever been using rules automatically created by libvirt (if any), I'm in fact wondering if I even need to do anything.


Proving the equality of 2 functions

Question: You are given that $f(n)=g(n, f(n-1))$ (some initial values given). Looking at the first few terms, it becomes obvious that $f(n)=h(n)$. How does one go about proving this?
Induction seemed obvious at first, but I found it hard applying induction to this type of problem (with recursive functions, so difficult to rearrange):

Hypothesis:$h(n)=g(n, f(n-1))$
Show that $h(t, f(t))=g(n, f(n-1))$ implies
  both
$(1)$ $g(1, f(1-1))=h(1),$ and
$(2)$ $h(n+1, f(n+1))=g(n+1, f(n-1+1))$?

I don't think $(2)$ is correct, as by the same logic you could prove $n^2=n^3$ by the fact that$(1)^2=(1)^3$ and that $n^2=n^3$ implies $(n+1)^2=(n+1)^3$. How is $(2)$ really done?
Is there another method besides induction more suited to this problem?
Comment: Do you mean that $f(n)=g(n,f(n-1))$?
Comment: Yes, I condensed notation incorrectly.
Answer: I'm going to assume that you meant that $f(n)=g\big(n,f(n-1)\big)$, as what you wrote attempts to define $f(n)$ in terms of itself.
What you need to do is show that $h$ satisfies the same initial conditions and recurrence as $f$. Presumably verifying that $h$ and $f$ satisfy the same initial conditions is not a problem. You have some $n_0$ such that $f$ satisfies the recurrence $f(n)=g\big(n,f(n-1)\big)$ for all $n\ge n_0$, so you must show that $h(n)=g\big(n,h(n-1)\big)$ for $n\ge n_0$. Your induction step will consist in letting $n>n_0$ be arbitrary, assuming as your induction hypothesis that $h(k)=g\big(k,h(k-1)\big)$ for $n_0\le k<n$, and somehow using this to show that $h(n)=g\big(n,h(n-1)\big)$.
Comment: Thanks- I was going the wrong way, trying to force $h(n)$ out of $g(n,f(n-1))$.
Comment: @Alyosha: You're welcome. (It sounds like you've got it, but it may help to think of it this way: you just want to show that $h$ and $f$ start in the same place and change in the same way from $n$ to $n+1$.)

Proving the equality of 2 functions


Run another command-line app from PowerShell

Question: I think this has been asked many times yet I can't find an answer that works for me.

I need to construct a command line from variables.
I need to run that command line executable.
I need to have the results spew out onto the same screen as my script.

I'm trying to run Putty SCP with a custom source and destination.
I've messed around with & and Invoke-Expression but its impossible. Some simple #1 use-case things in PowerShell are so incredibly hard they eat away at all that's good about it.
The only way I can see to do this is to run it within a new Process instance and setup all the output redirection and then pipe it back out on the PS screen after it finished.
And I know this could fail because the output buffer can get full unless you're hooked-into the events and are scooping it out.
The other way is to write my command line to a batch file and run that.
Any help appreciated. There has to be a simpler way.
Edit
For example:
[string]$scpPath = Find-PathToPuttyScpExecutable;
[string]$scpArguments = "-v -r -pw " + $MarkLogicServerPassword + " " + $MarkLogicSourcePath + " " + $MarkLogicServerUserName + "@" + $ServerName + ":" + $MarkLogicDestinationRootPath

I need to execute $scpPath + " " + $scpArguments.
Comment: Third way is to write a CmdLet in C# but although I've done this in the past, I want to avoid loading a module.
Comment: "I've messed around with & and Invoke-Expression but its impossible" - I'm pretty sure it's not. Post your code & point out what isn't working, and someone can try to help. Otherwise, this starts sounding like a rant.
Comment: post the exe name, its parameters you need and what variables you are plugging in and also mention where they go
Comment: Hmm/Grr. I tried to post a screen dump but the .png that Snipping Tool makes isn't understood by SO!
Comment: Screenshots of code are terrible anyway. Can't copy/paste, can't search.
Comment: I agree, although it wasn't really code as a trail of trial and errors at a console.
Answer: Don't get so attached to strings. Just run commands with arguments:
[string]$scpPath = Find-PathToPuttyScpExecutable;
&$scpPath -v -r -pw $MarkLogicServerPassword $MarkLogicSourcePath "$($MarkLogicServerUserName)@$($ServerName):$($MarkLogicDestinationRootPath)"

PowerShell will handle the quoting for you. In most cases it works well and I doubt you'll stumble over the edge cases here.
If you have to create the argument list on the fly, then you should use an array and pass that:
$scpArguments = '-v',
                '-r',
                '-pw',
                $MarkLogicServerPassword,
                $MarkLogicSourcePath,
                "$($MarkLogicServerUserName)@$($ServerName):$($MarkLogicDestinationRootPath)"

&$scpPath @scpArguments

Comment: I did not see that coming. Must adjust mental model. Thanks Joey.
Comment: Powershell needs either an array of string args or spaces between them on the line so it can tokenize them. A single string with spaces in it will be interpreted as a single token.


Opening a public folder item via code and confusion about ids

Question: After some reading I'm beginning to understand that there are multiple formats for the various ids used in exchange and Outlook.  I'm trying to clear up some confusion, here is the scenario.
We have a vendor product that is crawling public folder content in Exchange server and identifying messages that meet certain criteria.  When this software captures each message it stores an id that looks similar to the following:
AAIARgAAAAAAGkRzkKpmEc2byACqAC/EWgkAzDDxpv7lakqqtxgSLYsXTwAAAoOedgAA+v7vRoYnskqzbHwT4KwucwAAIH9adQAALgAAAAAAGkRzkKpmEc2byACqAC/EWgMAzDDxpv7lakqqtxgSLYsXTwAAAoOedgAA

I'm responsible for writing a WinForms application that presents these messages in a list and among other things allows them to open the message in Outlook.  For purposes of this question, you may assume the user has access to the message.
In looking through the Outlook API and inspecting the message properties it looks like the only id I can find there takes the form:
000000001A447390AA6611CD9BC800AA002FC45A0900CC30F1A6FEE56A4AAAB718122D8B174F000002839E760000FAFEEF468627B24AB36C7C13E0AC2E730000207F5A750000

I've read material that suggests these could be the same id expressed in different formats but have had no luck using the ConvertId operation in the EWS services.
Can anyone confirm whether these are truly different representations of the same id or completely different entities?  And whether it is possible to get from one to the other?
Answer: These are not the same ids - they are different ids referring to the same object.
If you are having problems with the ConvertId EWS separation, you might want to post a separate ConvertId specific question.


sbt 1.9 issue with spark 3.4.1 in Intellij with scala 3.3.0 version

Question: I have installed 1.9 SBT & intellij . now, I want to configure spark 3.4.1 version with 3.3.0 scala version in Intelliji by using below code in built.sbt

Is there any solution of it ??
Thank you

I was expecting it to get succeeed but encountered error
Comment: In IntelliJ, in the build panel, click on the 4 lines, one of them should have a more explicit error message. Or just run SBT from CLI.
Answer: There is no release published compatible with scala 3.3.0 for spark-core or any other version of spark-core.
Just changing
ThisBuild / scalaVersion := "3.3.0"

For
ThisBuild / scalaVersion := "2.13.11"

Should fix your problem. You can also use scala 2.12.x

You have these links to read more about that combination:

Scala 3 and Spark?

After the release of Scala 3, one of the most common questions asked by developers was: "When will we be able to write Spark jobs using Scala 3?".
Up till now, the answer was: "Not yet" but everything changed after the release of Spark 3.2.0, which brought Scala 2.13 support. Scala 3 projects can depend on Scala 2.13 libraries, so can we finally write Spark jobs using Scala 3? The answer is yes, in theory

github repo spark-scala3

This repository aims at making the adoption of Scala 3 easier for projects using Apache Spark
Comment: Thanks Gaston . I changed scala version to 2.13.11 and spark version of 3.2.2 with 1.9 sbt version and it worked for me.
Comment: spark `3.2.2` is a bit old. If you are starting a new project, I suggest to use the latest one. In case you need to deal with a legacy one, you can use the version you need for that. Just keep in mind to keep updated the version of your dependencies to avoid security issues and incompatibility between them


Filter collection by qty

Question: I try to filter a collection by quantity with:
$_productCollection->addAttributeToFilter('qty', array('gt' => 30));
but that doesn't work.
Can somebody give me a hint, to filter a product collection by quantity?
I also tried:
$stockCollection = Mage::getModel('cataloginventory/stock_item')->getCollection()
                             ->addFieldToFilter('qty', array('gt' => 99999999));
$entityIds = array();
foreach ($stockCollection as $item) {
    $entityIds[] = $item->getOrigData('product_id');
}

$_productCollection->addAttributeToFilter('id', array('in' => $entityIds));

The entityId array is empty, but the $_productCollection still returns products?!
Answer: Explanation:
You were close on your second attempt.  There's a special method for adding a qty filter in Mage_CatalogInventory_Model_Resource_Stock_Item_Collection
/**
 * Add filter by quantity to collection
 *
 * @param string $comparsionMethod
 * @param float $qty
 * @return Mage_CatalogInventory_Model_Resource_Stock_Item_Collection
 */
public function addQtyFilter($comparsionMethod, $qty)
{
    $methods = array(
        '<'  => 'lt',
        '>'  => 'gt',
        '='  => 'eq',
        '<=' => 'lteq',
        '>=' => 'gteq',
        '<>' => 'neq'
    );
    if (!isset($methods[$comparsionMethod])) {
        Mage::throwException(
            Mage::helper('cataloginventory')->__('%s is not a correct comparsion method.', $comparsionMethod)
        );
    }

    return $this->addFieldToFilter('main_table.qty', array($methods[$comparsionMethod] => $qty));
}

Solution:
$stockIds = Mage::getModel('cataloginventory/stock_item')
    ->getCollection()
    ->addQtyFilter('>=', 30)
    ->getAllIds();

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addIdFilter($stockIds)
    ->setPageSize(10);

Filter collection by qty


Montando um Web Scraping com Python

Question: tudo bem? Pois bem, sou um entusiasta de programção, e peguei um tutorial para fazer webscraping. A lógica eu até entendi, porém estou enfrentando um problema quando um dos dados estão faltando no site, abaixo deixo o código e minha analise do problema enfrentado:
import requests
from bs4 import BeautifulSoup

URL = "https://www.classcentral.com/subject/data-science"
page = requests.get(URL)

soup = BeautifulSoup(page.content, "html.parser")

Course = []
Duration = []
Start_Date = []
Offered_By = []
No_Of_Reviews = []
Rating = []

def find_2nd(string, substring):
    return string.find(substring, string.find(substring) + 1)

def find_1st(string, substring):
    return string.find(substring, string.find(substring))

for i in soup.findAll("span",{'class' : 'text-1 weight-semi line-tight'}):
    b = str(i)

    #print(b  [  find_1st(b,'>')+1  :  find_2nd(b,'<')  ]  )
    Course.append(b[find_1st(b,'>')+1:find_2nd(b,'<')])

course = []
for i in Course:
    i = i.strip()
    print(i)
    course.append(i)

# # Num of Reviews
for i in soup.findAll("span",{'class' : 'large-down-hidden block line-tight text-4 color-gray'}):
    b = str(i)
    print(b[find_1st(b,'>')+1:find_2nd(b,'<')])
    No_Of_Reviews.append(b[find_1st(b,'>')+1:find_2nd(b,'<')])

Pois bem, entrando no site e fazendo uma busca, existe um curso que encontra-se sem reviews. O problema disso tudo, é que quando vou transformar isso em um DataFrame, ocorre o erro de length. Ou seja, não consigo gerar o DataFrame, por causa desse valor faltante. Não coloquei o código completo para não ficar mais extenso, por que o restante esta dando certo.
Alguém saberia me ajudar ? Como faria para que o código entendensse que essa informação não existe, coloque o valor de 0 e continue com a implementação do código.
Answer: O que causa esse problema é que os elementos sem reviews e os elementos com várias reviews têm classes completamente diferentes. Seguem dois exemplos que eu tirei da página:
24 Reviews

No reviews yet.

Então eu modifiquei o programa pra checar se um elemento tem as classes do primeiro do exemplo, porque esse é o caso mais comum. Se não tiver, o programa procura por um elemento com as classes medium-down-hidden text-4 color-gray italic, porque isso indica que ele não tem nenhuma review.
Você também não precisa usar as funções find_1st e find_2nd pra ler o texto dentro do elemento span, porque é muito mais fácil digitar só nome_do_objeto.text. O resultado é o mesmo.
import requests
from bs4 import BeautifulSoup

URL = "https://www.classcentral.com/subject/data-science"
page = requests.get(URL)

soup = BeautifulSoup(page.content, "html.parser")

td_list = soup.findAll("td", {"class": "hide-on-hover fill-space relative"})
for i, td in enumerate(td_list):
    try: # Classe com > 0 reviews
        reviews = True
        my_span = td.findChildren("span", {"class" : "large-down-hidden block line-tight text-4 color-gray"})[0]
    except IndexError: # Classe com 0 reviews
        reviews = False
        my_span = td.findChildren("span", {"class" : "medium-down-hidden text-4 color-gray italic"})[0]

    output = " ".join(my_span.text.split())

    if reviews:
        print(i, "\t", output)
    else:
        print(i, "\t", output, "<-- No reviews!")

Comment: Nossa Krossbow, muito obrigado pela ajuda amigo. Obrigado mesmo.

Montando um Web Scraping com Python


Unable to Invoking a Skill with a Specific Request from echosim.io

Question: Here is the Alexa Skill code:
'use strict';
const Alexa = require("alexa-sdk");

exports.handler = function(event, context, callback) {
    console.log("skill-sample-nodejs-hello-world Received an event");
    console.log("event=");
    console.dir(event);
    const alexa = Alexa.handler(event, context);
    alexa.registerHandlers(handlers);
    alexa.execute();
};

const handlers = {
    'LaunchRequest': function () {
        console.log("LaunchRequest called()");
        this.response.speak('Hello World Init!').listen("I am listening SayHelloInit");
        this.emit(':responseReady');
        //this.emit('SayHelloInit');
    },
    'HelloWorldIntent': function () {
        console.log("hello world intent called");
        this.response.speak('Hello World How are you!').listen("I am listening sayhello");
        this.emit(':responseReady');
        //this.emit('SayHello');
    },
    'AMAZON.HelpIntent': function () {
        const speechOutput = 'This is the Hello World Sample Skill. ';
        const reprompt = 'Say hello, to hear me speak.';

        this.response.speak(speechOutput).listen(reprompt);
        this.emit(':responseReady');
    },
    'AMAZON.CancelIntent': function () {
        this.response.speak('Goodbye!');
        this.emit(':responseReady');
    },
    'AMAZON.StopIntent': function () {
        this.response.speak('See you later!');
        this.emit(':responseReady');
    },
    'SessionEndedRequest': function () {
        console.log("SESSIONENDEDREQUEST");
        this.response.speak("SessionEndedRequest. Goodbye!");
        this.emit(':responseReady');
    },
    'Unhandled': function() {
        console.log("UNHANDLED");
        const message = 'Unhandled';
        this.response.speak(message).listen(message);
        this.emit(':responseReady');
    }
};

Here are some observed strange behaviors:
From the Alexa simulator in the Amazon Developer Console, could not invoke the skill by "start hello world to go home", the response is "Sorry, I don't know that.". But after I  invoke the skill by "start hello world", I can invoke by "start hello world to go home" and get response "Hello World How are you!".
From Echosim.io, I can invoke the skill by "start hello world", but I could never invoke by "start hello world to go home". It responses with "Sorry I do not know that". Also, none of the reprompt speech is played out.
From cloudwatch log, sometimes I see "SessionEndedRequest" sent to the lambda function with the reason code "USER_INITIATED". I did not say any of "stop, cancel" etc. How is the USER_INITIATED SessionEndedRequest triggered? Is this somehow related to the fact that reprompt speech is never played out?
"go home" is mapped as the following:
            {
              "name": "HelloWorldIntent",
              "samples": [
                  "hello",
                  "say hello",
                  "who are you",
                  "go home",
                  "hello world"
              ],
              "slots": []
            }

Answer: I have seen many posts having trouble getting the reprompt going lately. I think the SDK might not build the response as intended in the first line.
this.response.speak(speechOutput).listen(reprompt);
this.emit(':responseReady');

Try instead this line.
this.emit(':ask', speechOutput, reprompt);

This should be equivalent to yours.
Regarding the problem with echosim.io. Do you use a proper microphone to record your utterance? In my experience, echoism.io had a lot of trouble identifying what i was saying even though i was using my headset microphone.
Instead, i would recommend to either use an echo device if possible or the newly introduced Test Simulator BETA in the developer console.
Comment: I saw a comment somewhere saying echosim.io does not play reprompt.


Product of permutations and subgroup generated by permutation(s)

Question: I'm get confused while working with permutations, so I have some questions.
$\sigma$ = (1,7,3)(2,10,4,8)
$\rho$ = (3,7)
$\tau$ = (1,7)
First I am told to compute $\tau$$\sigma$$\tau^{-1}$
I dont if i went about it the right way, anyway my final result is (1,3,7)(2,10,4,8) (I computed  $\tau$$\sigma$ first - right to left- and then ($\tau$$\sigma$ )$\tau^{-1}$.) Is my result correct?
<$\sigma$,$\rho$> is a subgroup of $S_{10}$. I have to check if $\sigma$ is a normal subgroup of <$\sigma$,$\rho$>. My idea was to use the index=2 check by finding the order of <$\sigma$,$\rho$> . Will that work?
Also, what does <$\sigma$,$\rho$> look like? if it were <$\sigma$$\rho$> I understand the elements, but i am unsure whether the comma means something that i am not grasping.
Answer: In theory you can do the multiplication in any order you like, because groups are associative. However, in practice you can actually do all the multiplication simultaneously! The permutation you wrote down is the correct answer, but this is hopefully a quicker method:
You said $\sigma = (1 \: 7 \: 3)(2 \: 10 \: 4 \: 8)$ and $\tau = (1 \: 7)$, and we want to calculate $\tau \sigma \tau^{-1}$. We know this is some permutation on $\{1, \ldots, 10\}$, so can just figure out where it send various elements.
Let's start with 1. $\tau^{-1}$ sends 1 to 7. $\sigma$ sends 7 to 3. $\tau$ doesn't affect 3, so we know $\tau \sigma \tau^{-1}$ sends 1 to 3. If we continue in this way, we find $\tau \sigma \tau^{-1}$ then sends 3 to 7 and 7 to 1, so have $\tau \sigma \tau^{-1} = (1\: 3\: 7)  (\text{some other stuff})$.
(In fact, there's an even quicker way: when we conjugate $\sigma$ by $\tau$ that has the same effect as relabelling the names of the elements that $\sigma$ permutes, by the permutation given by $\tau$. That is, we swap over the 1 and the 7 in the definition of $\sigma$!)

In answer to your next question, if the index of $H$ in $G$ is 2 then $H$ is normal, but not all normal subgroups of $G$ have index 2 I'm afraid.
In order to answer the question about how to check normality, I'll actually clear up your last question first: $\langle \sigma, \rho \rangle$ is the group generated by $\sigma$ and $\rho$. It's the smallest group that contains both $\sigma$ and $\rho$, and consists of all the possible things you can get from multiplying together $\sigma$, $\sigma^{-1}$, $\rho$ and $\rho^{-1}$.
This means that to check if $\langle \sigma \rangle$ is normal in $\langle \sigma, \rho \rangle$, it's enough to check whether when you conjugate $\sigma$ by $\sigma$, $\sigma^{-1}$, $\rho$ and $\rho^{-1}$ you end up in $\langle \sigma \rangle$ in each case.
However, clearly this will be the case for $\sigma$ (because $\langle \sigma \rangle$ is a subgroup), so you don't need to check $\sigma$ or $\sigma^{-1}$. Also, if $\rho \sigma \rho^{-1} \in \langle \sigma \rangle$ then $\rho^{-1} \sigma \rho \in \langle \sigma \rangle$, so you in fact only need to check $\rho \sigma \rho^{-1} \in \langle \sigma \rangle$.
Comment: Very clarifying. I have a (maybe stupid) question. $\sigma$ has order 12, so if i compute $\rho$$\sigma$$\rho^{-1}$, how do i know it is included in the subgroup generated by $\sigma$ without having to compute all of the elements?

* Actually, the result is equal to $\sigma$, but question still holds (generally)
Comment: I can't think of anything that's particularly quick, I'm afraid. There are cases where you could tell that it's definitely *not* in the subgroup generated by $\sigma$, e.g. by looking at the length of the disjoint cycles. I think in general you would have to at least compute $1, \sigma, \ldots, \sigma^6$ (and then can see their inverses by inverting the disjoint cycles that make them up).


signature of biliner form and the signature on the induced Hermitian form

Question: Let $V$ be finite dimension vector space over $\Bbb{R}$, and assume that $b:V\times V \to \Bbb{R}$ is the symmetric bilinear form, (therefore all eiginvalue are reals)
Then we can define the associated Hermitian form to be $h:V_\Bbb{C} \times V_\Bbb{C} \to \Bbb{C}$ such that $h(x,y) = b(x,\bar{y})$ (which is Hermitian symmetric, all the eigenvalue are also real)
I want to prove that signature of $b$ and $h$ are the same, however I lack a bit of knowledge in linear algebra and do not know to to prove it?

Let $\{e_i\}$ be the real basis of $V$ , then it will be the complex basis for $V_{\Bbb{C}}$, therefore the matrix associated to $b$ has the form $[b(e_i,e_j)]$ while the matrix associated to $h$ has the form $[h(e_i,e_j)] = [b(e_i, \bar{e_j})] = [b(e_i, e_j)] = b_{ij}$ therefore they are the same matrix ?
where $\bar{e_i} = \overline{e_i\otimes 1} = e_i\otimes \bar{1} = e_i$?
Comment: Just diagonalize.
Comment: Thank you, Can you have a look at my proof? I found the matrix for both form are the same? It seems a bit weird since the conjugation of the real basis it's again itself. @Qiaochu Yuan
Comment: That's what it means to be a real vector. There's no issue here.
Comment: yeah real is defined to be conjugation invariant.
Answer: I found the reference in Artin's Algebra book Chapter 8. This chapter answers my question.
Given any basis we have the matrix associated to the Hermitian form, it's $[h_{ij}] = [h(e_i,e_j)] = [b(e_i,\bar{e_j})] = b_{ij}$ which is real symmetric hence also Hermitian symmetric.
Although the matrix looks the same but the expression are the not same , that is :
$$h(x,y) = Y^*AX\\b(x,y) = Y^tAX$$

As Qiaochu point out we can always diagonalize it, even if the form is degenerate (but needs symmetric , hermitian condition.), which is proved on Artin's book theorem 8.4.10.


Clearing out Sinatra Assetpack asset pipeline

Question: I'm playing around with this package of Sinatra and Coffeescript and can't seem to clear the asset pipeline. When I update backbone.js to the most recent version, the app (run with shotgun watch) continues to serve the version of backbone.js that I've just replaced!
I am sure there is a rake command or something to clear the asset pack, but I cannot find it in any of the documentation.
rake assets:clean is telling me that rake doesn't know that task.
Answer: Seems like you aren't cache busting properly. Have you looked into using Sinatra Asset Pack for your asset management? It has support for coffescript and will automatically bust your cache so new changes will be recognized right away.
Another option is to just clear your cache with a hardreload, shift+f5 or clear it manually in your browser.


save image with text as a image to photo gallery in javascript

Question: I have a temporary image which i want to copy to gallery using javascript(phonegap).
Any help?
function save() {
  var image = document.getElementById("tempImg");
  //upload image to gallery of mobile . But how??
}

My image contains photo and text together...
i just want to arrange all div data including image inside div with some text on it and save it as an full image with any format .jpg,png etc in javascript.
I referred this link but that is for canvas to image but i want div to image .
Canvas to PhotoLibrary [Phonegap]
Comment: can you show an example (e.g. screenshot) of what your "image" looks like?
Comment: @VladStirbu : It shouldn't matter what the image looks like. I imagine that it is dynamically created/edited by the user. At any rate, I was able to [answer the question](http://stackoverflow.com/a/15914207/2093695) without knowing what it looks like.
Answer: You might want to check out this url: http://html2canvas.hertzen.com/.
Using this script, you can convert your div into a canvas, then use the "Canvas to PhotoLibrary [Phonegap]" to do the rest.
Your code would look something like this:
function save() {
    var image = document.getElementById("tempImg");
    html2canvas(image, {
        onrendered: function(canvas) {
            // use "Canvas to PhotoLibrary [Phonegap]" on the canvas variable
        }
    });
}

Answer: you save this using session storage(or)local storage
save:
var z1,z2,z3;
function save() {
var a=$("#theme1_text").val();
var b=$("#image_div").css("background-image");
var c=$("#background_theme1").css("background-image");
sessionStorage.z1=a;
sessionStorage.z2=b;
sessionStorage.z3=c;
    };

view:
function view() {
$("#theme1_text").val(sessionStorage.z1);
$("#image_div").css("background-image",sessionStorage.z2);
$("#background_theme1").css("background-image",sessionStorage.z3);
    };

Comment: This won't actually save it to the PhotoLibrary or even convert it into an image, will it?


Which is the maximum number of combinations between two populations

Question: I have two populations of size N1 and N2:
pop1 = {a,b,c,d,e,f,g} and
pop2 = {h,i,j,k,l}
I want to produce combinations of this two populations swapping individuals between the two but keeping the same population sizes.
Which is the number of unique new populations I can create?
Comment: This reads somewhat like a routine textbook-style question. Is this a question for a class?
Comment: The time of class questionaries is long gone for me. Sorry if the question was too simple.
Answer: Are you talking about permutations (in which the order matters) or combinations (in which the order doesn't matter)? You say permutations, but you talk about unique populations so I assume that you mean combinations.
Let n be the number of unique individuals and k be the size of one of the categories (it doesn't matter if you use N1 or N2):
$$ \frac{n!}{k!(n-k)!} $$


Solution to simultaneous polynomial equations.

Question: Given any $\beta \in R$, do there exist integers $k,l,m$, and a real number $x$ such that:
$l=4x^{3}m+6x^{2}m^{2}+4xm^{3}-2xm$,
as well as
$x^{4}-x^{2}=k+\beta$ ?
Comment: Yes, sure. Take $k=-\beta$ and $x=0$, with $l=m=0$.
Comment: $\beta$ is not necessarily an integer, while $k$ is
Comment: @DietrichBurde Doesn't work if $\beta\notin\mathbb Z$.
Answer: From the first equation, $x$ is algebraic. This implies $\beta$ algebraic, which might not hold.
There are countably many values of $\beta$ that give solutions. We can enumerate them by considering all triples $(k,l,m)$, finding the roots in $x$ and computing $\beta=x^4-x^2-k$.
Comment: Yes, indeed. Thanks for pointing out that $\beta$ can only be countable. In general, sums and products of algebraic numbers are algebraic, and so we conclude the first statement.


Calculate $f(x)=\int_1^x \sqrt{t(3t-2)} \, dt$

Question: I am struggling with this integral calculation.
Calculate:
$$f(x)=\int_1^x \sqrt{t(3t-2)} \, dt$$
for $x\geq 0$
Comment: A series of substitutions should work
Comment: What part exactly are you struggling with?
Comment: Can you explain what technique needs to be used?
Comment: Take a look here:https://math.stackexchange.com/questions/390080/definite-integral-of-square-root-of-polynomial
Answer: Hint:
Let $u = 3t - 2\implies\mathrm dt = 3\,\mathrm du$. Therefore,
$$\int\sqrt{t(3t - 2)}\,\mathrm dt\equiv\frac1{3^{3/2}}\int\sqrt{u^2 + 2u}\,\mathrm du = \int\sqrt{(u + 1)^2 - 1}\,\mathrm du$$
Let $u + 1 = \sec (v)\implies\mathrm du = \sec(v)\tan(v)\,\mathrm dv$. Therefore,
$$\begin{align}\int\sqrt{(u + 1)^2 - 1}\,\mathrm du&\equiv\int\sqrt{\sec^2(v) - 1}\sec(v)\tan(v)\,\mathrm dv \\ &= \int\sec(v)\tan^2(v)\,\mathrm dv \\ &= \int\sec^3(v) - \sec(v)\,\mathrm dv\end{align}$$
From here, linearity is your friend. Notice that the reduction formula for $$\int\sec^nx\,\mathrm dx$$ is well known. You fill find at the end that the integral is only defined for $x\ge 0$.
Answer: Complete square
$$f(x)=\int_1^x \sqrt{3t^2-2t} \> dt = \frac1{\sqrt3} \int_1^x\sqrt{(3t-1)^2-1}\>dt$$
and let $3t-1=\cosh u$. Then
\begin{align}
f(x)=&\ \frac1{3\sqrt3}\int_{\cosh^{-1}2}^{\cosh^{-1}(3x-1)}\sinh^2 u \, du\\
=& \ \frac1{6\sqrt3}\left(-u+\sinh u\cosh u\right) \bigg|_{\cosh^{-1}2}^{\cosh^{-1}(3x-1)}\\
=& \ \frac1{6\sqrt3}\left(\cosh^{-1}2-\cosh^{-1}(3x-1)+\sqrt3(3x-1)\sqrt{3x^2-2x} -2\sqrt3 \right)
\end{align}


Why does my VBScript function differently if it is opened by a batch script rather than a person?

Question: Simply put, I have a VBScript titled "tyrian_soundtest.vbs" that plays an .mp3 that is titled "tyrian_soundtest.mp3"
The VBScript code is below
Set Sound = CreateObject("WMPlayer.OCX.7")
Sound.URL = "tyrian_soundtest.mp3"
Sound.Controls.play
do while Sound.currentmedia.duration = 0
wscript.sleep 1
loop
wscript.sleep (int(Sound.currentmedia.duration)+1)*1000

When opened, it plays the .mp3. Simple enough.
The trouble comes in when I run a batch script titled "tyrian_soundtest.bat". Relative to it, the .vbs and .mp3 are in a folder called sfx. Here is what one iteration of that file contained.
@echo off
start %cd%\sfx\tyrian_soundtest.vbs
exit /b

The result is an error stating that Windows couldn't find the file path, likely due to it containing a space. Other attempts of the .bat were replacing line 2 with
start .\sfx\tyrian_soundtest.vbs

or
start "%cd%\sfx\tyrian_soundtest.vbs"

Any attempt I've made gives one of three results. Option 1: There is no error, but the audio simply never plays. Option 2: An error is thrown about the file directory not being found. Option 3: That file path opens up in a new cmd window, but the .vbs is never run.
Is there any way format the .bat to get the .vbs to run through the without an error being caused?
Comment: If the vbs is already in the current working directory, you should not have to specify any path and only the script.  When using the `START` command the first set of quotes is considered the `TITLE` of the window.  So you use an empty set of quotes. `start "" "%cd%\sfx\tyrian_soundtest.vbs"`.  Personally as a best practice I normally use cscript.exe to launch my vbscripts from a batch file.
Comment: The issue could also be the path to the mp3 file. Give full path to the file.in `Sound.URL`
Comment: @Squashman This had a peculiar result, the file will properly play now, but only if the vbscript is in the same file directory (despite the folder sfx being specified)
Answer: The main issue is that there is used in batch file and in the VBScript file the current directory path. The current directory on starting %SystemRoot%\System32\cmd.exe to process the batch file can be any directory.
The Windows Explorer sets the directory of the batch file as current directory on double clicking the batch file resulting in starting cmd.exe by explorer.exe to process the double clicked batch file of which full qualified file name is passed to cmd.exe after the option /c as additional argument. But if the batch file is stored on a network resource accessed using UNC path, the Windows command processor changes the current directory from the network resource to %SystemRoot% (the Windows directory) and the batch file fails to start Windows Script Host to process the VBS file. See also: CMD does not support UNC paths as current directories.
A batch file can be also started by right clicking on it and using Run as administrator. This can result in making the directory %SystemRoot%\System32 (the Windows system directory) the current directory. See also: Why does 'Run as administrator' change (sometimes) batch file's current directory?
That are just two of many examples where the current directory is different to the directory containing the batch file. So if a batch file references other files stored in same directory as the batch file itself or a subdirectory of the batch files directory, it is advisable to reference these files with the full path of the batch file instead of using a path relative to current directory.
Example:
The used files are stored in directory C:\Temp\Development & Test as follows:

sfx

tyrian_soundtest.vbs
tyrian_soundtest.mp3

tyrian_soundtest.bat

A user opens a command prompt window which usually results in making the directory referenced with %USERPROFILE% or with %HOMEDRIVE%%HOMEPATH% the current directory. A user executes next in the command prompt window:
"C:\Temp\Development & Test\tyrian_soundtest.bat"

So the current directory is definitely not the directory containing the batch file.
The batch file can be coded as follows to start nevertheless the Windows Script Host for processing the VBS file tyrian_soundtest.vbs and successfully play the MP3 file tyrian_soundtest.mp3.
@start "" /D "%~dp0sfx" %SystemRoot%\System32\wscript.exe //NoLogo "%~dp0sfx\tyrian_soundtest.vbs"

%~dp0 references the drive and path of argument 0 which is the full path of the currently processed batch file. The batch file path referenced with %~dp0 always ends with a backslash. For that reason the concatenation of %~dp0 with a file/folder name or wildcard pattern should be always done without using an additional backslash as that would result in two \ in series in complete argument string and the Windows file management would need to fix that small error by replacing \\ by just \ before passing the argument string to the file system. See also the Microsoft documentation about Naming Files, Paths, and Namespaces which explains which automatic corrections are usually applied on file/folder strings before passing them to the file system.
The internal command START of cmd.exe interprets the first double quoted argument string as title string for the console window as it can be seen on running in a command prompt window start /? and reading the output help. For that reason it is not enough to use just:
@start "%~dp0sfx\tyrian_soundtest.vbs"

That would result in starting one more command process with its own console window with the full qualified file name of the VBS file as title of the console window.
The Windows Script Host processing a VBS file by default on Windows exists in two versions:

%SystemRoot%\System32\cscript.exe is the console version.
%SystemRoot%\System32\wscript.exe is the Windows GUI version.

The usage of the console version cscript.exe results usually in opening a console window by the parent process if the parent process is not itself a console application running already with an opened console window like on execution of a batch file processed by %SystemRoot%\System32\cmd.exe being also a console application.
The usage of the Windows GUI version wscript.exe results in no opening of a window by default at all. The processed script file must contain commands to open a window if that is wanted at all.
The difference can be also seen on running from within a command prompt window cscript /? and next wscript /?. The first command results in printing the help for the command line options of Windows Script Host in already opened command prompt window while the second command results in showing a graphic window by wscript.exe displaying the same usage help.
The usage help of Windows Script Host explains also how each user can define which version of Windows Script Host is the default for executing scripts. So it is not advisable to specify just the VBS file name with full path on the command line with start and let cmd.exe look up in Windows registry which version of Windows Script Host to run to process the VBS file. It is better to explicitly run the version of Windows Script Host most suitable for playing the MP3 file which is in this case the Windows GUI version wscript.exe opening by default no window at all to play the MP3 file in background.
So it would be possible to use:
@start "" %SystemRoot%\System32\wscript.exe //NoLogo "%~dp0sfx\tyrian_soundtest.vbs"

There is an empty title string defined with "" as the started executable wscript.exe is a Windows GUI application for which no console window is opened at all by cmd.exe. So the title string does not really matter and can be an empty string.
But there is left one problem with that command line. The VB script references the MP3 file without path which means with a path relative to current directory. The current directory is %USERPROFILE% and not C:\Temp\Development & Test\sfx which contains the MP3 file tyrian_soundtest.mp3. So the VB script would fail to find the MP3 file to play.
There are two solutions to fix this:

The usage of the following command line in the batch file:
 @start "" /D "%~dp0sfx" %SystemRoot%\System32\wscript.exe //NoLogo "%~dp0sfx\tyrian_soundtest.vbs"

The option /D of command START is used to explicitly set the subdirectory sfx of the batch file directory as start in respectively current directory for the process wscript.exe which cmd.exe starts using the Windows kernel library function CreateProcess with an appropriate created structure STARTUPINFO.

The VBS file references the MP3 file tyrian_soundtest.mp3 with its full path which the VB script file determines itself from its own full qualified file name. That can be achieved in the VB script file tyrian_soundtest.vbs by using in the second line:
Sound.URL = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) + "\tyrian_soundtest.mp3"

Best would be using both possible solutions as in this case the VB script file would work also on being executed by a different process than cmd.exe processing the batch file tyrian_soundtest.bat and deletion of directory %~dp0sfx is not possible as long as started wscript.exe is running because of this directory is the current directory of running Windows Script Host.
So the batch file as well as the VB script file work now both independent on which directory is the current directory as both reference the files with full path determined by the scripts themselves from their full qualified file names.


Restricted OLS have less variance than OLS?

Question: According to Gauss-Markov Theorem, ordinary least squares (OLS) is the best linear unbiased estimator (BLUE). How then can restricted OLS have less variance?
Please tell me the reason.
Comment: I suppose the OP thinks so because of the following sentence *"Consequently, the diagonal elements of  $ V(\hat{\beta}_{R})$ (variances of each  $ \hat{\beta}_{Rj}$) are equal to or less than the corresponding elements of  $ V(\hat{\beta})$ (variances of each  $ \hat{\beta}_{j})$. This means that, if the a priori information is correct (as we will show later , in this case  $ \textrm{E}(\hat{\beta}_{R})=\beta)$, the estimator vector  $ \hat{\beta}_{R}$ is more efficient than the OLS estimator."* It's in the reference he linked http://fedc.wiwi.hu-berlin.de/xplore/tutorials/xegbohtmlnode18.html
Comment: I proposed an edit to your question. If your edit does not address your question please correct it.
Comment: No entirely sure but if OLS assumption of no correlation not met, but [GLS](https://en.wikipedia.org/wiki/Generalized_least_squares) correlation assumption met then possibly restricted OLS has the lesser variance.
Comment: Please explain why you think the variance is smaller with the restrictions!
Answer: The main intuition is that restricted OLS are generally biased. So there is a tradeoff between bias and variance: you reduce variance but you allow bias.

An example: suppose that you want to estimate the average height of the people in your state. You may have learned that if you have a random sample (say of 2000 individuals), a "reasonable" estimator is the sample average, which is unbiased. But you have "prophecy" skills and you know for sure that the average of the population is 175cm. Then there is no variance at all, it is zero, which is lower than any estimator you can come up with. But, except if you are a really good prophet (or your cheated with data) it is likely to be biased.

A more explicit answer to your question would be a direct comparison of the variances of the restricted and unrestricted estimator.

$$Var(\beta_u) = \sigma^2(X'X)^{-1}$$
$$Var(\beta_c) = \sigma^2(X'X)^{-1} - \sigma^2(X'X)^{-1}R'(R(X'X)^{-1}R')^{-1}R(X'X)^{-1}$$
Therefore the variance of the restricted estimator is always weakly smaller than the variance unrestricted estimator, with equality when the restrictions are true.

Advanced : You can see this early test discussing the topic: the condition so that

$MSE(\hat{\beta_u}) - MSE(\hat{\beta_c})$ is positive semidefinite [$\beta_u$ is the unconstrained, $\beta_c$ the constrained estimator]
The condition is met iff $\lambda< 1/2$, where
$$\lambda = \frac{1}{2\sigma^2}(R\beta-r)'(R(X'X)^{-1}R')^{-1}(R\beta-r),$$
where $R\beta = r$ is the vector of constraints you impose.
Answer: I don't think restricted OLS are biased. Look at Hansen's textbook Econometrics section 8.4 "Finite sample properties". Theorem 8.2 says CLS estimators are unbiased for $\beta$.
Comment: Hello and Welcome to CV! What about the variance of CLS (which is what the question is asking about)?
Comment: The restricted case is only unbiased when the restriction is true.
Answer: Consider $X_1 \sim N(\mu_1,1)$ and $X_2 \sim N(\mu_2,1)$. And we want to estimate $\mu_1$ and $\mu_2$.

Unrestricted case. We will use $\hat{\mu}_i = X_i$ and the variance of the error will be equal to one.

Restricted case. Let for instance impose the restriction $\mu_1+\mu_2 = 0$ or $\mu_1 = - \mu_2$. Now we will estimate a single parameter $\hat{\mu}  = \frac{X_1-X_2}{2}$ instead (and we can make the relationships $\hat{\mu}_1 = \hat{\mu}$, $\hat{\mu}_2 = -\hat{\mu}$).
The variance of the estimate will now be equal to $1/2$. Indeed, it is a smaller variance.

Restricted case. When the restriction is untrue. If we do not truly have $\mu_1 = - \mu_2$ then our estimate $\hat{\mu} \sim N(\frac{\mu_1 - \mu_2}{2}, \frac{1}{2})$ will be biased and we may have a larger error.
The restricted case is not unbiased.


?: in Objective-C

Question: In this iOS tutorial, there is a line of code with a ? followed by a :. In the context of the comment for the code, I thought it was some sort of ternary operation, however, that's obviously not the syntax for a ternary operator. Is there a name for what is happening in this code with the ?:?
// Initialize the list of weather items if it doesn't exist
NSMutableArray *array = self.xmlWeather[@"weather"] ?: [NSMutableArray array];

Answer: It's a GCC extension:

6.7 Conditionals with Omitted Operands
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.
Therefore, the expression
x ? : y

has the value of x if that is nonzero; otherwise, the value of y.
This example is perfectly equivalent to
x ? x : y

In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.

?: in Objective-C


Display Suite Custom Wrappers and Custom Classes Tabs Not Appearing in Manage Display

Question: I am using Display Suite layouts for some of my pages. I want to add in some custom classes for the regions. However, the custom classes and custom wrappers tabs are not appearing on the Manage Display screen for my view modes. I am able to add custom classes on the Display Suite Custom Classes screen, but cannot apply them to the display, as the tabs are not there.
Am I missing something? I have seen videos where they appear for other users so don't know why they are not appearing for me.
Below is a screenshot showing the missing tabs.

I want to basically target the view mode as a class on the page. At the moment, it is only inserting the layout I have selected as a class, so if I am using the same layout for different view modes I can't differentiate between them if they are for the same content type.
Answer: Two possibilities come to mind.
1) Have you saved since you selected "One Column" as the layout? The configuration options change once you select something other than -None-
or
2) Have you checked that you have the correct Display Suite permissions? Namely, 'Administer classes' and 'Administer fields'
Comment: It was my mistake. I didn't realise Drupal 8 included its own native layouts in the layout dropdown and I had selected the Drupal One Column Layout not the Display Suite One Column Layout.
Comment: Thank you for your answer. Yes, I have saved it and I checked the permissions as well and the tabs are not showing. I think I might need to put a request in the module issue queue.
Comment: Well I have the same problem. I am using indeed layouts from Display Suite and I checked the permissions and they are fine, but Custom wrappers tab doesn't show up. Any other ideas? Thanks!
Comment: Forget it! I deleted the display, recreated it and suddenly the option was there... I also installed in the mean time the 'Display Suite Extras' module, not sure this was the actual solution, but worth to give it a try.


How to use css to implement same effect as having a  inside target element?

Question: I want all empty
 elements in html to have a line break inside it, and use css to make this effect.
Details:
Both of the p tags below should have same appearance (across browsers and zoom levels)
All other customs styles of p tags are same

p:empty {
  /** How can I code here (or some other way css codes can achieve this) **/
}

background: I want to show preview of the editing content inside prosemirror editor, while the editor doesn't preserve
 inside
 when serialize the content to json and make it look different when preview rendered from json. see: discuss.prosemirror
Comment: :empty will not work if anything is in  tag, try to explain your question in more details. if possible try to give us visual what exactly you are trying to achieve
Comment: I assume you're trying to do this to create equal spacing somewhere? A line break is a html element that is not a fixed height - it depends on other factors including line height and whether it has any styling of its own. There is no easy way to try replicate the behaviour of a html element in CSS. Tell us what exactly are you trying to achieve, and maybe we can give a better solution
Answer: There's several ways you could do this, here's how you could it using the same logic behind your own code by simply adding a space Unicode after it's content :

p:empty:after {
  content: '\00a0';
}

p {
  outline: 1px solid red;
}

To demonstrate :

console.log(document.getElementById("first").offsetHeight)
console.log(document.getElementById("second").offsetHeight)
p:empty:after {
  content: '\00a0';
}
p {
  outline: 1px solid red;
}

Answer: An empty inline-block element can also do the job:

p:empty:after {
  content: '';
  display:inline-block;
}

p {
  outline:1px solid red;
}

Or like below:

p:empty:after {
  content: ' ';
  white-space:pre;
}

p {
  outline:1px solid red;
}

Comment: I tested this, but there is still some different in the appearance. currently `content: '\00a0'` is the only working approach.
Comment: @dongjy you have probably more CSS involved, as you can test in the snippet both produce the same output
Comment: The god of CSS has spoken, so a +1 I shall give
Comment: @TemaniAfif Thanks, the second solution does work, but not the first. After research I found something very strange: you can create a new html and copy & paste `inline-block` solution (the first one) code into it and then open the html file with browser to see the different layout from the one produced by click *run code snippet* button below this snippet. The empty `` has zero height in both firefox & chrome. Can you figure out why the difference?
Comment: @dongjy are you declaring the doctype on the top of your file?
Comment: @TemaniAfif Thank you, add `` at the top of html file then both solutions work. You are a master.
Answer: You can give the
 an explicit height and line-height like this:
p {
  height: 1em;
  line-height: 1em;
}

Working Example:

table, tr, th, td {
  border: 1px solid rgb(191, 191, 191);
}

p {
  height: 1em;
  line-height: 1em;
  text-align: center;
  border: 1px solid red;
}

  Column 1
  Column 2

Two

Four

Two

Four

Comment: Yes, you are correct @dongjy - as I said above, the line height for the `p` tag influences the display height and different paragraphs could have different lineheight set by different selectors in CSS.
Comment: I test this, there is still some different in the appearance, may `` not exactly `1em` as of `line-height` and `height` ?


Unable to override Mui Accordion using Styled Utility

Question: I want to override Accordion CSS using Mui styled utility but I am unable to get apply Accordion css onto it. There's an underlying class which I can't point to in my code. This is the mui class:

This is my code for Accordion

const CustomizedAccordion = styled(Accordion)<AccordionProps>(({ theme }) => ({
    root: {
        "& .MuiPaper-root": {
            color: 'darkslategray',
            backgroundColor: '#E4FAF4',
            borderRadius: '0.6rem',
            boxShadow: 'none'
        }

    },
    paddingBottom: '1.6rem',
    boxShadow: 'none',

}));
Answer: I had same problem but when I read MUI docs in detail. Basically they set square corners by default 'true'.
To change square corners to rounded, we need to change this default value of sqaure prop as false.
They use sx prop to set border radius.
<Accordion square='false' sx={{borderRadius: '30px', background: 'tan'}}>

enter image description here
Hope this will help you!
Answer: <Accordion square={true} sx={{borderRadius: '30px'}}>

square should be boolean - if you set it to true you can add borderRadius in sx
Answer: const CustomizedAccordion = styled(Accordion)(() => ({
  '& .MuiPaper-root': {
    color: 'darkslategray',
    backgroundColor: '#E4FAF4',
    borderRadius: '0.6rem',
    boxShadow: 'none'
  },
  paddingBottom: '1.6rem',
  boxShadow: 'none'
}));

Comment: Not sure why but I cant seem to get this working, nothing happens..
Answer: I had the same problem and the solution is in the props
<Accordion disableGutters />

If you set it to true, the margin disappears. Link to Accordion API
Answer: I want to modify expanded style from its style which has code as
.css-kj1tus-MuiPaper-root-MuiAccordion-root.Mui-expanded { margin: 16px 0; }
to margin:0px 0px 0px 4px;
But, unable to make it working.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Not a good idea to post your query as an answer to a question.


What are some applications of modules, but not of vector spaces?

Question: Some background: I'm taking Matrix Analysis, and my professor seems to think vector spaces are foundational to all of mathematics. What are some interesting applications from other areas of mathematics (or the outside world) that arise from modules, but are not applications of vector spaces?
Comment: Building on the comment by hardmath, the integral cohomology (which, for each degree, is an Abelian group, but not a vector space) of a smooth manifold is an object of importance in symplectic, algebraic, and complex geometry.  For example, it is a source of the (characteristic) Chern classes of complex vector bundles.
Comment: It is less of an application than an equivalence, but abelian groups are the same things as $\mathbb{Z}$-modules.
Comment: An enormous amount of classical linear algebra can be presented using modules over PIDs. Representations of groups are basically modules over group rings.
Answer: You may be aware of the importance of the Jordan Normal Form of a matrix. If not you can google it and check the fact that every square matrix has a unique representation as the closest similar matrix to a diagonal matrix, is very useful for the resolutions of huge systems of equations. Well, in order to prove this, you can consider a vector space over a field k as a k[x]-module and use a battery of results of R-modules for a ring R.


Show that $M^m + A = M^{m+1}$ with $M,A$ matrices?

Question: Let $M,A$ denote matrices with
$$
M = \left(\begin{array}{cc}
1 & 1 \\
0 & 1
\end{array}\right),
~~~~
A = \left(\begin{array}{cc}
0 & 1 \\
0 & 0
\end{array}\right).
$$

Show that $$M^m + A = M^{m+1}.$$

$~$
Context: I encountered this problem when trying to prove that $M^m = E_2 + mA$ (1) by induction (where $E_2$ is the $2\times 2$ identity matrix. Adding $A$ on both sides yields $M^m + A = E_2 + mA +A =E_2 + (m+1)A$. Equation (1) would follow if $M^m + A = M^{m+1}$.
Comment: You may want to prove instead that $$M^m = \begin{bmatrix} 1 & m \\ 0 & 1 \end{bmatrix}$$
Comment: Hint: Induction, using $MA=A$.
Answer: Since $MA=A$, we prove by induction.
When $m=0$, check that:
$$M^1=M^0+A$$
where $M^0=\begin{pmatrix}1&0\\0&1\end{pmatrix}=I.$
Now, if $M^{m+1}=M^m+A$ then multiply both sides by $M$, and you get $$M^{m+2}=M^{m+1}+MA=M^{m+1}+A$$

More generally, if $A^2=0$ and $M=I+A$ then $MA=A+A^2=A$ and you have again that $M^{m+1}=M^{m}+A$.
Answer: By the Cayley-Hamilton Theorem, $M$ satisfies its characteristic polynomial, so $(M-I)^2 = 0$ where $I$ is the identity matrix.  Since $A = M - I$, then
\begin{align*}
M^{m+1} - M^m - A  &= M^m(M-I) - (M-I) = (M^m - I)(M-I)\\
&= (M^{m-1} + M^{m-2} + \cdots + M + I)(M-I)^2 = 0
\end{align*}
so $M^{m+1} = M^m + A$.


Objective-C protocol static method?

Question: I have a protocol in Objective-C, something like this:
@protocol Handler
+(NSString*) getValue;
@end

So now say I have an instance that inherits this protocol and I want to call this method:
[handlerInstance getValue];

This gives a warning because the getValue method is not an instance method. How can I properly call this method from my instance? (Without knowing the concrete class)? I'm guessing something like this, but I'm not exactly sure:
[[handlerInstance class] getValue];

Answer: [[handlerInstance class] getValue];

Yes, like this.
Unlike Java and C++, class methods can only be sent to the class.
Comment: Not all of us.  Trying it out before posting doesn't give others the benefit of the knowledge.  I came here searching for how this would behave because 1.) it was quicker than trying it out and 2.) if there were pitfalls I hadn't thought of, someone would likely note them here.  Posting first is therefore less work for everyone who comes later.  Thanks Kenny and Zenox.
Comment: @chakrit: `[[instance class] getValue]`. If you have a `Class cls`, then do `[cls getValue]`. Note that this method will not execute if `handler == nil`.
Comment: So if I have a variable `id handler` do I assign `instance` or `[instance class]` ? Will this work even without an instance available? (Only a `Class`)?
Comment: Seriously, I guess I shouldn't have second guessed myself!
Comment: In general the point of class methods is not using an instance.

Objective-C protocol static method?