text:
Q: What's the usage of setBindingContext() and the difference from element binding? In the 1.5.2.3 Defining a Binding Path section of OpenUI5 demokit:

A context exists either for each entry of the aggregation in case of aggregation binding or can be set explicitly for a control by using the setBindingContext method.

In the 1.5.3.3 Element Binding section of OpenUI5 demokit:

Element binding allows to bind elements to a specific object in the model data, which will create a binding context and allow relative binding within the control and all of its children.

It seems to me that the two techniques actually do the same thing. They both create a binding context for a control so that bindings of the containing controls will resolve relatively to it. But what's the difference between them? In what scenario will either of them come into play?
The setBindingContext doesn't work in the following code:https://jsbin.com/bigope/edit?html,output
However, if I change oPanel.setBindingContext("/nameinfo"); to oPanel.bindElement("/nameinfo");, it works, why?

A: setBindingContext requires you to pass a Context like this:
oPanel.setBindingContext(new sap.ui.model.Context(oModel, "/nameinfo"));

The difference between those two is conceptual.
The Binding Context is used as a parent context for all bindings (for that model) in that Control or its children. It only holds a reference to the used model, (a part of) the path and optional another parent context. It is used when creating relative bindings.
The bindElement method on the other hand behaves like every other bind* method.
It creates a binding (in this case, a ContextBinding) which allows change events, data binding, etc.
Additionally the created ContextBinding also serves as a BindingContext for other bindings, just like a Context added with setBindingContext would do.
Not confusing at all, right ;)?
Reading the code for ManagedObject might help you to understand the internals better. (bindObject = bindElement)


text:
Q: How to capture the next event based on a condition I have a huge data set but I will explain the problem based on an example.
In the below table I have a Unique ID, I have a Date (time series for each Unique ID) and status of that Unique ID.
Unique ID   Date    Status
        1   Jan-06  Active
        1   Feb-06  Active
        1   Mar-06  Not active
        1   Apr-06  Stable
        1   May-06  Active
        1   Jun-06  Stable
        1   Jul-06  Active
        1   Aug-06  Active
        1   Sep-06  Active
        2   Oct-06  Active
        2   Nov-06  Not active
        2   Dec-06  Stable
        2   Jan-07  Active
        2   Feb-07  Stable
        2   Mar-07  Active
        2   Apr-07  Active
        2   May-07  Active

Result I am trying to get to is to capture the date of  next event of happening (Not active or stable )
If you see below unique ID 1 was active as of Jan 2006, we need to capture when it hit not active or stable, it hit some time in March 06.
If you see below unique ID 1 was active as of May 2006, we need to capture when it hit not active or stable, it hit some time in Jun 06.
Note: No Need to add any date for IDs which are already in not active or stable
Unique ID   Date    Status  Result
        1   Jan-06  Active  Mar-06
        1   Feb-06  Active  Apr-06
        1   Mar-06  Not active  NA
        1   Apr-06  Stable  NA
        1   May-06  Active  Jun-06
        1   Jun-06  Stable  NA
        1   Jul-06  Active  Always active
        1   Aug-06  Active  Always active
        1   Sep-06  Active  Always active
        2   Oct-06  Active  Nov-06
        2   Nov-06  Not active  NA
        2   Dec-06  Stable  NA
        2   Jan-07  Active  Feb-07
        2   Feb-07  Stable  NA
        2   Mar-07  Active  Always active
        2   Apr-07  Active  Always active
        2   May-07  Active  Always active

A: Generate example data:
> set.seed(1234)
> id <- rep(1:3, times=c(10,10,10))
> date <- seq(as.Date("2000/1/1"), by = "month", length.out = length(id))
> date <- format(date,  "%b-%y")
> status <- sample(c("Active", "Not Active", "Stable"), length(id), replace=TRUE)
> data.frame(id, date, status)
   id   date     status
1   1 Jan-00     Active
2   1 Feb-00 Not Active
3   1 Mar-00 Not Active
4   1 Apr-00 Not Active
5   1 May-00     Stable
6   1 Jun-00 Not Active
7   1 Jul-00     Active
8   1 Aug-00     Active
9   1 Sep-00 Not Active
10  1 Oct-00 Not Active
11  2 Nov-00     Stable
12  2 Dec-00 Not Active
13  2 Jan-01     Active
14  2 Feb-01     Stable
15  2 Mar-01     Active
16  2 Apr-01     Stable
17  2 May-01     Active
18  2 Jun-01     Active
19  2 Jul-01     Active
20  2 Aug-01     Active
21  3 Sep-01     Active
22  3 Oct-01     Active
23  3 Nov-01     Active
24  3 Dec-01     Active
25  3 Jan-02     Active
26  3 Feb-02     Stable
27  3 Mar-02 Not Active
28  3 Apr-02     Stable
29  3 May-02     Stable
30  3 Jun-02     Active

Replace the last "Active" observation for each id with "Always Active" in copies of date and status variables:
> id_last_active <- (id != c(id[-1], FALSE)) & (status == "Active")
> date2 <- as.character(date)
> date2[id_last_active] <- "Always Active"
> status2 <- status
> status2[id_last_active] <- "Always Active"

Use which() to get positions of non-"Active" observations (regardless of id), and use diff() and rep() to create a vector of positions of the next non-"Active" event for the group of prior "Active" events. Then get the date of the next non-active event for "Active" events:
> nonactive <- which(status2 != "Active")
> status_len <- c(nonactive[1], diff(nonactive))
> next_event <- date2[rep(nonactive, times = status_len)]
> next_event[status2 %in% c("Stable", "Not Active")] <- NA

Print the data by id (using by()):
> dat <- data.frame(id, date, status, next_event)
> by(dat, dat$id, function(x) x)
dat$id: 1
   id   date     status next_event
1   1 Jan-00     Active     Feb-00
2   1 Feb-00 Not Active       <NA>
3   1 Mar-00 Not Active       <NA>
4   1 Apr-00 Not Active       <NA>
5   1 May-00     Stable       <NA>
6   1 Jun-00 Not Active       <NA>
7   1 Jul-00     Active     Sep-00
8   1 Aug-00     Active     Sep-00
9   1 Sep-00 Not Active       <NA>
10  1 Oct-00 Not Active       <NA>
---------------------------------------------------------------
dat$id: 2
   id   date     status    next_event
11  2 Nov-00     Stable          <NA>
12  2 Dec-00 Not Active          <NA>
13  2 Jan-01     Active        Feb-01
14  2 Feb-01     Stable          <NA>
15  2 Mar-01     Active        Apr-01
16  2 Apr-01     Stable          <NA>
17  2 May-01     Active Always Active
18  2 Jun-01     Active Always Active
19  2 Jul-01     Active Always Active
20  2 Aug-01     Active Always Active
---------------------------------------------------------------
dat$id: 3
   id   date     status    next_event
21  3 Sep-01     Active        Feb-02
22  3 Oct-01     Active        Feb-02
23  3 Nov-01     Active        Feb-02
24  3 Dec-01     Active        Feb-02
25  3 Jan-02     Active        Feb-02
26  3 Feb-02     Stable          <NA>
27  3 Mar-02 Not Active          <NA>
28  3 Apr-02     Stable          <NA>
29  3 May-02     Stable          <NA>
30  3 Jun-02     Active Always Active

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle SQL find missing sequence in varchar2 field I am new to oracle and to this forum. I have searched and found answers on how to do this with a column of just numbers but this has txt at the beginning then a sequenced number.
I have a table that has a varchar2 column named  myid which has characters with a number at the end which is in order the number at the end is always 6 digits with leading zeros.
Hello_002190
Hello_002188
Bye_000187
Bye_000185
Bye_000184
Get_008133
Get_008131
Gone_001112
Gone_001110
Gone_001109

I need an Oracle SQL script that will show me all the missing rows.
The result for the above should be:
Hello_002189
Bye_000186
Get_008132
Gone_001111

Thanks in advance for the help

A: SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE table_name ( value ) AS
SELECT 'Hello_002190' FROM DUAL UNION ALL
SELECT 'Hello_002188' FROM DUAL UNION ALL
SELECT 'Bye_000187' FROM DUAL UNION ALL
SELECT 'Bye_000185' FROM DUAL UNION ALL
SELECT 'Bye_000184' FROM DUAL UNION ALL
SELECT 'Get_008133' FROM DUAL UNION ALL
SELECT 'Get_008131' FROM DUAL UNION ALL
SELECT 'Gone_001112' FROM DUAL UNION ALL
SELECT 'Gone_001110' FROM DUAL UNION ALL
SELECT 'Gone_001109' FROM DUAL;

Query 1:
WITH data ( prefix, suffix ) AS (
  SELECT SUBSTR( value, 1, INSTR( value, '_' ) ),
         TO_NUMBER( SUBSTR( value, INSTR( value, '_' ) + 1 ) )
  FROM   table_name
),
bounds ( prefix, min_suffix, max_suffix ) AS (
  SELECT prefix, MIN( suffix ), MAX( suffix )
  FROM   data
  GROUP BY prefix
)
SELECT prefix || TO_CHAR( column_value, 'FM000000' ) AS missing_value
FROM   bounds b
       CROSS JOIN
       TABLE(
         CAST(
           MULTISET(
             SELECT b.min_suffix + LEVEL - 1
             FROM   DUAL
             CONNECT BY b.min_suffix + LEVEL - 1 <= b.max_suffix
           ) AS SYS.ODCINUMBERLIST
         )
       )
MINUS
SELECT value FROM table_name

Results:
| MISSING_VALUE |
|---------------|
|    Bye_000186 |
|    Get_008132 |
|   Gone_001111 |
|  Hello_002189 |


