text:
Q: Which algorithm is faster? I'm creating a small game, where the computer generate pseudo random number in give range, and the user have to guess it. I also made the option to play computer vs computer. I mean the computer generate random number and the computer should guess it.
The easiest way I found was to create for loop and increase a variable by 1 until it guesses it.  But I decided to try to create my own algorithm about this.
Basically the variable that holds the guess number is equal to range / 2, and then the program enters into the while loop where if the random number > the number which is generated by logic(the one which is = to range /2) then 2 it to two and add 1 to it. If the number is < the program * by 2 and add one to it until it guess the number.
Here is code in C++:
void aiVsAI(int range){ // range argument is used to be given to the randome generator func
    int random_number = generate_random_number(range); // assigning the random number to variable
    int guess = range / 2; // the computer guess number
    int tries = 0; // how many tries the computer needed to guess the number
    while(guess != random_number){ // while the guess isn't equel to the random number
        if(guess > random_number){ // if the guess is > than the random number
            guess = guess / 2 + 1; // dev it to 2 and add one to it
        }
        else if(guess < random_number){ // if the number is < than the number then
            guess = guess * 2 + 1; // * it with 2 and add one
        }
        tries++; // increase the number of tires
    }
    std::cout << tries;
}

the generate_random_number is function that will generate pseudo-random number.
My question is which algorithm is faster this one or just using for loop and increasing variable with one until it guess the number?

Here is the full code if anyone need it for something:
#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>

//function that will generate random number
int generate_random_number(int range){  // the range argument is used to represent the maximum value of the number
    if(range < 10){ // the range couln't be < 10 but can be ==
        std::cout << "range can't be less than 10";
        exit(1);
    }
    std::srand(time(NULL)); // making sure that the random number will be different every time
    return rand() % range; // returning the random generated number in the specific range
}

//Game computer vs computer
void aiVsAI(int range){ // range argument is used to be given to the randome generator func
    int random_number = generate_random_number(range); // assigning the random number to variable
    int guess = range / 2; // the computer guess number
    int tries = 0; // how many tries the computer needed to guess the number
    while(guess != random_number){ // while the guess isn't equel to the random number
        if(guess > random_number){ // if the guess is > than the random number
            guess = guess / 2 + 1; // dev it to 2 and add one to it
        }
        else if(guess < random_number){ // if the number is < than the number then
            guess = guess * 2 + 1; // * it with 2 and add one
        }
        tries++; // increase the number of tires
    }
    std::cout << tries;
}

// Game human vs human
void humanVsAI(int range){ // range argument is given to the generate random function
    int random_number = generate_random_number(range); // assigning the random number to variable
    int input = 0; // this var represents the user input
    int tries = 0; // the number of tries user had make to guess the number
    while(input != random_number){
        std::cout << "Enter number: "; // alerting the user to enter a number
        std::cin >> input; // getting the number
        if(input < random_number) // checking if the input > than the random num
            std::cout << "You didn't guess it,you are too low..., try again!\n"; // alerting the user
        else{ // else it will be > than the number
            std::cout << "You didn't guess it,you are too high..., try again!\n"; // alerting the user
        }
        tries++; // increasing tries by one for each try//
    }
    std::cout << "\n\nYou guess it! You need " << tries << " to do this.\n\n";
}

//game Human vs Human
void humanVsHuman(int range){
    int number_to_guess; // the number which must be guessed
    int user_guess; // user input
    int guess;
    std::cout << "Enter number int range 1- "<< range<<": \n"; // alerting the user to enter number
    std::cin >> number_to_guess; // entering number
    for(int i = 0; i < 100;i++){ //Clearing the screen
        std::cout << "\n";
    }
    while(user_guess != number_to_guess){
        guess++;
        std::cout << "Please enter numer:\n"; // alerting the user
        std::cin >> user_guess; // Getting the user input
        if(user_guess < number_to_guess)
            std::cout << "You didn't guess it,you are too low..., try again!\n";
        else if(user_guess > number_to_guess)
            std::cout << "You didn't guess it,you are too high..., try again!\n";
    }
    std::cout << "You guess the number\n";
}
int main(){
    std::string game_type;
    char play_game;
    int range = 0;
    while(1){
        std::cout << "Please enter range(type 100 to leave it as default)\n";
        std::cin >> range;
        std::cout <<"What you want to play AI vs human, human vs human or AI vs AI ?\n";
        std::cin.ignore(); // for get line
        std::getline(std::cin, game_type); // getting the user input
        std::cin.clear(); // clearing
        if(game_type == "AI vs AI" || game_type == "ai vs ai"){ // if the user chose AI vs AI
            std::cout<<"You choosed AI vs AI\n";
            aiVsAI(range); // calling the AI function
        }
        else if(game_type == "human vs ai"
                || game_type  == "ai vs human"
                || game_type == "human vs AI"
                || game_type == "Human vs AI"
                || game_type == "Human vs ai"
                ){ // if the user chossed AI vs human
            std::cout << "You choosed human vs AI\n";
            humanVsAI(range); // calling the human vs human function
        }
        else if(game_type == "human vs human"
                ||game_type == "Human vs Human"
                ||game_type == "Human vs human"
                ||game_type == "human vs Human"){ // if the user choosed human vs human
            std::cout <<"You choose human vs human\n";
            humanVsHuman(range); // calling the human vs human function
        }
        else{ // In case of any error
            std::cerr << "An error occured!";
        }
        std::cout << "Do you want to play another game?\n"; // do you want another game????
        std::cin >> play_game;
        if(play_game == 'y' || play_game == 'Y')
           std::cout <<" starting another game\n";
        else
            break;  // enough playing for now.
    }
    return 0;

}

A: The more sophisticated algorithm is definitely more efficient: it requires logarithmic time vs. linear time to find the value. Here is a description of binary search; that's basically what you have reinvented.

A: As long as the guess is consistently high, your algorithm performs well by roughly halving the guess.
Once you have made a low guess, the algorithm severely deteriorates in performance. By doubling after a low guess, you are guaranteed that the next guess will be too high. Now, the +1 factors come into play (especially the one after halving), which let you walk towards the right number at half the speed of a normal loop.
For performance measurements, I would expect the slow walk up to be the dominant factor, making your algorithm slower on average than the simple loop. Given your measurements, either my expectations are wrong, or the distribution of your pseudo-random values happens to be slightly in favor of your algorithm.

If you want a challenge, you could try to implement a binary search. With a range of 100, that algorithm is able to find any number within 10 steps (given that it knows the range).


text:
Q: NAudio - Stream audio outward in realtime via RTP I am using NAudio for my audio needs, but I've run into a thorny issue.  I have a remote device that can receive RTP audio.  I would like to stream an audio file to that device (after u-law or similar encoding + RTP wrapping).  However, there doesn't seem to be a mechanism to maintain the outgoing timing for the RTP packets.
For example, a WaveOut player "manages" timing by simply responding to requests from the underlying sound/directx layers.  In this manner, the timing is actually maintained by the sound drivers using a "pull" method.
What I'm looking for is a component that can provide the correct "pull" timing on an (e.g.) IWaveProvider (or similar) so that I can take each packet, RTP-ify it, and send it over the wire.
So, here's the core code:
IPEndPoint target = new IPEndPoint(addr, port);
Socket sender = new Socket( AddressFamily.InterNetwork,
                            SocketType.Dgram,
                            ProtocolType.Udp );

IWaveProvider provider = new AudioFileReader(filename);
MuLawChatCodec codec = new MuLawChatCodec();  // <-- from chat example
int alignment = provider.BlockAlign * 32;  // <-- arbitrary
byte [] buffer = new byte [alignment];

try
{
    int numbytes;
    while( (numbytes = provider.Read(buffer, 0, alignment)) != 0 )
    {
        byte [] encoded = m_Codec.Encode(buffer, 0, numbytes);
        m_Sender.SendTo(buffer, numbytes, SocketFlags.None, target);
    }
}
catch( Exception )
{
    // We just assume that any exception is an exit signal.
}

What happens is that the while loop just grabs "audio" as fast as it can and blows it out the UDP port.  This won't work for RTP, since we need to maintain the proper output timing.
As a test, I tried a WaveOut with a NotifyingSampleProvider, feeding each L/R pair to the encoder/RTP-ifier/sender, and it seemed to work fine.  However, the side effect of the audio playing out of the local speaker (via WaveOut) is not acceptable for the application I'm working on (e.g. we may want to stream multiple different files to different devices simultaneously).  We also might be using the audio hardware for (e.g.) simultaneous softphone converstations.  Basically, we don't want to actually use the local audio hardware in this implementation.
So, does anyone know of (or written) a component that can provide the proper timing for the sender side of things?  Something that can grab audio at the proper rate so that I can feed the encoder/sender chain?

A: In case anyone is interested, I got it to work.  I had to add a few components, and refine the timing down to a very fine level.
Added:

*

*Now using NAudio.Wave.Mp3FileReader.  I uses this because it provides timing information with each frame that you read.

*Configurable 'buffering' (it buffers frame times, not actual audio)

*Managing timing more precisely with System.Diagnostics.Stopwatch and Socket.Poll
Here's a condensed (single-threaded) version of the code with no try/catches, etc. The actual stuff uses a player thread and some other synch mechanisms, and lets you 'cancel' playing by killing the socket.
// Target endpoint.  Use the default Barix UDP 'high priority'
// port.
IPEndPoint target = new IPEndPoint( IPAddress.Parse("192.168.1.100"), 3030 );

// Create reader...
NAudio.Wave.Mp3FileReader reader = new Mp3FileReader("hello.mp3");

// Build a simple udp-socket for sending.
Socket sender = new Socket( AddressFamily.InterNetwork,
                            SocketType.Dgram,
                            ProtocolType.Udp );

// Now for some 'constants.'
double ticksperms = (double)Stopwatch.Frequency;
ticksperms /= 1000.0;

// We manage 'buffering' by just accumulating a linked list of
// mp3 frame times.  The maximum time is defined by our buffer
// time.  For this example, use a 2-second 'buffer'.
// 'framebufferticks' tracks the total time in the buffer.
double framebuffermaxticks = ticksperms * 2000.0;
LinkedList<double> framebuffer = new LinkedList<double>();
double framebufferticks = 0.0f;

// We'll track the total mp3 time in ticks.  We'll also need a
// stopwatch for the internal timing.
double expectedticks = 0.0;
Stopwatch sw = new Stopwatch();
long startticks = Stopwatch.GetTimestamp();

