text:
Q: Receive text message with Twilio node module and respond with a text message var http = require('http');
var twilio = require('twilio')(ACCOUNT_SID, AUTH_TOKEN);
var qs = require('querystring');

http.createServer(function (req, res) {
  var body = '';
  req.setEncoding('utf8');

  req.on('data', function(data) {
    body += data;
  });

  req.on('end', function() {
    var data = qs.parse(body);
    var jsonString = JSON.stringify(data);
    var jsonDataObject = JSON.parse(jsonString);

    // log the received message
    console.log(jsonDataObject.Body);

      twilio.messages.create({
      to:'MY_PHONE_NUMBER',
      from:'TWILIO_NUMBER',
      body:'Hello World'
      }, function(error, message) {
        if (error) {
          console.log('There was an error.')
          console.log(error.message);
        }
      });

      res.writeHead(200, {'Content-Type': 'text/xml'});
      res.end();
  });

}).listen(1337, '127.0.0.1');

console.log('TwiML servin\' server running at http://127.0.0.1:1337/');

I'm trying to use the Twilio node module to receive a text message and in turn respond to that text message once received. There seems to be no problem receiving the message as I'm able to log the body. But, I get a 401 Authenticate error when I try and respond to that message. I'm using ngrok to expose my localhost so I can hook it into Twilio's API. Please see below:

Where am I going wrong here?

A: Twilio developer evangelist here.
You actually don't need to use the REST API in order to reply to an incoming message to a Twilio number. You can, in fact, respond to the incoming HTTP request with TwiML that describes the message in response.
To do this, you need to use the <Message> verb. In your application, this would look like:
First, just require the twilio module without the account credentials:
var twilio = require("twilio");

Then, respond to the incoming request with TwiML, like so:
  req.on('end', function() {
    var data = qs.parse(body);
    var jsonString = JSON.stringify(data);
    var jsonDataObject = JSON.parse(jsonString);

    // log the received message
    console.log(jsonDataObject.Body);

    var twiml = new twilio.TwimlResponse();
    twiml.message("Hello world");

    res.writeHead(200, {'Content-Type': 'text/xml'});
    res.end(twiml.toString());
  });

Let me know if this helps at all.

A: var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

var server = app.listen(80, function () {
   var host = server.address().address
   var port = server.address().port
   console.log(" web app listening at http://%s:%s", host, port)

})

app.post('/txt', urlencodedParser,(req, res) => {
  const twiml = new MessagingResponse();

  twiml.message('Finally Twilio works!');
  res.status(200);
  res.send(twiml.toString());

  });

Under your phone number in the console.
You can click webhooks and change it to the http://"putyourserverhere"/txt
This will automatically text back the inbound user.
Enjoy. Make sure you have the newest version of twilio installed.


text:
Q: push files into git remote repo using different user account I want to push my code changes to git remote repo, I am able to pull changes but it is not allowing me to push the changes.
I am using ssh key authentication for authorization, the keys are generated using my email id. But the windows system where I am doing development is a admin account. I have kept the required private public key into .ssh folder but since the windows user is different than the account using which I configured key it is giving pre-receive hook declined error. I have tried by setting the user name and user email same as the account used for key gen using git config command, but not luck so far. Any help is really appreciated.

A: I was able to do it from Eclipse. Configured the ssh key path in network setting and then to commit code using my account, first add the untracked files to git index and then you would be able to see those file in Git Staging view. There it will show your staged changes and you enter commit message, then there will be author and committer by default it will be having the value of whichever user account you have logged in like in my case it was admin account, but I changed it to my account manually and then do commit and push. Doing this I was able to push the code to repository successfully.
Author abc<abc.@mail.com>
Committer abc<abc.@mail.com>

redpajama_set_name: RedPajamaStackExchange


text:
Q: A few doubts with showing Lorentz invariance of Dirac equation and probability current Trying to understand some about Lorentz invariance and representation theory, I thought that the best way is with an example of application: Show the Lorentz invariance of the Dirac Equation
$$(i \hbar \gamma^\mu \partial_\mu  - m c )\psi(x) = 0 \tag1$$ where the $x$ denotes the four-position.
So I use the transformation rules:
$$\psi^\prime(x^\prime) = S[\Lambda] \psi(x) \implies \psi(x) = S^{-1}[\Lambda] \psi^\prime(x^\prime) \tag2$$
$$ \partial_\mu =
\frac{\partial}{\partial x^\mu} =
 \frac{\partial x^{\mu^\prime}}{\partial x^\mu} \frac{\partial}{\partial x^{\mu^\prime}} =
 \Lambda_\mu^{\mu^\prime} \frac{\partial}{\partial x^{\mu^\prime}} =  \Lambda_\mu^{\mu^\prime} \partial_{\mu^\prime} \tag3 $$
Replacing $(2)$ and $(3)$ on $(1)$, and premultiplying by $S[\Lambda]$, we get:
$$S[\Lambda](i \hbar \gamma^\mu \Lambda_\mu^{\mu^\prime} \partial_{\mu^\prime}  - m c )S^{-1}[\Lambda] \psi^\prime(x^\prime) = 0 \tag4$$
And then distributing I get:
$$(i \hbar X^{\mu^\prime} \partial_{\mu^\prime}  - m c )\psi^\prime(x^\prime) = 0 \tag5$$
where $X^{\mu^\prime} = S[\Lambda] \Lambda_\mu^{\mu^\prime} \gamma^\mu S^{-1}[\Lambda]$. And I showed that $$[X^{\mu^\prime},X^{\nu^\prime}] = 2\eta^{\mu^\prime \nu^\prime} \tag6$$
So my first question. Is $(6)$ enough for saying that $X^{\mu^\prime}$ are gamma matrices and with this say that the Dirac equation is Lorentz Invariant?
How can I get the Transformation relation $(2)$? I know that cames from the action of the Lorentz group, but I saw that the action takes the form: $\psi^a(x) \rightarrow S[\Lambda]_b^a \psi^b(\Lambda^{-1}x)$ wich I don't understand very well and just confuses me. So how I procced with knowing $x' = \Lambda x$?


text:
Q: Taxonomy term breadcrumb; how? Given a taxonomy term (perhaps in a taxonomy*.php template) how to construct a breadcrumb going up the full ancestry of the term?
Is there any shorter way other than a "brute-force" loop to query current term's parent -> query term's parent -> query term's parent etc.?

A: You can use get_ancestors for this:
get_ancestors( $term_id, 'taxonomy' );

Of course this will only work on hierarchical elements. Additionally, this will only work reasonably well if only one term per level is assigned, take a look at my comment here and my answer here to get a little bit deeper insight into that.


text:
Q: How to check if a value exist in a 2d matrix array PHP I recently started experimenting with multidimensional arrays in PHP and I was wondering what is the most effective way to check if a value exists in a 2D matrix array.
Example: I want to find if user_id = 7 exists in the 2d matrix array. How can I achieved that ?
$matrix = array();
$query = "SELECT
            CAST(AVG(r.rating_value) AS DECIMAL(10,1)) as 'rating',
            u.user_id,
            s.store_id
        FROM odr o
            INNER JOIN rating r ON o.rating_id = r.rating_id
            INNER JOIN store s ON o.store_id = s.store_id
            INNER JOIN user u ON o.user_id = u.user_id
        GROUP BY s.store_id, u.user_id
        ORDER BY rating_value;";

$result = $mysqli->query($query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 1) {
    while ($row = $result->fetch_array()) {
        $matrix[$row['user_id']][$row['store_id']] = $row['rating'];
    }
}
var_dump($matrix);

//output:
//array(2) { [41]=> array(1) { [35]=> string(3) "5.0" } [37]=> array(2) {
//[37]=> string(3) "5.0" [35]=> string(3) "5.0" } }


text:
Q: Probability of getting heads in a coin toss A fair coin is tossed five times. What is the probability of getting a sequence of
three heads?
What i tried
Since the probability of getting a head and not getting a head is $0.5$. The probability of getting three heads is $0.5^3$ while there is a $0.5^2$ chance of not getting a head. But since the  three heads are in sequence out of five toss, the total probability  is a multiplication of  $ \left(
\begin{array}{c}
   5 \\
    3 \\
  \end{array}
\right).0.5^3.0.5^2=5/16$
Is my working correct. Could anyone explain. Thanks

A: Not quite right. You need a sequence of three heads, not just any three heads. You've counted HHTHT as a valid coin-toss-sequence, whereas according to the question it shouldn't be.
The only allowable sequences are HHHTT, THHHT, TTHHH, HHHHT, THHHH, HTHHH, HHHTH, HHHHH.

A: Hint:
${5\choose 3} =10$ is the number of sequences where you have 3 heads and 2 tails. The heads have not to occur consecutive. The number of sequences with exact 3 heads consecutive are
$hhhtt, \ thhht, tthhh$
Therefore you have only 3 arrangements. Each arrangement has a probability of $0.5^5$
Remark:
If you can have more then 3 consecutive heads, then you have 6 arrangements.

A: If the probability of getting a head is $p$, and the probability of not getting a head is $q=1-p$, then the probability of getting 3 or more consecutive heads is
$$\begin{align}
\underbrace{3 p^3 q^2}_{P(HHH)}+\underbrace{2p^4q^1}_{P(HHHH)}+\underbrace{p^5q^0}_{P(HHHHH)}&=p^3(3q^2+2pq+p^2)\\
&=6p^5\qquad\text{(as }q=p\text{)}\\
&=\frac 3{16}\qquad\text{(}p=\frac 12\text{)}
\end{align}$$
This method can also be used if $p\neq\frac12$.

A: You know that there are exactly $2^5 = 32$ unique outcomes in the game. Now in your "win" case, you must have exactly a sequence of three heads, so let's represent this $HHH$ sequence with a variable $W$. Now, you can simplify your question to: how many unique arrangements of $WTT$ are there? We must have $3! \over 1!2!$, or 3 unique arrangements.
Each unique arrangement has probability $P(H)^{N(H)}P(T)^{N(T)}$, where $N$ is the number of objects in a group and $P$ is the probability function. Since every one of our three arrangements must have three heads and two tails, and since the probability of getting heads/tails is 0.5, then each arrangement has probability $0.5^30.5^2 = {1 \over 32}$. So the solution is $3({1 \over 32}) = {3 \over 32}$ .
Note: the number of unique arrangements of a group with common elements is
$$N(total)! \over N(a_1)!N(a_2)!N(a_3)!\cdots$$
Where each $a_i$ is a unique element. In our case, we have only 2 unique elements's: $W$, and $T$, so $N(W) = 1$, $N(T) = 2$, and $N(total) = 3$. Of course, this strategy fails when two elements $a_i$ and $a_j$ have common elements, so watch out for that when using this strategy.