text:
Q: Pre-populate the github new issue form using the querystring Is there a way to have a link for a new git issue that pre-populates labels and the assignment field to labels and a user that is specified in the query string?
My use case is that I'd like to have a link that I can give to testers that will ensure they select the correct labels for my feature and also have the git issue assigned to me.

A: I found out that the format is https://github.com/[user]/[repo]/issues/new?title=[title]&assignee=[user]&body=[body]&labels[]=label1&labels[]=label2

A: This is now:
https://github.com/[user]/[repo]/issues/new?title=[title]&assignee=[user]&body=[body]&labels=label1,label2

since Nov 2017. See: https://github.com/isaacs/github/issues/99#issuecomment-343061332


text:
Q: About generics in Java and Scala I am confused by the generic subtyping.
In Java, if type A is a subtype of B, generic type C<A> and C<B> are invariant. For instance, ArrayList<Base> is not a subtype of ArrayList<Derived>.
However, in Scala, generic type C<A> and C<B> are covariant if type A is a subtype of B. So what's the property of generic class in Scala has but not in Java?

A: Firstly note that variance is a property of generic type parameters, not of the parameterized types themselves.
Secondly: you are wrong about scala - type parameters are invariant by default. Let us investigate!
Java
Java has use-site variance annotations. That is, you can declare methods like this:
boolean addAll(Collection<? extends T> c);

There is, however, one form of "parameterized type" (I use the term loosely) in which the type parameters are covariant: Java Arrays! (This is actually insane because Arrays are mutable and hence it is easy to circumvent the type system). Consider the following:
public static void subvert(Object[] arr) { arr[0] = "Oh Noes!"; }

And then:
Integer[] arr = new Integer[1];
subvert(arr); //this call is allowed as arrays are covariant
Integer i = arr[0];

A good interview question this one: what happens?
Scala
In Scala, you have declaration-site variance. That is, the variance of a type parameter is declared alongside the parameter (using the annotations + and -):
trait Function1[-I, +O]

This says that the trait Function1 has two type parameters, I and O which are contra- and co-variant respectively. If no +/- annotation is declared, then the type parameter is invariant. For example, Set is invariant in its type parameter:
scala> def foo(set: Set[Any]) = ()
foo: (set: Set[Any])Unit

scala> Set(1)
res4: scala.collection.immutable.Set[Int] = Set(1)

scala> foo(res4)
<console>:10: error: type mismatch;
 found   : scala.collection.immutable.Set[Int]
 required: Set[Any]
Note: Int <: Any, but trait Set is invariant in type A.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
              foo(res4)
                  ^

List is however, declared as being covariant:
scala> def bar(list: List[Any]) = ()
bar: (list: List[Any])Unit

scala> List(1)
res6: List[Int] = List(1)

scala> bar(res6)

Why not ask the compiler?
Another way of demonstrating this is to ask the compiler directly for subtype-evidence:
scala> class Cov[+A]
defined class Cov

scala> implicitly[Cov[Int] <:< Cov[Any]]
res8: <:<[Cov[Int],Cov[Any]] = <function1>

But with an invariant type parameter
scala> class Inv[A]
defined class Inv

scala> implicitly[Inv[Int] <:< Inv[Any]]
<console>:9: error: Cannot prove that Inv[Int] <:< Inv[Any].
              implicitly[Inv[Int] <:< Inv[Any]]
                        ^

Lastly, contravariance:
scala> class Con[-A]
defined class Con

scala> implicitly[Con[Any] <:< Con[Int]]
res10: <:<[Con[Any],Con[Int]] = <function1>

See also identifier <:<


text:
Q: this integral $\int\frac{2-\sin{x}}{\sin^2{x}-\sin{x}+1}dx$ Find integral
$$\int\dfrac{2-\sin{x}}{\sin^2{x}-\sin{x}+1}dx$$
As suggested ,we take the Weierstrass Substitution is often useful in integrals such as the original.
$$
\begin{align}
\sin(x)&=\frac{2z}{1+z^2}\\
\cos(x)&=\frac{1-z^2}{1+z^2}\\
\mathrm{d}x&=\frac{2\,\mathrm{d}z}{1+z^2}
\end{align}
$$
I known is equal to
$$\int\dfrac{4(z^2-z+1)}{z^4-2z^3+6z^2-2z+1}dz$$
but I don't know how I should calculate the last integral.

A: Here's my revised solution that is shorter in working (which is still ridiculously long). The only tedious part is the simplifiying of the integrand after the Weierstrass Substitution. Outline:
Let $ y = \frac \pi 2 - x $, we get
$ \begin{eqnarray} \displaystyle \int \frac{\cos y - 2}{\cos^2 y - \cos y + 1} \, dy & = & \displaystyle \int \frac{(-\sin y) + (\sin y + \cos y - 2)}{\cos^2 y - \cos y + 1} \, dy \\ & = & \int \frac{-\sin y}{\cos^2 y - \cos y + 1} \, dy + \int \frac{\sin y + \cos y - 2} {\cos^2 y - \cos y + 1} \, dy \end{eqnarray} $
The first integral can be solved via substitution of $ p = -\cos y $ then convert it in the form of $ \large\displaystyle \int \frac{ds}{a^2+s^2} = \frac1a \tan^{-1} \left( \frac sa\right) $
For the second integral, we use the  Weierstrass Substitution as suggested. Let $ t = \tan\left( \frac y2\right) $ and the integrand simplifies to
$ \large \frac{-6t^2+4t-2}{(t^2+1)^2} $
Apply partial fraction
$ \large \frac{4t}{(t^2+1)^2} - \frac6{t^2+1} + \frac4{(t^2+1)^2} $
Which can be easily integrated.
If I'm correct, back substituting everything yields
$ \large \frac2{\sqrt3} \tan^{-1} \left(\frac2{\sqrt3}\sin x\right) - \frac{2(\sin x + 1)}{\tan \frac x2 + 1} - 4\cot^{-1} x + C $

A: Hint
Note
$$\dfrac{2-\sin{x}}{\sin^2{x}-\sin{x}+1}=\dfrac{1}{w_{1}-w_{2}}\left(\dfrac{2-\sin{x}}{\sin{x}-w_{1}}-\dfrac{2-\sin{x}}{\sin{x}-w_{2}}\right)$$
where $w_{1},w_{2}$ are equation $x^2-x+1=0$complex roots
and
$$\dfrac{2-\sin{x}}{\sin{x}-w_{1}}=-1+\dfrac{2-w_{1}}{\sin{x}-w_{1}}$$
$$\dfrac{2-\sin{x}}{\sin{x}-w_{2}}=-1+\dfrac{2-w_{2}}{\sin{x}-w_{2}}$$
use this following
$$\int\dfrac{1}{\sin{x}-A}dx=\dfrac{2\arctan{\left(\dfrac{1-A\tan{\frac{x}{2}}}{\sqrt{A^2-1}}\right)}}{\sqrt{A^2-1}}$$
then you can solve it


text:
Q: clean URL using .htaccess I'm trying to redirect the links on my domain.
What I'm trying to achieve is:
When the user clicks on a link to
mydomain.com/index.php?dir=myfolder
I want him to be redirected to exactly this URL but the browser bar is supposed to show this URL:
mydomain.com/myfolder
Since I don't have access to how the links are established (it's a php-site) I am trying to do this with just the .htaccess-file.
This is what I have:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} subdomain.mydomain.com
RewriteCond %{REQUEST_URI} (.*)/style.css [OR]
RewriteCond %{REQUEST_URI} (.*)/script.js [OR]
RewriteCond %{REQUEST_URI} (.*)/logo.png
RewriteRule (.*) http://www.subdomain.com%{REQUEST_URI} [R=301,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?dir=$1 [L]

So when I enter "mydomain.com/myfolder" into the browser it works fine and the URL in the address-bar stays like this. But when I enter "mydomain.com/index.php?dir=myfolder" it works as well but the URL also stays the same (which is not what I want).
I assume that I need to somehow change the URL with the .htaccess-file and have it then (as I already have) rewritten to then php-scheme.
I did several approaches now but I have no idea how to do this.
I hope you understand my question and can help me!
Thank you!
EDIT:

The solution ( thanks to @anubhava):
RewriteEngine on
RewriteBase /

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?dir=([^\s]+) [NC]
RewriteRule ^ %1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?dir=/$1 [L]

A: Just append this rule at the end of your existing .htaccess file:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?dir=([^\s]+) [NC]
RewriteRule ^ %1? [R=301,L]

A: I think you question is about making /index.php?dir=example redirect to /example. The below example issues a permanent redirection:
RewriteRule ^index\.php\?dir=?$ /$1 [NC,R=301,L]

A: To prettify URLs of the format mydomain.com/index.php?dir=myfolder as mydomain.com/myfolder, try the following rewrite rule in your .htaccess file:
RewriteEngine on
RewriteRule ^([^/\.]+)/?$ /index.php?dir=$1 [L]