// Now we just read frames until a null is returned.
int totalbytes = 0;
Mp3Frame frame;
while( (frame = reader.ReadNextFrame()) != null )
{
    // Make sure the frame buffer is valid.  If not, we'll
    // quit sending.
    byte [] rawdata = frame.RawData;
    if( rawdata == null ) break;

    // Send the complete frame.
    totalbytes += rawdata.Length;
    sender.SendTo(rawdata, target);

    // Timing is next.  Get the current total time and calculate
    // this frame.  We'll also need to calculate the delta for
    // later.
    double expectedms = reader.CurrentTime.TotalMilliseconds;
    double newexpectedticks = expectedms * ticksperms;
    double deltaticks = newexpectedticks - expectedticks;
    expectedticks = newexpectedticks;

    // Add the frame time to the list (and adjust the total
    // frame buffer time).  If we haven't exceeded our buffer
    // time, then just go get the next packet.
    framebuffer.AddLast(deltaticks);
    framebufferticks += deltaticks;
    if( framebufferticks < framebuffermaxticks ) continue;

    // Pop one delay out of the queue and adjust values.
    double framedelayticks = framebuffer.First.Value;
    framebuffer.RemoveFirst();
    framebufferticks -= framedelayticks;

    // Now we just wait....
    double lastelapsed = 0.0f;
    sw.Reset();
    sw.Start();
    while( lastelapsed < framedelayticks )
    {
        // We do short burst delays with Socket.Poll() because it
        // supports a much higher timing precision than
        // Thread.Sleep().
        sender.Poll(100, SelectMode.SelectError);
        lastelapsed = (double)sw.ElapsedTicks;
    }

    // We most likely waited more ticks than we expected.  Timewise,
    // this isn't a lot.  But it could cause accumulate into a large
    // 'drift' if this is a very large file.  We lower the total
    // buffer/queue tick total by the overage.
    if( lastelapsed > framedelayticks )
    {
        framebufferticks -= (lastelapsed - framedelayticks);
    }
}

// Done sending the file.  Now we'll just do one final wait to let
// our 'buffer' empty.  The total time is our frame buffer ticks
// plus any latency.
double elapsed = 0.0f;
sw.Reset();
sw.Start();
while( elapsed < framebufferticks )
{
    sender.Poll(1000, SelectMode.SelectError);
    elapsed = (double)sw.ElapsedTicks;
}

// Dump some final timing information:
double diffticks = (double)(Stopwatch.GetTimestamp() - startticks);
double diffms = diffticks / ticksperms;
Console.WriteLine("Sent {0} byte(s) in {1}ms (filetime={2}ms)",
                 totalbytes, diffms, reader.CurrentTime.TotalMilliseconds);

A: Basically you need to generate a clock to drive sample delivery. The AudioFileReader inherits from WaveStream which provides the current time for the samples via CurrentTime (calculated off of WaveFormat.AverageBytesPerSecond). You should be able to use this to timestamp the audio packets.
Also, depending of your project needs you may want to look at StreamCoder's MediaSuite.NET product. I've used it in the past to do similar things, it abstracts out much of the transport level complexity for this sort of thing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SMTP server response: 530 5.7.0 Must issue a STARTTLS command first. windows 7 Well I'm using windows 7 and I am trying to send e-mail with mail() function in php.
I wrote and tried a lot but still can not send. This is my code:
 ini_set("SMTP","smtp.gmail.com");
ini_set("smtp_port","25");

$to = 'asdf@gmail.com';
$subject = 'hi';
$msg = 'Test';
$headers ='Reply-To: shawn.danisa@gmail.com' . "\r\n" .
        'From: postmaster@localhost' ."\r\n" .
        'X-Mailer: PHP /' . phpversion();
mail($to, $subject,$msg,$headers);

and I get :
  SMTP server response: 530 5.7.0 Must issue a STARTTLS command first. x42sm11770579eel.41 - gsmtp

I tried with port 587 but then I get :
    SMTP server response: 530 5.7.0 Must issue a STARTTLS command first.      y51sm11859758eeu.0

Please help with port 465 my page even do not load. Again I am using windows 7.

A: Use a library like Swiftmailer that will handle this for you: http://swiftmailer.org/docs/sending.html


text:
Q: iTunes not playing without audio devices connected to audio port I am trying to use iTunes to loop through a playlist of videos – I do not need any audio output for these videos.
If I unplug the audio device (headphones, speakers, etc.) from the audio jack on the back of the computer, iTunes freezes and Windows shows me some errors about no audio devices being detected.
Is there a way to make iTunes play without an audio device connected to the jack?
I'm assuming this is a Windows issue because I don't think that the iTunes app would check for a connected audio device before playing anything?

A: I've found a fake audio driver somewhere that basically allows iTunes to play without any audio devices on the computer, this make sure that iTunes keeps playing and solves the problem. You can probably use any audio driver that fakes audio devices for this purpose...


text:
Q: CSS rotated element at bottom without height and width I have a problem with absolute positioning an element with transform: rotate() css.
I have read other posts on SO with similar problem and I used some solutions but still not solve my problem. I tried transform-origin etc.
I want to place my rotated link at the any X position: left, center, right & Y: bottom of a header. I need solution where I don't know width, height of element (different texts).
I think I have a 90% of solution but problem is my link is not placed whre I want. The X position changes with lenght of text.
I have a working code below:

<!doctype html>

  <meta charset="utf-8">

LOREM
IPSUM

Dolor sit amet, consectetur adipiscing elit. Vestibulum tristique sapien eget magna rutrum, ac fringilla diam elementum.

      learn more

    webpageeeeeee
scrollersbarrrrrrrrssssssssssssssss

Thanks, for any reply.

A: I changed your HTML to be like this :

LOREM
IPSUM

Dolor sit amet, consectetur adipiscing elit. Vestibulum tristique sapien eget magna rutrum, ac fringilla diam elementum.

  learn more
  webpageeeeeee
scrollersbarrrrrrrrssssssssssssssss

I added class to the first child of the div.header-content and put the element that you want to rotate inside this div not outside it as you was doing.
Then, I changed the style for the .link-decor to be
.link-decor {
    border-top: 2px solid #ed217c;
    color: #ffffff;
    font-size: 14px;
    position: absolute;
    top: 100%;
    left: 0px;
    padding-left: 30px;
    transform: rotate(-90deg) translate(-100%, 0);
    transform-origin: 0 0;
}

and added position relative to the new class .in-header

body {
    background: #333333;
    font-family: Arial, sans-serif;
  }

  .header-content {
    background: #cccccc;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 712px;
    margin: 0 auto;
    padding: 0 45px;
    position: relative;
    width: 1200px;
  }
  .in-header{
    position: relative;
  }

  .link-decor {
    border-top: 2px solid #ed217c;
    color: #ffffff;
    font-size: 14px;
    position: absolute;
    top: 100%;
    left: 0px;
    padding-left: 30px;
    transform: rotate(-90deg) translate(-100%, 0);
    transform-origin: 0 0;
  }
<!doctype html>

  <meta charset="utf-8">

LOREM
IPSUM

Dolor sit amet, consectetur adipiscing elit. Vestibulum tristique sapien eget magna rutrum, ac fringilla diam elementum.

      learn more
      webpageeeeeee
scrollersbarrrrrrrrssssssssssssssss


text:
Q: Difference between width: 50% and flex: 50% in a CSS flexbox? When its container has a display for flex, what is the difference between setting an element to be flex: 50% and width: 50%. The outcome appears to be the same:
ul {
  display: flex;
  flex-flow: row wrap;
}

.table a {
  flex: 50%;
  background: grey;
}

.table2 a {
  width: 50%;
  background: grey;
}

  ad ds fdsaf dsfa dsfj dsf dsfj lkdsjflkdsa jflkdsja lkfjdslkjfldska jlkfdsajlkdjslkajflkd sjalkfjdslkjdsalkjdlakjfldksjflkdsjflkdsjd fdsd
  b
  c
  d

  ad ds fdsaf dsfa dsfj dsf dsfj lkdsjflkdsa jflkdsja lkfjdslkjfldska jlkfdsajlkdjslkajflkd sjalkfjdslkjdsalkjdlakjfldksjflkdsjflkdsjd fdsd
  b
  c
  d

http://codepen.io/anon/pen/KAbof