A: This is just me, but I'd take a direct approach and (since you only have 5 events to consider) draw out a table or chart of all the possible outcomes for first only 2 or 3 events, see if you can scale up, then check your calculation against that.
I find when people aren't inwardly certain in a solid way about the algorithm, a bit of visual intuition can really help.


text:
Q: Bash shell continue nested loop over fresh files I have a bunch of video clips and I want to pick a set of music for each of them.
I wrote a script which iterates over each clip and randomly pick mp3 based on its length.
E.g. if a clip lasts 10:30, then it adds up several mp3 which length sum is equal to the clip length.
#!/bin/bash
for v in clips/*; do
videolength=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $v | awk '{print int($0)}');
mp3s=0
names=""
    for m in music/*; do
    audiolength=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $m | awk '{print int($0)}');
        while [[ $videolength -ge $mp3s ]]; do
            (( mp3s+=audiolength ))
            names+=$v" "
            mv "$m" "used/$m"
            break
        done
    continue
    done
echo "music for this clip: "${names[*]}
# ffmpeg things here
done

This script works fine, except it iterates over same first mp3 from my list of 100+ mp3.
How can I mark as used and skip already used mp3 and for next clips pick only fresh mp3?
Currently the script moves mp3 to another folder but it doesn't seem very wise.
Is there any smart way to iterate only over new files inside a nested loop?

A: Try this:
#!/bin/bash
used=""
for v in clips/*; do
    videolength=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$v" | awk '{print int($0)}');
    mp3s=0
    names=""
    for m in music/*; do

        # check if the file "$m" was already used
        # "$used" is a newline separated file with names in it
        # we filter out "$m" from it. If it exists, that means that it was used.
        if <<<"$used" grep -q -x "$m"; then
           echo "File $m was already used"
           continue;
        fi

        audiolength=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$m" | awk '{print int($0)}');
        if (( videolength >= mp3s )); then # I guess you meant if not while, cause it has break on the end, so it acts as if
            (( mp3s += audiolength ))
            names+=$v" " # didn't you mean "$m" here?

            # save "$m" to the list of used files.
            used+="$m"$'\n'

        fi
    done
    echo "music for this clip: "${names[*]}

     # ffmpeg things here

done

You can save the used names inside a variable separated by newlines. Then use grep on the list to check if the name was already used.


text:
Q: Why spectral radius $\rho\left(A\right) > 0$ for $A \geq 0$ with $A^k > 0$ for positive integer $k$? Why does spectral radius $\rho\left(A\right) > 0$ for a non-negative matrix $A \in M_n$, i.e., $A \geq 0$ with $A^k > 0$ for some positive integer $k$?
I guess it is related to Perron-Frobenius theorem? right? if yes, do we have a short and simple proof for non-experts like me?
Thank you very much

A: $A$ is nonnegative, so it has a nonnegative eigenvector $v$ for the eigenvalue $\rho(A)$ and in turn, $A^kv=\rho(A)^kv$. Since $A^k>0$ and $v$ is nonnegative but nonzero, the product $A^kv$ is positive. Therefore the equality $A^kv=\rho(A)^kv$ implies that $\rho(A)>0$ and $v>0$.
As pointed out in a comment, this result is also regarded as part of Perron-Frobenius theorem for primitive matrices.


text:
Q: What can I do about 99% disk usage (only 0.9 MB/s)? My new laptop is two months old, the first day I got this laptop I noticed this but I assumed it was a bug in Windows 8. However I still have this issue today after reformatting and installing all updates.
The problem is that the disk shows 99% usage from an application...
In this case Dropbox, but the usage is never over 2 MB/s; in this case it is 0.8 MB/s.
What can I do about this?

A: I've seen a similar behavior on some computers at work. You have a pretty good chance to be infected with a trojan malware. I'll suggest to run malware and virus scans on your PC.

A: I had the same issue. It got resolved after updating Intel® Chipset Device Software. Download this from Intel website for your chipset and install to see if it resolves the issue.
This link will help get the right drivers http://www.intel.com/content/www/us/en/support/detect.html


text:
Q: Unable to install updates apt-get install -f I am unable to install updates over my ubuntu 14.04 machine, due to unmet dependencies for katepart, machine is suggesting me to use apt-get install -f to fix it after which it  is showing the following error
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following extra packages will be installed:
kate-data
The following NEW packages will be installed:
kate-data
0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded.
78 not fully installed or removed.
Need to get 0 B/1,546 kB of archives.
After this operation, 10.1 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
(Reading database ... 587315 files and directories currently installed.)
Preparing to unpack .../kate-data_4%3a4.13.3-0ubuntu0.1_all.deb ...
Unpacking kate-data (4:4.13.3-0ubuntu0.1) ...
dpkg: error processing archive /var/cache/apt/archives/kate-data_4%3a4.13.3-0ubuntu0.1_all.deb (--unpack):
trying to overwrite '/usr/share/kde4/apps/katepart/syntax/nesc.xml',which is also in package nescc 1.3.4-2
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Errors were encountered while processing:
/var/cache/apt/archives/kate-data_4%3a4.13.3-0ubuntu0.1_all.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

How can I fix it? I have tried the solution for problem Why does dpkg give a "Broken pipe" error while installing an update?

A: The command should be
sudo apt-get install -f
Try this:

*

*sudo apt-get autoclean  (This clears the cache)

*sudo apt-get clean (Almost the same as above,  but doesn't hurt to run anyway)

*sudo apt-get autoremove (Just in case there's something ib the way
Then try to reinstall katepart.

A: Try use the aptitude command. It seems it solves very well dependencies between packages and libraries. But first run the clean steps with aptitude and apt-get. Eventually update the repository with more download sources in /etc/apt/sources.list.


text:
Q: rndc: connect failed: 127.0.0.1#953: connection refused This is a very annoying problem that i am having with the rndc reload
I am getting the following error:
rndc: connect failed: 127.0.0.1#953: connection refused

However the following work fine,
[root@cbgfx ~]# service named restart
Stopping named: .                                          [  OK  ]
Starting named:                                            [  OK  ]

[root@cbgfx ~]# tail -f /var/log/messages
Aug  7 12:51:09 cbgfx named[31990]: zone 120.88.167.in-addr.arpa/IN: loaded serial 14
Aug  7 12:51:09 cbgfx named[31990]: zone 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa/IN: loaded serial 0
Aug  7 12:51:09 cbgfx named[31990]: zone domain.com/IN: domain.com/MX 'mail.servergreek.com' has no address records (A or AAAA)
Aug  7 12:51:09 cbgfx named[31990]: zone domain.com/IN: loaded serial 14
Aug  7 12:51:09 cbgfx named[31990]: zone localhost.localdomain/IN: loaded serial 0
Aug  7 12:51:09 cbgfx named[31990]: zone localhost/IN: loaded serial 0
Aug  7 12:51:09 cbgfx named[31990]: managed-keys-zone ./IN: loaded serial 4
Aug  7 12:51:09 cbgfx named[31990]: zone domain.com/IN: sending notifies (serial 14)
Aug  7 12:51:09 cbgfx named[31990]: zone 120.88.167.in-addr.arpa/IN: sending notifies (serial 14)
Aug  7 12:51:09 cbgfx named[31990]: running

The vps has ipv6 ip address, is there anything i missed here?
Thanks in advance guys

A: clear the file of directory /var/cache/bind/ and after in terminal bash
/etc/bind/bind9 restart

A: I fixed it myself , it was a permission and ownership issue.To fix it you need to execute those ssh commands
Fix rndc connection refused error
chown root:named /etc/rndc.key
chmod 640 /etc/rndc.key

A: The problem might not only be in rndc.key.
The easiest way to detect is running:
service named restart
Check if there is any error, if there is an error, run:
systemctl status named.service
Check any permission denied error. It could be in the log files as well.

A: In my case as bsentosa comment I needed start process named, you can enable to named start together within system
$ systemctl enable named

A: I am on Mac OS X (Ventura), with Bind9 installed through Brew. I ran into the same issue. I had to run named with sudo to make this error disappear: It was an ownership issue.
Also, you should pay attention to named logs, sometimes you have just errors in your *.zone file.
I hope it will help Mac users landing here.


text:
Q: R/Shiny: Group by and Summarise on column selected in dropdown? I am very new to R and Shiny, so I apologize in advance if this is too basic.
I am trying to render a bar graph where I select the X and Y off dropdowns. I need to aggregate by average values of Y for each X I choose. When I ran the below code, I got an error stating "Column 'y' not found". I cannot pass the actual column name selected as that can change. How do I solve this issue?
        output$MultivariatePlot <- renderPlotly({
      if (input$Apply > 0){
        isolate({
          req(data$Policies)

          x <- input$MultivariateX
          y <- input$MultivariateY

          rv$g <- data$Policies %>%
            group_by(y) %>% summarise(y = mean(y)) %>%
            ggplot2::ggplot(aes_(x = sym(x), y = sym(y))) +
            # ggplot2::stat_summary(fun.y = "mean", geom = "bar") +
            ggplot2::geom_bar(stat='identity') +
            ggplot2::scale_fill_manual(values = rara::ColorSelect(2)) +
            ggplot2::theme_classic() +
            ggplot2::theme(panel.grid.major = element_line(color = 'gray80', linetype = 'longdash', size = 0.3)) +
            ggplot2::labs(title = paste('Comparison Between', x, 'and', y))
        })

A: You can use !!sym(x) in places that you would normally use the symbol version of x, and !!sym(y) in places where you would normally use the symbol version of y.
This turns your code into the following:
rv$g <- data$Policies %>%
  group_by(!!sym(x)) %>%
  summarise(!!sym(y) := mean(!!sym(y))) %>%
  ggplot2::ggplot(aes(x = !!sym(x), y = !!sym(y))) +
  ggplot2::geom_bar(stat='identity') +
  # etc

There's one last complication in there, which is that you had to use := instead of = when it's to the right of a sym(). (Also note that aes_ isn't usually recommended anymore, so I used x = !!sym(x) in regular aes(), and geom_col() is a shortcut for ggplot2::geom_bar(stat='identity')).
Here's a reproducible example of the above, which takes two strings for x and y and aggregates + plots them:
x <- "cyl"
y <- "mpg"

mtcars %>%
  group_by(!!sym(x)) %>%
  summarise(!!sym(y) := mean(!!sym(y))) %>%
  ggplot2::ggplot(aes(x = !!sym(x), y = !!sym(y))) +
  ggplot2::geom_col()


text:
Q: How to convert dateTime in the correct ISO string with javascript I try to get the dateTIme in this format:
"2021-01-27T07:30:00Z"

so: yyyy-MM-ddTHH:mm:ssZ
But I get as format like this:
2021-01-27T09:48:00.000Z

So it seems that there is a extra double 00 in it.
So I have it now like this:
startLineChartDate = new Date();
 this.startLineChartDate.setHours(1,0,0, 0);
const startDate = this.startLineChartDate.toISOString();

And I want to start time always on current day with: 00:00:00
But so what I have to change?
Thank you

A: If you want to convert date to ISO String. just use toISOString method. eg;

a = new Date().toISOString();
console.log(a)

If you want something else, please mention the format


text:
Q: Google Cloud Error: The zone does not have enough resources available to fulfill the request Apologies if this question comes off a bit ranty, but is this error supposed to be commonplace? I'm trying to use a compute instance with GPUs attached in the asia-east1 region. However I frequently (at this point every day) encounter this issue for hours at a time. Today I stopped the instance I was using for all of about 2 minutes before starting it again only to get this error. I've used AWS in the past and never had this issue. How are people supposed to use gcloud in any serious capacity when it seemingly never has enough resources available?

A: This is a common error message that appears from time to time. Many resources (CPUs, IPs, etc) in the Asia Regions/zones are at full capacity.
Also, note that if you are a Free Trial user, you will not be able to use GPUs, if you want to use GPUs you might need to upgrade your account


text:
Q: Having Trouble With Strings, Arrays, and IP Addresses (VB.NET) I have a piece of code that pings a list of NIST servers and retrieves the time they have. This is the original code that works perfect:
'Server IP addresses from
'http://tf.nist.gov/tf-cgi/servers.cgi - current as of 05/20/2016
Private Shared Servers() As String = {
      "129.6.15.28" _
    , "129.6.15.29" _
    , "129.6.15.30" _
    , "98.175.203.200" _
    , "66.199.22.67" _
    , "64.113.32.5" _
    , "198.111.152.100" _
    , "216.229.0.179" _
    , "24.56.178.140" _
    , "132.163.4.101" _
    , "132.163.4.102" _
    , "132.163.4.103" _
    , "128.138.140.44" _
    , "128.138.141.172" _
    , "198.60.73.8" _
    , "131.107.13.100" _
    , "216.228.192.69"
}

Public Shared LastHost As String = ""
Public Shared LastSysTime As DateTime

Public Shared Function GetTime() As DateTime
    'Returns UTC/GMT using an NIST server if possible,
    ' degrading to simply returning the system clock

    'If we are successful in getting NIST time, then
    ' LastHost indicates which server was used and
    ' LastSysTime contains the system time of the call
    ' If LastSysTime is not within 15 seconds of NIST time,
    '  the system clock may need to be reset
    ' If LastHost is "", time is equal to system clock

    Dim host As String
    Dim result As DateTime

    LastHost = ""
    For Each host In Servers
        Try
            If My.Computer.Network.Ping(host) Then
                LastHost = host
                result = GetNISTTime(host)
            End If
        Catch ex As Exception
            MsgBox("There was an error retrieving the internet time. Please try again.", MsgBoxStyle.Exclamation, "Sync Error")
        End Try
    Next

    If LastHost = "" Then
        'No server in list was successful so use system time
        result = DateTime.UtcNow()
    End If

    Return result
End Function

However, I'm trying to modify it so I can use a list of NIST server IP addresses saved in a My.Settings or My.Resources file instead (so I can modify the I addresses easily). So basically just go down each line just like the above working code. Except the following code doesn't work like the above code; it just returns something along the lines of "System.Strings[]":
'Server IP addresses from
'http://tf.nist.gov/tf-cgi/servers.cgi - current as of 05/20/2016
'Declares stting that loads server IP addresses
Public Shared VanServ As String = My.Resources.VanillaServerIPList
Public Shared Serv As String = My.Settings.ServerIPList
Public Shared Servers() As String

Public Shared LastHost As String = ""
Public Shared LastSysTime As DateTime

Public Shared Function GetTime() As DateTime
    'Returns UTC/GMT using an NIST server if possible,
    ' degrading to simply returning the system clock

    'If we are successful in getting NIST time, then
    ' LastHost indicates which server was used and
    ' LastSysTime contains the system time of the call
    ' If LastSysTime is not within 15 seconds of NIST time,
    '  the system clock may need to be reset
    ' If LastHost is "", time is equal to system clock
    Servers = Serv.Split(vbCrLf)

    Dim host As String
    Dim result As DateTime

    LastHost = ""
    For Each host In Servers
        Try
            If My.Computer.Network.Ping(host) Then
                LastHost = host
                result = GetNISTTime(host)
            End If
        Catch ex As Exception
            MsgBox("There was an error retrieving the internet time. Please try again.", MsgBoxStyle.Exclamation, "Sync Error")
        End Try
    Next

    If LastHost = "" Then
        'No server in list was successful so use system time
        result = DateTime.UtcNow()
    End If

    Return result
End Function

The My.Resources.VanillaServerIPList and My.Settings.ServerIPList look as follows (and before you say to check if the lists are null, both lists do in fact contain the following values):
129.6.15.28
129.6.15.29
129.6.15.30
98.175.203.200
66.199.22.67
64.113.32.5
198.111.152.100
216.229.0.179
...and so on; each IP is on a new line

A: Here is what I finally landed on:
'Variables
'-------------------------------------------------------------------------------
Private Shared VanServArray As Array 'Used to store "vanilla" list of NIST server IPs stored in My.Settings.VanillaServerIPList
Private Shared ServArray As Array 'Used to store list of NIST server IPs stored in My.Settings.ServerIPList
Private Shared Result As DateTime 'Stores DateTime retrieved from NIST Server

Public Shared LastHost As String = ""
Public Shared LastSysTime As DateTime 'Stores last available system DateTime

'Functions
'-------------------------------------------------------------------------------
Public Shared Function GetTime() As DateTime
    'Returns UTC/GMT using an NIST server if possible,
    ' degrading to simply returning the system clock

    If My.Settings.ServerIPList Is Nothing Then
        'If the user modifiable list of NIST server IP addresses IS null (null = TRUE) then
        'Put pre-stored, read-only "vanilla" StringsCollection of IP Addresses into the Array
        ServArray = My.Settings.VanillaServerIPList.Cast(Of String)().ToArray
    Else
        'If the user modifiable list of NIST server IP addresses IS NOT null (null = FALSE) then
        'Put the user modifiable StringsCollection of IP Addresses into an Array
        ServArray = My.Settings.ServerIPList.Cast(Of String)().ToArray
    End If

    'Assign null value to LastHost
    LastHost = ""

    'Runs the "If Then" logic that pings all IPs in the array
    'Ping each IP and try to retrieve results
    For Each IP As String In ServArray
        Try
            'Shows each IP in Debug console
            Debug.WriteLine(IP, "IP Addresses")

            If My.Computer.Network.Ping(IP) Then
                LastHost = IP
                Result = GetNISTTime(IP)
            End If
        Catch ex As Exception
            'Return "Sync Error 0x01"
            MsgBox("There was a sync error while retrieving the updated internet time. Please try again.", MsgBoxStyle.Critical, "Sync Error 0x01")
            Debug.WriteLine("There was a sync error while retrieving the updated internet time. Please try again.", "Sync Error 0x01")
        End Try
    Next

    'No server in list was successful so use system time
    If LastHost = "" Then
        'Return "Sync Error 0x02"
        MsgBox("No server in list returned the time. The sytem time has not been updated.", MsgBoxStyle.Critical, "Sync Error 0x02")
        Debug.WriteLine("No server in list returned the time. The sytem time has not been updated.", "Sync Error 0x02")
        Result = DateTime.UtcNow()
    End If

    Return Result

End Function


text:
Q: Loading custom config file into a Codeigniter library I know this is probably simple, but I'm not getting. I've created a library, and I want to load the parameters from a config file. So here's an example of what I have:
// libraries/Mylib.php
class Mylib {
   var $ci;
   var $key;
   public function _construct {
     $this->ci =& get_instance();
     $this->ci->config->load('mylib');
     $this->key = $this->ci->config->item('key');
   }
   public function myKey() {
     return "Key=" . $this->key;
   }
}

// config/mylib.php
$config['key'] = 'randomcharacters';

I load the library, and try to print out the myKey function, but it just returns "Key=", without the actual key. What am I missing?

A: It seems like you missed an underscore for your constructor:
instead of
public function _construct () {

you should use
public function __construct () {


text:
Q: Running an ARM OS(CooCox) on X86 using qemu I am new to qemu and have a board that uses the STM32F4103 processor. There is a program on it that runs on CooOS. I want to simulate the embedded code on an X86 machine and believe qemu is the way. Am i on the right path ?
Any help will be much appreciated.


text:
Q: I have an intel I3 processor by my task manager CPU history shows 4 graphs does that mean I have four cores? I have an intel I3 processor by my task manager CPU history shows 4 graphs does that mean I have four cores? I thought i3 only has two cores. isn't that right

A: No, an i3 only has 2 Cores, but it has 4 threads, Threads are what is showing up in task manager. Threads are Different to cores, while having 4 threads will give you more performance than just 2 threads, they will not give you more performance than 4 cores.
Read this for a better explanation that I can give you - http://crave.cnet.co.uk/laptops/intel-core-i3-i5-i7-laptop-cpus-explained-i-caramba-49304725/

A: The i3's have what's called Hyper-Threading.   This is where certain sections (but not all) of the processor are duplicated so that it can handle more than one task (aka: thread) at one time.
A single hyper-threaded processor (core) has the ability to deal with two threads at the same time, and it is presented to the system as an additional "Logical" processor.
So a CPU with two physical cores that are hyper-threaded (like the i3) will report the two physical processors and the two logical processors to the OS, making it appear as if the computer has 4 processors so that the OS can properly distribute the task load(s) amongst the processors it sees.


text:
Q: Find the two square roots of $i$ I have this question I am stumped upon for my Test-Review:
Write $i$ as a complex number in polar form. Use the result and DeMoivre's Theorem to find the square roots of $i$.
I got the first question:
$i = a + bi$
$0 + 1i$
$z = \sqrt{0 ^ 2 + 1 ^ 2}$
$z = 1$
$\Theta = \tan^-1(y/x)$
$\Theta = \tan^-1(0/1)$
$\Theta = 90^\circ$
Therefore... answer is $1 \cdot cis(90)$... Ok I got that but the Demoivre theorem and the sqrt I couldn't understand... This is the answer.. from anwser key:
a) $cis(90^\circ)$
b) $cis(45 ^\circ) , circ(225 ^\circ)$
I'm following
My teacher follows same way as this: http://hotmath.com/hotmath_help/topics/polar-form-of-a-complex-number.html
Formulas Available

A: Okay, I have tried to do my best earlier... but go through this step by step.
$z_1 = a + i\,b\\
z_2 = x + i\,y \\
z_1z_2 = (a + i\,b)(x + i\,y) = (ax + i\,bx + i\,ay + i^2\,by)$
$i^2 = -1$, and you can combine the $i$ terms.
$z_1z_2 = (ax - by)  + i\,(ay + bx)$
Okay, if you are already lost re-read this.
If $z_1$ and $z_2$ are in polar...
$z_1 = \rho_1 (\cos \theta + i \sin\theta)\\
z_2 = \rho_2 (\cos \phi + i \sin\phi)\\
z_1z_2 =\rho_1\rho_2 (\cos\theta\cos\phi - \sin\theta \sin\phi + i(\sin\theta \cos \phi + \cos \theta \sin \phi)$
This is the same multiplication that we did in rectangular coordinates.
But notice how this ties out to the angle addition formulas for $\cos$ and $\sin$
$z_1z_2 =\rho_1\rho_2 (\cos(\theta+\phi) + i\sin(\theta+\phi))$
When we multiply complex numbers we add the angles!  This is particularly noticeable in polar form, but it is just as true in Cartesian form.
$z^2 = z\cdot z =$$ \rho (\cos \theta + i \sin\theta)\rho (\cos \theta + i \sin\theta)\\
\rho^2 (\cos 2\theta + i \sin2\theta)\\$
De Moivre's theorem:
$z^n = \rho^n (\cos n\theta + i \sin n\theta)$
and it works just as well when $n$ is a fraction as it does when $n$ is a whole number.
$\sqrt z = z^{1/2}$
$\sqrt z = \pm \rho^{1/2} (\cos \frac{\theta}{2} + i \sin \frac{\theta}2)$
Everything up to this point is actually on your cheat-sheet in condensed from.  But rather than just memorizing formula, try to understand what is actually going on, and where those formula are coming from.
And to the problem at hand:
$z = 0 + i\\
z = (\cos 90 + i \sin 90)\\
z^{1/2} = \pm (\cos 45 + i \sin 45)\\
z^{1/2} =  (\cos 45 + i \sin 45), (\cos 225 + i \sin 225)$
Advanced stuff:  This is not something you are expected to know in precaluculs, but if you ask the question on this board people may assume you know this.
Complex numbers in polar form can be translated into exponential form as follows:
$z = \rho e^{i\theta}\\
z^n = \rho^n e^{i\theta n}\\
z^{1/n} = \rho^\frac1n e^{\frac{i\theta}{n}}\\
$

A: Solution $1$
Let $z=x+iy\in \Bbb C$ such that $z^2=i$.  then $z^2=x^2-y^2+2xyi=i$. It follows that
$$
x^2=y^2\iff x=\pm y\\
2xyi=i \iff x=\frac 1 {2y}
$$
Then, $x=\pm\frac 1 {2x}$, we get that $x=\pm\sqrt2/2$ , so we get $z_1=\sqrt 2/2+\sqrt 2 /2i$, $z_2=-z_1$.

Having the $x,y$ coordinates, you can put these numbers in polar form if you please.

Solution $2$
Let $z=r \operatorname{cis}(\theta)$. We want $z^2=i$, but $z^2=r^2 \operatorname{cis}(2\theta)$.
Now, $|i|=1$, $|z^2|=r^2$ and as we want $z^2=i$, we need $r^2=1$, i.e $r=1$.
Comparing angles now, we need $2\theta=90^\circ+360^\circ k$, that is, $\theta=45^\circ+180^\circ k$ or $\theta_1=45^\circ,\theta_2=225^\circ$ (note that if you add more $180^\circ$s, we get back $45,225,45,\cdots$.
So the two square roots of $i$ are $z_1=1\cdot \operatorname{cis}(45^\circ)$ and $z_2= 1\cdot \operatorname{cis}(225^\circ)$.

I suggest you stop looking at your formulas and start thinking about the problem without them, as shown here, they're not needed, the only fact you 'needed to know' was that $i$'s angle is $90^\circ$.

A: You have $i = e^{i\pi/2}$ so this has two square roots, $e^{i\pi/4}$ and $-e^{i\pi/4} = e^{5i\pi/4}.$

A: In general, let $z=x+iy$ where $x$ and $y$ are real-valued numbers.  We can express $z$ in Polar Coordinates as $z=\sqrt{x^2+y^2}e^{i\arctan(x,y)}$ where the Arctangent Function $\arctan(x,y)$ is given by
$$
\arctan(x,y)=\begin{cases}
\arctan(y/x)&,x>0\\\\
\pi+\arctan(y/x)&,x<0,y>0\\\\
-\pi+\arctan(y/x)&,x<0,y<0\\\\
\pi/2&,x=0,y>0\\\\
-\pi/2&,x=0,y<0
\end{cases}$$
Then, the square root of $z$, $z^{1/2}$ is one of the two values
$$z^{1/2}=\pm (x^2+y^2)^{1/4}e^{i\arctan(x,y)/2} \tag 1$$
We can convert $z^{1/2}$ back to rectangular coordinates using Euler's Identity on $(1)$.  Proceeding accordingly gives
$$\begin{align}
z^{1/2}&=\pm (x^2+y^2)^{1/4}\left(\cos\left(\frac12 \arctan(x,y)\right)+i\sin\left(\frac12\arctan(x,y)\right)\right)\\\\
&=\pm\sqrt{\frac{\sqrt{x^2+y^2}+x}{2}}\pm i\,\text{sgn}(y)\sqrt{\frac{\sqrt{x^2+y^2}-x}{2}}\tag 2
\end{align}$$
where in arriving at $(2)$ we used the Half-Angle Formulae for the sine and cosine funcitons.
Applying $(2)$ to the case for which $x=0$ and $y=1$, we find that
$$\sqrt{i}=\pm\left(\frac{1}{\sqrt{2}}+i\frac{1}{\sqrt{2}}\right)$$


text:
Q: What Java data structure/design pattern best models this object, considering it would perform these methods?
Methods:
1.  getDistance(CityA,CityB) // Returns distance between two cities
2.  getCitiesInRadius(CityA,integer) // Returns cities within a given distance of another city
3.  getCitiesBeyondRadius(CityA,integer) //Returns cities beyond a given distance of another city
4.  getRemoteDestinations(integer) // Returns all city pairs greater than x distance of each other
5.  getLocalDestinations(integer) //Returns all city pairs within x distance of each other

A: The simplest implementation would be a two dimensional array if the data is known at compile time. Then you could just use some clever construction of what a City object is to figure out which index to use. This would make it pretty hard to extend though.
Another way to do it is to define a class type of something like Distance which contains two end points which are City objects. The idea would be that the order of the City objects shouldn't matter and that when storing them you make sure you're not double counting anything.
The data structure then could use any combinations of ArrayLists or Hashtables indexed by City objects . My preferred method would probably be to keep just an Arraylist<Distance> objects and define helper methods to determine if the given index is relevant to the question at hand. Of course this is potentially slow but on small data sets it's good enough.
For the ___Destinations methods it might be helpful to borrow a functional programming idea and make a method which returns a temporary list of distances with only the target city involved and then search again. But this is in no way necessary.

A: public class Map {
    private Hashmap<String, City> cities;
    public Distance getDistance(CityA,CityB) // Returns distance between two cities
    public List<City> getCitiesInRadius(CityA, Distance) // Returns cities within a given distance of another city
    publi List<City> getCitiesBeyondRadius(CityA,Distance) //Returns cities beyond a given distance of another city
    public List<City> getRemoteDestinations(Distance) // Returns all city pairs greater than x distance of each other
    public List<City> getLocalDestinations(Distance) //Returns all city pairs within x distance of each other
 }

public class City {
    private String name;
    private HashMap<City, Distance> distanceTo;
    //getter/setters etc
}

You'll need to keep track of distances in both directions, not just one.  Ie, Abernathy to Gruver, and then Gruver will also have Abernathy's distance.

A: What about this:
public class City{

   private String name;
   private List<AdjCities> adjCities;

   //getters and setters
}

public class AdjCity{
   private int distance;
   private City targetCity;

   public void(int distance, City targetCity){
     this.distance= distance;
     this.city = city;
   }
}

So now initialize every city (say, NYC, Boston etc.)  then set the adjacent city to NY (say, Boston is connected to NY with distance '300'). So now initialize 'AdjCity' with 'targetCity' (Boston) and distance is 200. And add this to the list of AdjCity objects.
Now you can put this in a collection and from here I think you can proceed if it makes any sense to you.
Thanks

A: If there's a distance between every city, and every city is known in advance, I'd use a 2 dimensional array.  For simplicity and speed, I'd use the whole thing, even though you're storing all the distances twice.  Then you'll want a 1 dimensional array (ArrayList might work better) to link the indexes in your distance table to actual City objects (which in the simplest case would just be their names as Strings and their table index number).  Then add cities to a Map keyed on names to get the their indexes.  If you know the number of cities in advance, and even if you don't, a HashMap is probably what you want.  Now, given a name, you can find a row/column in the table, scan it for numbers you like, turn desired column/row index into a City object, and return whatever you want from that (name, for instance).
If the vast majority of city pairs do not have distances, skip the 2D array, and create a Connection class that references two cities and contains a distance.  Then the City class would contain a list of Connection objects, and you have a graph (as in graph theory).  There's lots of ways to work with them.

A: This will be slow.
It seems add operation will eventually require O(N), where N is number of existing cities in the collection. This will be slower and slower as more cities are added.
I can't think of a way to lazy-evaluate the distance. It seems to me all-pair distances must be calculated up front. Maybe someone can offer better suggestions.
Remark. SortedMap Seems wrong. It doesn't allow duplicate keys (two doubles having same value). However, the chances of two pairs of cities with same distance seems remote to me ...
public class CityCollection
{
    private List<City> cities;

    // Cache distances when cities added, because expensive to calculate
    private Map<Pair<City, City>, double> distances;

    // sorted by pairwise distances
    private SortedMap<double, Pair<City, City>> sortedByDistances;

    public void add(City city)
    {
        if (cities.contains(city)) return;
        for (City oldCity : cities)
        {
            Pair<City, City> pair = new Pair<City, City>(oldCity, city);
            double distnace = getDistance(oldCity, city);
            distances.put(pair, distance);
            sortedByDistances.put(distance, pair);
        }
        cities.add(city);
    }

    // this is possibly very very slow, or very very fast...
    public static double getDistance(City origin, City destination)
    {
        Query q = new Query(
            origin.getCentroid().toString(),
            destination.getCentroid().toString(),
            "GreatCircle");
        // .. wait for query to finish
        return q.distance();
    }

    // implement your other methods here
}


text:
Q: AWS EKS cluster with Istio sidecar auto inject problem and pod ext. db connection issue I built a new cluster with Terraform for a AWS EKS, single node group with a single node.
This cluster is using 1.22 and cant seem to get anything to work correctly.
So Istio will install fine, i have installed versions 1.12.1, 1.13.2, 1.13.3 & 1.13.4 and all seem to have the same issue with auto injecting the sidecar.
Error creating: Internal error occurred: failed calling webhook "namespace.sidecar-injector.istio.io": failed to call webhook: Post "https://istiod.istio-system.svc:443/inject?timeout=10s": context deadline exceeded
But there are also other issues with the cluster, even without using Istio. My application is pulled and the pod will build fine but can not connect to the database. This is an external DB to the cluster - no other build (running on Azure) have any issues connecting to the DB
I am not sure if this is the issue with the application not connecting to the ext. DB but the sidecar issue could have something to do with BoundServiceAccountTokenVolume?
There is a warming about it being enabled on all clusters from 1.21 - a little odd as i have another applications with istio, running on another cluster with 1.21 on AWS EKS!
I also have this application running with istio without any issues in Azure on 1.22

A: I seem to have fix it :)
It seems to be a port issue with the security groups. I was letting terraform build its own group.
When I opened all the ports up in the 'inbound' section it seemed to work.
I then closed them all again and only opened 80 and 443 - which again stopped Istio from auto-injecting its sidecar
My app was requesting to talk to Istio on port 15017, so i opened just that port, along sided ports 80 and 443.
Once that port was opened, my app started to work and got the sidecar from Istio without any issue.
So it seems like the security group stops pod-to-pod communication... unless i have completely messed up my terraform build in some way


text:
Q: What technology to use for home network I live in panel-house (cube with concrete walls, reinforced with steel) which is part of bigger block. Recently I have successfully setup wifi network through the flat, but at the recieving end I have really bad reception (-80dB). One problem is the environment and the other problem is interference with other wifi's in the block. The radio spectrum is really overflowing...
I would like to move the AP to better position in flat, but the problem is, it would mean to lay ~12m of UTP cable which would be also mean reconstruction of the flat, to properly hide the cables.
So I was wondering if there is any better option. I'm considering two options listed below:
a) Use power network adapter. This thing is plugged into electric outlet and provides ethernet connection between 2-N places. The manufacturer says it can reach 300 meter, but I'm a bit skeptical about this number. The thing is, that our flat has only aluminum wires, roughly 25 years old... My another concern is security.
b) Second option I'm considering is to use WiFi repeater. I have drawn a simple diagram od flat layout:

The green AP would be the position of the repeater.
What is your opinion on the proposed setup options? Thanks for any feedback.
UPDATE: Some more details. The router I have is Tp-Link WR741ND, running N WiFi, 2.4 GHz. The router is locked by my ISP, so I cannot really tinker with it. 5 GHz is unfortunatelly not an option, because the PCs are laptops without 5GHz capabilities. Plus there are smartphones on the network which doesn't have 5Ghz either.

A: I would go with the repeater option. The location looks good, 2.4GHz network should have good coverage from that location.
As for using 5GHz in this kind of flat - I would not suggest it anyway, unless your router supports dual band (broadcasting on both 2.4GHz and 5GHz at the same time). 5GHz may be faster and less saturated, but it doesn't penetrate walls nearly as well as 2.4GHz due to the higher frequency.
For saturation problems, you can probably change the channel number from the repeater settings to a less used channel. You can read more about changing channels here.

A: I live in a concrete house (Germany) and I'm using tp-link powerline adapters - faster than wireless (though slower than the advertised speed) and they can be secured with 128bit aes

A: I've messed with everything you've talked about before, and I can make a few suggestions to how to go about it.
When homeplug works it works - but when it dosen't, you're out of luck. I'm using 15 year old copper wiring, and it works reasonably well, but I tested it before I went all in.
I strongly recommend testing with the cheapest kit you can find (I went with a ~75 dollar pair of 200 mbps Homeplug AV adaptors from aztech), then building out if it works - I've added a 500 mbps gig-e switch to my desk). Once you're sure it works, in typical configurations, you'd want to go for units with passthrough - this lets you actually use the plug, and isolates noise from systems that are plugged into that connector (so its perfect for places where you have PCs with SMPS - which produce noise).
Connections between paired devices is encrypted (AES 128) and should be reasonably secure. They come with a default private network name, so you may want to change that.
My network, simplified (I have another AP... and so on ) now looks like this

The two routers have different SSIDs and cover different parts of the apartment - I have complete coverage loss at a specific beam, and as such a repeater wasn't an option. Since the secondary router is not a DHCP server, the systems are on the same subnet. In theory this setup should let you run an AP in a different channel, or band, or even both.


text:
Q: Save the Row data in Table using Javascript Hi Here I am trying to save the data which user enter in a table. I have written Javascript for this.
<script type="text/javascript">

        function Savefile() {

            var tbl = document.getElementById("modaltable");
            var final = " ";
            var finalvalue = " ";
            if (tbl != null) {
                for (var i = 0; i < tbl.rows.length; i++) {
                    for (var j = 0; j < tbl.rows[i].cells.length; j++) {
                        var text = document.getElementById("Comment").value;
                        var typeofscram = document.getElementById("<%=DropDownList2.ClientID %>").value;
                        var scramblerreq = document.getElementById("<%=DropDownList1.ClientID %>").value;
                        var final = text + " " + typeofscram + " " + scramblerreq;

                    }
                    finalvalue += final;
                }
            }
            var myCsv = finalvalue;
            window.open('data:text/csv;charset=utf-8,' + escape(myCsv));

        }
    </script>

But it is saving only first row values. But I need to save the remaining row values also. In second row also it is saving first row details.Any mistake in above code.


text:
Q: Call instances of custom object with different parameters I want to call an instance of a custom object twice with one parameter different, the problem is if I set its config property it changes accordingly if I create 2 instances, but if I don't specify the property when calling the second instance of the object, it inherits the set parameter from the first instance.
I want the second instance to use the default parameter unless it is manually set when calling it.
I tried making an elem variable and prepend it to queried elements but it didn't work.
HTML:

test

test

JS:
(function() {

// Utility
if ( typeof Object.create !== 'function' ) {
    Object.create = function( obj ) {
        function F() {};
        F.prototype = obj;
        return new F();
    };
}

var objTest = {

    config: {
        value: 'some text'
    },

    init: function(elem, config) {

        var self = this;
        this.elem = elem;

        $.extend(this.config, config);

        this.doIt();
    },

    doIt: function() {
        var self = this;
        $(self.elem + ' .test p').text(this.config.value);
        console.log($(self.elem + ' .test p'));
    }

};

var parent = Object.create( objTest );

parent.init('.parent', {
    value: 'first div text'
});

// if you comment out the value parameter from the following instance, it will inherit from previous object instance
var parentSecond = Object.create( objTest );

parentSecond.init('.parent-second', {
    value: 'second div text'
});

})(); // end self invoking function

A: The problem is that your config object is getting shared among all the instances of your object. Hence you must create a new config object for each instance.
    var objTest = {

        init: function(elem, config) {

            var self = this;
            this.elem = elem;
            if(!this.config)
            {
                this.config = {
                value: 'some text'
                };
            }
            $.extend(this.config, config);

            this.doIt();
        },

        doIt: function() {
            var self = this;
            $(self.elem + ' .test p').text(this.config.value);
            console.log($(self.elem + ' .test p'));
        }

    };

This would work just fine for you. Though I would prefer the prototype approach for this.
function objTest ()
{
    //you could also merge init function in this constructor
    this.config = {
        value: 'some text'
    };
}
objTest.prototype = {
    init = function (elem, config) {
       var self = this;
        this.elem = elem;
        if(!this.config)
        {
            this.config = {
            value: 'some text'
            };
        }
        $.extend(this.config, config);

        this.doIt();

    },
    doIt: function() {
        var self = this;
        $(self.elem + ' .test p').text(this.config.value);
        console.log($(self.elem + ' .test p'));
    }

}

var parent = new objTest();

parent.init('.parent', {
    value: 'first div text'
});

var parentSecond = new objTest();

parentSecond.init('.parent-second', {
    value: 'second div text'
});


text:
Q: Does anyone know how to use titlecase in component.ts file instead in html file? I tried the following code but it's not working.
import { Component } from '@angular/core';
import { TitleCasePipe } from '@angular/common';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  title = 'Working with Pipe';
  testValue = this.titleCasePipe.transform('firstletter should be upper case.');

  constructor(
    public titleCasePipe: TitleCasePipe
  ){}

}

enter image description here

A: Add TitleCasePipe in the providers array of the metadata of your component :
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
providers: [TitleCasePipe]
})

Stackblitz example

A: You can just create an object, else, add in providers as @Gérôms say
  title = 'Working with Pipe';
  titleCasePipe=new TitleCasePipe()
  testValue = this.titleCasePipe.transform('firstletter should be upper case.');

  constructor(){
  }

A: Put your code inside constructor like this,
 testValue: string;

 constructor(
    public titleCasePipe: TitleCasePipe
 ){
    this.testValue = this.titleCasePipe.transform('firstletter should be upper case.');
 }

A: Without Pipe

Here is your Simple Solution with TitleCase
you can use directly like this you don't have to put extra code angular already give's this features
HTML
<p>
  {{name | titlecase}} <!-- this is titlecase by default -->
</p>

TS
name = 'Working with Pipe';

With Pipe
you can check in input field also like this
HTML
<input type="text" id="firstName" name="name"
[ngModel]="name | titleCase"
(ngModelChange)="name=$event"
#firstName="ngModel">

TS
import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'titleCase'})
export class TitleCasePipe implements PipeTransform {
    public transform(input:string): string{
        console.log(input);
        if (!input) {
            return '';
        } else {
            return input.replace(/\b\w/g, first => first.toLocaleUpperCase())
        }
    }
}

and don't forgot to add in declaration like this
declarations: [ TitleCasePipe ],

Here is my stackBlitz you can check here


text:
Q: Hana Text Search over different tables with different weights We are wondering whether SAP Hana supports a text search over entities whose texts are in different tables (e.g. the entity "Product 42" references one text in table A and two texts in table B). We want to assign a different weight to each hit depending on the table in which this hit was found, e.g. when the search term was found in table A this counts more than when it was found in table B.
It seems that using the predicate "contains()" this cannot be realized. The "SAP HANA Search Developer Guide" [1] states on page 46 that all columns listed in contains() have to belong to the same table.
Is there an "Application Function Library" (AFL) that offers such functionality for text search?
Thank you and kind regards, Michael
[1] http://help.sap.com/hana/SAP_HANA_Search_Developer_Guide_en.pdf, Document Version: 1.0 - 2014-11-26.

A: In the meanwhile I found out that a weighted text search with Hana can be realized as follows:

*

*Create an Attribute View which contains the relevant text columns from different tables.

*Ensure that all text attributes/columns are selected as output, i.e. they should appear in the view "Output" under "Columns" when "Data Foundation" is chosen in the view "Scenario". You might also want to have at least one key attribute as output.

*Click on each of the text attributes in view "Output" under "Columns". The properties for this attribute should be displayed in view "Property". Select tab "Search Properties" in this view and set property "Freestyle Search" to "True" and enter a value for property "Weights for Ranking".
After this you can perform a text search using this attribute view with SQL, for example:
SELECT score(), key_attribute ...
       FROM "_SYS_BIC"."SOME.PACKAGE/MY_ATTRIBUTE_VIEW"
       WHERE contains( ( attribute1, attribute2, ... ), 'search term' )
       ...
       ORDER by score() DESC;

Please note the different types of quotation marks used in the FROM clause and around the search term.

A: you can also create a search rule set (referenced in the search developer guide) to annotate different weights and fuzziness thresholds for each column. the search rule set will reference an attribute view and within the attribute view you can include multiple tables


text:
Q: php cURL request to instsagram API creates page lag I am using cURL toaccess instagrams API on a webpage I am building. THe functionality works great, however, page load is sacrificed. For instance, consider this DOM structure:

*

*Header

*Article

*Instagram Photos (retrieved via cURL)

*Footer

When loading the page, the footer will not load until the instagram hotos have been fully loaded with cURL. Below is the cURL function that is being called:
function fetchData($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

$result = fetchData("https://api.instagram.com/v1/media/search?lat={$lat}&lng={$lng}&distance={$distance}&access_token={$accessToken}");
$result = json_decode($result);

So after this function is run, then the rest of the DOM is displayed. If I move the function call below the footer, it does not work.
Is there anything I can do to load the entire webpage and have the cURL request setn on top of the loading site (not cause a lag or holdup)?
UPDATE: Is the best solution to load it after the footer, and then append it to another area with js?

A: You can cache the result json into a file that is saved locally. You can make a cronjob that is called ever minute and update the locally cache file. This makes your page loading much more faster. The downside is that your cache is updating even when you don't have visitors and you have a delay of a minute in data from instagram.


text:
Q: pubnub push notification titanium android I using pubnub chat for android using titanium appcelerator platform, I had  just crossed about the push notification to android via pubnub , It provides its own development kit for the chat clients but i tried to use it for android, I couldn't there is existing sample for ios but not for android actually.
Anybody had crossed this issue...let me know how to use this.
Pub nub help link for push notification....

A: When using PubNub in an Android app (Phonegap or Native), you do not need to use GCM because you can implement a subscribe at boot service that forwards incoming messages to the background app using Intents. See this example for more details:
https://help.pubnub.com/entries/21720011CanmyAndroidAppReceiveMessagesWhileInactive
That KB article has a link (hard to see in the article) that will lead you to the Subcrib-at-Boot example in the PubNub Andriod github repo here:
https://github.com/pubnub/java/tree/master/android/examples/SubscribeAtBoot
Android with Phonegap
You need to implement a Phonegap JavaScript/Java bridge which has a bit of work that can be implemented by following our Android Subscribe-at Boot (above) service solution and piece it together.
http://www.tipsfromsiliconvalley.com/2013/07/06/createaserviceonandroidwithphonegapap plication/

A: Actually it is pretty simple as i thought to create a pubnub notification. We have to simply run background service and in that do the following steps.,

*

*Add background service using this BOOT_COMPLETED Titanium module ,

*Before suscribe a new channel inside the background service code. (for eg.: MY_notify_channel),

*Next go to your chat screen , Next to the line that you are publishing to your private dynamic channel, Publish once again to our MY_notify_channel .

*That's it when ever you publishing you get a message received in your service box, you have segregate your message in that and then create a notification manually.
Titanium.Android.Notification link


text:
Q: Passing a select value to Oracle database I'm working on this code I used Oracle HR database as my database, I'm trying to filter database results based on multiple select, but I keep getting this error:

Warning: oci_execute(): ORA-00933
  Warning: oci_fetch_array(): ORA-24374

and no results, my code:
index.php

<title>Employees Search</title>

<form method="get" name="Form2" id="Form2">
    <select  id="DEPARTMENT_ID" name="DEPARTMENT_ID">
        <option value="">DEPARTMENT:</option>
        <option value="90">90</option>
        <option value="60">60</option>
        <option value="100">100</option>
        <option value="30">30</option>
    </select>
    <select id="MANAGER_ID" name="MANAGER_ID" >
        <option value="">MANAGER ID:</option>
        <option value="100">100</option>
        <option value="102">102</option>
        <option value="103">103</option>
        <option value="108">108</option>
    </select>
    <input type="button" value="   Search   " onclick="checkinput()" />
</form>

<?php include "emp.php"; ?>

emp.php
<?php

    $conn = oci_connect('hr', ' ', 'My-PC:1521/XE');
    if (!$conn) {
        $e = oci_error();
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }
    if(isset($_GET['DEPARTMENT_ID'])||isset($_GET['MANAGER_ID'])){
        $DEPARTMENT_ID=$_GET['DEPARTMENT_ID'];
        $MANAGER_ID=$_GET['MANAGER_ID'];
        $sql="SELECT * FROM EMPLOYEES WHERE ";

        if($DEPARTMENT_ID != "")
        {
            $sql = $sql."DEPARTMENT_ID=".$DEPARTMENT_ID;
            if($MANAGER_ID != "")
            {
                $sql = $sql."MANAGER_ID=".$MANAGER_ID;
            }
        }
        else
        {
            if($MANAGER_ID != "")
            {
                $sql = $sql."MANAGER_ID=".$MANAGER_ID;
            }
        }

        $stid = oci_parse($conn, $sql);
        oci_execute($stid);

        echo "

Employee No.	First Name	Last Name	PHONE NUMBER	Email	Job Title	MANAGER_ID	DEPARTMENT_ID
";
        while ($row = oci_fetch_array($stid, OCI_ASSOC )) {
            echo "
";
            echo "".$row['EMPLOYEE_ID']."	";
            echo "".$row['FIRST_NAME']."	";
            echo "".$row['LAST_NAME']."	";
            echo "".$row['PHONE_NUMBER']."	";
            echo "".$row['EMAIL']."	";
            echo "".$row['JOB_ID']."	";
            echo "".$row['MANAGER_ID']."	";
            echo "".$row['DEPARTMENT_ID']."	";
            echo "
";
            echo"
";
        }
    }
?>

A: Everything seems correct expect SQL when Department and manager id is not null.
<?php

    $conn = oci_connect('hr', ' ', 'My-PC:1521/XE');
    if (!$conn) {
        $e = oci_error();
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }
    if(isset($_GET['DEPARTMENT_ID'])||isset($_GET['MANAGER_ID'])){
        $DEPARTMENT_ID=$_GET['DEPARTMENT_ID'];
        $MANAGER_ID=$_GET['MANAGER_ID'];
        $sql="SELECT * FROM EMPLOYEES WHERE ";

        if($DEPARTMENT_ID != "")
        {
            $sql = $sql."DEPARTMENT_ID=".$DEPARTMENT_ID;
            if($MANAGER_ID != "")
            {
                $sql = $sql."AND MANAGER_ID=".$MANAGER_ID;
            }
        }
        else
        {
            if($MANAGER_ID != "")
            {
                $sql = $sql."MANAGER_ID=".$MANAGER_ID;
            }
        }

        $stid = oci_parse($conn, $sql);
        oci_execute($stid);

        echo "

Employee No.	First Name	Last Name	PHONE NUMBER	Email	Job Title	MANAGER_ID	DEPARTMENT_ID
";
        while ($row = oci_fetch_array($stid, OCI_ASSOC )) {
            echo "
";
            echo "".$row['EMPLOYEE_ID']."	";
            echo "".$row['FIRST_NAME']."	";
            echo "".$row['LAST_NAME']."	";
            echo "".$row['PHONE_NUMBER']."	";
            echo "".$row['EMAIL']."	";
            echo "".$row['JOB_ID']."	";
            echo "".$row['MANAGER_ID']."	";
            echo "".$row['DEPARTMENT_ID']."	";
            echo "
";
            echo"
";
        }
    }
?>

Changed Line :
$sql = $sql."AND MANAGER_ID=".$MANAGER_ID;
May be reason as SQL failed to parse this query.
As If both are not empty and assumed 10 then you query will be looked like SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID=10 MANAGER_ID=10; which is not syntactically correct.


text:
Q: DataAdapter.Fill returns the row count but Rows.List is null I'm really puzzled about this. I have a table in SQL Server with three nvarchar(255) columns and a couple rows just for testing. the following code correctly returns the column names and the row count of 2 but  Rows.List = null. If I use reader.Read() I can read the data in the rows so the query is returning the data. Any query that alters the data in the tables such as an INSERT INTO ... will work perfectly.
    DataTable results = new DataTable;
    int rowsAffected = 0;
    string connectionString = "Server=<serverName>;Database=<databaseName>;Integrated Security=SSPI";
    string query = "SELECT * FROM testTable";
    using (SqlConnection conn = new SqlConnection(connectionString))
    using (SqlCommand command = new SqlCommand(query, conn))
    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
         rowsAffected = dataAdapter.Fill(results);

When this is done, results.Rows.Count = 2 which is correct, and results.Rows.List = null which is WRONG. Why isn't there any data being returned to me?

A: I'm not sure what you are trying to accomplish, but the method DataRowCollection.List is 1.) protected, so you probably just see it's value in the debugger, and 2.) returns always null because this is the reflected implementation:
protected virtual ArrayList List => (ArrayList) null;

You have already the DataRowCollection in results.Rows, so you can either enumerate it in a foreach or access s DataRow via it's index. If you really want a List<DataRow> you could use:
List<DataRow> rowList = results.AsEnumerable().ToList();

If you want a DataRow[] use ToArray instead.


text:
Q: UIDocumentInteractionController prevent Airdrop in the 'Open in' sheet
In my app, I'm allowing users to share photos via Instagram, which requires the use of UIDocumentInteractionController.  Airdrop is automatically detected if the phone supports it.  How do I remove it from this 'Open in' action sheet?
Even if I begin the sharing process with a UIActivityViewController and call setExcludedActivityTypes:, eventually I must use  a UIDocumentInteractionController, and when I do, Airdrop appears again.  Here is the code when the share button gets tapped:
NSURL *instagramURL = [NSURL URLWithString:@"instagram://location?id=1"];

if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"Image.igo"];

    NSData *imageData = UIImagePNGRepresentation(imageToShare);
    [imageData writeToFile:savedImagePath atomically:YES];
    NSURL *imageUrl = [NSURL fileURLWithPath:savedImagePath];
    docController = [[UIDocumentInteractionController alloc] init];
    docController.UTI = @"com.instagram.exclusivegram";
    docController.URL = imageUrl;
    [docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

}
else
{
    NSLog(@"no insta");
}

A: As far as I can tell you can't. I need to disable this option also. But on UIDocumentInteractionController it is completely inaccessible. Pretty bad API experience in my book.
If the user selects an App in the list your App gets the callbacks
-(void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application

-(void)documentInteractionController: (UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application

If the user selects AirDrop you don't get notified at all.

A: This cannot be removed and apple is still trying to make airdrop accessible everywhere, so we might have to see that in few more places in future. From 7.1 update, it will for sure come in UIDocumentInteractionController irrespective of airdrop status(on or off on device)
And one more bad things is there is no callback for airdrop sharing, which means your app never knows about the sharing status. The below 2 delegate will not work for share.
-(void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application

-(void)documentInteractionController: (UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application

I hope apple will expose some delegate method to make  this possible in future versions.


text:
Q: Call super in overridden class method I want to add a new custom UIButtonType to the UIButton class via a category like so:
enum {
    UIButtonTypeMatteWhiteBordered = 0x100
};

@interface UIButton (Custom)

+ (id)buttonWithType:(UIButtonType)buttonType;

@end

Is it possible to get the super implementation of that overridden method somehow?
+ (id)buttonWithType:(UIButtonType)buttonType {
    return [super buttonWithType:buttonType];
}

The code above is not valid since super refers to UIControl in this context.

A: You can replace the method at runtime with your own custom method like so:
#import <objc/runtime.h>

@implementation UIButton(Custom)

// At runtime this method will be called as buttonWithType:
+ (id)customButtonWithType:(UIButtonType)buttonType
{
    // ---Add in custom code here---

    // This line at runtime does not go into an infinite loop
    // because it will call the real method instead of ours.
    return [self customButtonWithType:buttonType];
}

// Swaps our custom implementation with the default one
// +load is called when a class is loaded into the system
+ (void) load
{
    SEL origSel = @selector(buttonWithType:);

    SEL newSel = @selector(customButtonWithType:);

    Class buttonClass = [UIButton class];

    Method origMethod = class_getInstanceMethod(buttonClass, origSel);
    Method newMethod = class_getInstanceMethod(buttonClass, newSel);
    method_exchangeImplementations(origMethod, newMethod);
}

Be careful how you use this, remember that it replaces the default implementation for every single UIButton your app uses.  Also, it does override +load, so it may not work for classes that already have a +load method and rely on it.
In your case, you may well be better off just subclassing UIButton.
Edit: As Tyler notes below, because you have to use a class level method to make a button this may be the only way to override creation.

A: Jacob has a good point that category methods act differently than subclass methods.  Apple strongly suggests that you only provide category methods that are entirely new, because there are multiple things that can go wrong otherwise - one of those being that defining a category method basically erases all other existing implementations of the same-named method.
Unfortunately for what you're trying to do, UIButton seems to be specifically designed to avoid subclassing.  The only sanctioned way to get an instance of a UIButton is through the constructor [UIButton buttonWithType:].  The problem with a subclass like Jacob suggests (like this):
@implementation MyCustomButton

+ (id)buttonWithType:(UIButtonType)buttonType {
  return [super buttonWithType:buttonType]; //super here refers to UIButton
}

@end

is that the type returned by [MyCustomButton buttonWithType:] will still be a UIButton, not MyCustomButton.  Because Apple hasn't provided any UIButton init methods, there's not really a way for a subclass to instantiate itself and be properly initialized as a UIButton.
If you want some customized behavior, you can create a custom UIView subclass that always contains a button as a subview, so that you can take advantage of some of UIButton's functionality.
Something like this:
@interface MyButton : UIView {}

- (void)buttonTapped;

@end

@implementation MyButton

-(id)initWithFrame:(CGRect)frame {
  if (self = [super initWithFrame:frame]) {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = self.bounds;
    [button addTarget:self action:@selector(buttonTapped)
     forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
  }
  return self;
}

- (void)buttonTapped {
  // Respond to a button tap.
}

@end

If you want the button to do different things depending on more complex user interactions, you can make more calls to [UIButton addTarget:action:forControlEvents:] for different control events.
Reference: Apple's UIButton class reference

A: No, this is not possible when you use a category to augment a class' functionality, you are not extending the class, you are actually wholly overriding the existing method, you lose the original method completely. Gone like the wind.
If you create a subclass of UIButton, then this is totally possible:
enum {
    UIButtonTypeMatteWhiteBordered = 0x100
};

@interface MyCustomButton : UIButton {}

@end

@implementation MyCustomButton

+ (id)buttonWithType:(UIButtonType)buttonType {
    return [super buttonWithType:buttonType]; //super here refers to UIButton
}

@end


text:
Q: vb.net loop running next too fast I have this code in my vb application:
    For Each fi In aryFi
        If System.IO.File.Exists(fi.FullName) = True Then
            TextBox2.Text = TextBox2.Text + "File: " + fi.Name + vbCrLf
            TextBox2.Refresh()

            TextBox2.Text = TextBox2.Text + "Printing File" + vbCrLf
            TextBox2.Refresh()
            ' Create object, passing in text
            Dim psi As New ProcessStartInfo
            psi.UseShellExecute = True
            psi.Verb = "print"
            psi.WindowStyle = ProcessWindowStyle.Hidden
            psi.FileName = fi.FullName

            Dim p = Process.Start(psi)

            TextBox2.Text = TextBox2.Text + "Moving File" + vbCrLf
            TextBox2.Refresh()
            System.IO.File.Move(My.Settings.FolderPath + "\" + fi.Name, My.Settings.FolderPath + "\COMPLETED\" + fi.Name)
            TextBox2.Text = TextBox2.Text + vbCrLf + vbCrLf + "------------------------------------------------------------" + vbCrLf
            TextBox2.Refresh()

            p.WaitForExit()

        End If
    Next

It loops through a directory of files and prints each file individually.
Once it has printed the file, it moves it into another directory so its not processed again.
It seems that, it is running the next loop before the file has been moved so its trying to print the same file over and over again
how can i stop this from happening


text:
Q: Import and transpile external library with Webpack and typescript-loader I have project that uses Webpack and Typescript (typescript-loader). My tsconfig.json file is pretty straightforward and is set to target ES5:
{
    "compilerOptions": {
        "outDir": "./public/dist",
        "noImplicitAny": false,
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
    }
}

The webpack configuration file contains the following rule for my typescript files:
module: {
    rules: [{
       test: /\.ts?$/,
       loader: 'ts-loader'
    }]
},

All my project files are being compiled as intended to ES5 code and run fine. However, in one of my TS files I import a library installed through NPM: import * as striptags from "striptags"
The problem is that this file is not transpiled into ES5 and ends up with const and let keywords in my bundle that is targeted at ES5 devices. This causes JS errors.
How can I import the external striptags library and transpile it to ES5 so it doesn't break my client-side code?
I'm using TypeScript 2.6.1 and Webpack 3.10.0. Thanks!

A: I noticed that I did not read the readme of the striptags library correctly. It states that you should use the 2.x.x branch for ES5 support. Everything works fine now.


text:
Q: Pandas column for sequence of variable I'd like help creating a new column in Pandas that indicates whether something happened before or after in a sequence. I've included a description of the problem and a small sample of the dataframe as a dictionary below.
The dataframe is a list of interventions that happen to users as a "text" or a "call". Each row is an intervention. So, for instance, User122 had two calls and then a text (indicated in the sequence column).
I'd like a new column that specifies whether an intervention happened before or after the first instance of a call. So, for user122, there would be three rows in a new column, "text_after_call" that would be an Series of something like 'before, before, after', because the first instance of a text is in sequence 3, and calls where sequence 1 and 2. If a user has no text or call associated with it, the value would be NaN.
I think the solution would involve creating a loop through each user and checking whether the row with the first instance of "text" is greater or less than the sequence of last 'call', but I'm not sure how to do that.
Any help is appreciated and let me know if I can make this question any easier to answer!
{'sequence': {0: 1.0,
  1: 2.0,
  2: 3.0,
  3: 1.0,
  4: 1.0,
  5: 2.0,
  6: 1.0,
  7: 2.0,
  8: 3.0},
 'text_or_call':
 {0: call,
  1: call,
  2: text,
  3: text,
  4: text,
  5: nan,
  6: text,
  7: call,
  8: call},
 'user': {0: 'user122',
  1: 'user122',
  2: 'user122',
  3: 'user124',
  4: 'user125',
  5: 'user125',
  6: 'user126',
  7: 'user126',
  8: 'user126'}}

A: If we want to specify if texts are before or after the first call of a user, first we have to find the index of the first call for each user.
first_call_index = df.groupby(['user']).apply(lambda x: np.min((x.loc[x['text_or_call'] == 'call']).index))

This yields a dataframe containing the index of each users' first call. We can merge this with our original dataframe on user.
df_index = df.merge(first_call_index.reset_index().rename(columns={0:'first_call_index'}))

Afterwards we can just compare the index of each row with the value in the first_call_index row and test if the current row is a text message. If the index of the current row is before the first_call_index we set the value to before, if the other way around, we set the value to after.
df_index.loc[(df_index['first_call_index'] < df_index.index) & (df_index['text_or_call'] == 'text'), 'text_after_call'] = 'After'
df_index.loc[(df_index['first_call_index'] > df_index.index) & (df_index['text_or_call'] == 'text'), 'text_after_call'] = 'Before'

Result
sequence    text_or_call    user    first_call_index    text_after_call
0   1.0     call            user122     0.0             NaN
1   2.0     call            user122     0.0             NaN
2   3.0     text            user122     0.0             After
3   1.0     text            user124     NaN             NaN
4   1.0     text            user125     NaN             NaN
5   2.0     NaN             user125     NaN             NaN
6   1.0     text            user126     7.0             Before
7   2.0     call            user126     7.0             NaN
8   3.0     call            user126     7.0             NaN


text:
Q: Does my database need to connect to a server? I'm very new to SQL and databases. I'm currently following this tutorial for creating a Magento website: https://www.tutorialspoint.com/magento/magento_installation.htm
and I'm on Step 4. It says to create a new database for my site (which I'm running on localhost/magento right now). I downloaded MySQLWorkbench for this, and when I click "Create new connection", I put localhost/magento into the "hostname" section.
I'm just not sure how I'm supposed to create a database for my specific website, and if it needs to be connected to the URL.
Hope somebody can help me out in simple terms :)
Thanks.

A: A schema and a connection are two different things. So, creating a new connection does not mean to create a new schema/database.
You can create a database (or schema) in your server by using MySQL Workbench. After you opened a connection to your server, you will see the SQL IDE, a page with the treeview containing your current schemas, an SQL editor and various other stuff. In the schema tree use the context menu on any node to create the schema:

After that you can create a user with only the necessary rights for that single schema. Use the Administration -> Users and Privileges section for that:

Then assign the user access rights (e.g. for SELECT + DELETE) for that new schema by first allowing access to that new schema:

and finally set the required privileges:

Note: the backslash in the priv list is an escape sequence, because the string there is used as a pattern and the underscore ('_') is used as a placeholder in MySQL. Hence it must be escape to be used literally.

A: Nope, when you "create a database", think of it like you are creating a folder or a directory.
So, you'd create one with any name you want.  Ex:  my_fun_db  or   magneto_db, etc.
You will eventually then create a user who has access to THAT database.
Ex:  magneto_user / passwordxyz
And you'd assign that user to have full access to your magneto database.


text:
Q: Spacing problem after a list at the beginning of a theorem In the following example, how (if possible) can one make the line after the fruits be formatted in the same way as the line after the vegetables in a "clean" way without moving the apple to a new line?  Here, by a "clean" way, I mean not having to specify the spacing explicitly (in the text or buried in a new macro).
\documentclass{article}
\usepackage{amsthm}
\theoremstyle{definition}
\newtheorem*{thm}{Theorem}

\begin{document}
\begin{thm}
\begin{enumerate}
\item apple
\item orange
\end{enumerate}
This is indented like a paragraph with no extra vertical spacing before it.
\end{thm}

\begin{enumerate}
\item lettuce
\item cabbage
\end{enumerate}
This is how I want it.
\end{document}

A: if you must start a theorem with a run-in enumerated list, you can enter the first line manually, then begin the enumerate on the next line starting with "2":
\documentclass{article}
\usepackage{amsthm}
\theoremstyle{definition}
\newtheorem*{thm}{Theorem}

\begin{document}
\begin{thm}
1. apple
\begin{enumerate}
\setcounter{enumi}{1}
%\item apple
\item orange
\end{enumerate}
This is how I want it.
\end{thm}

\end{document}

if the first item is more than one line long, or in an italic theorem statement where the document class sets the item numbers upright, a more
elaborate approach is needed.


text:
Q: character counting game for random name android I am trying to learn Android. I want to build a simple letter counting app for counting random name, that is my code l have problem with onclickListerner. Thank you in advance Counting Themed Game
public class MainActivity extends Activity  implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b = (Button)findViewById(R.id.button1);
    TextView nameView = (TextView)findViewById(R.id.nameView);
    nameView.setText("saya");
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            public boolean onCreateOptionsMenu(Menu menu) {
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }

            public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();
                if (id == R.id.action_refresh) {
                    TextView nameView = (TextView)findViewById(R.id.nameView);
                    nameView.setText("van");
                }
                return super.onOptionsItemSelected(item);

            }

        }
    });
}

A: Replace this:
b.setOnClickListener() ;

With this:
button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Your code here
            }
        });

And remove this:
@Override
public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stu
}

A: Since you're extending the onclicklistener, you should call b.setOnClickListener(this);


text:
Q: Minimal "Task Queue" with stock Linux tools to leverage Multicore CPU What is the best/easiest way to build a minimal task queue system for Linux using bash and common tools?
I have a file with 9'000 lines, each line has a bash command line, the commands are completely independent.
command 1 > Logs/1.log
command 2 > Logs/2.log
command 3 > Logs/3.log
...

My box has more than one core and I want to execute X tasks at the same time. I searched the web for a good way to do this. Apparently, a lot of people have this problem but nobody has a good solution so far.
It would be nice if the solution had the following features:

*

*can interpret more than one command (e.g. command; command)

*can interpret stream redirects on the lines (e.g. ls > /tmp/ls.txt)

*only uses common Linux tools

Bonus points if it works on other Unix-clones without too exotic requirements.

A: Can you convert your command list to a Makefile? If so, you could just run "make -j X".

A: GNU Parallel http://www.gnu.org/software/parallel/ is a more general tool for parallelizing than PPSS.
If runfile contains:
command 1 > Logs/1.log
command 2 > Logs/2.log
command 3 > Logs/3.log

you can do:
cat runfile | parallel -j+0

which will run one command per CPU core.
If your commands are as simple as above you do not even need runfile but can do:
seq 1 3 | parallel -j+0 'command {} > Logs/{}.log'

If you have more computers available to do the processing you may want to look at the --sshlogin and --trc options for GNU Parallel.

A: Okay, after posting the question here, I found the following project which looks promising: ppss.
Edit: Not quite what I want, PPSS is focused on processing "all files in directory A".

A: Well, this is a kind of fun question anyway.
Here's what I'd do, assuming bash(1) of course.

*

*figure out how many of these commands can usefully run concurrently.  It's not going to be just the number of cores; a lot of commands will be suspended for I/O and that sort of thing.  Call that number N.  N=15 for example.

*set up a trap signal handler for the SIGCHLD signal, which occurs when a child process terminates. trap signalHandler SIGCHLD

*cat your list of commands into a pipe

*write a loop that reads stdin and executes the commands one by one, decrementing a counter.  When the counter is 0, it waits.

*your signal handler, which runs on SIGCHLD, increments that counter.

So now, it runs the first N commands, then waits.  When the first child terminates, the wait returns, it reads another line, runs a new command, and waits again.
Now, this is a case that takes care of many jobs terminating close together.  I suspect you can get away with a simpler version:
 N=15
 COUNT=N
 cat mycommands.sh |
 while read cmd
 do
   eval $cmd &
   if $((count-- == 0))
   then
       wait
   fi
 od

Now, this one will start up the first 15 commands, and then run the rest one at a time as some command terminates.

A: Similar distributed-computing fun is the Mapreduce Bash Script:
http://blog.last.fm/2009/04/06/mapreduce-bash-script
And thanks for pointing out ppss!

A: You can use the xargs command, its --max-procs does what you want. For instance Charlie Martin solution becomes with xargs:
tr '\012' '\000' <mycommands.sh |xargs --null --max-procs=$X bash -c

details:

*

*X is the number of processes max. E.g: X=15. --max-procs is doing the magic

*the first tr is here to terminate lines by null bytes for xargs --null option so that quotes redirection etc are not expansed wrongly

*bash -c runs the command

I tested it with this mycommands.sh file for instance:
date
date "+%Y-%m-%d" >"The Date".txt
wc -c <'The Date'.txt >'The Count'.txt

A: This is a specific case, but if you are trying to process a set of files and produce another set of output files, you can start #cores number of processes, and check if an output file exists before processing it. The example below converts a directory of .m4b files to .mp3 files:
Just run this command as many times as you have cores:
ls *m4b|while read f; do test -f ${f%m4b}mp3 || mencoder -of rawaudio "$f" -oac mp3lame -ovc copy -o ${f%m4b}mp3; done &

A: You could see my tasks queue written on bash: https://github.com/pavelpat/yastq

A: Task Queue + Parallelized + Dynamic addition
Using a FIFO, this script fork itself to process the queue. This way, you can add commands to the queue on the fly (when the queue is already started).
Usage: ./queue Command [# of children] [Queue name]
Example, with 1 thread:

./queue "sleep 5; echo ONE"
./queue "echo TWO"

Output:

ONE
TWO

Example, with 2 thread:

./queue "sleep 5; echo ONE" 2
./queue "echo TWO"

Output:

TWO
ONE

Example, with 2 queues:

./queue "sleep 5; echo ONE queue1" 1 queue1
./queue "sleep 3; echo ONE queue2" 1 queue2

Output:

ONE queue2
ONE queue1

The script (save it as "queue" and chmod +x queue):
#!/bin/bash

#Print usage
[[ $# -eq 0 ]] && echo Usage: $0 Command [# of children] [Queue name] && exit

#Param 1 - Command to execute
COMMAND="$1"

#Param 2 - Number of childs in parallel
MAXCHILD=1
[[ $# -gt 1 ]] && MAXCHILD="$2"

#Param 3 - File to be used as FIFO
FIFO="/tmp/defaultqueue"
[[ $# -gt 2 ]] && FIFO="$3"

#Number of seconds to keep the runner active when unused
TIMEOUT=5

runner(){
  #Associate file descriptor 3 to the FIFO
  exec 3<>"$FIFO"

  while read -u 3 -t $TIMEOUT line; do
    #max child check
    while [ `jobs | grep Running | wc -l` -ge "$MAXCHILD" ]; do
      sleep 1
    done

    #exec in backgroud
    (eval "$line")&
  done
  rm $FIFO
}

writer(){
  #fork if the runner is not running
  lsof $FIFO >/dev/null || ($0 "QueueRunner" "$MAXCHILD" "$FIFO" &)

  #send the command to the runner
  echo "$COMMAND" > $FIFO
}

#Create the FIFO file
[[ -e "$FIFO" ]] || mkfifo "$FIFO"

#Start the runner if in the runner fork, else put the command in the queue
[[ "$COMMAND" == "QueueRunner" ]] && runner || writer


text:
Q: NameError: undefined local variable or method `current_protocol_version' for # I have some problems with my unit test.
When i run my unit test i have some problem with:

*

*timestamp

*undefined loacal variable or method
========== 1 ============
When i run the unit test, i have an error with timpestamp and date field. it say:
  -      "date"=>"2011-11-05T22:03:54+09:00",
  ?                           ^        ^
  +      "date"=>"2011-11-05T20:03:54+07:00",
  ?                           ^        ^
         "finished"=>1,
         "position"=>"",
         "timestamp"=>"2014-03-21T09:43:05+07:00",
         "type"=>"new type"},
       "content_id2"=>
        {"bookmark_suffix_max"=>3,
         "bookmarks"=>
          [{"date"=>"", "label"=>"", "name"=>"", "position"=>""},
           {"date"=>"", "label"=>"", "name"=>"", "position"=>""}],
  -      "date"=>"2011-11-04T22:03:54+09:00",
  ?                           ^        ^
  +      "date"=>"2011-11-04T20:03:54+07:00",
  ?                           ^        ^
         "finished"=>1,
         "position"=>"",
  -      "timestamp"=>"2011-11-04T22:03:54+09:00",
  ?                                ^        ^
  +      "timestamp"=>"2011-11-04T20:03:54+07:00",
  ?                                ^        ^
         "type"=>""}},
     "timestamp"=>"2014-03-21T09:43:05+07:00"}
test_merge1_with_conflict_1:_should_update_bookmark_info_with_client's_'date'_field(AccountBookmarkInfoTest)

Is it because of time_zone ? or something else. I already fix the - with + but i've still have same error with that.
============ 2 ===============
Error: test_ContentsJsonCache.key_for_params_should_depend_all_query_parameters(ContentsJsonCacheTest)
  NameError: undefined local variable or method `current_protocol_version' for #<App:0x007fcc0a3f8800>
app/models/app.rb:166:in `implements_purchase_bonus_feature?'
app/models/app.rb:174:in `include_purchase_bonuses_in_contents_json?'
app/models/contents_json_cache.rb:21:in `key_for_params'
test/unit/contents_json_cache_test.rb:22:in `block in <class:ContentsJsonCacheTest>'

current_local_version is in :
**Controller. define : app.current_protocol_version

**Models. define :

    attr_accessible :current_protocol_version,
                    :name,
                    ....
**test->functional->app.controller_test.rb

    app = apps :one
    app.current_protocol_version = '1.1.9'
    assert_false app.implements_account_feature?

A: To fix timestamp error do this in your code.
if you have code like this below:
before.
time.parse var

after
time.zone.parse var