text:
Q: How does the JVM determine where FileDescriptor.out (STDOUT) goes on Windows? I have an issue hovering somewhere between the JVM and Windows, and I fear I'm not knowledgeable enough about either to ask the question very well, but here goes:
I have some non-Java code (it's SAS SCL code, but I'm hoping that a knowledge of SAS isn't necessary to answer this) that launches a Java process and redirects its STDOUT and STDERR streams to SAS's conception of a named pipe. That Java process writes some text to System.out. The SAS code then attempts to read that text from the pipe.
This has worked for a long time on many systems, but recently problems have cropped up on Windows. The issues might be specific to Java 7 (though possibly Java 6 as well), and/or possibly specific to Windows 7 and later.
There are two contexts from which this code may be called. In one context, it works fine; in the other, SAS doesn't see any output from the Java process (which appears to be running successfully based on other output). When it doesn't work, the 'fread' call appears to block until the Java process is complete; however, that call just returns 'EOF'.
(Specifically: if run from a SAS Workspace Server process, it works. If it runs from batch-mode SAS, it doesn't. I'm not clear what exactly is different between these two environments, though the process owner is different.)
In the case where it doesn't work, I briefly see a Windows console window that contains the STDOUT output that SAS should be but isn't seeing. In the case where it does work, I don't see such a window, but that might be a result of the process running under a different OS user than the one I'm logged in as.
Given all that, I guess my question is: how does the JVM determine where STDOUT ends up? Could the JVM be writing the output to a console window instead of the desired STDOUT stream connected to the SAS pipe? What are the salient aspects of the environment that the JVM looks at when making this determination?
EDIT 2013-02-20:
Further investigation shows that when launching the Java process, SAS does the following:
cmd /C <java command>

This is done in both contexts in which the code is run.
I tested with Java 5, and the behavior is the same as for Java 7: this doesn't appear to be Java version-specific.
Windows 7+ is the common thread. I'm guessing this is related to the new ConHost.exe process added in Windows 7/Windows Server 2008 R2.


text:
Q: How to set Bootstrap modal height fixed when data-slide occurs for Carousel I'm trying to use carousel effect inside BootStrap modal, here if data-slide size of fist modal-body gets differed due to lesser content in second slide the size of second div is minimized to smaller height.
Is there a possible way to have fixed size for all carousel-item while performing data-slide??

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
            </button>

Title

Header Note

This is First Page

                            APR 1

                            XXXXXXXXXXXX

                            XXXXXXXXXXXXX

                            XXXXXXXXXX XXX

                            XXXXXX

                            <input type="submit" class="btn btn-primary" name="pay-shortpay" value="Pay Now"
                             href="#carousel-example-generic" id="paynowbtn" data-slide="next">

                            XXXXX

                            XXXX

                            XXXXXXXX

                            XXXXXX

                            XXXXXX

                            <input type="submit" class="btn btn-primary" name="pay-shortpay" href="#carousel-example-generic" id="paynowbtn" value="Pay Now" data-slide="next">

This is Second Page

                         <input type="submit" class="btn btn-primary"  href="#carousel-example-generic" id="paynowbtn" value="Go Back" data-slide="prev">

Example:
http://www.bootply.com/opdfUNQsDy
Both need to have same height

A: CSS
.modal-content{
  height: 300px;
  overflow: scroll;
}

It will give a fixed height.


text:
Q: How to create different versions of a site in Liferay? I have built my site with default language being in Spanish and now I want to build the English version of it. I have added the link 'In English' to the Spanish site, and when clicked takes me to www.example.com/en. The control panel on the English site converts to English as well, which is fine. Then I try to translate the contents from Spanish to English.
Here is what I do: let's say I take the 'Contact' menu, where I have the contact page. In the URL then it looks like this: www.example.com/en/contact. Through Edit, I go to the text editor, localize the language to English, change the title and the content of the page into English and save it in a hope to see the changes on the English version only, but the change is also shown on the Spanish version, that is it overrides the Spanish version, which means that the page is the same on both the language versions. I thought the copy that is under www.example.com/en/contact is a different instance of the web content than that on www.example.com/contact, but I was wrong.
The question is how to create the English version of the site then? Should I copy the whole site's theme into a folder e.g. /en and make the changes from there? or there is another way to do this?

A: 1: Create a content

2: Add tranlation

3: Put tranlation

with www.example.com/en/contact, www.example.com/bg/contact, etc. you can see the tranlation.


text:
Q: php Search engine the keywords are not working When i would search for the keywords that i have specified in my database it will return everything from my database not just the corresponding links that have the keywords attached to the link. here is my code
        <?php
        $q = $_GET['q'];
        $terms = explode(" ", $q);
        $query = "SELECT * FROM search ";

        foreach ($terms as $each){
            $i=0;
            $i++;
                if ($i == 1)
                    $query .= "keywords LIKE '%$each%' ";
                else
                    $query .= "OR keywords LIKE '%$each%' ";

        }

        //connect
        mysql_connect("localhost", "root", "");
        mysql_select_db("search");

        $query = mysql_query("SELECT * FROM search");
        $numrows = mysql_num_rows($query);
        if ($numrows > 0){

            while($row = mysql_fetch_assoc($query)){
                $id = $row['id'];
                $title = $row['title'];
                $description = $row['description'];
                $keywords = $row['keywords'];
                $link = $row['link'];

                echo "
$title

$link
$description

";
            }
        }
        else
            echo "No Results Found

Suggestions:

                Make sure all words are spelled correctly.

                Try different keywords.

                Try more general keywords.";

        //disconnect
        mysql_close();

    ?>

A:  <?php
    $q = $_GET['q'];
    $terms = explode(" ", $q);

    //connect
    mysql_connect("localhost", "root", "");
    mysql_select_db("search");

    $query = "SELECT * FROM search ";

    $i=1;
    foreach ($terms as $each){
        if ($i == 1) {
            $query .= "WHERE ";
            $query .= "keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
        } else {
            $query .= "OR keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
        }
        $i++;
    }

    $query = mysql_query($query);
    $numrows = mysql_num_rows($query);
    if ($numrows > 0){

        while($row = mysql_fetch_assoc($query)){
            $id = $row['id'];
            $title = $row['title'];
            $description = $row['description'];
            $keywords = $row['keywords'];
            $link = $row['link'];

            echo "
$title

$link
$description

";
        }
    } else {
        echo "No Results Found

Suggestions:

            Make sure all words are spelled correctly.

            Try different keywords.

            Try more general keywords.";
    }
    //disconnect
    mysql_close();

?>

Fixes:
1) Removed second $query that was being defined. It selected all rows.
2) Moved initial $i declaration. It was being set back to 0 each loop.
3) Added WHERE
4) Moved $i++ after the if statement and set initial $i to 1.
5) Added mysql_real_escape_string so that data is escaped properly.
Recommendations:
I highly recommend taking a look at MySQLi (http://us2.php.net/mysqli) or PDO (http://us3.php.net/pdo)
Please let me know if this works or if you need further assistance.

A: A first sight,  i see a couple  of errors.
 $i=0;
 $i++;
     if ($i == 1)

$i Will ALWAYS be one are.
you might want to move $i = 0; BEFORE the foreach
$query = mysql_query("SELECT * FROM search");

You build a query, but in the end you're not using it.  you probably want to do : $query = mysql_query($query);   instead.    ( and also for code clarity using a different variable name for the output ? ) .
mysql_query is deprecated. Useless you're in a hurry,  check PDO

A: First, you're missing the WHERE keyword before the conditions. So it should be:
    foreach ($terms as $i => $each){
        $each = mysql_real_escape_string($each); // Prevent SQL injection
        if ($i == 0)
            $query .= "WHERE keywords LIKE '%$each%' ";
        else
            $query .= "OR keywords LIKE '%$each%' ";

    }

You don't need to increment your own counter variable, you can use the array indexes from $terms.
Second, after all that work to create $query, you're not using it. You wrote:
    $query = mysql_query("SELECT * FROM search");

That should be:
    $query = mysql_query($query);

BTW, it's generally a bad idea to reuse variables like that, it gets confusing when you use the same variable for different things. I suggest you call the second $query something like $results.

A: Change this line
$query .= "keywords LIKE '%$each%' ";

By
$query .= " Where keywords LIKE '%$each%' ";

And also cnhange this line
$query = mysql_query("SELECT * FROM search");

By
$query = mysql_query($query);


text:
Q: How do I initialize and fill a vector of type vector >? I am trying to return a write a function that creates a vector<vector<int> > and fills it and returns it. I am facing segmentation fault when trying to push elements into a vector<vector int>. Can anyone help me with this problem?
 vector<vector<int> > Solution::prettyPrint(int A)
    {
        vector<vector<int>> arr;

        for(int x=1;x<(2*A);x++)
        {
            for(int y=1;y<(2*A);y++)
            {
                int xp=x,yp=y;
                if(x>A) xp=2*A-x;
                if(y>A) yp=2*A-y;

                int min=(xp<yp)?xp:yp;

                arr[x-1].push_back(A+1-min);
            }
        }

        return arr;
    }

A: arr[x-1].push_back(A+1-min);

You are trying to access arr[x-1], but arr is an empty vector at that moment.
Since you know that arr is going to be of size 2*A-1 (at least that is what comes out from your code), you can put a
arr.resize(2*A-1); before the beginning of the outer loop, or directly when declaring it:
vector<vector<int> > arr(2*A-1);
You can go further and initialize even the inner vectors:
    for(int x=1;x<(2*A);x++)
    {
        arr[x-1].resize(2*A-1);
        for(int y=1;y<(2*A);y++)

and substitute
arr[x-1].push_back(A+1-min);
with
arr[x-1][y-1]=(A+1-min);

A: You need to do (assuming your matrix is of size ROWS x COLS)
vector<vector<int>> arr(ROWS, vector<int>(COLS));

and there is no more need for push_back anymore. The whole memory for the 2D array is now reserved so you can just use arr[i][j] to write into it. The code is also a bit faster than using push_back, since push_back does slow re-allocations when it needs to resize the vector.
However try avoiding such nested vectors as they are slow. Use a flat vector instead and map from 2D to 1D and vice versa.

A: That's right don't go in complex structures save your time and energy and make your project faster. Take a 2D array instead of push_back use arr[i][j]


text:
Q: mysql query select just last record by time I have table like this:
table exchaneRate
╔════╦══════════╦══════════════╦═════╦══════╦══════════════════╗
║ id ║ officeID ║ currencyCode ║ buy ║ sell ║ startDateTime    ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 01 ║  off_1   ║       AA     ║  65 ║  75  ║ 2015═10═01 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 02 ║  off_1   ║       BB     ║  64 ║  73  ║ 2015═10═01 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 03 ║  off_1   ║       AA     ║  55 ║  65  ║ 2015═09═25 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 04 ║  off_1   ║       BB     ║  54 ║  63  ║ 2015═09═25 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 05 ║  off_1   ║       AA     ║  30 ║  42  ║ 2015═09═15 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 06 ║  off_1   ║       BB     ║  40 ║  48  ║ 2015═09═15 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 07 ║  off_2   ║       AA     ║  65 ║  75  ║ 2015═10═01 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 08 ║  off_2   ║       BB     ║  65 ║  75  ║ 2015═10═01 12:00 ║
╚════╩══════════╩══════════════╩═════╩══════╩══════════════════╝

And I have request like this to select data:
    select `currencyCode`, `buy`, `sell` from `exchangeRate`
where `officeID` = 'off_1' and startDateTime <= '2015-09-30 00:00';

And I want this result:
╔══════════════╦═════╦══════╗
║ currencyCode ║ buy ║ sell ║
╠══════════════╬═════╬══════╣
║       AA     ║  55 ║  65  ║
╠══════════════╬═════╬══════╣
║       BB     ║  54 ║  63  ║
╚══════════════╩═════╩══════╝

But request returns all record AA, BB, AA, BB, AA, BB... from table. But I need just last records for each currencyCode for this officeID.
How can I do that?

A: try like this
select `currencyCode`, `buy`, `sell` from `exchangeRate`
where id in
( select max(id) from exchangeRate
   where `officeID` = 'off_1' and startDateTime <= '2015-09-30 00:00' group by currencyCode
)

SQLFIDDLE

A: I would go with the following approach.  The inner query determines the records you want for each currencyCode using your time range.  The original exchangeRate table is then filtered on this inner query through an INNER JOIN to give the output you want.
SELECT t1.currencyCode, t1.buy, t1.sell
FROM exchangeRate t1 INNER JOIN
(
    SELECT currencyCode, MAX(startDateTime) AS maxTime
    FROM exchangeRate
    WHERE startDateTime <= '2015-09-30 00:00' AND officeID = 'off_1'
    GROUP BY currencyCode
) t2
ON t1.currencyCode = t2.currencyCode AND t1.startDateTime = t2.maxTime

Click below for a running demo.
SQLFiddle

A: Try like this
SELECT currencyCode,
 SUBSTRING_INDEX(GROUP_CONCAT(buy ORDER BY startDateTime DESC),',',1) as buy_1,
 SUBSTRING_INDEX(GROUP_CONCAT(sell ORDER BY startDateTime DESC),',',1) as sell_1,
 SUBSTRING_INDEX(GROUP_CONCAT(startDateTime ORDER BY startDateTime DESC),',',1) as date_1
FROM exchangeRate
WHERE officeID = 'off_1'
GROUP BY currencyCode
HAVING date_1 <= '2015-09-30 00:00'
ORDER BY currencyCode


text:
Q: Unable to promote a site on the Sites page I am the Global Admin for our SharePoint tenant. However, I am not able to promote a site on the Sites page. I have read this article, though lack the "Manage the promoted sites below" link that it displays.
Here is a screen shot of what the Global Admin actually sees on our Sites page. Note that there is not a "Manage the promoted sites below" link.

Here is a screen shot of what the documentation says the Global Admin should see.

A: From this blog post, we found another way to promote a site.

*

*portal.office.com/admin > ADMIN > SharePoint

*user profiles

*Manage promoted sites


text:
Q: Threading for sending continuous values to server I am using this tutorial . I have added the following code to send my value to server continuously but its not working  . Thanks
 public class MyService extends Service {
    private static final String TAG = "MyService";
    protected static Boolean c = true;
    ServicesDemo sd = new ServicesDemo();

    private Timer timer = new Timer();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
        startservice();
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");

    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
         c=true;

                }

private void startservice() {

    timer.scheduleAtFixedRate( new TimerTask() {

    public void run() {

         try {

             String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
             data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

             //Toast.makeText(MyService.this, "Latitude is = "+la+"Longitude is = "+longi, Toast.LENGTH_SHORT).show();
             URL url = new URL("http://mediasense4.appspot.com/add.jsp?lat="+(int) (Math.random() * 45)+"&longi="+(int) (Math.random() * 45)+"&personid="+2+"&status="+3+"&name="+5+"");

             //URL url = new URL("http://mediasense4.appspot.com/add.jsp?lat="+241+"&longi="+654+"");

                    URLConnection conn = url.openConnection();
                    conn.setDoOutput(true);
                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.write(data);
                    wr.flush();
                    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                                        String line = null;
                                        String response = "";
                                        while ((line = rd.readLine()) != null) {
                                           response += line;

                                        }

                                        wr.close();
                                        rd.close();

                            }
                            catch (Exception e) {
                                //e.printStackTrace();
                            }

    }

    }, 0, 5000);

    ; }}

when i click on start button the logcat appears with the following errors
05-24 21:18:56.347: DEBUG/dalvikvm(5070): GC freed 8615 objects / 520600 bytes in 87ms
05-24 21:18:56.487: DEBUG/dalvikvm(491): GC freed 267 objects / 13280 bytes in 107ms
05-24 21:18:56.927: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=10&longi=34&personid=2&status=3&name=5
05-24 21:18:56.927: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:18:56.927: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:18:56.937: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:18:57.597: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=39&longi=16&personid=2&status=3&name=5
05-24 21:18:57.597: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:18:57.597: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:18:57.597: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:18:58.557: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=3&longi=18&personid=2&status=3&name=5
05-24 21:18:58.557: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:18:58.557: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:18:58.557: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:18:59.577: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=15&longi=38&personid=2&status=3&name=5
05-24 21:18:59.587: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:18:59.587: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:18:59.587: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:00.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=8&longi=17&personid=2&status=3&name=5
05-24 21:19:00.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:00.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:00.567: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:01.577: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=40&longi=36&personid=2&status=3&name=5
05-24 21:19:01.577: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:01.577: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:01.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:02.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=32&longi=4&personid=2&status=3&name=5
05-24 21:19:02.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:02.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:02.567: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:03.677: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=18&longi=36&personid=2&status=3&name=5
05-24 21:19:03.687: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:03.687: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:03.687: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:04.827: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=18&longi=4&personid=2&status=3&name=5
05-24 21:19:04.827: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:04.837: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:04.837: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:05.287: DEBUG/dalvikvm(475): GC freed 101 objects / 5376 bytes in 159ms
05-24 21:19:05.597: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=44&longi=44&personid=2&status=3&name=5
05-24 21:19:05.597: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:05.597: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:05.597: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:06.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=23&longi=44&personid=2&status=3&name=5
05-24 21:19:06.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:06.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:06.567: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:07.577: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=2&longi=16&personid=2&status=3&name=5
05-24 21:19:07.577: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:07.587: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:07.587: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:08.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=1&longi=3&personid=2&status=3&name=5
05-24 21:19:08.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:08.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:08.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:09.577: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=5&longi=31&personid=2&status=3&name=5
05-24 21:19:09.577: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:09.577: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:09.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:10.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=39&longi=10&personid=2&status=3&name=5
05-24 21:19:10.577: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:10.577: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:10.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:11.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=37&longi=23&personid=2&status=3&name=5
05-24 21:19:11.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:11.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:11.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:12.407: DEBUG/dalvikvm(5070): GC freed 8568 objects / 514384 bytes in 91ms
05-24 21:19:12.667: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=36&longi=29&personid=2&status=3&name=5
05-24 21:19:12.667: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:12.667: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:12.667: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:13.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=23&longi=6&personid=2&status=3&name=5
05-24 21:19:13.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:13.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:13.567: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:14.637: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=37&longi=31&personid=2&status=3&name=5
05-24 21:19:14.637: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:14.637: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:14.637: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:15.577: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=7&longi=19&personid=2&status=3&name=5
05-24 21:19:15.577: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:15.577: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:15.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:16.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=10&longi=2&personid=2&status=3&name=5
05-24 21:19:16.577: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:16.577: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:16.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:17.557: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=39&longi=4&personid=2&status=3&name=5
05-24 21:19:17.557: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:17.557: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:17.557: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:18.557: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=2&longi=15&personid=2&status=3&name=5
05-24 21:19:18.557: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:18.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:18.567: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:19.577: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=22&longi=33&personid=2&status=3&name=5
05-24 21:19:19.577: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:19.577: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:19.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:20.557: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=22&longi=37&personid=2&status=3&name=5
05-24 21:19:20.557: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:20.557: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:20.557: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:21.657: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=3&longi=8&personid=2&status=3&name=5
05-24 21:19:21.657: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:21.657: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:21.657: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:22.577: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=0&longi=13&personid=2&status=3&name=5
05-24 21:19:22.577: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:22.577: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:22.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:23.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=4&longi=22&personid=2&status=3&name=5
05-24 21:19:23.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:23.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:23.577: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:24.587: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=34&longi=12&personid=2&status=3&name=5
05-24 21:19:24.587: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:24.587: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:24.587: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:25.597: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=28&longi=18&personid=2&status=3&name=5
05-24 21:19:25.597: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:25.597: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:25.597: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:26.557: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=7&longi=2&personid=2&status=3&name=5
05-24 21:19:26.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:26.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:26.567: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:27.567: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=6&longi=12&personid=2&status=3&name=5
05-24 21:19:27.567: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:27.567: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:27.567: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:28.777: DEBUG/dalvikvm(5070): GC freed 8824 objects / 524672 bytes in 90ms
05-24 21:19:28.787: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=38&longi=33&personid=2&status=3&name=5
05-24 21:19:28.797: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:28.797: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:28.797: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:29.717: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=39&longi=30&personid=2&status=3&name=5
05-24 21:19:29.717: WARN/System.err(5070):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)
05-24 21:19:29.717: WARN/System.err(5070):     at com.example.MyService$1.run(MyService.java:82)
05-24 21:19:29.717: WARN/System.err(5070):     at java.util.Timer$TimerImpl.run(Timer.java:290)
05-24 21:19:30.577: WARN/System.err(5070): java.io.FileNotFoundException: http://mediasense4.appspot.com/add.jsp?lat=4&longi=4&personid=2&status=3&name=5