A: There is no effective difference in this instance.
In fact, it's because flex is shorthand for flex-grow, flex-shrink and flex-basis combined.
flex-basis defines the default size of an element before the remaining space is distributed.
So in this case, you have defined all a children` to 50%.
Reference Article: http://css-tricks.com/snippets/css/a-guide-to-flexbox/


text:
Q: How to solve this inequality. Let $\alpha$, $\beta$, $\gamma$ be the angles of a triangle. Show that
$\sin\frac{\alpha}{2}.\sin\frac{\beta}{2}.\sin\frac{\gamma}{2}<{\frac{1}{4}}$

A: HINT:
$$2\sin\frac\alpha2\sin\frac\beta2=\cos\frac{\alpha-\beta}2-\cos\frac{\alpha+\beta}2$$
and $$\cos\frac{\alpha+\beta}2=\cos\frac{\pi-\gamma}2=\sin\frac\gamma2$$
Now use this method

A: As $0<\dfrac\alpha2<\dfrac\pi2,\sin\dfrac\alpha2>0$ etc.,
using A.M. $\ge$ G.M
$$\frac{\sin\dfrac\alpha2+\sin\dfrac\beta2+\sin\dfrac\gamma2}3\ge\sqrt[3]{\sin\dfrac\alpha2\cdot\sin\dfrac\beta2\cdot\sin\dfrac\gamma2} $$
Again as sine is concave in $[0,\pi]$ using Jensen's Inequality
$$\frac{\sin\dfrac\alpha2+\sin\dfrac\beta2+\sin\dfrac\gamma2}3\le\sin\left(\dfrac{\dfrac\alpha2+\dfrac\beta2+\dfrac\gamma2}3\right)=\sin\frac\pi6=\frac12$$


text:
Q: HTML+JS Расчеты в динамической таблице Таблица, в которую вводятся данные содержит ячейки - цена, количество. При вводе данных стоимость должна считаться автоматически. В этой таблице должны быть функции удаления и добавления строк. Сделано добавление и удаление строк.
Проблема в том, что у меня считается стоимость только в первой строке, а в остальных стоимость не считается...

var DynamicTable = (function(GLOB) {
  var RID = 0;
  return function(tBody) {
    if (!(this instanceof arguments.callee)) {
      return new arguments.callee.apply(arguments);
    }
    tBody.onclick = function(e) {
      var evt = e || GLOB.event,
        trg = evt.target || evt.srcElement;
      if (trg.className && trg.className.indexOf("add") !== -1) {
        _addRow(trg.parentNode.parentNode, tBody);
      } else if (trg.className && trg.className.indexOf("del") !== -1) {
        tBody.rows.length > 1 && _delRow(trg.parentNode.parentNode, tBody);
      }
    };
    var _rowTpl = tBody.rows[0].cloneNode(true);
    var _correctNames = function(row) {
      var elements = row.getElementsByTagName("*");
      for (var i = 0; i < elements.length; i += 1) {
        if (elements.item(i).name) {
          if (elements.item(i).type &&
            elements.item(i).type === "text" &&
            elements.item(i).className &&
            elements.item(i).className.indexOf("glob") !== -1) {
            elements.item(i).value = RID;
          } else {
            elements.item(i).name = RID + "[" + elements.item(i).name + "]";
          }
        }
      }
      RID++;
      return row;
    };
    var _addRow = function(before, tBody) {
      var newNode = _correctNames(_rowTpl.cloneNode(true));
      tBody.insertBefore(newNode, before.nextSibling);
    };
    var _delRow = function(row, tBody) {
      tBody.removeChild(row);
    };
    _correctNames(tBody.rows[0]);
  };
})(this);

var tbls = document.getElementById("dynamic");
for (var r = 0; r < tbls.rows.length; r++) {
  // последовательнный перебор всех рядов в каждой таблице
  var input = document.getElementsByTagName('input'),
    array = ['load', 'keyup'],
    i = array.length;
  while (i--) {
    window['on' + array[i]] = function() {
      function $(i) {
        return ~~input[i].value;
      }
      input[3].value = $(1) * $(2);
      var vvv = $(1) * $(2);
      document.getElementById('sum').value = $(3).toFixed(2);

      var thisRow = tbls.rows;
      thisRow.cells[3] = thisRow.cells[1] * thisRow.cells[2];
      alert("ghj");
    };
  }
};

new DynamicTable(document.getElementById("dynamic"));
<!DOCTYPE html>

  <title>TASK 1</title>

Таблица учета покупок.

  <form name="calc" class="calc">

          Товар
          Цена, руб.
          Количество
          Стоимость, руб.

               <input type="text" name="text" value="Наименование">

               <input type="number" value="0.00" required pattern="\d+(\.\d{2})?" >

               <input type="number" value="0.000" required pattern="\d+(\.\d{3})?">

              <input type="number" id="sum" required pattern="\d+(\.\d{2})?"  >

            <button type="button" class="add">+</button>
            <button type="button" class="del">-</button>

  </form>

A:

var DynamicTable = (function(GLOB) {
  var RID = 0;
  return function(tBody) {
    if (!(this instanceof arguments.callee)) {
      return new arguments.callee.apply(arguments);
    }
    tBody.onclick = function(e) {
      var evt = e || GLOB.event,
        trg = evt.target || evt.srcElement;
      if (trg.className && trg.className.indexOf("add") !== -1) {
        _addRow(trg.parentNode.parentNode, tBody);
      } else if (trg.className && trg.className.indexOf("del") !== -1) {
        tBody.rows.length > 1 && _delRow(trg.parentNode.parentNode, tBody);
      }
    };
    var _rowTpl = tBody.rows[0].cloneNode(true);
    var _correctNames = function(row) {
      var elements = row.getElementsByTagName("*");
      for (var i = 0; i < elements.length; i += 1) {
        if (elements.item(i).name) {
          if (elements.item(i).type &&
            elements.item(i).type === "text" &&
            elements.item(i).className &&
            elements.item(i).className.indexOf("glob") !== -1) {
            elements.item(i).value = RID;
          } else {
            elements.item(i).name = RID + "[" + elements.item(i).name + "]";
          }
        }
      }
      RID++;
      return row;
    };
    var _addRow = function(before, tBody) {
      var newNode = _correctNames(_rowTpl.cloneNode(true));
      tBody.insertBefore(newNode, before.nextSibling);
    };
    var _delRow = function(row, tBody) {
      tBody.removeChild(row);
    };
    _correctNames(tBody.rows[0]);
  };
})(this);

/* ДОБАВЛЕНО */
window.onkeyup = function() {
  for (var r = 0; r < document.getElementById("dynamic").rows.length; r++) {
    document.getElementsByTagName('input')[r * 4 + 3].value = document.getElementsByTagName('input')[r * 4 + 1].value * document.getElementsByTagName('input')[r * 4 + 2].value;
  }

};

new DynamicTable(document.getElementById("dynamic"));
<!DOCTYPE html>

  <title>TASK 1</title>

Таблица учета покупок.

  <form name="calc" class="calc">

          Товар
          Цена, руб.
          Количество
          Стоимость, руб.

                   <input type="text" name="text" value="Наименование">

              <input type="number" value="0.00" required pattern="\d+(\.\d{2})?" >

               <input type="number" value="0.000" required pattern="\d+(\.\d{3})?">

             <input type="number" id="sum" required pattern="\d+(\.\d{2})?"  >

            <button type="button" class="add">+</button>
            <button type="button" class="del">-</button>

  </form>


text:
Q: Project Euler Problem 87, prime power triplets The problem goes:
How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power?
And here is the link to the problem: https://projecteuler.net/problem=87
I'm having a problem when trying to get the right answer for higher inputs. My code in python is below. The function primestill(n) returns a generator of all primes below n and works just fine. I would appreciate any help.
def many2(x):
    counter = 0
    s1 = int(x**(1/4))+1
    for i in primestill(s1):
        s2 = int((x-i**4)**(1/3)) + 1
        for j in primestill(s2):
            s3 = int((x - i**4 - j**3)**(1/2))+1
            for k in primestill(s3):
                if i**4 + j**3 + k**2 < x:
                   counter += 1
    return counter

A: You should generate a list of primes up to the largest one that will fit under the 50 million mark.  This would be the largest prime with a square below 50M.
There are only 908 primes up to that largest prime so your loops can just combine these primes.
Note, however, that there are several combinations of primes that can produce the same sum so you will need to ensure that you count each sum only once (using a set for example).
To optimize the process you can break the nested loops once you reach a prime that would go beyond the maximum (50M):
# find eligible primes (Eratosthenes sieve)
N        = 50_000_000
maxPrime = int(N**0.5)
sieve    = [0,0]+[1]*maxPrime
p,np     = 1,2
primes   = []
while np<=maxPrime:
    p,np = np,p+2
    if not sieve[p]: continue
    primes.append(p)
    sieve[p*p::p] = [0]*len(sieve[p*p::p])

# nested loops to count distinct sums made from a**2 + b**3 + c**4
sums = set()
for c in primes:
    for b in primes:
        b3c4 = b**3 + c**4
        if b3c4 >= N: break
        for a in primes:
            s = a*a+b3c4
            if s >= N: break
            sums.add(s)

print(len(sums))


text:
Q: What short story had a man who taught himself to see with his fingers? When I was a kid (around 1981), I once read a short story where the main character gradually taught himself to see with his fingers. He used this skill to read books without looking at them (by seeing the text, not feeling it). And he may have used it for other things, I'm not sure. He was excited about this new skill/talent at first, but somehow it came back to haunt him in some way (the story had quite a dark mood by the end).
I have it stuck in my head that this story was by Roald Dahl (or possibly Rudyard Kipling, I used to get them a little crossed), but I haven't been able to find anything like this by him. At any rate, I think it was by someone who was generally known for lighter fare.
I'm pretty sure it was a short story, not a novel.
Can anyone think what this might have been?

A: "The Wonderful Story of Henry Sugar"

This story was indeed written by Roald Dahl. According to the Wikipedia description:

Henry, an independently wealthy man who enjoys gambling, finds and
  reads a doctor's report on a strange patient the doctor met while
  stationed at a hospital in India. This patient, who called himself
  "The Man Who Sees Without Using His Eyes", had the ability to see even
  after the doctors had medically sealed the man's eyes shut and
  bandaged his head. The man was part of a circus act and used his
  ability to make money. When interviewed in more detail by the curious
  doctors he gave an account which they wrote up. The man claimed he had
  been interested in magic all his life, and managed to study with Yogi
  Fakeirs in India, by which he develops the ability to see through thin
  objects such a paper or playing cards, and can see around solid
  objects such as a wooden door if he is allowed a finger or hand around
  it. The doctors decide the man could be of great benefit as a teacher
  of the blind, and return to the circus, only to find the show
  cancelled, when the Man Who Sees Without Using His Eyes has died.

He can see things with, say, a finger:

"Quite honestly, I don't know exactly how it is I can see without my
  eyes. But what I do know is this; when my eyes are bandaged, I am not
  using the eyes at all. The seeing is done by another part of my body."
"Which part?" I asked him.
"Any part at all so long as the skin is bare. For example, if you put
  a sheet of metal in front of me and put a book behind the metal, I
  cannot read the book. But if you allow me to put my hand around the
  sheet of metal so that the hand is seeing the book, then I can read
  it."
"The Wonderful Story of Henry Sugar"

There is a dark twist at the end; however, it never happened. Dahl is simply saying what would happen "if the story were fiction":

At first, the clot seems to be stationary. Then it moves. The movement
  is very slight, no more than a millimetre or two. The blood inside the
  vein is pumping up behind the clot and pushing past it and the clot
  moves again. It jerks forward about half an inch. This time, up the
  vein, towards the heart. Henry watches in terror. He knows, as almost
  everyone else in the world knows, that a blood-clot which has broken
  free and is travelling in a vein will ultimately reach the heart. If
  the clot is a large one, it will stick in the heart and you will
  probably die. . ..
 That wouldn't be such a bad ending for a work of fiction, but this story is not fiction. It is true. The only untrue things
  about it are Henry's name and the name of the gambling casino. Henry's
  name was not Henry Sugar. His name has to be protected. It still must
  be protected. And for obvious reasons, one cannot call the casino by
  its real name. Apart from that, it is a true story.
"The Wonderful Story of Henry Sugar"


text:
Q: MarkLogic TDE xpath on multiple repeating fields I need to create template using TDE. Eventually i want to be able to view data in using my view. The problem i see is because of multiple repeating elements in my xml. Can anyone please help me on how to create such a template. Here is the sample of the xml:
<entity>
  <id>id-2</id>
  <name>pub-2</name>
  <series name="s-21">s-21</series>
  <series name="s-22">s-22</series>
  <series name="s-23">s-23</series>
  <location>loc-1</location>
  <location>loc-2</location>
</entity>

I want to see 6 rows for the combination of both the repeatable fields i.e. series and location in this case. Any help will be highly appreciable.

A: Found a way using nested templates. Here is an example template:
<template xmlns="http://marklogic.com/xdmp/tde">
  <context>entity</context>
  <rows>
    <row>
      <schema-name>main</schema-name>
      <view-name>root</view-name>
      <view-layout>sparse</view-layout>
      <columns>
        <column>
          <name>id</name>
          <scalar-type>string</scalar-type>
          <val>id</val>
        </column>
        <column>
          <name>name</name>
          <scalar-type>string</scalar-type>
          <val>name</val>
        </column>
    </columns>
    </row>
  </rows>

  <templates>
    <template>
      <context>series</context>
      <rows>
        <row>
          <schema-name>main</schema-name>
          <view-name>series</view-name>
          <view-layout>sparse</view-layout>
          <columns>
            <column>
              <name>idParent</name>
              <scalar-type>string</scalar-type>
              <val>../id</val>
            </column>

            <column>
              <name>series</name>
              <scalar-type>string</scalar-type>
              <val>fn:string(.)</val>
              <nullable>true</nullable>
            </column>
          </columns>
        </row>
      </rows>
    </template>
    <template>
      <context>location</context>
      <rows>
        <row>
          <schema-name>main</schema-name>
          <view-name>location</view-name>
          <view-layout>sparse</view-layout>
          <columns>
            <column>
              <name>idParentlocation</name>
              <scalar-type>string</scalar-type>
              <val>../id</val>
            </column>
            <column>
              <name>name</name>
              <scalar-type>string</scalar-type>
              <val>fn:string(.)</val>
              <nullable>true</nullable>
            </column>
          </columns>
        </row>
      </rows>
    </template>
  </templates>
</template>

Here is the sql query:
select * from main.root
join main.location on main.location.idParentlocation = main.root.id
join main.series on main.series.idParent = main.root.id


text:
Q: Angular typescript implement same generic interface twice on class Hi I have bee kicking around code for awhile I do have a work around but I feel that it is not correct. Any help is much appreciated.
I am using the pattern shown here enter link description here
I am trying to implement the same generic interface twice for two different models where one is nested inside the other which is representative of nested JSON object. I have used the adapter pattern. this is where I am at:
import { Injectable } from '@angular/core';
import { Adapter } from './core/adapter';
import { map } from 'rxjs/operators';

export class MatchPoint {

constructor(
    public matchFlag: number,
    public maxIndividualScore: number,
    public inquiry: string,
    public mrc: number,
    public reason3: number,
    public reason2: number,
    public reason1: number,
    public numOfResults: number,
    public trans_id: string,
    public searchResult: SearchResult[]
) { }
}

export class SearchResult {

constructor(
    public jns: string,
    public city: string,
    public totalScorePrint: string,
    public cpin_count_i: string,
    public name: string,
    public ppbin: string,
    public hdistph: string,
    public phones: string,
    public searchlevel: string,
    public jas: string,
    public hdisttax: string,
    public cpbin: string,
    public state: string,
    public street: string,
    public totalScoreDecay: string,
    public ns1: string,
    public ns: string,
    public lvid: string,
    public zip5: string,
    public mrc: string
) { }
}

@Injectable(
{ providedIn: 'root' }
)
export class MatchPointAdapter implements Adapter<MatchPoint>,
**Adapter<SearchResult>** {

adapt(item: any): MatchPoint {
    return new MatchPoint(
        item.matchFlag,
        item.maxIndividualScore,
        item.inquiry,
        item.mrc,
        item.reason3,
        item.reason2,
        item.reason1,
        item.numOfResults,
        item.trans_id,
        this._adapt(item.searchResult) // need to loop and use the adapt
    );
}

_adapt(item: any[]): SearchResult[] {
    return new SearchResult(
        item.jns,
        item.city,
        item.totalScorePrint,
        item.cpin_count_i,
        item.name,
        item.ppbin,
        item.hdistph,
        item.phones,
        item.searchlevel,
        item.jas,
        item.hdisttax,
        item.cpbin,
        item.state,
        item.street,
        item.totalScoreDecay,
        item.ns1,
        item.ns,
        item.lvid,
        item.zip5,
        item.mrc
    );
}

}

Here is the workaround I have:
export class MatchPointAdapter implements Adapter<MatchPoint> {

adapt(item: any): MatchPoint {
    return new MatchPoint(
        item.matchFlag,
        item.maxIndividualScore,
        item.inquiry,
        item.mrc,
        item.reason3,
        item.reason2,
        item.reason1,
        item.numOfResults,
        item.trans_id,
        this.getSearchResults(item.searchResult)
    );
}

getSearchResults(searchResult: any[]): SearchResult[] {
    return searchResult.map((item: any) =>
        new SearchResult(
            item.jns,
            item.city,
            item.totalScorePrint,
            item.cpin_count_i,
            item.name,
            item.ppbin,
            item.hdistph,
            item.phones,
            item.searchlevel,
            item.jas,
            item.hdisttax,
            item.cpbin,
            item.state,
            item.street,
            item.totalScoreDecay,
            item.ns1,
            item.ns,
            item.lvid,
            item.zip5,
            item.mrc
        ));
}
}

Thanks


text:
Q: SQL Server connection identification I have several developers which connect to production and test servers where we have DBs with similar names and structures. In SSMS there are info related to the connection, but sometimes are not properly displayed and/or hidden.
I know that it is possible to customize the status bar of each connection in SSMS, but how do you ensure that your developer is connecting to the right server before he runs a query? Is there any way to handle this?
THANKS!

A: One answer is to not have developers touching production servers, and have deploys managed by someone else. This is often a requirement depending on the sensitivity of the data you are dealing with.

A: In SSMS, the connection information is displayed on a per query tab basis - all the devs have to do is mind what the tab label says.  Click the "New Query" button, and read what the tab is labelled.
After that, it's a matter of knowing which instance is Dev, Test, or Prod.  But you can make it more obvious by defining an alias that explicitly says "Dev", "Certification", "Production", etc via the Aliases node in SQL Server Configuration Manager.  The caveat is that these are defined on a per workstation basis.
But OrbMan brings up a good point that Production access should be severely limited.

A: Sounds like your devs require training.  Failing that, replace the broken part...


text:
Q: Vertically align padded matrix with different rows Allow me to elaborate: I have a square matrix that by padding zeros to the right columns, became non-square. I want to use one zero to represent the zero submatrix to ideally achieve this:

Instead what I got is this:

For the moment I faked it by replacing a \ddot with two dots in consecutive rows hence achieving odd number of rows:

Needless to say I don't like my hack.
Any advice?
\documentclass{article}
\usepackage{bm,delarray}
\begin{document}
    \[
    \bm{\Sigma} =
      \left[
      \begin{array}{cccc|c}
        \bm{\sigma}_1 & & & & 0 \\
        & \bm{\sigma}_2 & & & 0\\
        & & \ddots & & 0 \\
        & & & \bm{\sigma}_m & 0
      \end{array}
      \right]
    \]
    \[
    \bm{\Sigma} =
      \left[
      \begin{array}{ccccc|c}
        \bm{\sigma}_1 & & & & &  \\
        & \bm{\sigma}_2 & & & & \\
        & & . & & & 0 \\
        & & & . & &  \\
        & & & & \bm{\sigma}_m &
      \end{array}
      \right]
    \]
\end{document}

A: This way?
\documentclass{article}
\usepackage{bm, delarray, multirow

\begin{document}

    \[
    \bm{\Sigma} =
      \left[
      \begin{array}{cccc|c}
        \bm{\sigma}_1 & & & & \multirow{4}{*}[-0.5ex]{\Large$ 0 $} \\
        & \bm{\sigma}_2 & & & \\[-0.5ex]
        & & \ddots & & \\[-0.5ex]
        & & & \bm{\sigma}_m &
      \end{array}
      \right]
    \]

\end{document}

A: A quick work-around: use \smash for \ddots because it has more height than other math symbols. There are other options, of course, if you don't like this hack; one can increase inter-row space via \renewcommand{\arraystretch}{1.5} for example, or adding \vphantom{\ddots} to all other rows without \ddots.
\documentclass{article}
\usepackage{bm,delarray}
\begin{document}
    \[
    \bm{\Sigma} =
    \left[
    \begin{array}{cccc|c}
    \bm{\sigma}_1 & & & & 0 \\
    & \bm{\sigma}_2 & & & 0\\
    & & \smash{\vcenter{\hbox{$\ddots$}}} & & 0 \\
    & & & \bm{\sigma}_m & 0
    \end{array}
    \right]
    \]
\end{document}

A: Nest a matrix in the array
\documentclass{article}
\usepackage{amsmath}
\usepackage{bm}

\begin{document}

\[
\bm{\Sigma} =
\left[\begin{array}{@{}c|c}
  \begin{matrix}
  \bm{\sigma}_1 \\
  & \bm{\sigma}_2 \\
  & & \ddots \\
  & & & \bm{\sigma}_m
  \end{matrix}
& 0
\end{array}\right]
\]

\end{document}


text:
Q: FullCalendar & Symfony 1.3 insert data in DB without form i'm trying to use fullCalendar's plugin in my symfony projet, but i have some trouble to insert data into database.
i have a page calendar/index, where we can see the calendar, and the javascript to create an event etc.
my first approach was to do something simple. Insert the title of the event in database, for that i try this :
$.ajax({
    type: "POST",
    url: "calendar/data",
    data: title,
    dataType: 'script'
});

And now i would like to insert the title in my database with the executeData in actions.class.php, but the only way to insert data into database that i know is  with form.
My question is :
Can i do something like that, and if yes, how insert data in the database ?

A: You have to grab in php the header sent to your php script:
First change this and try:
$.ajax({
    type: "POST",
    url: "calendar/data",
    data: {title:'my title to insert'}, //data: title,
    //dataType: 'script' remove this
});

In the beggining of your php script you should have this:
<?php

//Error Reporting -> You don´t need to have the next 4 lines, ignore them.
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);

/*Try to fetch the title*/
if($_POST['title']){
   var_dump($_POST['title']);
   //You should see your title on top of the webpage or in network debug from chrome or firefox in XHR separator
 }else{ echo "Crap no title"; }

 ?>

Also make sure your in the same domain, cross domain ajax requests are a pain...


text:
Q: Dimensional Vector spoace with injective surjective and bijective I know there are similar questions on the internet, but I'm not getting it smart.
i hope u can help me,
Let $B,C$ finite dimensional Vector space with $\dim(C) = \dim(B)$ and $R \in Hom(B,C)$.
Then it should be equivalent to R is injective, R is surjective and R is bijective.
I hope u can help me to construct a proof

A: Note: This is a reply to the original version of the question, where it was specified that $B$ and $C$ were "endless dimensional". So of course it's irrelevant to the current version, where $B$ and $C$ are finite-dimensional. May as well leave it here, to show that the hypothesis is needed.
The question is totally unclear, and the comment doesn't clarify things much. It seems possible that you actually want to prove that $R$ is injective if and only if $R$ is surjective. If so:
(i) you should say so!
(ii) you can't prove that because it's false. Say $B$ is the space of sequences of real numbers. Let $C=B$, and define $R:B\to C$ by $$Rx=(0,x_1,x_2,\dots).$$
Then $R$ is injective  but not surjective.
You should give a similar example of a linear map which is surjective but not injective.

A: As @David has mentioned, it would help if you made the question clearer. Since the statement does not hold for infinite-dimensional vector spaces, is it possible that you actually want to prove it for finite-dimensional vector spaces?
If that is the case, choose a basis for $B$; say, $\lbrace x_1,\dots ,x_n\rbrace$. If $R$ is injective, try showing that $\lbrace R(x_1),\dots ,R(x_n)\rbrace$ is linearly independent in $C$. Here you must use (a) that $R$ is injective and (b) that $R$ is linear. Then conclude from dimension considerations that $\mathrm{span} (R(x_1),\dots ,R(x_n))$ is a basis for $C$, hence showing that $R$ is surjective.
The proof of surjective $\Rightarrow$ injective is somewhat similar.
Walkthrough. In case you give up, here is a walkthrough of the proof for injective $\Rightarrow$ surjective. Let $\lbrace x_1,\dots ,x_n\rbrace$ be as above. Then $\mathrm{dim} (B) = \mathrm{dim} (C) = n$. We will show that $\lbrace R(x_1),\dots ,R(x_n)\rbrace$ is a basis for $C$.
First we must see that $R(x_1),\dots ,R(x_n)$ are linearly independent. Suppose we have
$$
\alpha_1R(x_1)+\dots +\alpha_n R(x_n) = 0.
$$
But $R$ is linear, so we get:
$$
R(\alpha_1x_1 + \dots + \alpha_nx_n) = 0.
$$
Since $R$ is injective, we then have
$$
\alpha_1x_1 + \dots + \alpha_n x_n = 0.
$$
But $x_1,\dots ,x_n$ are linearly independent, so we must have $\alpha_i = 0$ for each $i=1,\dots ,n$. This shows that $R(x_1),\dots ,R(x_n)$ are linearly independent. Hence they must span an $n$-dimensional subspace of $C$. Since $C$ is $n$-dimensional, this must be all of $C$. But then $R$ is surjective.


text:
Q: How to transfer array? Introduction:
I'm using a objc++ to Swift bridge where I implemented a delegate to Swift like:
func callback(_ myCallbackValue: String!) {
   print(myCallbackValue);
}

and a objc++ function that does a callback like:
[self.delegate myCallbackInstance: myCallbackValue];

Some example code:
The callback using simple Types like "String", "int" or "double" is working fine - but I got big problems to callback 2d-arrays (from c++ vectors) like :
(objc++) vector<vector<String>>    ->    (swift) [[String]]

e.g. c++:
vector<vector<String>>myVector = { {"1", "dh", "o4"}, {"2", "5", "1"} };

to swift:
let myCallback : [[Sting]] = ?? // should get [ ["1", "dh", "o4"], ["2", "5", "1"] ]

My quesion:

How can I implement this specific callback the right way?

Any help would be very appreciated! Thanks.


text:
Q: Javascript OO question So I want to build a form validation class/object in javascript. The way I see it working would be something like this:
var form=new Validation();
form.addField("name","Your name","required");
form.addField("email","Email Address","is_email");
.........
form.validate();

I was thinking that the validation class would be defined something like this?
validation
{
  var fields=new Array();
  var labels=new Array();
  var rules=new Array();
  var count=0;

  function addField(field,label,rule)
  {
    this.fields[count]=field;
    this.labels[count]=label;
    this.rules[count]=rule;
    this.count=count+1;
  }

  function validate()
  {
    var valid;
    for (x=0; x< count; x++)
    {
      valid=false;
      switch (this.rules[x])
      {
         case 'required':
           valid=this.validate_required(this.fields[x]);
           break;

         case 'email':
           valid=this.validate_email(this.fields[x]);
           break;
       }

       if (! valid)
         this.addError(this.fields[x],this.rules[x],this.labels[x]);
     }

     if (this.hasErrors())
       return false;
     else
       return true;
   }

..........
}

I'm aware that this probably isn't possible as it is right now. My question is, what can I do to so the first block of code (which creates a new instance of Validation and adds the rules to it) would work?
Thanks in advance.

A: You're just missing some OO notation. Lines marked with a "// ***" comment are the ones I changed from your original code sample:
function Validation() // ***
{
  var fields=new Array();
  var labels=new Array();
  var rules=new Array();
  var count=0;

  this.addField = function (field,label,rule) // ***
  {
    fields[count]=field; // ***
    labels[count]=label; // ***
    rules[count]=rule;   // ***
    count=count+1;
  }

  this.validate = function () // ***
  {
    var valid;
    for (x=0; x< count; x++)
    {
      valid=false;
      switch (rules[x]) // ***
      {
         case 'required':
           valid=this.validate_required(fields[x]); // ***
           break;

         case 'email':
           valid=this.validate_email(fields[x]); // ***
           break;
       }

       if (! valid)
         this.addError(fields[x],rules[x],labels[x]); // ***
     }

     if (this.hasErrors())
       return false;
     else
       return true;
   }
}

Oh and I didn't see validate_required(), validate_email(), addError() nor hasErrors(). Might wanna add those.

A: Javascript is Prototype-based programming language.So there is no true way to have classes.
The way create classes (or simulate it) is by using function that have state and more functions inside it encompassing behavior.
To solve your question,you can create the Validation Class by using a global level function and instantiate it with new keyword for each form you have.
So actually you just need to make your class definition a function.(Convention:Capital V is just used as notation to designate that this function is a class)
function Validation()
{
  var fields=new Array();
  var rules=new Array();
  var labels=new Array();
  var errors=new Array();
  var count=0;

  function addError(field,rule,label){
    //add error in errors array
  }

  function validate_required(field){
    //do required validation
  }

  function validate_email(field){
    //do email validation
  }

  return function(){

      addField = function(f,r,l){
        this.fields[count]=f;
        this.rules[count]=r;
        this.labels[count]=l;
        this.count=count+1;
      }

      validate = function ()
      {
        var valid;
        for (x=0; x< count; x++)
        {
          valid=false;
          switch (this.rules[x])
          {
             case 'required':
               valid=validate_required(this.fields[x]);// create private function
               break;

             case 'email':
               valid=validate_email(this.fields[x]);// create private function
               break;
           }

           if (! valid)
             addError(this.fields[x],this.rules[x],this.labels[x]);
         }

         if (this.hasErrors())
           return false;
         else
           return true;
       }
   }
}

To understand more about JavaScript and its features (and nuisances) , you can go through Douglas Crockford's home page .it has many easy to follow through JavaScript references especially related to Prototype and inheritance .


text:
Q: How to retrieve the contents of entry and text widget and assign it to a variable in tkinter using python Well I have the following code which I wrote for creating a gui based email client using python.I used tkinter.I want that the text the user writes in the entry widget gets assigned to the variables sender,password,receiver,message.
I have used entry widget for getting the values of sender,password,receiver and text widget for the message .How to do so?I tried many methods(like the get method,the textvariable method) for this but its not getting executed.I am a newbie and hence would prefer an answer which does not involve classes.Please reply soon!Its urgent.Thanks for your help.I am just showing you what I did in case of assigning value to variable sender but i want this for all the four variables.
import smtplib
from Tkinter import *
import tkMessageBox

def Composemail(sender,password,receivers,message):
    try:
        server = smtplib.SMTP()
        server.connect('smtp.gmail.com',587) # for eg. host = 'smtp.gmail.com', port = 587
        server.ehlo()
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, receivers, message)
        #smtpObj = smtplib.SMTP_SSL('smtp.gmail.com',587)
        #smtpObj.sendmail(sender, receivers, message)
        tkMessageBox.showinfo("Sending Mail information","Mail sent.")
    except smtplib.SMTPException, error:
        tkMessageBox.showinfo("Sending Mail information","Sending Mail failed.Try again  later.")

a=Tk()
a.title("MailsNow-A new place for sending emails")
a.geometry("1000x700")
b=Label(a,fg="Purple",text="From")
b.pack()
sender=StringVar() #the problem starts here
c=Entry(a,bd=5,width=100,textvariable=sender)
c.pack()
d=Label(a,fg="Purple",text="Password")
d.pack()
e=Entry(a,bd=5,width=100,show="*")
e.pack()
password='abc'
f=Label(a,fg="Purple",text="To")
f.pack()
receivers = 'abc@gmail.com'
g=Entry(a,bd=5,width=100)
g.pack()
h=Label(a,fg="Purple",text="Subject")
h.pack()
i=Entry(a,bd=5,width=100)
i.pack()
j=Label(a,fg="Purple",text="Type your email here")
j.pack()
k=Text(a,bd=5,height=20,width=100)
k.pack()
message = """From: From Person <abc@gmail.com>#I want to know how to do the same for text #widget too
To: To Person <xyz@gmail.com>
Subject: SMTP e-mail test

Hi , now I can send you emails using this......hurrah1!using Sending mail transfer protocol by a python
code!!!!
"""
l=Button(a,
text="Sendmail",bg="Purple",activebackground="Yellow",
command=lambda:Composemail(sender,password,receivers,message))
l.pack()
a.mainloop()

A: In your specific case, you don't need to use StringVar.  This should be what you want:
import smtplib
from Tkinter import *
import tkMessageBox

def Composemail(sender,password,receivers,message):
    try:
        server = smtplib.SMTP()
        server.connect('smtp.gmail.com',587)
        server.ehlo()
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, receivers, message)
        tkMessageBox.showinfo("Sending Mail information","Mail sent.")
    # Just a tip, "error" isn't defined yet so it will blow up.
    except smtplib.SMTPException, error:
        tkMessageBox.showinfo("Sending Mail information","Sending Mail failed.Try again  later.")

a=Tk()
a.title("MailsNow-A new place for sending emails")
a.geometry("1000x700")
b=Label(a,fg="Purple",text="From")
b.pack()
c=Entry(a,bd=5,width=100)
c.pack()
d=Label(a,fg="Purple",text="Password")
d.pack()
e=Entry(a,bd=5,width=100,show="*")
e.pack()
f=Label(a,fg="Purple",text="To")
f.pack()
g=Entry(a,bd=5,width=100)
g.pack()
h=Label(a,fg="Purple",text="Subject")
h.pack()
i=Entry(a,bd=5,width=100)
i.pack()
j=Label(a,fg="Purple",text="Type your email here")
j.pack()
k=Text(a,bd=5,height=20,width=100)
k.pack()

def getstuff():
    # You can retrieve the text entered into an entrybox using the get method
    sender=c.get()
    password=e.get()
    receivers=g.get()
    subject=i.get()
    # Since textboxes are multiline, I have to tell it what text to get.
    # 0.0,END is saying "get everything from start to finish".
    message=k.get(0.0,END)

    # One thing I noted was that you are not sending the subject to
    # Composemail.  Is this what you want?
    Composemail(sender,password,receivers,message)

l=Button(a, text="Sendmail",bg="Purple",activebackground="Yellow",
command=getstuff)
l.pack()

a.mainloop()

When you click the "Sendmail" button, everything you entered into the application is gathered and sent to Composemail.  From there, you can do whatever you want with it.
p.s.  I threw out some of your code so I could work with your problem better.


text:
Q: VB - How to obtain category color for Outlook AppointmentItem First time here...
I'm editing OlCalndr.dot macros (import Outlook Calendar info into Word) and trying to grab the category color for each appointment.
I have the AppointmentItem object, and appt.Categories will return a String of the categories this appointment has.  However, I can't figure out how to get the category color.
Grateful for any help...
cheers,
David

A: You have to manually look up the category name into the categories catalog from the Namespace.

*

*Obtain the string of categories from the AppointmentItem.Categories

*Split (on ','). Find the first Name.

*Obtain the full collection of available categories from Application.Session.Categories

*Enumerate through the categories until you find the one with the name from step (2).

*This category will have a Color (from the olCategoryColor enumeration).


text:
Q: The first iteration of nested loops does not iterate till last element I need to print the largest contiguous sum of elements in list. The answer is correct if it is in any iteration other than the first iteration.
n = int(input())

s = input()
s = s.split()
u = []
print(s)

for i in range(0, n):
    sum = s[i]
    for j in range(i, n-1):

        if int(s[j]) + int(s[j+1]) >= int(sum):
            sum = int(sum) + int(s[j+1])
            print(s[j], s[j+1])
            print(int(sum))
        else:
            u.append(int(sum))
            break

u.sort()
print(u[-1])

Above is the code.
Input:
5
1 2 3 4 5

Output:
14

Expected output:
15

A: You can delete the first input.
This will work.
But I dont understand what you want. So... I'll edit it when you say it's wrong and how I need to do it.
s = input()
s = s.split()
sum = 0

for i in range(0, len(s) - 1):
    if s[i] = s[i + 1]
    sum += int(i)
print(sum)


text:
Q: Can I use wildcards in the filemap of hg convert I have a repository with one file (subdir/a.txt), and the one revision, adding it.
If I run hg convert with a filemap consisting of include subdir/a.txt, it works just fine.
But if the filemap is include subdir/*.txt, include */a.txt, or include **/*.txt, the resultant repository has no revisions in it.
Is it possible do use wildcards in the filemap of hg convert?
--
The reason I want to do this is so that I can create a new repository with history, but without any binary files.  I want to be able to do something like exclude **/*.dll.  Is there any way to do that?

A: Wildcards do not seem to be supported, but you can use hg manifest --all to get a list of all files present in all changesets, and do some filtering and editing of the output to generate what to exclude.  Something like the following to list all the DLL file paths on Windows:
hg manifest --all | findstr \.dll


text:
Q: SQL Server cannot connect to Visual Studio using Server Explorer I'm a beginner developer, when I tried to connect database to Visual Studio by means of the Server Explorer, this error message pops up.

Does anyone know how to fix this?


text:
Q: Selecting parent records of children that meet multiple conditions (but not together) with SQLite I don't know why I can wrap my head around this query. I think I am not asking the correct question which is why I am struggling to find an answer.
I have two tables. items and skus. I am trying to identify items that have skus that meet both the following conditions:

*

*Has a SKU with a price_date > specified date

*Has a SKU with a custom = 1.

Using the below example:
items

ID
Name

1
My Item 1

2
My Item 2

skus

ID
ItemID
SKU
price_date
custom

1
1
1234
2020-12-11*
0

2
1
5678
2020-05-01
1*

2
2
ABDC
1900-01-01
0

I am trying to get my query to return "My Item 1" from the items table as it has one sku that is greater than my specified date and another that has a custom value equaling 1. The problem is that my query only "hits" if a SKU meets both conditions together (meaning 1 sku must met all conditions). In the table you can see that SKU ID 1 meets my first condition and SKU ID 2 meets my seconds condition for parent item "My Item 1"
The below query return nothing even though the skus for My Item 1 meet the conditions.
SELECT * FROM items
LEFT JOIN skus ON items.ID=skus.ItemID
GROUP BY items.ID
HAVING sku.price_date>date('2020-12-01') AND sku.custom=1

How can I make the query look at all child items together, and then return the item if all conditions are met, regardless of if the conditions hit in a single sku together?

A: Instead of JOIN skus, we need to first figure out which ItemID-s qualify..  I am using MCNT as table prefix Multiple Conditions Not Together...
SELECT [ItemID]
  FROM [StackOver].[dbo].[MCNTskus]
  Group By [ItemID]
  Having
       max([price_date]) > ('2020-12-01')
     and
       max([custom])  = 1

Then use that as FROM and do LeftJoin of items
With qualSKUs as
(SELECT [ItemID]
  FROM [StackOver].[dbo].[MCNTskus]
  Group By [ItemID]
  Having
       max([price_date]) > ('2020-12-01')
     and
       max([custom])  = 1
)
SELECT MCNTitems.ID, MCNTitems.Name
    FROM qualSKUs
LEFT JOIN MCNTitems ON MCNTitems.ID=qualSKUs.ItemID
GROUP BY qualSKUs.ItemID,MCNTitems.ID, MCNTitems.Name

Resulting in
ID  Name
1   My Item 1


text:
Q: Can't return appended value from within a Python process I am running Python 2.6.5 on Ubuntu 8.10.
For a project I am working on, I need to run several processes concurrently and save each of their outputs into their own respective lists. Since I can't return the output value directly from the process, I am passing the output list as an argument to my target function and appending the output to that list. The problem is that when I try to access that list after running the process, the list is still empty. A simplified version of the problem I'm having is below along with the error message.
Code:
from multiprocessing import Process
import sys, math, os,commands

outputs = []

def calculate(a,b,outputs):
    c = a*b
    outputs.append(c)
    #return c

outputs1 = []

p1 = Process(target = calculate, args = (2,3,outputs1))

p1.start()
p1.join()

print 'len(outputs1) = ' + str(len(outputs1))

print 'outputs1 = ' + str(outputs1[0])

Error:
len(outputs1) = 0
Traceback (most recent call last):
  File "append_test.py", line 23, in <module>
    print 'outputs1 = ' + str(outputs1[0])
IndexError: list index out of range

I am trying to keep each process completely independent of the others for fear of corrupting data. I've looked into trying to use the Array module from multiprocessing, but it appears that append is specific to lists. When I run the exact same code with Thread instead of Process, I get the desired output with no problem, which leads me to believe this is an issue of memory sharing.

A: When you use separate processes, each process gets its own copy of everything in memory. That's why the parent process never sees anything in its outputs: each child process is appending to its own copy of outputs.
You need to use some form of interprocess communication. Python's multiprocessing library supplies two features for this: pipes and queues.
For example, using a Queue:
>>> from multiprocessing import Process, Queue
>>> def f(q): q.put("hello from the child process")
...
>>> q = Queue()
>>> p = Process(target=f, args=(q,))
>>> p.start()
>>> p.join()
>>> q.get()
'hello from the child process'

A: The section titled Exchanging objects between processes  in the in the online documentation of themultiprocessingmodule says that it [only] "supports two types of communication channel between processes" and goes on to mention Queues and Pipes. Notably it does not mentionlistobjects likeoutputs1. This makes sense because the two processes don't share memory AFAIK.
I'm not sure, but I also suspect you might need to put the section of your code that creates the process and starts it, etc inside of anif __name__ == '__main__':clause to prevent the subprocess from creating a sub-subprocess.
In summary, I think you're going to have to rework things to use one of those two for interprocess communications -- Queues seem like the logical choice to me.


text:
Q: Cassndra/Spark Correlating Data points seperated by million record I have sensor data and the approx format shows the way i am storing it in a cassandra table.
CREATE TABLE sensor_log (
    sensor_id BIGINT,
    created_at TIMEUUID,
    SensorEventType TEXT,
    PRIMARY KEY(sensor_id, created_at)
)
WITH CLUSTERING ORDER BY (created_at DESC)

There are like 10 different types of events(SensorEventType) which occur. Say they are named
(SensorEventType)SET1...SET10.

And i am keeping the data for 90 days.
Some of these types of events occur quite frequent and some are very infrequent.
so what is happening is SET1 occurs say on day1 and SET9 occurs on after day 60. In Between this there are many other SensorEventType records which are logged. So in between there will be 100 Millions of data points.
example

SENSOR_ID   Data stored Clustered by created_at.
 1         SET2,SET1,SET3,SET4....100millionrandomSET....SET9,SET3,SET4....
 2         SET4,SET5,SET1,SET4....100millionrandomSET....SET2,SET9,SET6....

each SET stored in sequential manner by created_at

I need to correlate for each sensor the fact that SET1 AND SET9 data points in a logic to derive some information. I am thinking of using spark for the same.
The Correlation is purely based on the SensorEventType and is the business logic requirement to find the time duration between the SET9 and SET1. So If SET9 happened after SET1 then note the time duration between the occurrence and save it in another table.
Now the question is in order to correlate the data in Spark it seems that i need to actually load all the data points , all million of them in memory to correlate between SET1 AND SET9. Is that a right way to think about solving this design problem.
Any one has better pointers to how this should be designed and how correlation in spark across million in between data point would work. I am new to spark, any help would be appreciated in understanding.

A: I'm not sure I fully understand your use case, but it seems like perhaps you don't need to use Spark and could do this correlation in plain Cassandra.
Instead of (or perhaps in addition to) your table that records all events for a sensor in a single partition, why not add the event type to the partition key like this:
CREATE TABLE sensor_log (
    sensor_id BIGINT,
    created_at TIMEUUID,
    SensorEventType TEXT,
    PRIMARY KEY((sensor_id, SensorEventType), created_at)
)
WITH CLUSTERING ORDER BY (created_at DESC)

This will put each SET value in its own partition for each sensor that you can query independently.
By doing that, the 100 million data points in between SET1 and SET9 events  would be put in separate partitions and would not get in your way.  So when a SET9 event comes in, just select the most recent data point from the SET1 partition for that sensor:
SELECT created_at FROM sensor_log WHERE sensor_id=x and SensorEventType=SET1 LIMIT 1;

Now you subtract that created_at time from the created_at time of the incoming SET9 event.
Partitioning like this would also simplify using Spark since you would create RDD's from these smaller partitions, and only load the SET1 and SET9 partitions instead of all the SET types.


text:
Q: Blueimp jQuery File Upload Audio/Video restriction Can anyone please tell me how can I restrict audio/video file upload using Blueimp jQuery File upload?
I found the whitelisting using the following option acceptFileTypes:  /(\.|\/)(gif|jpe?g|png)$/i, but I want to blacklist audio and video files instead of whitelisting.
I have tried the following to negate .exe and .js files acceptFileTypes: /(\.|\/)(?!exe|js)$/i which is restricting all file types regardless of its extensions.
Thanks in advance

A: You are putting $in wrong place. If you want to find anything except .exe, .js, use
(\.|\/)(?!(exe|js)$)

Regex Demo
Reason :- Lookaheads are of zero width-assertion. It means that they do not consume any characters. In your regex
(\.|\/)(?!exe|js)$

you are checking for exe or js just after . using lookahead. As soon as it is checked the position resets just after .. Now your regex is checking whether it is end of string using $. But there is a character left, so it is not end of string and your regex will fail for any extension.
Below, there is some visual to explain for your regex (\.|\/)(?!exe|js)$
for string abcd.jpg. (Spaces only for clarity)
    abcd .  jpg
        ^^  ^^
        ||  ||
(Matches .) (New position after consuming .)

What follows after . is jpg, which should not be matched to either exe or js <---good till here
As lookahead is of zero-width, the position remains where it is after checking what follows is neither exe nor js
 abcd . jpg
        ^^
        ||
 Check whether its $ i.e. end of string. This is False because we have j. So no match is returned

If you want to blacklist audio and video file, here is starter
(?:[.\\])(?!(mp3|m4a|wmv|mp4|mkv)$)\w+

Regex Demo


text:
Q: How do I do word Stemming or Lemmatization? I've tried PorterStemmer and Snowball but both don't work on all words, missing some very common ones.
My test words are: "cats running ran cactus cactuses cacti community communities", and both get less than half right.
See also:

*

*Stemming algorithm that produces real words

*Stemming - code examples or open source projects?

A: Martin Porter's official page contains a Porter Stemmer in PHP as well as other languages.
If you're really serious about good stemming though you're going to need to start with something like the Porter Algorithm, refine it by adding rules to fix incorrect cases common to your dataset, and then finally add a lot of exceptions to the rules.  This can be easily implemented with key/value pairs (dbm/hash/dictionaries) where the key is the word to look up and the value is the stemmed word to replace the original. A commercial search engine I worked on once ended up with 800 some exceptions to a modified Porter algorithm.

A: Based on various answers on Stack Overflow and blogs I've come across, this is the method I'm using, and it seems to return real words quite well. The idea is to split the incoming text into an array of words (use whichever method you'd like), and then find the parts of speech (POS) for those words and use that to help stem and lemmatize the words.
You're sample above doesn't work too well, because the POS can't be determined. However, if we use a real sentence, things work much better.
import nltk
from nltk.corpus import wordnet

lmtzr = nltk.WordNetLemmatizer().lemmatize

def get_wordnet_pos(treebank_tag):
    if treebank_tag.startswith('J'):
        return wordnet.ADJ
    elif treebank_tag.startswith('V'):
        return wordnet.VERB
    elif treebank_tag.startswith('N'):
        return wordnet.NOUN
    elif treebank_tag.startswith('R'):
        return wordnet.ADV
    else:
        return wordnet.NOUN

def normalize_text(text):
    word_pos = nltk.pos_tag(nltk.word_tokenize(text))
    lemm_words = [lmtzr(sw[0], get_wordnet_pos(sw[1])) for sw in word_pos]

    return [x.lower() for x in lemm_words]

print(normalize_text('cats running ran cactus cactuses cacti community communities'))
# ['cat', 'run', 'ran', 'cactus', 'cactuses', 'cacti', 'community', 'community']

print(normalize_text('The cactus ran to the community to see the cats running around cacti between communities.'))
# ['the', 'cactus', 'run', 'to', 'the', 'community', 'to', 'see', 'the', 'cat', 'run', 'around', 'cactus', 'between', 'community', '.']

A: http://wordnet.princeton.edu/man/morph.3WN
For a lot of my projects, I prefer the lexicon-based WordNet lemmatizer over the more aggressive porter stemming.
http://wordnet.princeton.edu/links#PHP has a link to a PHP interface to the WN APIs.

A: Look into WordNet, a large lexical database for the English language:
http://wordnet.princeton.edu/
There are APIs for accessing it in several languages.

A: I use stanford nlp to perform lemmatization. I have been stuck up with a similar problem in the last few days. All thanks to stackoverflow to help me solve the issue .
import java.util.*;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.ling.CoreAnnotations.*;

public class example
{
    public static void main(String[] args)
    {
        Properties props = new Properties();
        props.put("annotators", "tokenize, ssplit, pos, lemma");
        pipeline = new StanfordCoreNLP(props, false);
        String text = /* the string you want */;
        Annotation document = pipeline.process(text);

        for(CoreMap sentence: document.get(SentencesAnnotation.class))
        {
            for(CoreLabel token: sentence.get(TokensAnnotation.class))
            {
                String word = token.get(TextAnnotation.class);
                String lemma = token.get(LemmaAnnotation.class);
                System.out.println("lemmatized version :" + lemma);
            }
        }
    }
}

It also might be a good idea to use stopwords to minimize output lemmas if it's used later in classificator. Please take a look at coreNlp extension written by John Conwell.

A: I tried your list of terms on this snowball demo site and the results look okay....

*

*cats -> cat

*running -> run

*ran -> ran

*cactus -> cactus

*cactuses -> cactus

*community -> communiti

*communities -> communiti

A stemmer is supposed to turn inflected forms of words down to some common root. It's not really a stemmer's job to make that root a 'proper' dictionary word. For that you need to look at morphological/orthographic analysers.
I think this question is about more or less the same thing, and Kaarel's answer to that question is where I took the second link from.

A: The stemmer vs lemmatizer debates goes on. It's a matter of preferring precision over efficiency. You should lemmatize to achieve linguistically meaningful units and stem to use minimal computing juice and still index a word and its variations under the same key.
See Stemmers vs Lemmatizers
Here's an example with python NLTK:
>>> sent = "cats running ran cactus cactuses cacti community communities"
>>> from nltk.stem import PorterStemmer, WordNetLemmatizer
>>>
>>> port = PorterStemmer()
>>> " ".join([port.stem(i) for i in sent.split()])
'cat run ran cactu cactus cacti commun commun'
>>>
>>> wnl = WordNetLemmatizer()
>>> " ".join([wnl.lemmatize(i) for i in sent.split()])
'cat running ran cactus cactus cactus community community'

A: This looks interesting:
MIT Java WordnetStemmer:
http://projects.csail.mit.edu/jwi/api/edu/mit/jwi/morph/WordnetStemmer.html

A: Take a look at LemmaGen - open source library written in C# 3.0.
Results for your test words (http://lemmatise.ijs.si/Services)

*

*cats -> cat

*running

*ran -> run

*cactus

*cactuses -> cactus

*cacti -> cactus

*community

*communities -> community

A: The top python packages (in no specific order) for lemmatization are: spacy, nltk, gensim, pattern, CoreNLP and TextBlob. I prefer spaCy and gensim's implementation (based on pattern) because they identify the POS tag of the word and assigns the appropriate lemma automatically. The gives more relevant lemmas, keeping the meaning intact.
If you plan to use nltk or TextBlob, you need to take care of finding the right POS tag manually and the find the right lemma.
Lemmatization Example with spaCy:
# Run below statements in terminal once.
pip install spacy
spacy download en

import spacy

# Initialize spacy 'en' model
nlp = spacy.load('en', disable=['parser', 'ner'])

sentence = "The striped bats are hanging on their feet for best"

# Parse
doc = nlp(sentence)

# Extract the lemma
" ".join([token.lemma_ for token in doc])
#> 'the strip bat be hang on -PRON- foot for good'

Lemmatization Example With Gensim:
from gensim.utils import lemmatize
sentence = "The striped bats were hanging on their feet and ate best fishes"
lemmatized_out = [wd.decode('utf-8').split('/')[0] for wd in lemmatize(sentence)]
#> ['striped', 'bat', 'be', 'hang', 'foot', 'eat', 'best', 'fish']

The above examples were borrowed from in this lemmatization page.

A: If you know Python, The Natural Language Toolkit (NLTK) has a very powerful lemmatizer that makes use of WordNet.
Note that if you are using this lemmatizer for the first time, you must download the corpus prior to using it.  This can be done by:
>>> import nltk
>>> nltk.download('wordnet')

You only have to do this once.  Assuming that you have now downloaded the corpus, it works like this:
>>> from nltk.stem.wordnet import WordNetLemmatizer
>>> lmtzr = WordNetLemmatizer()
>>> lmtzr.lemmatize('cars')
'car'
>>> lmtzr.lemmatize('feet')
'foot'
>>> lmtzr.lemmatize('people')
'people'
>>> lmtzr.lemmatize('fantasized','v')
'fantasize'

There are other lemmatizers in the nltk.stem module, but I haven't tried them myself.

A: Do a search for Lucene, im not sure if theres a PHP port but I do know Lucene is available for many platforms. Lucene is an OSS (from Apache) indexing and search library. Naturally it and community extras might have something interesting to look at. At the very least you can learn how it's done in one language so you can translate the "idea" into PHP.

A: If I may quote my answer to the question StompChicken mentioned:
The core issue here is that stemming algorithms operate on a phonetic basis with no actual understanding of the language they're working with.
As they have no understanding of the language and do not run from a dictionary of terms, they have no way of recognizing and responding appropriately to irregular cases, such as "run"/"ran".
If you need to handle irregular cases, you'll need to either choose a different approach or augment your stemming with your own custom dictionary of corrections to run after the stemmer has done its thing.

A: The most current version of the stemmer in NLTK is Snowball.
You can find examples on how to use it here:
http://nltk.googlecode.com/svn/trunk/doc/api/nltk.stem.snowball2-pysrc.html#demo

A: You could use the Morpha stemmer.  UW has uploaded morpha stemmer to Maven central if you plan to use it from a Java application.  There's a wrapper that makes it much easier to use.  You just need to add it as a dependency and use the edu.washington.cs.knowitall.morpha.MorphaStemmer class.  Instances are threadsafe (the original JFlex had class fields for local variables unnecessarily).  Instantiate a class and run morpha and the word you want to stem.
new MorphaStemmer().morpha("climbed") // goes to "climb"

A: .Net lucene has an inbuilt porter stemmer. You can try that. But note that porter stemming does not consider word context when deriving the lemma. (Go through the algorithm and its implementation and you will see how it works)

A: Martin Porter wrote Snowball (a language for stemming algorithms) and rewrote the "English Stemmer" in Snowball. There are is an English Stemmer for C and Java.
He explicitly states that the Porter Stemmer has been reimplemented only for historical reasons, so testing stemming correctness against the Porter Stemmer will get you results that you (should) already know.

From http://tartarus.org/~martin/PorterStemmer/index.html (emphasis mine)
The Porter stemmer should be regarded as 'frozen', that is, strictly defined, and not amenable to further modification. As a stemmer, it is slightly inferior to the Snowball English or Porter2 stemmer, which derives from it, and which is subjected to occasional improvements. For practical work, therefore, the new Snowball stemmer is recommended. The Porter stemmer is appropriate to IR research work involving stemming where the experiments need to be exactly repeatable.

Dr. Porter suggests to use the English or Porter2 stemmers instead of the Porter stemmer. The English stemmer is what's actually used in the demo site as @StompChicken has answered earlier.

A: In Java, i use tartargus-snowball to stemming words
Maven:
<dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-snowball</artifactId>
        <version>3.0.3</version>
        <scope>test</scope>
</dependency>

Sample code:
SnowballProgram stemmer = new EnglishStemmer();
String[] words = new String[]{
    "testing",
    "skincare",
    "eyecare",
    "eye",
    "worked",
    "read"
};
for (String word : words) {
    stemmer.setCurrent(word);
    stemmer.stem();
    //debug
    logger.info("Origin: " + word + " > " + stemmer.getCurrent());// result: test, skincar, eyecar, eye, work, read
}

A: Try this one here: http://www.twinword.com/lemmatizer.php
I entered your query in the demo "cats running ran cactus cactuses cacti community communities" and got ["cat", "running", "run", "cactus", "cactus", "cactus", "community", "community"] with the optional flag ALL_TOKENS.
Sample Code
This is an API so you can connect to it from any environment. Here is what the PHP REST call may look like.
// These code snippets use an open-source library. http://unirest.io/php
$response = Unirest\Request::post([ENDPOINT],
  array(
    "X-Mashape-Key" => [API KEY],
    "Content-Type" => "application/x-www-form-urlencoded",
    "Accept" => "application/json"
  ),
  array(
    "text" => "cats running ran cactus cactuses cacti community communities"
  )
);

A: I highly recommend using Spacy (base text parsing & tagging) and Textacy (higher level text processing built on top of Spacy).
Lemmatized words are available by default in Spacy as a token's .lemma_ attribute and text can be lemmatized while doing a lot of other text preprocessing with textacy.  For example while creating a bag of terms or words or generally just before performing some processing that requires it.
I'd encourage you to check out both before writing any code, as this may save you a lot of time!

A: df_plots = pd.read_excel("Plot Summary.xlsx", index_col = 0)
df_plots
# Printing first sentence of first row and last sentence of last row
nltk.sent_tokenize(df_plots.loc[1].Plot)[0] + nltk.sent_tokenize(df_plots.loc[len(df)].Plot)[-1]

# Calculating length of all plots by words
df_plots["Length"] = df_plots.Plot.apply(lambda x :
len(nltk.word_tokenize(x)))

print("Longest plot is for season"),
print(df_plots.Length.idxmax())

print("Shortest plot is for season"),
print(df_plots.Length.idxmin())

#What is this show about? (What are the top 3 words used , excluding the #stop words, in all the #seasons combined)

word_sample = list(["struggled", "died"])
word_list = nltk.pos_tag(word_sample)
[wnl.lemmatize(str(word_list[index][0]), pos = word_list[index][1][0].lower()) for index in range(len(word_list))]

# Figure out the stop words
stop = (stopwords.words('english'))

# Tokenize all the plots
df_plots["Tokenized"] = df_plots.Plot.apply(lambda x : nltk.word_tokenize(x.lower()))

# Remove the stop words
df_plots["Filtered"] = df_plots.Tokenized.apply(lambda x : (word for word in x if word not in stop))

# Lemmatize each word
wnl = WordNetLemmatizer()
df_plots["POS"] = df_plots.Filtered.apply(lambda x : nltk.pos_tag(list(x)))
# df_plots["POS"] = df_plots.POS.apply(lambda x : ((word[1] = word[1][0] for word in word_list) for word_list in x))
df_plots["Lemmatized"] = df_plots.POS.apply(lambda x : (wnl.lemmatize(x[index][0], pos = str(x[index][1][0]).lower()) for index in range(len(list(x)))))

#Which Season had the highest screenplay of "Jesse" compared to "Walt"
#Screenplay of Jesse =(Occurences of "Jesse")/(Occurences of "Jesse"+ #Occurences of "Walt")

df_plots.groupby("Season").Tokenized.sum()

df_plots["Share"] = df_plots.groupby("Season").Tokenized.sum().apply(lambda x : float(x.count("jesse") * 100)/float(x.count("jesse") + x.count("walter") + x.count("walt")))

print("The highest times Jesse was mentioned compared to Walter/Walt was in season"),
print(df_plots["Share"].idxmax())
#float(df_plots.Tokenized.sum().count('jesse')) * 100 / #float((df_plots.Tokenized.sum().count('jesse') + #df_plots.Tokenized.sum().count('walt') + #df_plots.Tokenized.sum().count('walter')))


text:
Q: Expected value for European Roulette Probability below is the query to calculate expected value?

Probabilities P(x)= 1/37 = 0.0270   P'(x)=1-1/37=0.9729
 Expected value=100 * 0.0270-0.9729*100 for betting 100 $ on number 5,
What could be wrong with the solutions above.. Thank you..

A: The problem with your solution is that winning Roulette with a bet placed on a single number pays out 36x the bet, not 2x. The solution is therefore:
$$(3600 - 100) * \frac{1}{37} + (0 - 100) * \frac{36}{37} = -2.70$$


text:
Q: running java file from shell script I am new to run java files through shell script, this may be very basic question for those who are experienced or few knowledge in shell script. I have java file called Main.java under
C:\project\Tranmissions\com.abc.files\src\main\java\com\abc\files
   +Main.java

I have shell script called run.sh:
#!/bin/bash

java -Xmx300m -classpath com.abc.files.Main -mainclass com.abc.files.payroll.f401k.xyz.AdpCwMain -driver org.hsqldb.jdbc.JDBCDriver

exit $?

This script I have placed under
C:\project\Tranmissions\com.abc.files.

Now, I have downloaded cygwin to run the script as
./run.sh

When I run this, I am getting following basic java error:
java.lang.NoClassDefFoundError: com/abc/files/Main
Caused by: java.lang.ClassNotFoundException: com.abc.files.Main
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: com.abc.files.Main.  Program will exit.
Exception in thread "main"

I am using STS(Eclipse) with maven command install to run the java files. and able to run my class "Main" java program.

A: You shouldn't need to specify -mainclass, just give the class with the main. Also the classpath has the com.abc prefix as does your class. You probably want the classpath to be the current dir and then give your class. If your JDBC isn't in the classpath you'll also get an error. Try something like so:
java -Xmx300m -classpath . \
  com.abc.files.payroll.f401k.xyz.AdpCwMain \
  -driver org.hsqldb.jdbc.JDBCDriver

Run with #!/bin/bash -x to show what commands are actually executed.

A: You call "java" command on a file called Main.java, you should compile the Main.java class first with "javac". "java" is then used when the program ends in .class, ie Main.class

A: You are not compiling the code , before you execute the line.
javac line is missing in run.sh
Why dont you try j2sch, it make your life even simpler.


text:
Q: expected expression error on if else statement Could anyone explain why does it show an expected expression error after "else"? I thought I was doing everything right.
thank you
#include <iostream>
using namespace std;

int main()
{
    double x; // number of hours work per week
    double z; //grosspay
    double w; //withholding amounts
    double n; //net pay
    int y; // number of dependents

cout<<"how many hours do you work in a week?"<<endl;
cin >> x;

    if(x<=40)
        if(y<3)
            z = 16.78*x;
            w = 0.06*x+0.14*x+0.05*x+10;
            n = z-w;
         cout<< "the grosspay is"<< z <<endl
             <<" the withholding amount is"<< w <<endl
             <<" the netpay is" << n <<endl;
        else---------------------------------------------------------expected expression error
            z= 16.78x;
            w= 0.06*x+0.14*x+0.05*x+10+35;
            n=z-w;
        cout<< "the grosspay is"<< z <<endl
            <<" the withholding amount is"<< w <<endl
            <<" the netpay is" << n <<endl;
    if(x>40)
        if(y<3)
            z= 16.78*40+(x-40*16.78);
            w= 0.06*x+0.14*x+0.05*x+10;
            n=z-w;
        cout<< "the grosspay is"<< z <<endl
            <<" the withholding amount is"<< w <<endl
            <<" the netpay is" << n <<endl;

A: You need to add proper {} in your code.
if(x<=40){
    if(y<3) {
    //^^some code
    }else{
   //^^some code
     }
}

A: Use brackets:
   if(x<=40)
   {
       if(y<3)
       {
           z = 16.78*x;
           w = 0.06*x+0.14*x+0.05*x+10;
           n = z-w;
           cout << "the grosspay is"<< z <<endl
             <<" the withholding amount is"<< w <<endl
             <<" the netpay is" << n <<endl;
        }
        else //no more error
        {
            z= 16.78x;
            w= 0.06*x+0.14*x+0.05*x+10+35;
            n=z-w;
            cout<< "the grosspay is"<< z <<endl
            <<" the withholding amount is"<< w <<endl
            <<" the netpay is" << n <<endl;
        }
    }
    if(x>40)
    {
        if(y<3)
        {
            z= 16.78*40+(x-40*16.78);
            w= 0.06*x+0.14*x+0.05*x+10;
            n=z-w;
            cout<< "the grosspay is"<< z <<endl
              <<" the withholding amount is"<< w <<endl
              <<" the netpay is" << n <<endl;
        }
    }


text:
Q: Is there an easy way to add a hide password type feature in python code? I'm creating a program that will require the user to enter a password. Is there a code that I can add in my program that way if someone is sitting behind the user or looking over his/her shoulder they don't see the password on the screen?

A: Use the built-in getpass module:
>>> import getpass
>>> x = getpass.getpass("enter password: ")
enter password:
>>> print(x)
'test'


text:
Q: What is the use of EC2 instance store if it only provides temporary storage? I am new to AWS and trying to understand the difference between instance store and EBS. Reading this page, it says:
The data on an instance store volume persists only during the life of the associated instance; if you stop or terminate an instance, any data on instance store volumes is lost
So then why would anyone use this? Also when I log in to my VM, and save a file to /home/xxx/yyy how do I know if its stored in instance store or in EBS?
From this page:
Instance Store Usage Scenarios
Instance store volumes are ideal for temporary storage of information that changes frequently, such as buffers, caches, scratch data, and other temporary content, or for data that is replicated across a fleet of instances, such as a load-balanced pool of web servers.

A: Amazon EC2 Instance Store is a storage volume that only exists while the EC2 instance is running. This is because the storage is directly attached to the host machine that runs the EC2 instances. When an instance is stopped, the resources (CPU, RAM, instance store) used by that virtual machine are made available to other users. Thus, the contents is lost.
In the early days of Amazon EC2, this was the only type of storage available. Users had to copy their data to Amazon S3 if they wanted it to remain after the instance terminated. In fact, there was no concept of "stopped" back then, since a stopped instance lost its disk storage and could not be restarted.
These days, fortunately, Elastic Block Store (EBS) can be used to persist data even when the associated EC2 instance is stopped. Thus, the instance can be restarted and all data stored on EBS volumes are still available.
Any data stored on Instance Store, however, is lost when the instance is stopped. This is why it is also called Ephemeral Storage.
As to which to use... it's best initially to only use EBS, because it operates in the way most people expect a disk to operate. Instance Store can be confusing for new users of EC2. However, there are several benefits to using Instance Store:

*

*It is free (no additional charge to use it, while there are charges associated with EBS)

*On modern instance types, it is SSD and very fast (in some cases, over 100,000 IOPS)

*It is great for swap files, temporary files and replicated data, which don't need to persist between reboots

Basically, the choice is yours... Start with EBS, then use Instance Store if you can see it providing a benefit.
See also: StackOverflow Benefits of EBS vs. instance-store (and vice-versa)


text:
Q: iOS 7 status bar foreground colour In iOS7 , is it possible to change status bar foreground(text, elements) colour to something other than white or black, without using any private API's?

A: Did you tried this :
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

from here and here
EDIT :
I tried this, it worked for me :
In your AppDelegate.m
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

In your AppDelegate.m application:didFinishLaunchingWithOptions: method
[self.yourNavigationController.navigationBar setBarTintColor:UIColorFromRGB(0x067AB5)];

from here

A: If you want the to set the color of the text and content in the status bar throughout the entire app you have two options. First, you can set the UIStatusBarStyle key in your Info.plist to UIStatusBarStyleLightContent or UIStatusBarStyleDefault. Second, you can use the UIApplication method setStatusBarStyle:animated:. In order to use this method you must set the UIViewControllerBasedStatusBarAppearance key in your Info.plist to NO. It is worth noting that this method of changing the UIStatusBarStyle app-wide can be done while the app is running. Below is an example of how to use this method.
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent     animated:NO];

If you want to change the color of the text and content in the status bar on a view-by-view basis you can take advantage of a new UIViewController method. To use this method you must set the previously mentioned UIViewControllerBasedStatusBarAppearance key in your Info.plist to YES. Below, I have demonstrated how this new method, preferredStatusBarStyle, can be overridden to adjust the color of the content in the status bar.
- (UIStatusBarStyle)preferredStatusBarStyle
{
     return UIStatusBarStyleLightContent;
}

Source: http://www.doubleencore.com/2013/09/developers-guide-to-the-ios-7-status-bar/
EDIT: (Don't know whether this is still possible in iOS7)
There is no direct way of changing the Status Bar color. We can just choose the status bar style using the "setStatusBarStyle" property and choose among the three available styles which are -
UIStatusBarStyleDefault
UIStatusBarStyleBlackTranslucent
UIStatusBarStyleBlackOpaque
However if you would like to change the color of status bar, there is a trick which can do the same -
Change the background color of your UIWindow object. And set the status bar style to "UIStatusBarStyleBlackTranslucent". This will set the color of status bar same as the background color of the window.
Add the following code to your AppDeligate.m file in the applicationDidFinishLaunchingWithOptions -
self.window.backgroundColor = [UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:1];
[application setStatusBarStyle:UIStatusBarStyleBlackTranslucent];

You may change the RGB color values as per your need.
Source: http://beageek.biz/how-to-change-background-color-status-bar-xcode-ios/


text:
Q: Forwarding an established TCP connection to another process on another port? On a Linux machine, you have a daemon that listens on TCP port A. However, it is usually stopped because it is rarely used and takes away a large amount of system resources. Instead, I want to do something like this:
Code an application that listens on port B and does the following as soon as a connection is established: If the daemon is stopped, start it and wait until it listens on port A. Now the difficult part: Connect the client to the daemon in a completely transparent way, i.e. without the client having to reconnect on port A. Also, but this is irrelevant for this question, the application will shut down the daemon when there are no connections for a certain amount of time.
Of course, I could have my application connect to the daemon and pipe all communication. I do not want that. I want some way to forward the established connection to the daemon and then get rid of the connected socket, while the client is now happily connected with the daemon. In some way, I want to give the daemon's process my already connected socket. Is there any way to do something like this?
I'm running Debian, if that's important. I would want to code the application in C/C++, and it's okay to have OS-specific solutions (i.e. use syscalls). Forgive me though, I am not much of a Linux coder, so I am not very familiar with Linux system programming. If there is some obvious way to do it, I simply didn't know.
Of course, I am open for any kind of suggestion.

A: This problem has a pre-existing standard solution, generically known as inetd.  It has been around for a long time, first in Unix systems and then Linux.
The more modern implementation is xinetd