A: It is not good to start a Service with infinite loop with sleep there to schedule a recurring task. As the service (by default) is started on UI-thread this behaviour can lead to poor UI responsiveness. It is better to consider one the following scenarios:

*

*You can try to use Timer.scheduleAtFixedRate.

*You can use a ScheduledThreadPoolExecutor.scheduleAtFixedRate or ScheduledThreadPoolExecutor.scheduleWithFixedDelay

*You can create your own Thread with Looper to implement an infinite Thread with message queue, bind Handler to it and then uset it to postDelayed
IMO the second one is most preferable.

A: From your code, you are invoking the write only once hence only one request will be made. And even if you are doing one network operation in the service it is advisable to use a thread. The onStart method runs on the main thread and if the network operation takes long, an Application Not Responding (ANR) error will be thrown.
Take a look at this blog for threading concepts.

A: The URL you're calling returns 500 Server Error when I call it by hand.  It seems like your problem could be at the server end?


text:
Q: Creating a Pandas DataFrame conditional on another DataFrame I have two DataFrames. The first, df1, has historical time series data for a variety of tickers with a DateTime index that looks like this:
                       ABC              DEF            XYZ
 2011-06-06            10.00            10.00          10.0000
 2011-06-17            10.00            10.00          10.0000
 2011-06-21            10.00            10.00          10.0000
 2011-06-22            10.00            10.00          10.0000
 2011-06-23            10.00            10.00          10.0000
 2011-06-24            10.00            10.00          10.0000
 2011-06-30            10.00            10.00          10.0000
 2011-07-11            10.00            10.00          10.0000

The second, df2, has three columns; a Start_Date, End_Date, and Ticker. Both the Start_Date and End_Date are in datetime format:
    End_Date Start_Date  Ticker
0 2011-06-27 2011-06-22  ABC
1 2011-06-30 2011-06-17  DEF
2 2011-06-25 2011-06-18  XYZ

I want to create a third DataFrame, df3, using the following code
df4 = df.copy()
df4.lock[:] = np.nan

Between df2['Start_Date'] and df2['End_Date'] I want to populate df3 rows with 1.00 and leave the other rows as np.nan.
I've tried to create a function and also to iterate over df2.
def pos():
    position = 1
    for i in df2['Ticker']:
        df3.at[df2['Start_Date'], i] = position
    return pos

or
def pos():
    position = 1
    for index, row in df2.iterrows:
        df3.at[index, row['Start_Date']] = position
    return pos

The resulting df3 would look like this:
                        ABC              DEF              XYZ
2011-06-06              NaN              NaN              NaN
2011-06-17              NaN              1.0              NaN
2011-06-21              NaN              1.0              1.0
2011-06-22              1.0              1.0              1.0
2011-06-23              1.0              1.0              1.0
2011-06-24              1.0              1.0              1.0
2011-06-30              NaN              1.0              NaN
2011-07-11              NaN              NaN              NaN
2011-07-13              NaN              NaN              NaN
2011-07-14              NaN              NaN              NaN

I am not having much luck with either. What is the best way to do this?
Thanks in advance

A: IIUC:
d2 = df2.set_index('Ticker')
df3 = df1.copy()
for tick, col in df3.iteritems():
    d2 = df2.set_index('Ticker')
    sd = d2.at[tick, 'Start_Date']
    ed = d2.at[tick, 'End_Date']
    df3.loc[sd:ed, tick] = 1

df3

             ABC   DEF   XYZ
2011-06-06  10.0  10.0  10.0
2011-06-17  10.0   1.0  10.0
2011-06-21  10.0   1.0   1.0
2011-06-22   1.0   1.0   1.0
2011-06-23   1.0   1.0   1.0
2011-06-24   1.0   1.0   1.0
2011-06-30  10.0   1.0  10.0
2011-07-11  10.0  10.0  10.0


text:
Q: object does not contain a definition for 'Skip' Umbraco razor I'm trying to sort some nodes by their first letter, and page them in razor.(Umbraco). But get a "object does not contain a definition for 'Skip'" error when it hits the foreach.
pagesToList = homeNode.Children.OrderBy("Name");

IEnumerable<DynamicNode> nl = @homeNode.Children.Items;
pagesToList = nl.Where(x => x.Name.StartsWith(currentLetter));

This is what @pagesToList outputs:
System.Linq.Enumerable+WhereListIterator`1[umbraco.MacroEngines.DynamicNode]

foreach(dynamic item in pagesToList.Skip(1){

}

A: You are possibly using the wrong property. If you are only after those nodes just below your homeNode, then don't use the Items property. Also, try not to cast your objects. C# has an effective var object. Assuming that homeNode is a DynamicNode, then it might be worth trying the following:

pagesToList = homeNode.Children.OrderBy("Name").Where(x => x.Name.StartsWith(currentLetter));

Then your code should work. Please note that again we are using var because we want the object declared at compile-time, instead of using dynamic, we should only really do when we are accessing some unknown, or dynamic, properties the pagesToList object):

foreach(var item in pagesToList.Skip(1)){

}

So to summarise, it looks like your code was using the property "Items", which gave us an array of DynamicNode[] instead of an IEnumerable object.
I hope this helps you out. Good luck!


text:
Q: Complex conjugate of an involved expression I understand the the complex conjugate of, say, $z:=\exp({a+ib})$ is $z:=\exp({a-ib})$.
However , I have a composite expression  and I'm not sure how to attack taking it's complex conjugate.
Say $z:=i\exp({ib}) / ({a + ic})$
I would be tempted to say that the denominator becomes ${a - ic}$, that the denominator changes signs & the exponential as well, so:
$z*:=-i\exp({-ib}) / ({a - ic})$
I'm asking because I need to compute the norm of a complex expression (which structurally is similar to this exemple) and I feel I'm about to embark on a rather lengthy derivation, based in part on the computation of that norm... hence would like to know if my understanding of the complex conjugate is accurate in a more involved case.
Thanks
EDIT: wrt to comment: a, b, and c are real (e.g. I have explicited any imaginary part)

A: If $z=e^{a+ib}$ then $z=e^a(\cos b+i\sin b)$, so $\bar z=e^a(\cos b-i\sin b)$ and then $\bar z=e^{a-ib}$.

A: The things you state are true, and here are some basic facts about complex conjugates and norms, some of which you have used:$$ (zw)^* = z^*w^* \:\text{and}\: \left(\dfrac{z}{w}\right)^* = \frac{z^*}{w^*}$$
also
$$ |zw| = |z|\cdot |w| \:\text{and}\: \left| \dfrac{z}{w} \right| = \dfrac{|z|}{|w|}$$
(for any complex $z$ and $w$).
Normally these are proved (or merely stated) immediately after conjugates and norms are introduced. Unless you're just starting with complex numbers it's probably okay for you to use them.

A: In general, if $f$ has a power series with real coefficients then $\overline{f(z)} = f( \overline{z})$. Hence $\overline{e^z} = e^\overline{z}$.
Since $\overline{wz} = \overline{w} \ \overline{z}$ and $\overline{\left( w \over z \right)}  = {\overline{w} \over \overline{z}}$, we have
$\overline{ \left ( {i \over a+ic} e^{ib}\right ) } = \overline{ \left ( {i \over a+ic} \right ) }\  \overline{ \left ( e^{ib}\right ) } = \left ( {\overline{i} \over \overline{a+ic}} \right ) e^{-ib}= {-i \over a-ic}e^{-ib}$.


text:
Q: Flutter / Dart / Firebase - Stream returning empty list I'm having an issue return a Stream to a StreamBuilder widget in flutter. I'm trying to access a custom class that is stored as a list in my users collection in firebase, but for some reason it continues to return an empty list.
Here is an example of my PhotoEntry custom class:
class PhotoEntry {
  final Timestamp date;
  final String fileUrl;

  PhotoEntry({
    @required this.date,
    @required this.fileUrl,
  });

  Map<String, dynamic> toMap() => {
        'date': date.millisecondsSinceEpoch,
        'fileUrl': fileUrl,
      };

  PhotoEntry.fromMap(Map<String, dynamic> data)
      : date = new Timestamp.fromMillisecondsSinceEpoch(data['date']),
        fileUrl = data['fileUrl'];

  PhotoEntry.initial()
      : date = Timestamp.now(),
        fileUrl = 'No Photo';
}

And here is the Stream that is giving me troubles. As I stated, it is returning an empty list:
Stream<List<PhotoEntry>> getUserPhotosStream(User user) {
    if (user == null) {
      return Stream.empty();
    }
    try {
      return _db
          .collection('users')
          .document(user.uid)
          .collection('photos')
          .snapshots()
          .map((list) => list.documents
              .map((doc) => PhotoEntry.fromMap(doc.data))
              .toList());
    } catch (e) {
      print(e);
      rethrow;
    }
  }

And getUserPhotosStream is used here:
  Widget _galleryPage() {
    return StreamBuilder<List<PhotoEntry>>(
      stream: _db.getUserPhotosStream(_user),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting ||
            !snapshot.hasData) {
          return Container(child: Center(child: CircularProgressIndicator()));
        } else {
          return ListView.builder(
            scrollDirection: Axis.horizontal,
            physics: BouncingScrollPhysics(),
            itemCount: _user.photos.length,
            itemBuilder: (context, index) {
              var photo = snapshot; // For debugging
              print(photo); // For dubigging

              // return Card(photo)
            },
          );
        }
      },
    );
  }

I've verified the collection and document titles are correct, and the User being passed in is not null and contains all the correct data. What am I doing wrong here?

A: I have come through a similar situation, not sure if this is exactly your case , but my answer could help people facing the empty list problem. In my case, there is a users collection inside of it there's a doctors collection which holds their messages collection.
my messages collection
I added a doctor object manually through the firebase dashboard as a field, therefore firebase wasn't able to access it a collection , and was always returning empty list. the following image may help understand better:
the right way to add dummy data


text:
Q: how can we find the nth 3 word combination from a word corpus of 3000 words I have a word corpus of say 3000 words such as [hello, who, this ..].
I want to find the nth 3 word combination from this corpus.I am fine with any order as long as the algorithm gives consistent output.
What would be the time complexity of the algorithm.
I have seen this answer but was looking for something simple.

A: (Note that I will be using 1-based indexes and ranks throughout this answer.)
To generate all combinations of 3 elements from a list of n elements, we'd take all elements from 1 to n-2 as the first element, then for each of these we'd take all elements after the first element up to n-1 as the second element, then for each of these we'd take all elements after the second element up to n as the third element. This gives us a fixed order, and a direct relation between the rank and a specific combination.
If we take element i as the first element, there are (n-i choose 2) possibilities for the second and third element, and thus (n-i choose 2) combinations with i as the first element. If we then take element j as the second element, there are (n-j choose 1) = n-j possibilities for the third element, and thus n-j combinations with i and j as the first two elements.
Linear search in tables of binomial coefficients
With tables of these binomial coefficients, we can quickly find a specific combination, given its rank. Let's look at a simplified example with a list of 10 elements; these are the number of combinations with element i as the first element:
i

1    C(9,2) = 36
2    C(8,2) = 28
3    C(7,2) = 21
4    C(6,2) = 15
5    C(5,2) = 10
6    C(4,2) =  6
7    C(3,2) =  3
8    C(2,2) =  1
             ---
             120 = C(10,3)

And these are the number of combinations with element j as the second element:
j

2    C(8,1) =  8
3    C(7,1) =  7
4    C(6,1) =  6
5    C(5,1) =  5
6    C(4,1) =  4
7    C(3,1) =  3
8    C(2,1) =  2
9    C(1,1) =  1

So if we're looking for the combination with e.g. rank 96, we look at the number of combinations for each choice of first element i, until we find which group of combinations the combination ranked 96 is in:
i

1    36    96 > 36    96 - 36 = 60
2    28    60 > 28    60 - 28 = 32
3    21    32 > 21    32 - 21 = 11
4    15    11 <= 15

So we know that the first element i is 4, and that within the 15 combinations with i=4, we're looking for the eleventh combination. Now we look at the number of combinations for each choice of second element j, starting after 4:
j

5     5    11 > 5    11 - 5 = 6
6     4     6 > 4     6 - 4 = 2
7     3     2 <= 3

So we know that the second element j is 7, and that the third element is the second combination with j=7, which is k=9. So the combination with rank 96 contains the elements 4, 7 and 9.

Binary search in tables of running total of binomial coefficients
Instead of creating a table of the binomial coefficients and then performing a linear search, it is of course more efficient to create a table of the running total of the binomial coefficient, and then perform a binary search on it. This will improve the time complexity from O(N) to O(logN); in the case of N=3000, the two look-ups can be done in log2(3000) = 12 steps.
So we'd store:
i

1     36
2     64
3     85
4    100
5    110
6    116
7    119
8    120

and:
j

2     8
3    15
4    21
5    26
6    30
7    33
8    35
9    36

Note that when finding j in the second table, you have to subtract the sum corresponding with i from the sums. Let's walk through the example of rank 96 and combination [4,7,9] again; we find the first value that is greater than or equal to the rank:
3     85    96 > 85
4    100    96 <= 100

So we know that i=4; we then subtract the previous sum next to i-1, to get:
96 - 85 = 11

Now we look at the table for j, but we start after j=4, and subtract the sum corresponding to 4, which is 21, from the sums. then again, we find the first value that is greater than or equal to the rank we're looking for (which is now 11):
6    30 - 21 =  9    11 > 9
7    33 - 21 = 12    11 <= 12

So we know that j=7; we subtract the previous sum corresponding to j-1, to get:
11 - 9 = 2

So we know that the second element j is 7, and that the third element is the second combination with j=7, which is k=9. So the combination with rank 96 contains the elements 4, 7 and 9.

Hard-coding the look-up tables
It is of course unnecessary to generate these look-up tables again every time we want to perform a look-up. We only need to generate them once, and then hard-code them into the rank-to-combination algorithm; this should take only 2998 * 64-bit + 2998 * 32-bit = 35kB of space, and make the algorithm incredibly fast.

Inverse algorithm
The inverse algorithm, to find the rank given a combination of elements [i,j,k] then means:

*

*Finding the index of the elements in the list; if the list is sorted (e.g. words sorted alphabetically) this can be done with a binary search in O(logN).

*Find the sum in the table for i that corresponds with i-1.

*Add to that the sum in the table for j that corresponds with j-1, minus the sum that corresponds with i.

*Add to that k-j.
Let's look again at the same example with the combination of elements [4,7,9]:
i=4 -> table_i[3] = 85
j=7 -> table_j[6] - table_j[4] = 30 - 21 = 9
k=9 -> k-j = 2
rank = 85 + 9 + 2 = 96

Look-up tables for N=3000
This snippet generates the look-up table with the running total of the binomial coefficients for i = 1 to 2998:

function C(n, k) { // binomial coefficient (Pascal's triangle)
    if (k < 0 || k > n) return 0;
    if (k > n - k) k = n - k;
    if (! C.t) C.t = [[1]];
    while (C.t.length <= n) {
        C.t.push([1]);
        var l = C.t.length - 1;
        for (var i = 1; i < l / 2; i++)
            C.t[l].push(C.t[l - 1][i - 1] + C.t[l - 1][i]);
        if (l % 2 == 0)
            C.t[l].push(2 * C.t[l - 1][(l - 2) / 2]);
    }
    return C.t[n][k];
}

for (var total = 0, x = 2999; x > 1; x--) {
    total += C(x, 2);
    document.write(total + ", ");
}

This snippet generates the look-up table with the running total of the binomial coefficients for j = 2 to 2999:

for (var total = 0, x = 2998; x > 0; x--) {
    total += x;
    document.write(total + ", ");
}

Code example
Here's a quick code example, unfortunately without the full hardcoded look-up tables, because of the size restriction on answers on SO. Run the snippets above and paste the results into the arrays iTable and jTable (after the leading zeros) to get the faster version with hard-coded look-up tables.

function combinationToRank(i, j, k) {
    return iTable[i - 1] + jTable[j - 1] - jTable[i] + k - j;
}
function rankToCombination(rank) {
    var i = binarySearch(iTable, rank, 1);
    rank -= iTable[i - 1];
    rank += jTable[i];
    var j = binarySearch(jTable, rank, i + 1);
    rank -= jTable[j - 1];
    var k = j + rank;
    return [i, j, k];

    function binarySearch(array, value, first) {
        var last = array.length - 1;
        while (first < last - 1) {
            var middle = Math.floor((last + first) / 2);
            if (value > array[middle]) first = middle;
            else last = middle;
        }
        return (value <= array[first]) ? first : last;
    }
}
var iTable = [0];    // append look-up table values here
var jTable = [0, 0]; // and here

// remove this part when using hard-coded look-up tables
function C(n,k){if(k<0||k>n)return 0;if(k>n-k)k=n-k;if(!C.t)C.t=[[1]];while(C.t.length<=n){C.t.push([1]);var l=C.t.length-1;for(var i=1;i<l/2;i++)C.t[l].push(C.t[l-1][i-1]+C.t[l-1][i]);if(l%2==0)C.t[l].push(2*C.t[l-1][(l-2)/2])}return C.t[n][k]}
for (var iTotal = 0, jTotal = 0, x = 2999; x > 1; x--) {
    iTable.push(iTotal += C(x, 2));
    jTable.push(jTotal += x - 1);
}

document.write(combinationToRank(500, 1500, 2500) + "
");
document.write(rankToCombination(1893333750) + "
");


text:
Q: Why does Java only read the second line of input? The problem with my code is this: I type my input into the first line in the console but it does not read it until I type anything and enter it into line 2.
For example: I type "Jayden" as a name, push enter, and nothing happens. I then type (insert any letters here) and then it prints "Your name is over 3 letters and starts with the letter J!".
Any ideas?
import java.util.*;
public class random {

    public static void main(String[] args) {
    // TODO Auto-generated method stub

        try (Scanner number = new Scanner(System.in)) {
            if (number.nextLine().startsWith("J") && number.nextLine().length() > 3 )
            {
                System.out.println("Your name is over 3 letters and starts with the letter J!");
            }

            else if  (number.nextLine().length() < 3)
            {
                System.out.println("Your name is too short!");
            }

            else if (number.nextLine().length() > 10)
            {
                System.out.println("Your name is too long!");
            }
        }
    }
}

A: The problem is that (as Elliot Frisch commented) every time you call nextLine() you consume the line, so  in your initial if statement
if (number.nextLine().startsWith("J") && // this nextLine reads an input line
    number.nextLine().length() > 3 )     // this nextLine reads a SECOND line

You want to read only one line, so call nextLine only once and save it in a variable.
Just add this to after the beginning of the try-block (declaring a variable):
String numberString = number.nextLine()

and then substitute the number.nextLine() with the variable in your conditions!

A: Store your user input into a variable, in my example, I've created a variable called String userInput = number.nextLine();
Then carry out your validation on the variable.
Example 1:
public static void main(String[] args) {

    Scanner number = new Scanner(System.in);
    System.out.print("Enter something : ");
    String userInput = number.nextLine();

    if (userInput.startsWith("J") && userInput.length() > 3) {

        System.out.println("Your name is over 3 letters and starts with the letter J!");

    } else if (userInput.length() < 3) {
        System.out.println("Your name is too short!");

    } else if (userInput.length() > 10) {
        System.out.println("Your name is too long!");

    }

}


text:
Q: Can only retrieve ID from Firebase database I am using NativeScript and the Firebase plugin so that I can retrieve inputted data by the unique ID. My problem is that I am only getting back the ID and not the data that's inside the ID. This is how the data is structured in Firebase: https://i.imgur.com/Jehig5r.png
The underlined is the ID of each log.
This is the code for when the item is tapped on, taking it to the edit page:
viewDetail(id: string){

    this.router.navigate(["./calendar-detail", id],
    {
        relativeTo: this.activatedRoute
    });
}

The edit component:
 private sub: any;
 public log: Observable<any>;

ngOnInit(){
this.sub = this.route.params.subscribe((params: any) => {
      this.id = params['id'];
      this.firebaseService.getMyLog(this.id).subscribe((log) => {
        this.ngZone.run(() => {
          for (let prop in log) {
            //props
            if (prop === "id") {
              this.id = log[prop];
            }
            if (prop === "mood") {
              this.mood = log[prop];
            }
            if (prop === "activity") {
              this.activity = log[prop];
            }
            if (prop === "other") {
              this.other = log[prop];
            }
          }
        });
      });
    });

This is the Firebase service that should be getting the log data from the ID:
 getMyLog(id: string): Observable<any> {
    return new Observable((observer: any) => {
      observer.next(this._allItems.filter(s => s.id === id)[0]);
    }).share();
  }

On the edit html page from this code, it shows the ID but not the "mood":

I'm still getting used to Nativescript and Angular so i'm not too sure if i'm making a silly mistake, any help would be greatly appreciated!
EDIT: This is how I am retrieving the list of "logs":
getLogList(): Observable<any> {
    return new Observable((observer: any) => {
      let path = 'Logs';

        let onValueEvent = (snapshot: any) => {
          this.ngZone.run(() => {
            let results = this.handleSnapshot(snapshot.value);
            console.log(JSON.stringify(results))
             observer.next(results);
          });
        };
        firebase.addValueEventListener(onValueEvent, `/${path}`);
    }).share();
  }


text:
Q: Why does sizeof return a value that is not the real size of the struct I have the following struct
struct vertice_t{
    char city;
    char connectedBy;
    unsigned short airportCost;
    unsigned short primKey;
    int queueIndex;
    struct adjacency_list_t * adjacencyList;
};

struct adjacency_list_t{
    struct adjacency_list_node_t *  first;
    struct adjacency_list_node_t *  last;
};

struct adjacency_list_node_t{
    unsigned short weight;
    struct vertice_t *  vertice;
    struct adjacency_list_node_t * next;
};

When I do sizeof(struct vertice_t) I get the value 24. But I can see by myself that this struct only takes 1 + 1 + 2 + 2 + 4 + 8 = 18Bytes
Why does this happen? Is there anyway I could compress the data in the struct above to make it smaller? This is for a project and I need to reduce the whole memory usage by 30%.
Thanks!


text:
Q: Discord.js v12 code breaks when upgrading to v13 When updating my discord.js to v13 there are many errors I get:
//member.hasPermission is not a function
member.hasPermission("SEND_MESSAGES")

//Cannot send an empty message
channel.send(someEmbed)

//Cannot send an empty message
channel.send({embed: someEmbed})

//Warning: The 'message' event was deprecated, use 'messageCreate' instead
client.on("message", msg => {})

//Cannot send an empty message
channel.send(user)

//[CLIENT_MISSING_INTENTS] Valid intents must be provided for the client
const client = new Client()

//channel.join is not a function
await channel.join()

These don't happen in v12, so how do I fix them in v13?

A: Discord.js v13 has a lot of changes, and those are only a few. Before updating to v13, you should change the following things
//member.hasPermission("SEND_MESSAGES")
member.permissions.has("SEND_MESSAGES")

//channel.send(someEmbed) / channel.send({embed: someEmbed})
channel.send({ embeds: [someEmbed] }) //make sure it's an array!

//client.on("message", msg => {})
client.on("messageCreate", msg => {})

//channel.send(user)
channel.send(user.toString())

//const client = new Client()
const { Intents, Client } = require("discord.js")
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]}) //more intents may be provided

//await channel.join()
const { joinVoiceChannel } = require("@discordjs/voice") //requires installation
joinVoiceChannel({
  channelId: channel.id,
  guildId: guild.id,
  adapterCreator: guild.voiceAdapterCreator
})

There are some more changes. You can see them in the guide


text:
Q: Append xml string into Existing xmlfile using c# I have an xml like this :
<name>

<class>

</class>

</name>

then i want to add the tag like this
<tia:Demographic><Age/><DOB/></tia:Demographic>

in between
<class>

How can we do that .
i am using following code.
XDoc.LoadXml(@"<name><class></class></name>");
XmlDocumentFragment xfrag = XDoc.CreateDocumentFragment();
 xfrag.InnerXml = @"<tia:Demographic><Age/><DOB/></tia:Demographic>";
 XDoc.DocumentElement.FirstChild.AppendChild(xfrag);
XDoc.Save(@"D:\test.xml");

but it throws an error that tia: not a registered namespace

A: Register the namespace using a XmlNamespaceManager .

A: You will need to register a namespace:
class Program
{
    static void Main()
    {
        var xdoc = new XmlDocument();
        xdoc.LoadXml(@"<name><class></class></name>");
        xdoc.DocumentElement.SetAttribute("xmlns:tia", "http://tia.com");
        var node = xdoc.CreateElement("tia", "Demographic", "http://tia.com");
        var xfrag = xdoc.CreateDocumentFragment();
        xfrag.InnerXml = @"<Age/><DOB/>";
        node.AppendChild(xfrag);
        xdoc.DocumentElement.FirstChild.AppendChild(node);
        xdoc.Save(Console.Out);
    }
}


text:
Q: Can Fused heal with Voidlight? Book three in The Stormlight Archives introduces new creatures called Fused, who can use Voidlight (the opposite of Stormlight) to accomplish similar things as one using Stormlight might do - like Lashings etc. Presumably Fused should be able to use this Voidlight to heal just like Kaladin can do.
My question is, when Moash killed one of the Fused, (who later comes back to life) by stabbing it with a dagger - which is not even close to a Shardblade wound, it should have been very easy for it to heal using Voidlight?

A: They can heal mortal wounds but not Shardblade wounds. see the Coppermind here. It also seems to work more slowly than Stormlight, being that

Shallan survives an arrow to the head, and Jasnah surives a knife to the chest.
Whereas, Moash kills a fused by stabbing it in the chest.


text:
Q: Why does my AJAX request return empty? WHAT I ALREADY LOOKED AT:
Failed to load resource: net::ERR_EMPTY_RESPONSE http://test.com
Failed to load resource under Chrome
Failed to load resource: net::ERR_EMPTY_RESPONSE when console not opened
Failed to load resource: net::ERR_EMPTY_RESPONSE

ERROR:
Failed to load resource: net::ERR_EMPTY_RESPONSE

CODE:
client
var load = 0;

    $( document ).ready(function() {
        if (load == 0) {
            load++;
            $.ajax({
                type: "POST",
                url: "/1/2",
                data: someData,
            }).done(function(response) {
                console.log("RESPONSE :"+response);
                if (response.charAt(0) == "F") {
                    localStorage.setItem("error_msg_local", response);
                } else if (response.charAt(0) == "L") {
                    localStorage.setItem("success_msg_local",response);
                } else {
                    localStorage.setItem("error_msg_local", "Internal error. Please try again.");
                }
            });
        }
    });

server
The request is sent with POST and will wait for the user to complete a certain action. If the user does nothing, after 120 seconds, "NO" is logged and "F" should be sent as a response.
router.post("/2", function(req, res, next){

        request.post({
            url: 'URL:Port',
            json: {
              JsonData: JsonData,
              timeout: "120000"
            }
        },
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                if (body.status == "success") {
                    //User completed action within 120 seconds, so do stuff
                }
                else {
                    //120 elapsed without user completing action, body.status == "nothing", so execute this:
                    console.log("NO");
                    res.send("F");
                }
            }
            else {
                console.log("ERROR: "+error);
            }
        });
});

QUESTION:
I am intentionally waiting 120 seconds to test my code. Nothing is logged on the client, but "NO" is logged on the server, so I know that res.send("F") should have been sent as a response.
Yet, I received "Failed to load resource: net::ERR_EMPTY_RESPONSE" in my browser console as an error message and nothing happens.
Here is everything that logs out in my terminal (server logs):
POST /1/2 - - ms - -
NO
POST /1/2 - - ms - -
NO

Strangely enough, it seems the request is triggered multiple times although I have called it only once ?
I even added a load counter to make sure it gets called only once, but it seems it gets called twice.
What should I do to only have one AJAX request and actually get the proper response from my server ?

A: The error description has it -- empty response. Your server received and logged the request, but sent nothing in return. It's possible the browser rejected the response such as for CORS, but I would expect a different error message in that case.
Do you have another means to test the URL, such as cUrl? I use Fiddler a bit to monitor and manipulate network traffic, which might be easier. Rule out the server before revisiting the client code.


text:
Q: Function is unhookable by Frida I have the following Java code and I'm trying to hook the getTimeZone function:
package com.myapp.models;

public class User {

    private String timeZone;

    public void setTimeZone(String str) {
        this.timeZone = str;
    }

    public String getTimeZone() {
        return this.timeZone;
    }
}

This is the frida code I'm trying to use:
Java.perform(function () {

    var User = Java.use("com.myapp.models.User");
    User.getTimeZone.implementation = function() {
        console.log("timezone requested")
        return 12;
    };

});

However, the hook does not seem to happen since the app crashes on getTimezone not returning a vlue:
10-21 12:17:23.013 26553 26553 E AndroidRuntime: Process: com.myapp.android, PID: 26553
10-21 12:17:23.013 26553 26553 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.myapp.models.User.getTimeZone()' on a null object reference
10-21 12:17:23.013 26553 26553 E AndroidRuntime:        at com.myapp.features.home.logs.updateChart(Presenter.java:370)
10-21 12:17:23.013 26553 26553 E AndroidRuntime:        at com.myapp.features.home.logs.loadGraph(Presenter.java:217)
10-21 12:17:23.013 26553 26553 E AndroidRuntime:        at com.myapp.features.home.logs.onResume(Fragment.java:313)

I know that there is no typo in the function and it is identified successfully since I ran in frida:
[Redmi Note 7::myapp]-> Java.use("com.myapp.models.User").getTimeZone
function
[Redmi Note 7::myapp]-> Java.use("com.myapp.models.User").getTimeZone.implementation
"0x7e3682a128"

A: Your Frida code has one major problem:
The definition of getTimeZone is String getTimeZone() hence you have to return a String.
But your Frida code return an int value: return 12;
Change it to return "12"; and your Frida code should work.
There may be a second problem in the Android app defining the User class (in one of the method com.myapp.features.home.logs.updateChart you have not included in your question). Based on the exception

java.lang.NullPointerException: Attempt to invoke virtual method java.lang.String com.myapp.models.User.getTimeZone()' on a null object reference

the app seems to call getTimeZone() without constructing an User() instance first. Unless you correct that the Frida hooking code can not work properly.


text:
Q: Is less than 1A enough for TP4056 module to charge one battery? I want to charge 3 separate 18650 cells with one charger. Each one of the batteries has their own TP4056 module. So in total there are 3 TP4056's. I know that TP4056 is rated at 1 amp input, though my USB charger only puts out 2 amps. I want to use USB male to 3 Micro USB splitter, to charge each battery equally, and by doing calculation: 2/3=0.666, each battery only gets 0.666 amps. So is 0.666A enough for TP4056 to charge a 18650 battery?

A: From the TP4056 datasheet:

Programmable Charge Current Up to
  1000mA

That means the TP4056 is able to handle charge currents from 0 to 1A (1000 mA). If you're only able to supply it with 2/3A (~666mA), so be it. All that happens is that it will take longer time to charge the cell/s.
Edit: As pointed out by Bimpelrekkie, you have to make sure that the USB charger you have in mind for this application behaves properly when subjected to this heavy current draw. But still, the answer to your question "is 0.666A enough for TP4056 to charge a 18650 battery?" is Yes, you can charge a 18650 cell using less than 1A of supply current.


text:
Q: how to remove the emails while uncheck the checkbox from text area using javascript , there are multiple emails generated dynamically how to remove the emails while unchecking the checkbox from text area, there are multiple emails generated dynamically i can remove all the emails while unchecking the checkbox except the first one...
here is my code
contactsCheckbox is id of checkboxes
showList is id of teenter code herextarea
var email = "";
    $(document).on('change', "#contactsCheckbox", function () {

        email = "";

        if (this.checked) {

            email = $(this).val().trim() + ";";
            $("#showList").val($("#showList").val() + email);
        }
        else {

            email = this.value;

            var strValAdded = $("#showList").val().toString();

            var rrr = strValAdded.indexOf(email.trim() + ";");

            if (strValAdded.indexOf(email.trim() + ";"))
                strValAdded = strValAdded.replace(email.trim() + ";", "");

            if (strValAdded.indexOf(email.trim()))
                strValAdded = strValAdded.replace(email.trim(), "");

            $("#showList").val(strValAdded);
        }

    });
stringbuilder.Append("
");
                stringbuilder.Append("<input type =\"checkbox\" id=\"contactsCheckbox\" class=\"chk\" value=\"" + data.Email + "\">" + data.Email + "");
                stringbuilder.Append("
");

A: So first, element IDs are supposed to be unique. It is not your issue but it is very bad practice and you should correct that anyway. It will cause you more headaches down the road if you do not learn that now.
Your real issue is that your "if" statements are triggering false when you get to a value with a zero index. It is interpreting the zero index as a boolean value check:
Change:
if (strValAdded.indexOf(email.trim() + ";"))
to
if (strValAdded.indexOf(email.trim() + ";") > -1)
Example attached and I put an alert cmd in there so you can more visibly see what is happening with the 0 index boolean check. I also changed your change trigger to look by class instead of ID because your are going to fix your html to no longer be invalid in the near future...hopefully.

    $(document).on('change', ".chk", function () {
        if (this.checked) {

            email = $(this).val().trim() + ";";
            $("#showList").val($("#showList").val() + email);
        }
        else {

            email = this.value;
            var strValAdded = $("#showList").val().toString();
            var rrr = strValAdded.indexOf(email.trim() + ";");

            alert(Boolean(strValAdded.indexOf(email.trim() + ";")));
            if (strValAdded.indexOf(email.trim() + ";") > -1) {
                strValAdded = strValAdded.replace(email.trim() + ";", "");
            }
            if (strValAdded.indexOf(email.trim()) > -1){
             strValAdded = strValAdded.replace(email.trim(), "");
            }
            $("#showList").val(strValAdded);
        }
    });

<input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever1@wherwever.com"> whatever1@wherwever.com

<input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever2@wherwever.com"> whatever2@wherwever.com

<input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever3@wherwever.com"> whatever3@wherwever.com

<input type="text" name="lname" style="width: 100%"  id="showList" disabled >


text:
Q: How to find out execution time of sqlite query? First thing:
Please read the question details before marking this as a duplicate.
I am using sqlite db with JAVA. Here's what I have already tried:

*

*I have tracked query times using start and end time from within JAVA code. But I want more accurate data.

*I have also tracked time using sqlite browser. But in sqlite browser, total time i.e. time to fetch data + time to plot data comes.

*I have also tried to track time using sqlite command line (.timer ON), but I get comparatively higher time values in all 3 heads: real, user, sys.

I want only the time that it takes to find and fetch data.
How can I find out the fetch time? I have to make a decision based on the actual time values, whether it will be beneficial for us to use sqlite db.
EDIT: How can I debug the query to know which part of query is taking how much time?


text:
Q: How to get access token from Authorisation Server using Apache Camel routes? I have an authorization server [Simple Class annotated with @SpringBootApplication,
@RestController,@Configuration,@EnableAuthorizationServer & oauth2 security] running on port 8081 which works fine & provides the access token when requested from POSTMAN using POST method along with needful parameters in the form of key value pair,
http://localhost:8080/oauth/token, but how should i implement the camel route in java to get the access token by passing parameters in body ?

A: This question is more about sending multipart/form-data with Apache Camel. I was playing with it some time ago and solved it with custom Processor, converting headers to multipart/form-data format with Content-Disposition: form-data.
This is my Processor converting headers to multipart/form-data format:
public class PrepareMultipartFormData implements Processor {
    private String[] multipartHeaders;

    public PrepareMultipartFormData(String... multipartHeaders) {
        this.multipartHeaders = multipartHeaders;
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        addMultipart(exchange.getIn(), multipartHeaders);
    }

    private static void addMultipart(Message message, String... multipartKeys){
        final String boundary = "---------------------------"+RandomStringUtils.randomAlphanumeric(9);
        message.setHeader(Exchange.CONTENT_TYPE, "multipart/form-data;boundary="+boundary);
        StringBuilder sb = new StringBuilder("--").append(boundary);

        for (String key: multipartKeys) {
                    sb.append("\r\n")
                    .append("Content-Disposition: form-data; name=\"").append(key).append("\"")
                    .append("\r\n\r\n")
                    .append(message.getHeader(key, String.class))
                    .append("\r\n")
                    .append("--").append(boundary);
        }
        message.setBody(sb.toString());
    }
}

To OAuth request token you need to send:

*

*HTTP headers

*

*Authorization header - This is part of standard HTTP component specified by endpoint options authUsername and authPassword

*Content-Type - This is added in my PrepareMultipartFormData Processor

*Form data - These are converted from headers in PrepareMultipartFormData Processor

*

*grant_type

*username

*password

*client_id

Final route can be implemented in this way:
(Replace constants with some expressions, to set it dynamically. If you need only token in response, add some unmarshalling, since this route returns JSON)
from("direct:getTokenResponse")
        .setHeader(Exchange.HTTP_METHOD, constant("POST"))
        .setHeader(Exchange.HTTP_PATH, constant("oauth/token"))
        .setHeader("grant_type", constant("password"))
        .setHeader("username", constant("admin"))
        .setHeader("password", constant("admin1234"))
        .setHeader("client_id", constant("spring-security-oauth2-read-write-client"))
        .process(new PrepareMultipartFormData("grant_type", "username", "password", "client_id"))
        .to("http://localhost:8080?authMethod=Basic&authUsername=oauth-endpoint-username&authPassword=oauth-endpoint-password")
        .convertBodyTo(String.class)
        .to("log:response");

Updating answer to provide a bit shorter implementation of PrepareMultipartFormData#addMultipart using MultipartEntityBuilder.
private static void addMultipart(Message message, String... multipartKeys) throws Exception{
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (String key: multipartKeys) {
        builder.addTextBody(key, message.getHeader(key, String.class));
    }
    HttpEntity resultEntity = builder.build();
    message.setHeader(Exchange.CONTENT_TYPE, resultEntity.getContentType().getValue());
    message.setBody(resultEntity.getContent());
}