text:
Q: Why is my enter selection not empty after data updates? I use d3 as part of a react project. At some point I display data (array of javascript objects) as shown below.
When I update the 2D data array I would like to update the position+size of the updated object(s) and conditionally draw the border.
However, I noticed that instead of only updating the svg objects related to the updated data, d3 always updates the first element of my data array and performs the enter operations for all other elements. Eventhough the objects haven't changed. The array reference should also be the same.
Why is that?
let bound = d3
  .select(this.svgRef.current)
  .selectAll(".square")
  .data(this.props.data, d => d);

//enter
bound
  .enter()
  .append("rect")
  .attr("class", "square")
  .attr("id", d => d.id)
  .attr("x", d => {console.log("enter", d); return d.x})
  .attr("y", d => d.y)
  .attr("width", d => d.width)
  .attr("height", d => d.height)
  .style("fill", d => {
    return d.c;
  })
  .style("stroke", d => {
    if (d.id == this.props.focus) {
      return "#FF0000";
    } else {
      return null;
    }
  });

//updates
bound
  .attr("x", d => { return d.x })
  .attr("y", d => d.y)
  .attr("width", d => d.width)
  .attr("height", d => d.height)
  .style("fill", d => {
    return d.c;
  })
  .style("stroke", d => {
    if (d.id == this.props.focus) {
      return "#FF0000";
    } else {
      return null;
    }
  });

bound.exit().remove();

The data has the following format:
[{
  "id":"1.png","c":"#FFFFFF",
  "d":["No Data"],
  "index":0,
  "x":0,
  "y":0,
  "width":115,
  "height":16
}, {
  "id":"2.png",
  "c":"#FFFFFF",
  "d":["Example Data"],
  "index":1,
  "x":115,
  "y":0,
  "width":115,
  "height":16
}, ...]

A: The answer to my problem seems to be an incorrect key function. The identity function doesn't seem to work with arrays of objects.


text:
Q: Boldfacing Plot Legend with words, numbers, and symbols in R I'm wondering how to boldface the entire phrase: "95% CI: [number 1 , number 2 ]" as a legend in my plot below? (Note: "number 1" and "number 2" are specified in my code below).
Here is my R code which requires a fix:
plot(1:10,ty="n",bty="n")

legend("topleft", legend=bquote(paste(bold("95% CI: [ ", .(round(.4432, 3)),
", " , .(round(.0034, 3))," ]"))),
                 bty="n", inset=c(0,.03))

P.S. If I omit the bold() part from the code, the entire phrase shows normally, but I loose the bolding effect.

A: Two options/workarounds:

*

*You can bold() each literal string individually, but I don't know how to bold the dynamic portions (e.g., .(round(.4432,3))). This would look like:
plot(1:10,ty="n",bty="n")
legend("topleft", legend=bquote(paste(bold("95% CI: [ "), .(round(.4432, 3)),
                                      bold(", ") , .(round(.0034, 3)),
                                      bold(" ]"))),
       bty="n", inset=c(0,.03))

The numbers are not bold.

*With this label/legend, you don't actually need bquote, so you can use the text.font option of legend to bold the whole string:
plot(1:10,ty="n",bty="n")
legend("topleft", legend=paste("95% CI: [ ", round(.4432, 3),
                               ", " , round(.0034, 3),
                               " ]"),
       bty="n", inset=c(0,.03), text.font=2)

The disadvantage with this is that you are you able to use math symbols.
The text.font is a legend-specific argument for the more-generic font parameter, found in ?par:
 'font' An integer which specifies which font to use for text.  If
      possible, device drivers arrange so that 1 corresponds to
      plain text (the default), 2 to bold face, 3 to italic and 4
      to bold italic.  Also, font 5 is expected to be the symbol
      font, in Adobe symbol encoding.  On some devices font
      families can be selected by 'family' to choose different sets
      of 5 fonts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Internet explorer connection is lost after 1 minute when using haproxy in between I have an angular client that calls a rest service deployed on an application server. Between the two stands a haproxy that forwards the requests coming from the client to the REST service. When using Internet explorer and the response time is greater than 1 minute, when the REST service returns, the response is not sent to the client. The client still waits for the response.
This seems to be a haproxy issue since when bypassing haproxy, the request returns as expected after ~3-4 minutes.
I have tried all the different timeouts (client, server, http-request) but nothing seems to solve this.
My haproxy configuration can be found below:
global
    log /dev/log    local0
    #log /dev/log    local1 notice
    #chroot /var/lib/haproxy
    #stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    maxconn 2000
    user haproxy
    group haproxy
    daemon

    # Default SSL material locations
    ca-base /etc/ssl/certs
    crt-base /etc/ssl/private

    tune.maxrewrite 1024
    tune.bufsize 32768

    # Default ciphers to use on SSL-enabled listening sockets.
    # For more information, see ciphers(1SSL). This list is from:
    #  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
    # An alternative list with additional directives can be obtained from
    #  https://mozilla.github.io/server-side-tls/ssl-config-generator/?server=haproxy
    ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
    ssl-default-bind-options no-sslv3

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    option  log-separate-errors
    option redispatch
    retries 3
    timeout connect 5000
    timeout client  1200s
    timeout server  1200s
    errorfile 400 /var/log/haproxy/errors/400.http
    errorfile 403 /var/log/haproxy/errors/403.http
    errorfile 408 /var/log/haproxy/errors/408.http
    errorfile 500 /var/log/haproxy/errors/500.http
    errorfile 502 /var/log/haproxy/errors/502.http
    errorfile 503 /var/log/haproxy/errors/503.http
    errorfile 504 /var/log/haproxy/errors/504.http

listen haproxy-monitoring
    bind *:1900
    mode http
    stats enable                                        # Enable satistics
    stats uri /haproxy?stats                            # Dashboard URL
    stats realm Strictly\ Private
    stats auth haproxyanalytics:haproxyanalytics              # Username / Password
    stats hide-version                                  # Hide the version of HAProxy used

# APACHE web servers
    #frontend haproxy-apache
    #    bind *:8001 transparent
    #    mode http
    #    default_backend apache-nodes

frontend http-in
    bind *:80 transparent
    acl has_special_uri path_beg /cxf
    use_backend rest-service if has_special_uri
    default_backend apache-web

backend apache-web
    mode http
    balance roundrobin
    option forwardfor                                               # ensures the forwarded request includes the actual client IP address
    option httpclose
    http-request set-header X-Forwarded-Port %[dst_port]
    http-request add-header X-Forwarded-Proto https if { ssl_fc }
    #option httpchk HEAD / HTTP/1.1\r\nHost:localhost                # defines the check HAProxy uses to test if a web server is still valid for forwarding requests
    server "apache-1" ${CURRENT_NODE_IP}:${APACHE_PORT} check

backend rest-service
    mode http
    balance roundrobin
    option forwardfor                                               # ensures the forwarded request includes the actual client IP address
    option httpclose
    option accept-invalid-http-request
    http-request set-header X-Forwarded-Port %[dst_port]
    http-request add-header X-Forwarded-Proto https if { ssl_fc }
    #option httpchk HEAD / HTTP/1.1\r\nHost:localhost                # defines the check HAProxy uses to test if a web server is still valid for forwarding requests
    server "karaf-1" ${CURRENT_NODE_IP}:${KARAF_REST_PORT} check


text:
Q: Assisted Attributions into Silverpop Has anyone worked with Silverpop (IBM)?  I am trying to get our view-through conversions such as a display banner or YouTube videos to sync into the Silverpop database system so we can see if they result in a sale.
Currently, we are only getting clicked through conversions from paid search.  Does anyone know what needs to be included in the Javascript in order to see the view through conversions and also all touchpoints in the journey?
Not sure if it is another cookie value or some type of tracking script.  The website is coded in JavaScript.


text:
Q: AJAX POST and PHP I have a AJAX script which sends a POST request to PHP with some values. When I try to retrieve the values in PHP, am not able to get anything.
The AJAX script is
xmlhttp.open("POST","handle_data.php",true);
xmlhttp.setRequestHeader("Content-type","text/plain");
var cmdStr="cmd1=Commanda&cmd2=Command2";
xmlhttp.send(cmdStr);
alert(xmlhttp.responseText);

The PHP script is
<?php
  echo $_POST['cmd1'];
?>

The output is just a plain empty alert box. Is there any mistake in the code?

A: xmlhttp.onreadystatechange = function()
{
    if(this.readyState == 4 && this.status == 200)
    {
        if(this.responseText != null)
        {
            alert(this.responseText);
        }
    };
}

You need to wait for the data to be received, use the onreadystatechange to delegate a callback.
http://www.w3.org/TR/XMLHttpRequest/

A: I don't know if it is required, but might you want to use application/x-www-form-urlencoded as the request header.

A: You should not be grabbing the response immediately after sending the request. The reason is because the A in Ajax stands for Asynchronous, and that means the browser won't wait for your XMLHttpRequest to complete before it continues to execute your JavaScript code.
Instead you should write a callback that only runs when the response is fully ready. Just before your xmlhttp.send(cmdStr); call, add this:
xmlhttp.onreadystatechange = function()
{
    if (this.readyState == 4 && this.status == 200)
    {
        // This line is from your example's alert output
        alert(this.responseText);
    }
}


text:
Q: Azure cloud service hosted website stops connecting database suddenly I have a website hosted on azure cloud services. The configuration is - Java 7, Tomcat 7, SQL Azure. Nowadays I am running into a problem. Suddenly, my website stops responding to pages which require database connectivity. I have used Apache Commons DBCP for connection pooling. I have checked all the logs but I could not find any connection failure logs. I have checked the DB connections on azure portal, which also looks okay to me. Please help me out on this and let me know what other information is required.
here is sql connection configuration-

*

*min connections - 20

*max connections 200

*num helpers - 10


text:
Q: Recurrence of a Markov chain (lemma of Pakes) For my course on Markov chains, we have to think about the following problem:

Consider the irreducible Markov chain with $P$ on the state space
  $S={0,1,2,...}$, with $p_{0,1}=1$, $p_{n,n+1}=1/(n+1)^2$ and
  $p_{n,0}=1-p_{n,n+1}$ for $n\geq 1$ (all other entries are zero).
  Check whether this Markov chain is transient or recurrent (Hint:
  $\prod_{n=2}^{\infty}(1-1/n^2)=1/2)$.

One way we've seen to prove recurrence of a Markov chain is the lemma of Pakes, which says that if for an irreducible Markov chain there exists a state $\bar{i}$ and a $\delta >0$ such that $\forall i > \bar{i}: D_i < -\delta$, then the chain is positive recurrent. The drift $D_i$ of state $i$ is defined as $D_i = \sum_{k=-i}^{\infty}k\,p_{k,k+i}$. For this specific Markov chain, we would have for all $i>0$ that $D_i = -i(1-1/(i+1)^2)+1/(i+1)^2=\frac{-i^3-2i^2+1}{(i+1)^2}$.
For me it seems to be clear from this that the lemma of Pakes is fulfilled. The above expression for the drift will become more and more negative as $i$ increases, so it is easy to pick a $\delta$ and $\bar{i}$ such that $\forall i > \bar{i}: D_i < -\delta$.
My problem however is that, despite the fact this seems the most straight-forward way to proceed, I made no use of the given hint whatsoever and I could not think of any other method to prove recurrence or transience in which the product in the hint (or any infinite product at all) would show up. My question now is twofold:

*

*Is the above way of proving positive recurrence correct or did I use the lemma of Pakes in the wrong way?

*In what method to prove recurrence or transience of this chain does the product of the hint show up?

A: I will assume that $p_{n,n+1}=1-1/(n+1)^2,$ not $p_{n,n+1}=1/(n+1)^2.$
Suppose you start at state $1$, i.e., $X_0=1$, and let $T_1=\inf(n\geq 1: X_n=1)$ be the return
time to the starting position. The escape probability satisfies
$$\mathbb{E}(T_1=\infty)\geq p(1,2)p(2,3)p(3,4)\cdots={1\over 2}>0.$$
Since the escape probability is bigger than zero, the chain is transient.


text:
Q: How to prove that $f(x,y) =(x^2-y^2)e^{-x^2-y^2} $ attains its maximum and its minimum. Let $f:\Bbb R^2\to \Bbb R$ given $$f(x,y) =(x^2-y^2)e^{-x^2-y^2} $$
what is tricking me are the odering of the following questions,

*

*Prove that $f$ attains its maximum and its minimum.

*solve $\nabla f(x,y)=0$ and

*Classical the global and local maximum and minimum of $f$

I have answered perfectly the two las questions I found and classify the extrema which are $(0,0), (0,1), (0,-1), (1,0)$ and $(-1,0).$ (the classification is easy to obtain within the Hessian matrix )

I am wondering how can one solve the first question ignoring the question 3. and 2.?

I was thinking about using some compactness argument. But here the domain $f$ is clearly not compact. Can any one help ?

A: You can use the extreme value theorem. It's not difficult to show that $f(x,y) \to 0$ as $\|(x, y)\| \to \infty$. Note also that $f(1, 0) = e^{-1} > 0$ and $f(0, 1) = -e^{-1} < 0$. By the limit expression, there must exist an $M$ large enough such that $\|(x, y)\| > M \implies |f(x, y)| < e^{-1}$. By the extreme value theorem, $f$ must attain a maximum and minimum on this compact ball $B[(0, 0); M]$, and such a maximum must be at least $e^{-1}$ and similarly the minimum is at most $-e^{-1}$. This maximum on $B[(0, 0); M]$ is therefore a global maximum, and similarly for the minimum.
The questions are, in my opinion, in a good order. Finding the stationary points and classifying them with derivative tests cannot show anything more than local maximality or minimality. Whereas, if you know in advance that a global maximum/minimum must exist, you know it must occur at a stationary point (since the function is differentiable), so it is sound to compare the values of the function at the stationary points, taking the greatest to be the maximum and the least to be the minimum.

A: Write the function in polar coordinates:
$$f(r,\theta)=r^2(\cos^2\theta-\sin^2\theta)e^{-r^2}=r^2e^{-r^2}\cos2\theta$$
and if we look for extrema values:
$$\begin{cases}f'_r=2re^{-r^2}\cos2\theta-2r^3e^{-r^2}\cos2\theta=2re^{-r^2}\cos2\theta(1-r^2)=0\iff r=1\\{}\\
f'_\theta=-2r^2e^{-r^2}\sin2\theta=0\iff2\theta=k\pi\,,\,\,k\in\Bbb Z\iff\theta=\frac k2\pi,\,\,k\in\Bbb Z\\{}\\
f''_{rr}=2e^{-r^2}\cos2\theta\left[1-r^2-2r(1-r^2)-2r^2\right]=2e^{-r^2}\cos2\theta\left[2r^3-3r^2-2r+1\right]\\{}\\
f''_{\theta\theta}=-4r^2e^{-r^2}\cos2\theta\\{}\\
f''_{r\theta}=-4r(1-r^2)e^{-r^2}\sin2\theta\end{cases}$$
and thus the Hessian is
$$H(r,\theta)=\begin{vmatrix}2e^{-r^2}\cos2\theta\left[2r^3-3r^2-2r+1\right]
&-4r(1-r^2)e^{-r^2}\sin2\theta\\
-4r(1-r^2)e^{-r^2}\sin2\theta&-4r^2e^{-r^2}\cos2\theta\end{vmatrix}=$$$${}$$
$$=-8r^2e^{-2r^2}\left[(2r^3-3r^2-2r+1)\cos^22\theta+2(1-r^2)^2\sin^22\theta\right]$$
Thus, at the critical points, we get:
$$H\left(1,\frac k2\pi\right)=-8e^{-2}(-2)\cos^2k\pi=16e^{-2}\cos^2k\pi>0\;,\,\,k\in\Bbb Z$$
and since
$$f''_{rr}\left(1,\frac k2\pi\right)=2e^{-2}\cos k\pi\cdot(-2)=-4e^{-2}\cos k\pi$$
we get that
$$\begin{cases}k\in\Bbb Z\;\text{odd}\implies f''_{rr}\left(1,\frac k2\pi\right)>0\implies\text{ we get a local minimum}\\{}\\
k\in\Bbb Z\;\text{even}\implies f''_{rr}\left(1,\frac k2\pi\right)<0\implies\text{ we get a local maximum}\end{cases}$$
We thus get the local extrema points are on the unit circle (or at the origin, which we didn't check since we assumed all the time $\;r>0\;$), and thus anyway they are within the closed unit disk, which is a compact set and thus the function, being continuous, attains its maximum and minimum there.


text:
Q: Where is EntitySet's "Results View"? When looking at a linked EntitySet<T> of a LINQ to SQL mapped entity, I see the following:

I'd like to see the following (achieved by using the .AsQueryable() extension method) so that I can click the little refresh icon and see the content:

Why can't I see the Results View on a regular plain EntitySet<T>?
Also, I've noticed that on this MSDN page it says:

In LINQ to SQL, the EntitySet<TEntity> class implements the IQueryable interface.

From what I can see, EntitySet<TEntity> doesn't inherit from either IQueryable nor IQueryable<T>. So what's up with that claim?

A: You'll find the answer to this question

The results view only works for
  collections which meet the following
  conditions

*

*Implement IEnumerable or IEnumerable (VB.Net only works for
  IEnumerable)

*Do not implement IList, IList, ICollection or
  ICollection (C# restriction only)

*Do not have a DebuggerTypeProxy attribute

*System.Core.dll is loaded in the debugee process

In particular #2, EntitySet<T> implement's IList<T> therefore the debugger won't show a "Results View" option.
Using the AsQueryable extension method returns an object which only implements IQueryable and IEnumerable and therefore will show the "Results View" option.
You can read more about the #2 in the answer given in the other question.

A: The terminology on the page you reference may be a bit off - since both EntitySet and IQueryable derive from IEnumerable, if EntitySet implemented IQueryable directly then implementing IEnumerable would be redundant.
What AsQueryable() does is convert the EntitySet to an EnumerableQuery (as shown in your second image) - and only after that conversion is done can the result view be seen.
Since EntitySet only derives from IEnumerable, this makes sense - as Enumerators don't return sets but references to individual members in a set, in a sequential order.


text:
Q: Enable cipher suite TLS_DH_anon_WITH_AES_128_CBC_SHA I need to connect to an old device, which doesn't support any modern cipher suites, currently, I get the error:
iwr : The request was aborted: Could not create SSL/TLS secure channel.

nmap's ssl script shows it allowing only these:
TLSv1.2:
|     ciphers:
|       TLS_DH_anon_WITH_3DES_EDE_CBC_SHA - F
|       TLS_DH_anon_WITH_AES_128_CBC_SHA - F
|       TLS_DH_anon_WITH_AES_256_CBC_SHA - F
|       TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA - F
|       TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA - F

But these don't seem to match up with any of the ciphers I can enable using powershell:
Get-TlsCipherSuite|%{$_.name}

Name
----
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
TLS_RSA_WITH_AES_256_GCM_SHA384
TLS_RSA_WITH_AES_128_GCM_SHA256
TLS_RSA_WITH_AES_256_CBC_SHA256
TLS_RSA_WITH_AES_128_CBC_SHA256
TLS_RSA_WITH_AES_256_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA

Am I missing ciphers? I wouldn't be too surprised if windows 10 had removed some ancient ones. I couldn't find any information about which ciphers should be available in different versions, or what the DH_anon resolve to in windows to be able to enable it.


text:
Q: Checking if list content is null I have a flutter app that checks a list, and depending on what the if else does, something pops up on the screen. I have an if that checks if the list is empty or its length equal to 0, an else that if the list has content, it shows on the screen. But in case the list has size, but its contents are null, and so nothing is built on the screen, what I want to do is return a Text() widget for example, which says 'nothing was found'. How can I treat this problem?
      if (colors == null || colors.length == 0)
        Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(40, 40, 40, 0),
            child: CircularProgressIndicator(),
          ),
        )
      else if() //What should I do here?
      //emptyState
      else ...colorsList()

A: You could do something like
if(colors?.where((e) => e != null)?.toList()?.isEmpty ?? true) {
    //do your thing when list or it's content is empty
}


text:
Q: I want to check if record exist and if not exist then i want to insert that record to database using golang package main

import (
    "database/sql"
    "fmt"

    "github.com/gin-gonic/gin"
)

func main() {

    router := gin.New()
    router.Use(gin.Logger())
    router.Use(gin.Recovery())
    db, err := sql.Open("mysql", "root:password@tcp(gpstest.cksiqniek8yk.ap-south-1.rds.amazonaws.com:3306)/tech")
    if err != nil {
        fmt.Print(err.Error())
    }
    err = db.Ping()
    if err != nil {
        fmt.Print(err.Error())
    }
    rows, err := db.Query("select sum(usercount) as usercount from ( select count(*) as usercount from category where name = 'construction' union all  select count(*) as usercount from sub_category where name = 'construction'  union all  select count(*) as usercount from industry where name = 'construction' ) as usercounts;")

}

A: One possible approach would be:
var exists bool
row := db.QueryRow("SELECT EXISTS(SELECT 1 FROM ...)")
if err := row.Scan(&exists); err != nil {
    return err
} else if !exists {
    if err := db.Exec("INSERT ..."); err != nil {
        return err
    }
}

A: First execute the select statement. Then with rows.Next() check if there is a record on the database. If not, execute the insert query.
rows, err := db.Query("select sum(usercount) as usercount from ( select count(*) as usercount from category where name = 'construction' union all  select count(*) as usercount from sub_category where name = 'construction'  union all  select count(*) as usercount from industry where name = 'construction' ) as usercounts;")
if err != nil {
    log.Fatal(err)
}

if rows.Next() {
    //exists
} else {
    db.Query("INSERT INTO...")
}

A: IGNORE is your friend!
You can do it directly with one query if you have a unique index of the field that you want to check with a query like this:
INSERT IGNORE .........;

A: I've created a function that can be used check if a user record exists or not,
you can repurpose it for other tables

func userWithFieldExists(field string, value string) bool {
    var count int64
    if err := config.DB.Model(&User{}).Select("id").Where(fmt.Sprintf("%s = ?", field), value).Count(&count).Error; err != nil {
        log.Errorf("unable to retrieved user: %v", err)
        return false
    }
    if count > 0 {
        return true
    }
    return false
}

It can be used like so:
userWithFieldExists("email", user.Email)


text:
Q: Member function overloading/template specialization issue I've been trying to call the overloaded table::scan_index(std::string, ...) member function without success. For the sake of clarity, I have stripped out all non-relevant code.
I have a class called table which has an overloaded/templated member function named scan_index() in order to handle strings as a special case.
class table : boost::noncopyable
{
public:
    template <typename T>
    void scan_index(T val, std::function<bool (uint recno, T val)> callback) {
        // code
    }

    void scan_index(std::string val, std::function<bool (uint recno, std::string val)> callback) {
        // code
    }
};

Then there is a hitlist class which has a number of templated member functions which call table::scan_index(T, ...)
class hitlist {
public:
    template <typename T>
    void eq(uint fieldno, T value) {
        table* index_table = db.get_index_table(fieldno);
        // code
        index_table->scan_index<T>(value, [&](uint recno, T n)->bool {
            // code
        });
    }
};

And, finally, the code which kicks it all off:
hitlist hl;
// code
hl.eq<std::string>(*fieldno, p1.to_string());

The problem is that instead of calling table::scan_index(std::string, ...), it calls the templated version. I have tried using both overloading (as shown above) and a specialized function template (below), but nothing seems to work. After staring at this code for a few hours, I feel like I'm missing something obvious. Any ideas?
    template <>
    void scan_index<std::string>(std::string val, std::function<bool (uint recno, std::string val)> callback) {
        // code
    }

Update:
I dropped the <T> decoration from the scan_index() call. The result was that the calls with a string parameter compile just fine, but calls with other types (e.g. double) resulted in the following error:
cannot convert parameter 1 from 'double' to 'std::string'

So I went back to using template specialization. Now I get this error:
error C2784: 'void table::scan_index(T,std::tr1::function<bool(uint,T)>)' :
  could not deduce template argument for 'std::tr1::function<bool(uint,T)>'
  from '`anonymous-namespace'::<lambda5>'

FYI: I am using VC++ 10.0
Solution:
I fixed this problem by dropping the templated scan_index() function from the table class and simply writing four overloaded functions (three of which are identical except for the signature). Luckily, they're all pretty short (less than ten lines) so it's not so bad.

A: You explicitly call templated member here:
index_table->scan_index<T>(value, [&](uint recno, T n)...

Since value is the template parameter you should be fine replacing that with:
index_table->scan_index(value, [&](uint recno, T n)...

A: You shouldn't explicitly specify the template argument- you should leave it to template argument deduction and overload resolution. This should allow the overload you posted in the very original code to be picked up and used.

A: prepared this simplified test (sorry, I don't have C++0x compiler atm):
class table
{
public:
    template <typename T>
    void scan_index(T val) {
        std::cout << "template\n";
    }

    template <>
    void scan_index<int>(int val) {
        std::cout << "specialization\n";
    }

    void scan_index(int val) {
        std::cout << "overloaded\n";
    }
};

class hitlist {
public:
    template <typename T>
    void eq(T value) {
        table tbl;
        tbl.scan_index<T>(value);
    }
};

int main(int argc, char* argv[])
{
    int i = 0;
    hitlist hl;
    hl.eq(i);
    return 0;
}

output is "specialization" (VC9). it's because hitlist::eq explicitly uses template version, so only template specialization will be considered. if you change tbl.scan_index<T>(value); to tbl.scan_index(value); overloaded version will be called.
tbh I don't know why your template specialization doesn't work, probably because of lambda, not complete C++0x support? which compiler?

A: Isn't the template specialisation be something like:
template <typename T>
void scan_index(T val, std::function<bool (uint recno, T val)> callback) {
    // code
}
template <>
void scan_index(std::string val, std::function<bool (uint recno, std::string val)> callback) {
    // code
}

This way C++ compiler recognizes scan_index has a specialisation rather than looking for the overloaded method. And I believe if you wanted it the way you can coded, you should probably put the specialised code before the template like this:
    void scan_index(std::string val, std::function<bool (uint recno, std::string val)> callback) {
        // code
    }
template <typename T>
    void scan_index(T val, std::function<bool (uint recno, T val)> callback) {
        // code
    }


text:
Q: Template classes in Python I'm attempting to create algebras in Python, and I'm finding it difficult to create parameterized classes.
As an example, consider this ProductWeight class. It holds two other Weight objects, with enforced types (at least statically, via mypy).
This will fail because (by design) I cannot access the classes for W1 and W2 to call their classmethods like zero. (They're not specified; ProductWeight is not templated.) ProductWeight doesn't know, when I create an instance, which types to bind to it.
from typing import Generic, TypeVar
W1 = TypeVar("W1")
W2 = TypeVar("W2")

class ProductWeight(Generic[W1, W2]):
    def __init__(self, value1: W1, value2: W2):
        self.value1_ = value1
        self.value2_ = value2

    @classmethod
    def zero(cls):
        return cls(W1.zero(), W2.zero())  # Will fail - no access to W1 and W2.

By contrast, this is straightforward in C++: because the type is parameterized, it is able to look up W1::Zero.
template<typename W1, typename W2>
public:
    ProductWeight(W1 w1, W2 w2) : value1_(w1), value2_(w2) {}
    static ProductWeight Zero() {
        return ProductWeight(W1::Zero(), W2::Zero());
    }
private:
    W1 value1_;
    W2 value2_;
};

Is there a workaround for this in Python? Either creating an inner class, or otherwise somehow providing types to the class (rather than to class instances)?
For the sake of a minimal reproducible example, you can use this implementation of another Weight type.
class SimpleWeight:
    def __init__(self, value):
        assert value in {True, False}
        self.value_ = value

    @classmethod
    def zero(cls):
        return cls(False)

weight1 = SimpleWeight(False)
weight2 = SimpleWeight(True)
product = ProductWeight(weight1, weight2)

print(SimpleWeight.zero())  # So far, so good.
print(ProductWeight.zero())  # Oof.
# Predictably, it failed because `ProductWeight` is not specialized.

And here's the predictable error message:
Traceback (most recent call last):
  File "garbage.py", line 32, in <module>
    print(ProductWeight.zero())  # Oof.
  File "garbage.py", line 14, in zero
    return cls(W1.zero(), W2.zero())  # Will fail - no access to W1 and W2.
AttributeError: 'TypeVar' object has no attribute 'zero'

Ideally, it would be possible to create a parametric type like this:
product = ProductWeight[SimpleWeight, SimpleWeight](weight1, weight2)
# And similarly:
print(ProductWeight[SimpleWeight, SimpleWeight].zero())

A: To solve this, it's paramount to realize that generics in C++ create multiple classes while in Python you will always have only one class, no matter what types the parameters in its constructor have.
In other words, in C++ vector<int> and vector<string> are two classes. If you bound them to Python interpreter you would have to assign them two different names, for example VectorInt and VectorString.
The code
def ProductWeight(value1, value2):
    def init(self, value1, value2):
        self.value1 = value1
        self.value2 = value2

    def zero(cls):
        return cls(cls.W1.zero(), cls.W2.zero())

    W1 = type(value1)
    W2 = type(value2)
    name = f'ProductWeight{W1}{W2}'

    try:
        return ProductWeight.types[name](value1, value2)
    except KeyError:
        pass

    cls = type(name, (), {'__init__': init})
    cls.W1 = W1
    cls.W2 = W2
    cls.zero = classmethod(zero)
    ProductWeight.types[name] = cls

    return cls(value1, value2)

ProductWeight.types = {}

class SimpleWeight:
    def __init__(self, value):
        assert value in {True, False}
        self.value_ = value

    @classmethod
    def zero(cls):
        return cls(False)

weight1 = SimpleWeight(False)
weight2 = SimpleWeight(True)
product = ProductWeight(weight1, weight2)

print(SimpleWeight.zero())
print(type(product).zero())

The code tries to respect your original API, you may create instances of class ProductWeight with generic parameters. However, you have to access an underlying type of an instance if you want to call its classmethod zero (notice the change from ProductWeight to type(product) at the last line).
You may save this reference to a variable for convenience.
The function ProductWeight serves as a generic factory. Each time you call it, it creates a name for the new class based on the types of the parameters. If such class already exists, it just returns a new instance of it. Otherwise, it creates the new class using the type function and then returns a new instance.
ProductWeight on its own is also a singleton object that has a dictionary of already created types.
Conclusion
You may notice that this solution uses significantly more memory than its C++ counterpart. However, given that you chose to use Python instead of C++, you will probably not worry about that too much.
More importantly, you will have to decide if this is the right path for you to take. Remember, in Python there are no generics, there are only "dynamics". So your way of thinking will bring in more obstacles than it will remove in the long run.
Making Python sound like C++
This part answers this edit to your question:

Ideally, it would be possible to create a parametric type like this:

product = ProductWeight[SimpleWeight, SimpleWeight](weight1, weight2)
# And similarly:
print(ProductWeight[SimpleWeight, SimpleWeight].zero())

Fear not, because this is actually possible. The following code uses __class_getitem__ from Python 3.7, however with a workaround it can be run on older versions as well, see this question about static getitem method.
Code rewritten
# SimpleWeight didn't change
from simple_weight import SimpleWeight

class ProductWeight:
    types = {}

    def __class_getitem__(cls, key):
        try:
            W1, W2 = key
        except ValueError:
            raise Exception('ProductWeight[] takes exactly two arguments.')

        name = f'{ProductWeight.__name__}<{W1.__name__}, {W2.__name__}>'

        try:
            return cls.types[name]
        except KeyError:
            pass

        new_type = type(name, (), {'__init__': cls.init})
        new_type.W1 = W1
        new_type.W2 = W2
        new_type.zero = classmethod(cls.zero)
        cls.types[name] = new_type

        return new_type

    def __init__(self):
        raise Exception('ProductWeight is a static class and cannot be instantiated.')

    def init(self, value1, value2):
        self.value1 = value1
        self.value2 = value2

    def zero(cls):
        return cls(cls.W1.zero(), cls.W2.zero())

weight1 = SimpleWeight(False)
weight2 = SimpleWeight(True)
product = ProductWeight[SimpleWeight, SimpleWeight](weight1, weight2)

print(SimpleWeight.zero())
print(ProductWeight[SimpleWeight, SimpleWeight].zero())

This takes an advantage of the fact that the bracket operator __getitem__ takes arbitrary number of arguments and packs them into a tuple which is its first parameter. You can unpack the tuple and get all the types. This can be extended to account for any number of types and even such a number that was chosen at runtime.
Inferred type
Last version lost the ability to infer the type from arguments passed to the constructor. By creating an abstract factory we can get this functionality back.
# SimpleWeight didn't change
from simple_weight import SimpleWeight

class ProductWeightAbstractFactory:
    def __call__(self, value1, value2):
        return self[type(value1), type(value2)](value1, value2)

    def __getitem__(self, types):
        W1, W2 = types
        name = f'ProductWeight<{W1.__name__}, {W2.__name__}>'

        try:
            return self.types[name]
        except KeyError:
            pass

        cls = type(self)
        new_type = type(name, (), {'__init__': cls.init})
        new_type.W1 = W1
        new_type.W2 = W2
        new_type.zero = classmethod(cls.zero)
        self.types[name] = new_type

        return new_type

    def __init__(self):
        self.types = {}

    def init(self, value1, value2):
        self.value1 = value1
        self.value2 = value2

    def zero(cls):
        return cls(cls.W1.zero(), cls.W2.zero())

ProductWeight = ProductWeightAbstractFactory()

weight1 = SimpleWeight(False)
weight2 = SimpleWeight(True)
product = ProductWeight[SimpleWeight, SimpleWeight](weight1, weight2)
inferred_product = ProductWeight(weight1, weight2)

print(SimpleWeight.zero())
print(ProductWeight[SimpleWeight, SimpleWeight].zero())
print(type(inferred_product).zero())

Note that you have to create an instance of the factory before using it:
ProductWeight = ProductWeightAbstractFactory()

Now you can create an object with an explicit type using the brackets:
product = ProductWeight[SimpleWeight, SimpleWeight](weight1, weight2)

Or you can infer the type to make the code concise:
product = ProductWeight(weight1, weight2)

Now it's closer to C++ like syntax than ever.
Type checking
To provide more safety when developping you can also introduce type checking in the constructor.
def init(self, value1, value2):
    def check_types(objects, required_types):
        for index, (obj, t) in enumerate(zip(objects, required_types)):
            if not issubclass(type(obj), t):
                raise Exception(f'Parameter {index + 1} is not a subclass of its required type {t}.')

    cls = type(self)
    check_types((value1, value2), (cls.W1, cls.W2))

    self.value1 = value1
    self.value2 = value2

This code will then fail:
product = ProductWeight[SimpleWeight, SimpleWeight](1, 2)


text:
Q: How i recover the deleted table from database source folder in repository in Informatica I am using Informatica 8.6 with Oracle 11g. By mistakenly, i have deleted a table emp from database source folder in repository.
Can i recover this. or how i can add a new table emp.
please suggest.
Thanks.

A: You can right-click on the folder in the repository,  "Find checkouts...". In the next screen, you get the list of checked out objects. Choose the source definition that you deleted, right click and "Undo Checkout".
In Informatica, when you delete an object, it is still checked in. Only if you check out again, does it actually get removed. Until then, you cannot import an object with the same name as the deleted object.

A: You might have got the fix by now however my input may also put a little flavor to it:
Versioned repository: Go to find check out and select un-do checkout to the deleted object as after deletion it will not go off line until an unless it is checked-in to the repository.
Non-versioned repository: You have to re-import the object with the required DSN with correct credentials.
Hope above said detail can help you to debug further.


text:
Q: Eigenvalue / Eigenvector Calculation I'm currently trying to compute the three smallest eigenvectors for a 34 by 34 matrix. While I was expecting this to take some time, Mathematica has been running for the past 3 hours, which seems maybe slightly disproportional to the task at hand. The matrix is a laplacian matrix, so it is relatively sparse. Here is my input (G is the graph itself):
A1 = AdjacencyMatrix[G];
D1 = DiagonalMatrix[VertexDegree[G]];
NL1 = IdentityMatrix[34] - MatrixPower[D1, -1/2].A1.MatrixPower[D1, -1/2];
EvecsNL1 = Eigenvectors[NL1,-3]

Any help is much appreciated.
Edit: Sorry about that:
G = ExampleData[{"NetworkGraph", "ZacharysKarateClub"}]

I'm trying to get accustomed to working with graph laplacians in mathematica, so I'm messing around with some included datasets.
Edit 2: Wow, I feel foolish. Thank you for your help.

A: Note that your A1 is a SparseArray, while your NL1 is a full list of lists, since you've formed it using IdentityMatrix and DiagonalMatrix which return full lists of lists.  This could have a huge impact on memory footprint as well as speed and accuracy of your computations, particularly if you're working with very large, sparse graphs.  I would take this into account when forming the Laplacian matrix.
As I understand it, the Laplacian matrix of a graph is its adacency matrix minus its vertex degree matrix.  We could implement this as a sparse matrix like so
g = GraphData[{"Kneser", {14, 6}}];
vertexDegrees = VertexDegree[g];
diagonalRules = Table[{i, i} -> -vertexDegrees[[i]],
  {i, 1, Length[vertexDegrees]}];
adjacencyRules = ArrayRules[AdjacencyMatrix[g]];
laplacian = SparseArray[Join[diagonalRules, adjacencyRules]];
Dimensions[laplacian]

(* Out: {3003, 3003} *)

It's a large matrix; let's look at just a piece of it.
MatrixForm[Normal[laplacian[[1282 ;; 1296, 1282 ;; 1296]]] /.
  0 -> Style[0, LightGray]]

I guess your version of the command to compute the 10 smallest eigenvalues would be
Eigenvalues[N[laplacian], -10] // AbsoluteTiming

(* Out: {2.454553, {-22.1063, -22., -22., -21.8781, -13.0058,
   -13., -13., -13., -12.9948, 4.5206*10^-15}} *)

You might try something like so:
Eigenvalues[N[laplacian], 10, Method -> {"Arnoldi",
  "Shift" -> 0, "BasisSize" -> 50}] // AbsoluteTiming

(* Out: {1.691656, {-13., -13., -13., -13., -13., -13., -13.,
   -13., -12.6622, -6.90978*10^-16}} *)

You can use the  Eigensystem command to check for accuracy.
{vals, vecs} = Eigensystem[N[laplacian], 10, Method -> {"Arnoldi",
  "Shift" -> 0, "BasisSize" -> 50}];
Norm[laplacian.vecs[[1]] - vals[[1]]*vecs[[1]]]

(* Out: 2.30196*10^-9 *)

{vals, vecs} = Eigensystem[N[laplacian], -10];
Norm[laplacian.vecs[[1]] - vals[[1]]*vecs[[1]]]

(* 0.284252 *)

It appears that the Arnoldi specified version is faster and more accurate.
I don't know a lot of the details behind the computations, particularly the second syntax with the -10.  Perhaps @DanielLichtblau or @ruebenko could comment on that.

A: For speeding up Mathematica code, a little analysis of a problem often goes a long way.
Analysis
Writing $\mathbb{G}$ for the diagonal matrix of vertex degrees and $\mathbb{A}$ for the adjacency matrix, this question seeks eigenvectors of $\mathbb{1} - \mathbb{G}^{-1/2} \mathbb{A} \mathbb{G}^{-1/2}$.  That is, it looks for solutions $(\mathbf{z}, \lambda)$ to
$$\mathbf{z} \left(\mathbb{1} - \mathbb{G}^{-1/2} \mathbb{A} \mathbb{G}^{-1/2} \right) = \lambda \mathbf{z}.$$
The square roots ought to give us pause: they are likely a significant complication in performing the arithmetic.
It is straightforward to rewrite this system of equations, though, as
$$\left(\mathbf{z} \mathbb{G}^{1/2}\right)\left(\mathbb{G^{-1} A}\right) = \left(1-\lambda\right)\left(\mathbf{z}\mathbb{G}^{1/2}\right).$$
Whence, if we solve
$$\mathbf{w}\left(\mathbb{G^{-1} A}\right) = \mu \mathbf{w}$$
then $\lambda = 1-\mu$ and $\mathbf{z} = \mathbf{w} \mathbb{G}^{-1/2}$.  The square roots come in only at the end as easy matrix multiplications, while $\mathbb{GA}$ is a rational matrix.  Hopefully, calculations involving it will be faster.
Solution
Here is an implementation:
f[g_, a_] := Module[{e, v},
   {e, v} = Eigensystem[DiagonalMatrix[1/g] . a];
   {1 - e, v.DiagonalMatrix[Sqrt[g]]}
   ];

Let's carry it out on the example data:
g = ExampleData[{"NetworkGraph", "ZacharysKarateClub"}];
{l, z} = f[VertexDegree[g], AdjacencyMatrix[g]]; // AbsoluteTiming

{31.8538219, Null}

Remarks
A half minute is reasonable (the output is huge and complicated).  The results agree with the (much faster) numerical solution to about five significant figures--but no more.  Thus, if higher accuracy is desired, this approach makes that feasible.  Typically, you would find the exact eigensystem and then immediately convert that to floating-point representation for all the (much less numerically involved) post-processing operations.
This implementation did not bother to assure that the eigenvectors are still of unit length.  If desired, do this after the fact by applying #/Norm[#]& to them.  Also, it returns all the eigenvectors and eigenvalues, rather than the three corresponding to the smallest absolute values of the eigenvalues. But finding those three requires only a simple post-check of the list of eigenvalues.  This is made necessary because we are really looking for the eigenvectors for which $\mu$ is as close to $1$ as possible and there's no savings associated with computing just them.
The output of this solution and that of a direct attack on the numerical version of the original problem may differ in two ways.  First, the eigenvalues will occur in a different order.  Second, even when the eigenvectors are normalized, they are determined only up to sign.  These differences are of no mathematical or practical consequence.
Finally, Eigensystem arranges to return a set of mutually orthonormal eigenvectors for any eigenvalue of multiplicity greater than one.  The modified approach described here may ruin their orthonormality.  That property can be restored, if desired, by applying a Gram-Schmidt process to each degenerate eigenspace.


text:
Q: If $H$ and $K$ are normal subgroups of $G$ and $H \cap K = \{e\}$, prove that $G \approx$ a subgroup of $G/H \oplus G/K$. If $H$ and $K$ are normal subgroups of $G$ and $H \cap K = \{e\}$, prove that $G \approx$ a subgroup of $G/H \oplus G/K$.
I see that any subgroup is of the form $\{(gB,gC): g \in G\}$ where $B$ and $C$ are subsets of $H$ and $K$, respectively, but from here I can't see how to modify this to become an isomorphism.  I tried using the first isomorphism theorem but I couldn't figure how to find the kernel for the homomorphism.

A: It's not true that any subgroup of $G/H\oplus G/K$ is of the form $\{(gB,gC):g\in G\}$ where $B\subset H$ and $C\subset K$. In fact this doesn't even make sense if $B$ is a proper subset of $H$, because $gB$ is not an element of $G/H$ (which consists of cosets of $H$).
To solve the problem, define a map $\varphi:G\to G/H\oplus G/K$ by
$$
\varphi(g)=(gH,gK).
$$
If $\varphi(g)=(H,K)$ then $gH=H\implies g\in H$ and $gK=K\implies g\in K$. Can you finish the proof from here?


text:
Q: How can I add 30 days from today's date in List I want to add 30 days from today's date in to spinner so I am adding through ArrayList bt How can I add thirty days to todays date in following for loop
 ArrayList<String> dates = new ArrayList<String>();
     Calendar cal = Calendar.getInstance();
        int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
                SimpleDateFormat df = new SimpleDateFormat("MMM-dd");

for (int i = cal.get(Calendar.DAY_OF_MONTH); i <= maxDay; i++)
     {
             dates.add( df.format(cal.getTime()));
             cal.set(Calendar.DAY_OF_MONTH, i + 1);
     }

Let assume today's day is 29 so it will only prints 29 -Sep and 30-Sep.If I change i=0 then it will print till maxDay but I want to resrtict user from selecting past date so I am starting from today's date
Second thing how can I dispay today(text) insted of today's date ?


text:
Q: Phonegap: "standalone" app with node.js I want to write a Phonegap app with a local node.js server.
Is this possible?
With node.js i can use a redis-client and sdl functionality.
This is Tim Caswalls talk about node.js and phonegap but i can not find any more info about it.

A: I think you should be looking into these
https://github.com/rogerwang/node-webkit
http://appjs.com/
here is an example
have a look at clipconverter.cc desktop
it uses appjs as far as i know


text:
Q: Vector and parametric form of the equation of lines tangent to a surface If we plot the graph of any $z=f(x,y)$ we will get a surface. If we take the partial derivatives at $(x_0,y_0)$ we will have two partial derivatives $f_x$ and $f_y$.
The equation of the tangent lines at that point along the $x$-axis and
$y$-axis will be, respectively,
$$z=z_0+f_x(x-x_0),y=y_0$$
and
$$z=z_0+f_y(y-y_0),x=x_0$$
As far I know the parametric forms of the two lines will be
$$(x,y,z)=(x_0+t_1,y_0,z_0+f_xt_1)$$ and  $$(x,y,z)=(x_0,y_0+t_2,z_0+f_yt_2)$$
My question is, am I right? If I'm not, what is correct parametric form of the two equations? I also want to know the vector and symmetric forms of the two equations with an explanation.

A: The slopes of the tangent lines at $(x_0,y_0)$ pointing in the $x$ and the $y$ direction are
$$m_x=\frac{\partial }{\partial x}f_x(x,y)\mid_{x=x_0,y=y_0}=f_x(x,y)\mid_{x=x_0,y=y_0}$$
and
$$m_y=f_y(x,y)\mid_{x=x_0,y=y_0}.$$
(That is, $m_x \not =f_x(x-x_0,y_0)$ and $m_y \not =f_y(x_0,y-y_0)$.)
We have lines whose slopes are  $m_x,m_y $ lie in the planes crossing the $y$ axis at $y_0$, the $x$ axis at $x_0$ and are  parallel to the the $y,z$ and the $x,z$ planes, respectively. Also, these lines go through the point $(x_0,y_0,f(x_0,y_0)).$
If I am not mistaken, we are talking about the following arrangement:

If this is not the case (if we are not talking about the red and the blue lines) then I revoke my answer.
We can easily write down the equation of the line lying in the $x,z$ plane, going through the point $x_0, f(x_0,y_0)$ and whose slope is $m_x$:
$$z=xm_x-m_xx_0+f(x_0,y_0).$$
In the case of our line we have to add that $y=y_0$.
Similarly, the equation of the other line is
$$z=ym_y-m_yy_0+f(x_0,y_0), \ x=x_0.$$
In parametric form, we have
$$(x(t),y(t),z(t))=(t,y_0,m_x(t-x_0)+f(x_0,y_0))$$
and
$$(x(t),y(t),z(t))=(x_0,t,m_y(t-y_0)+f(x_0,y_0)).$$


text:
Q: cannot receive json data post from app I use Yii php to receive data from android and ios app.
I tried postman as below picture:
http://i.stack.imgur.com/KaqX0.jpg
But in php, I always receipt "file_get_contents('php://input')":
------WebKitFormBoundaryHDGkntVW3uMr7FlA
Content-Disposition: form-data; name="email"

e3ma1il@domain.com
------WebKitFormBoundaryHDGkntVW3uMr7FlA
Content-Disposition: form-data; name="user"

test223user
------WebKitFormBoundaryHDGkntVW3uMr7FlA
Content-Disposition: form-data; name="password"

123456
------WebKitFormBoundaryHDGkntVW3uMr7FlA
Content-Disposition: form-data; name="firstname"

Le
------WebKitFormBoundaryHDGkntVW3uMr7FlA
Content-Disposition: form-data; name="lastname"

Phuong
------WebKitFormBoundaryHDGkntVW3uMr7FlA--

How to receive right json encode :(
It's take me 3 days, still not resolved

A: If you use Yii2 try to use yii\rest\ActiveController for API controllers and don't forget enable json input.
More info in yii2 docs - yii2 rest quick start
p.s. also, you can use "file_get_contents('php://input')" in actions, but i think it is not yii-way.


text:
Q: why using string prototype is so slow I investigated that if I modify prototype of object String it takes more time to evaluate compare with global function.
Basic example:
String.prototype.test = function() {
  return this.charCodeAt(0);
}
'test string'.test();

Is a much slower than:
function globalTest(str) {
  return str.charCodeAt(0);
}
globalTest('test string');

To more complex test see this jsperf statistic: http://jsperf.com/string-prototype-or-function


text:
Q: What are the stats for the MegaTower segments? Cities of Tomorrow introduced MegaTowers, which have many different segments which can be built.
So far I know these:
LW Residential: 800 workers, 400 shoppers and 200 students.
  800 cost per hour, 1200 rent per hour
T1 Office: 1200 LW, 400 MW and 100 HW workers.
  900 cost per hour, 1900 rent per hour.
  (no pollution, no freight, immune to techpoints)

I'm mainly interested in residential agent counts, goods counts, worker counts, cost and max rent per hour, and power consumption (in 10's of power units).  My theory is that these buildings pay less in rent and take more in power than equivalent original RCI would pay in tax.

A: "Apartment" is the name for Residential MegaTower segments.  It has workers and shoppers of matching wealth type + students.  It accumulates education level as you'd expect.
    Workers Shoppers Students Income Expense Power
LW      800     400       200   1200     800 4.8 MW
MW      400     200       100   1800    1320 2.4 MW
HW      200     100        50   3600    3320 1.2 MW

"Mall" is the name for Commercial MegaTower segments.  There are no Souvenirs. There are no freight orders.
   Goods Jobs Income Expense Power
LW  1500 ~175   1250     730 1.4 MW
MW   750 ~125   1750    1150 2.7 MW
HW   375  ~77   3100    2150 2.7 MW

"Office" is the name for Industrial MegaTower segments.  There is no pollution.  There is no freight produced.  They do not consume tech points.
    LWJobs MWJobs HWJobs Income Expense Power
T1     600    200     50   2550     950  9.7 MW
T2     400    200    100   3880    1460 10.6 MW
T3     200    200    150   4960    2480  8.4 MW

Notes:

*

*Numbers with "~" were not precisely measured.

*MW and T2 structures are same whether built with MegaTower art or Elite MegaTower art.

*Residential numbers are occupants

*Income, Expense, Power are per hour

*Jobs and Goods are per shift (12 hour cycle).  Double these numbers to get daily totals.

Strategy Notes:

*

*Residential units pay ~500 simoleans per hour if everything works perfectly.  Not good for making money.

*Billboard crowns add a bonus for Commercial and Industrial units in the tower.  These crowns are very important for money making.  HW C makes 950 net income without crowns and 4050 net income with full crowns.

*Offices pay more based on wealth levels of workers.  More than 50% of the income from T3 Office comes from the 150 HW workers.


text:
Q: How do I create a uninstantiated array of images in MATLAB I'm looking for a way to store a set of images in my MATLAB function. Is there a way to set aside space for n images ahead of time and initialize them later?
I tried doing something like this:
array_of_images = zeros(1,5); % array of 5 images

but when I try to initialize:
array_of_images(1,1) = imread('image_01.jpg');

MATLAB reports Assignment has more non-singleton rhs dimensions than non-singleton subscripts, so I am looking for a way to do something equivalent.

A: Check the output of  imread('image_01.jpg'), this propably something like 1200x800x3.
Then you have to preallocate ar=zeros(1200,800,3,5) and assign with ar(:,:,:,index)=imread('image.jpg')


text:
Q: Does google API allow us to get 'Usage of 3rd party apps authenticated through Google'? Does google API allow us to get 'List of user 3rd party apps authenticated through Google' ?
I can't find any references in documentation. But, it seems like it should be in API
https://support.google.com/a/answer/6294828?hl=en#zippy=%2Cautoprovisioning-status

A: If I understand correctly what you need is to get the list of all the third party apps that your users have logged into using their Google accounts using the Google APIs. If so, what you can use is the tokens.list method, that way your will retrieve all the tokens a user has issued to 3rd party applications.
You can use the displayText and clientId values you get in the response to identify the app, and check the scopes to see the permissions of the app.


text:
Q: How to select two object in dictionary in python I have a list of dictionary:
lst = [{'id': 449, 'created_at': '2021-06-02T11:01:43Z', 'process_status': 3},
 {'id': 453, 'created_at': '2021-06-02T14:41:42Z', 'process_status': 3},
 {'id': 477, 'created_at': '2021-06-03T13:34:13Z', 'process_status': 3}]

And I want to choose two object from it.
Also I tried this but not working:
filter_for_invoice_id = [object['created_at'] and object['id'] for object in lst if object['process_status'] == 3]

If i want to select only one object it's work pretty good but with more than one object it's not working

A: It seems that you do not want to select "object" but rather properties, or pairs, that would look like
filter_for_invoice_id = [{'created_at': o['created_at'], 'id': o['id']}
                         for o in lst if o.get('process_status') == 3]

But is there is more, you may use a second level iteration, with a given list of keys to keep
lst = [{'id': 449, 'created_at': '2021-06-02T11:01:43Z', 'process_status': 0},
       {'id': 453, 'created_at': '2021-06-02T14:41:42Z', 'process_status': 3},
       {'id': 477, 'created_at': '2021-06-03T13:34:13Z'}]

keys = {'created_at', 'id'}
filter_for_invoice_id = [{k: o[k] for k in keys} for o in lst if o.get('process_status') == 3]
print(filter_for_invoice_id)  # [{'created_at': '2021-06-02T14:41:42Z', 'id': 453}]

A: You can use the following statement too if you need the output as a list of list. Do note that if there is no process_status value, it will throw an error, you will need to handle that separately.
filter_for_invoice_id = [[object['created_at'], object['id']] for object in lst if object['process_status'] == 3]

A: If I understand your problem correctly you want to select one or more objects from lst based on a condition.
The simplest way to go about it is this:
filter_for_invoice_id = [item for item in lst if item['process_status'] == 3]
Also, I would not recommend using object as a variable name as it is a reserved word in Python.

A: try this one:
    lst = [{'id': 449, 'created_at': '2021-06-02T11:01:43Z', 'process_status': 0},
           {'id': 453, 'created_at': '2021-06-02T14:41:42Z', 'process_status': 0},
           {'id': 477, 'created_at': '2021-06-03T13:34:13Z', 'process_status': 3}]

    filter_for_invoice_id = [(object['created_at'], object['id'])
                             for object in lst if object['process_status'] == 3]

    print(filter_for_invoice_id)

A: I do not want to tell you what's wrong with your code.
You can test this one:
dic = {'id': 453, 'created_at': '2021-06-02T14:41:42Z', 'process_status': 3}
print(dic['id'])
print(dic['id'] and dic['created_at'])
print(dic.get('do_not_exists') and dic['created_at'])


text:
Q: Parse Server S3 file adapter with Heroku app I am trying to set up the s3 file adapter but I'm not sure if i am getting the formatting of something incorrect or something.  I have followed this:
https://github.com/ParsePlatform/parse-server/wiki/Configuring-File-Adapters#configuring-s3adapter
Guide exactly but when i uncomment the block of code below and put in my aws credentials then push the setup back to Heroku the app or dashboard won't start any longer, saying there is an application error:
//**** File Storage ****//
 filesAdapter: new S3Adapter(
    {
    "xxxxxxxx",
    "xxxxxxxx",
    "xxxxxxxx",
    {directAccess: true}
    }
 )

A: I would set it up as follows for Heroku:
Make sure that after performing all steps described in the guide your policy looks similar to this:
 {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::BUCKET_NAME",
                "arn:aws:s3:::BUCKET_NAME/*"
            ]
        }
     ]
 }

Now apply this policy to the bucket: select your bucket in S3 console, tap 'Properties' button in the top right corner. Expand 'Permissions' section, press 'Edit bucket policy' and paste json above in the text field.

Configure Parse Server in the index.js file:
var S3Adapter = require('parse-server').S3Adapter;
var s3Adapter = new S3Adapter(
    "AWS_KEY",
    "AWS_SECRET_KEY",
    "bucket-name",
    { directAccess: true }
);

and add two lines to the Parse Server init  (var api = new ParseServer({..})):
filesAdapter: s3Adapter,
fileKey: process.env.PARSE_FILE_KEY

A: Similar to Cliff's post, .S3Adapter has to be outside the ()
var S3Adapter = require('parse-server').S3Adapter;

And then inside parse server init:
 filesAdapter: new S3Adapter(
    {
    accessKey: process.env.S3_ACCESS_KEY || '',
    secretKey: process.env.S3_SECRET_KEY || '',
    bucket: process.env.S3_BUCKET || '',
    directAccess: true
    }
 )

This worked in this case.


text:
Q: Error converir NSData en NSString Tengo el siguiente código para convertir el body de una petición post en un string
let body: NSData = self.createBodyWithParameters(paramString, filePathKey: "image_name", imageDataKey: imageData!, boundary: boundary, nameParam: "dparam_string_post")
let bodyString: String = NSString(data: body, encoding: NSUTF8StringEncoding) as! String

Me da error en la segunda linea:
fatal error: unexpectedly found nil while unwrapping an Optional value

Y la variable tiene contenido, he realizado un print y me ha mostrado el contenido
EDITADO
Tambien he probado con:
let cadena = String(data: body, encoding: NSUTF8StringEncoding)

Pero me retorna nil

A: Hazlo así:
let newStr : String? = String(data: data, encoding: NSUTF8StringEncoding)

Y ten cuidado por que la variable es una variable opcional. O sea es de tipo String? no String.


text:
Q: versionone: get defects with project and change date filter from version one java sdk I am looking to retrieve list of all defects that belongs to project A and that have modified in last 24 hours. I used the given below code to retrieve list of all defects that belongs to project(project is a string variable containing name of the project)
        scope=defectType.getAttributeDefinition("Scope.Name");
        FilterTerm toDoTerm = Query.term(scope);
        toDoTerm.Equal(project);

Now i want to add one more condition, list only those defects that have been changed in last 24 hours.
I checked the versionone api but could not find any relevant java source code/example or function name.
How can i add conditions like "and" or "or" ?

A: You can use the GroupFilterTerm to concatenate filters (And or Or) like this:
FilterTerm toDoTerm = new FilterTerm(nameAttribute);
toDoTerm.equal(project);
FilterTerm dateFilter = new FilterTerm(dateAttribute);
Calendar c = Calendar.getInstance();
dateFilter.lessOrEqual(c.getTime());

GroupFilterTerm groupFilter = new AndFilterTerm(toDoTerm, dateFilter);
Collection<IAttributeDefinition> attributesToQuery = new LinkedList<IAttributeDefinition>();
attributesToQuery.add(nameAttribute);
attributesToQuery.add(dateAttribute);
query = new Query(storyAsset.getOid().getMomentless(), true);
query.getSelection().addAll(attributesToQuery);
query.setFilter(groupFilter);

In this example I am querying Defects that are in a specific project, and where the Defect ChangeDate (dateAttribute) value is less than or equal to today.
You´ll need to take into account how Java handles Date variables when you do the comparison.


text:
Q: Creating python calculator using python handling i've been training in python for a month now (i'm still noobish), and i'm with this project where i want to create calculator using python handlin (.txt files).
I know how to create a calculator (program) in python, no problems there, but i've encountered problem using .txt files.
So, i have .txt file called expression.txt that contains following:
9-1
6-3
So, it consists out of a number (9), operator (minus -), and number again (1).
I need to create a program that reads this expressions, and writes it and its result in a seperate file called result.txt
result.txt should look like this:
9-1=8
6-3=3
This is where i'm stuck, so im really hopeing that someone could give me a push.
class Calculator:

   def sub(self,a,b):

     return a - b

 with open('./expression.txt', 'r') as f:

   lines = f.readlines()

     for l in lines:

        if l[1] == '-':

           print(Calculator.sub(int(l[0]), int(l[2])))

     with open('./result.txt', 'w') as f2:

       f2.write('Test')

    with open('./result.txt', 'r') as f3:

      print(f3.read())

Thanks lads!

A: I'm relatively new to python but this is my shot at your problem;
class Calculator:

    def __init__(self, a, b):
        self.substraction = a - b

    def sub(self):
        return self.substraction

with open('./expression.txt', 'r') as f:

    for line in f.readlines():
        if line[1] == '-':

            with open('./result.txt', 'a') as file:
                file.write(f"{line[0]}-{line[2]}={Calculator(int(line[0]), int(line[2])).sub()}\n")

I made some changes to your Calculator class but it's far from optimal, I focused more on the writing into your results file aspect of the problem.
Your main issue is that you're opening your results file in write mode, which overwrites the text file completely, so by the time you reach your next calculation, you'll be deleting the results from the previous one.
This is probably not the best answer but it'll definitely set you off into the right direction.

A: class Calculator:
def __init__(self, a, b):
    self.substraction = a - b

def sub(self):
    return self.substraction

with open('./expression.txt', 'r') as f:
for line in f.readlines():
    if line[1] == '-':

        with open('./result.txt', 'a') as file:
            file.write(f"{line[0]}-{line[2]}={Calculator(int(line[0]), int(line[2])).sub()}\n")


text:
Q: Router behind router network setup My relative has bought a router instead of a switch which causes remote-access control issues on his network.
His existing network has a 1st router where all PCs are connected via LAN cables. The 2nd router connnects to the 1st router and the remaining PCs are connected to the 2nd router via LAN cables.
Normally, I would perform remote-access to help him out with some task. Now it seems all services behind the 2nd router are unavailable to me.
How can I resolve this issue?

A: Put the edge router into bridge mode, Disable DHCP and configure the second to function as  the DHCP server/port forwarder. Sometimes this option isn't available in consumer grade router/modems so your relative may find it easier to return the router and purchase a switch. Also keep in mind that even though having two routers on your network technically works, it really is wrecking bandwidth throughput due to a double NAT situation.


text:
Q: How to tokenize a text using RSyntaxText TokenMaker? I would like to just tokenize a text using RSyntaxtText's TokenMaker class. TokenMaker.getTokenList looks promising, however it only works for a single line and I'm a little bit worried that tokenizing a complete file isn't just calling this method for every line of the file (multi-line comments, opening/closing curly-braces, ...).
How would a minimal portion of code look like which properly tokenizes e.g. a Java file?


text:
Q: angular - catch backspace press I am trying to catch backspace press via ngKeypress, ngKeydown and ngKeyup,follwing  How can I detect keydown or keypress question.
Here is my HTML:
<input
       name="inputText"
       type="text"
       class="{{schema.class.control_part_class}} form-control"
       data-ng-model="data[schema.model]"
       ng-keydown = "changeInput($event)">
</input>

And directive link function:
scope.changeInput = function(e){
     $log.log('scope', scope); //scope
     $log.log('cont', controller); //controller
     $log.log(e); //works for any other key
     if(e.keyCode === 8){
         //keycode for backspace
         $log.log('backspace')
     }
};

I have tried replacing between ngKeypress, ngKeydown and ngKeyup and none of them work.
Entire code:
html

                *
                {{::schema.name}}

                <input
                    name="inputText"
                    type="text"
                    class="{{schema.class.control_part_class}} form-control"
                    data-ng-model="data[schema.model]"
                    data-ng-model-options="{ debounce: 300 }"
                    data-ng-disabled="{{::schema.disabled}}"
                    ng-keydown = "changeInput($event)"></input>

directive:
(function () {
    'use strict';

    function IsrTextField($log, $compile, $templateRequest) {
        $log = $log.getInstance('IsrTextField.directive', true);
        $log.debug("load()");

        var _templateUrl = 'common/directives/isr-text-field/templates/isr.text.field.tpl.html';
        var _inputElement = null;

        function _link(scope, iElem, iAttrs, controller) {
            $log.log('scope input', scope);
            function _onBlur() {
                $log.debug("_onBlur()");
                controller.eventRunner(controller.schema.events.on_blur.action, {
                    item: controller.schema.events.on_blur.args
                });
            }
            scope.changeInput = function(e){
                 $log.log('scope', scope); //scope
                 $log.log('cont', controller); //controller
                 $log.log(e); //works for any other key
                 if(e.keyCode === 8){
                    //keycode for backspace
                    $log.log('backspace')
                 }
             };

            //1. request template from server
            // Load the html through $templateRequest
            $templateRequest(_templateUrl)
                .then(function success(html) {
                    // Convert the html to an actual DOM node
                    var template = angular.element(html);
                    // Append it to the directive element
                    iElem.append(template);

                    // 1. get input element from template
                    _inputElement = $('.form-control', iElem);
                    if (!_inputElement) {
                        $log.warn("there is no .form-control element class");
                        return;
                    }

                    // set template attributes from schema (before compile)
                    if (controller.schema.modelOptions) {
                        _inputElement.attr("data-ng-model-options", controller.schema.modelOptions);
                    }

                    // set events/bind from schema
                    if (controller.schema.events && controller.schema.events.on_blur) {
                        if (controller.schema.events.on_blur.action) {
                            _inputElement.on('blur', _onBlur);
                        }
                    }

                    // And let Angular $compile it
                    $compile(template)(scope);
                }, function failure(error){
                    $log.error(error);
                });

            // cleanup
            scope.$on('$destroy',
                function destroy() {
                    $log.debug("destroy()");
                    if (_inputElement) {
                        _inputElement.off('blur', _onBlur);
                        _inputElement = null;
                    }
                });

        }

        var directive = {
            restrict: 'EA',
            scope: {
                schema: '=',
                data: '='
            },
            controller: 'isrTextFieldController',
            controllerAs: 'vm',
            bindToController: true,
            link: _link
        };

        return directive;

    }

    angular
        .module('common')
        .directive('isrTextField', IsrTextField);

})();

A: In a Controller
I wrote a clean example of your code and it seems to work.
JavaScript:
angular.module('myApp', [])
  .controller('TestController', TestController);

function TestController($scope, $log) {
  $scope.changeInput = function(e) {
    $log.log('scope', $scope); //scope
    $log.log(e); //works for any other key
    if (e.keyCode === 8) {
      //keycode for backspace
      $log.log('backspace');
    }
  };
}

HTML:

  <input name="inputText"
         type="text"
         ng-keyup="changeInput($event)">

JSFiddle: http://jsfiddle.net/wcws0ubm/1/

In a directive
If you want to encapsulate the <input> into a directive, you can use the following code:
HTML:

  <test-element></test-element>

JavaScript:
angular.module('myApp', [])
  .controller('TestController', ['$log', TestController])
  .directive('testElement', ['$log', testElement]);

function TestController($log) {
  $log.log("Controller loaded");
}

function testElement($log) {
  return {
    restrict: 'E',
    template: '<input name="inputText" type="text" ng-keyup="changeInput($event)">',
    link: function(scope) {
      scope.changeInput = function(e) {
        $log.log('scope', scope); //scope
        $log.log(e); //works for any other key
        if(e.keyCode === 8) {
          //keycode for backspace
          $log.log('backspace');
        }
      }
    }
  };
}

JSFiddle: http://jsfiddle.net/wcws0ubm/3/

A: With Angular 2+ you can bind the Backspace event directly on the element with keydown/keyup.
Using Special Modifier Keys and Combinations
This feature works for special and modifier keys like Enter, Esc, Shift, Alt, Tab, Backspace, and Cmd:

Key(s)
Key Name

Enter
<input (keydown.enter)="...">

Esc
<input (keydown.esc)="...">

Shift
<input (keydown.shift)="...">

Alt
<input (keydown.alt)="...">

Tab
<input (keydown.tab)="...">

Backspace
<input (keydown.backspace)="...">

Ctrl
<input (keydown.control)="...">

Cmd
<input (keydown.meta)="...">

But it also works for letters, numbers, arrows, and functional keys (F1 through F12):

Key(s)
Key Name

A
<input (keydown.a)="...">

9
<input (keydown.9)="...">

↑
<input (keydown.arrowup)="...">

F4
<input (keydown.f4)="...">

Source: https://www.digitalocean.com/community/tutorials/angular-binding-keyup-keydown-events


text:
Q: Ajax post returning data to address bar So I'm having an issue with ajax POST where it is returning the data to the address bar as if it's doing a get request but I've only every specified to do a POST. The funny thing is, this code was working when I pushed it to my git repo. I noticed the issue when I was testing a new commit, so I then reverted to this commit and the issue is appearing when before, it was not.
example return- http://localhost:50922/Agency?id=0&createdbytype=&lastupdatedbytype=&created=01%2F01%2F0001+00%3A00%3A00&lastupdated=01%2F01%2F0001+00%3A00%3A00&name=100test&address1=test&address2=test&address3=test&town=test&countyid=1&postcode=test&telephoneno=54252636&
My submit javascript function
function SubmitForm(form) {
        if ($(form).valid()) {
            $.ajax({
                type: "POST",
                url: form.action,
                data: $(form).serialize(),
                success: function(data) {
                    if (data.success) {
                        Popup.dialog('close');
                        dataTable.ajax.reload();

                        $.notify(data.message,
                            {
                                globalPosition: "bottom center",
                                className: "success"
                            });
                    }
                }
            });
        }
        return false;
    }

My form designator
<form>
@using (Html.BeginForm("AddOrEdit", "Agency", FormMethod.Post, new {onsubmit = "return SubmitForm(this)"}))

On post the form should run that piece of JS above but it only ever does a get request and as I said previously, this code was working.
The POST should post the data to a method in my controller but it never gets that far now. I've tried debugging from the top of the submit JS and as soon as I open the page, the first thing the debugger gets to is here:
function Delete(id) {
        if (confirm("Are you sure you wish to delete this item?")) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("Delete", "Agency")/'+id, //<- here
                success: function(data) {
                    if (data.success) {
                        dataTable.ajax.reload();

                        $.notify(data.message,
                            {
                                globalPosition: "bottom center",
                                className: "success"
                            });
                    }
                }
            });
        }
    }

Specifically
url: '@Url.Action("Delete", "Agency")/'+id,

The delete function however is working fine. It changes a boolean for the id passed as it is a soft delete where a tuple is marked as either deleted or not deleted.
I'm completely lost on why this issue is occuring. Any help is very much appreciated.

A: You have your BeginForm() inside a <form> element (nested forms are invalid html), and its the outer form (which by default is a GET) which is submitting,  not the inner form (and as a consequence your SubmitForm() script is never executed).
Remove the outer <form> form element.


text:
Q: Cannot access a disposed object when injecting DbContext through Azure Function I am receiving the following error when trying to inject the DbContext into an Azure Function:
Microsoft.EntityFrameworkCore: Cannot access a disposed object.

Here is the current function
    private readonly FundCentreContext _fundCentreContext;

    public GetDailyPrices(FundCentreContext fundCentreContext)
    {
        _fundCentreContext = fundCentreContext;
    }
    [Produces("application/json")]
    [FunctionName(nameof(GetDailyPrices))]
    public IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "api/dailyprices")] HttpRequest req,
        ILogger log)
    {

        //Parameters
        var parameters = req.GetQueryParameterDictionary();

        var page = int.Parse(parameters.GetValueOrDefault("page", "0"));
        var limit = int.Parse(parameters.GetValueOrDefault("limit", "10"));
        var offset = int.Parse(parameters.GetValueOrDefault("offset", "0"));
        var sort = parameters.GetValueOrDefault("sort", "asc");

        var fundService = new FundService(_fundCentreContext);

        var fundDailyPrices = fundService.GetAllDailyPricesByPage(page, limit, offset);

        return fundDailyPrices != null
            ? (ActionResult)new OkObjectResult(fundDailyPrices)
            : new BadRequestObjectResult("There was an error with your request");
    }

And also the StartUp to use the service has the following code:
services
    .AddDbContext<FundCentreContext>(options =>
        options.UseSqlServer("*ommited*"));

I can't work out why this error is occuring - debugging past the return statement works, and data can be seen in the fundDailyPrices object, however something after the return statement ends the whole function unexpectedly.

A: It's hard to tell with the code you've provided, but the most likely culprit is that you aren't materializing the result set until the context has gone out of scope. Again, we can't see all the code, but this happens when you do things like return an IQueryable directly. Any type of service call should return a materialized list (i.e. call ToList() or ToListAsync() on the result set before returning). It might also be caused by lazy-loading, if you've enabled that feature. If so, yo should make sure that all necessary relationships are eagerly loaded.
It's also weird that you're newing up your service with an injected context. You should simply inject your service, and since it has a constructor dependency on your context, that will be automatically injected into it. That ensures that both objects are operating in the same, or at least compatible, lifetime.
Also, don't use IDisposable with injected dependencies. We can't tell anything about your service class, but if it does implement IDisposable, remove that.


text:
Q: Change event called when changing element value IE 11/Angular I've created an directive to work with files. When I change the file or select a new one I call this code:
element.val('');
I'm doing this to be able to remove the selected file and select the same after that. If I don't do this, when I delete the selected file and select the same again, then the change event won't be called and I can't do what I need to do.
I just need to know if there is a way of avoid IE to call the change event when I change the value of the input.
I searched a little bit and found comments like this:
The onchange event on textboxes and textarea elements only fires when the element loses focus, and if its value is now other than its value when it got focus.
So, this change event was not supposed to be called when I just change de value programatically.
Any ideas?
EDIT:
I've created a jsfiddle with the behaviour

A: It seems that element.val('') emit a new change event, causing multiple calls to your listener. That said, you can avoid this weird behavior by checking the input value like the following:
element.bind('change', function(){
    if(!element.val()) {
      return;
    }
    element.val('');
    // code goes here
});


text:
Q: How to say to hibernate that I really have transient entity? I have entity O, it contains entity C and C contains Set<A>. I know that O and it's "subentities" are transient. When I call session.save(O) hibernate will check if C and every A entity doesn't exist, because they have keys already filled in (not generated on database, also not generated through custom IdentifierGenerator.
Is there any chance to force hibernate not to check the state of these entities? I know if they are without keys (key columns are null) then it will know that only insert into ... is needed. But if I save that entity with null keys, I would not know how to generate their values.

A: If C holds the foreign key to O and O is not mapped as cascading save or updates for C, hibernate should not check if C or Set<S> is persistent or transient when you call session.save(O).


text:
Q: Non-null field is null with Glide I use glide in my Kotlin project.
Currently, Java and Kotlin are mixed.
And I saw crash report from below code. (Not always but some user have this issue)
Glide.with(view.context)
                .load(HoianImage(images[position].file()))
                .asBitmap()
                .dontAnimate()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .listener(object : RequestListener<HoianImage, Bitmap> {
                    override fun onException(e: Exception, model: HoianImage, target: Target<Bitmap>, isFirstResource: Boolean): Boolean {
                        hideProgressBar(progressBar)
                        return false
                    }

                    override fun onResourceReady(resource: Bitmap, model: HoianImage, target: Target<Bitmap>, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean {
                        hideProgressBar(progressBar)
                        return false
                    }
                }).into(imageView)

The hideProgressBar() method signature is like below.
private fun hideProgressBar(progressBar: ProgressBar?) {
        progressBar?.visibility = View.GONE
    }

And the following is my crash report.
Exception java.lang.IllegalArgumentException: Parameter specified as non-null is null: method hsa.a, parameter e
com.towneers.www.ui.adapter.ImageViewAdapter$instantiateItem$1.onException$6f56094 (ImageViewAdapter.java:88)
com.towneers.www.ui.adapter.ImageViewAdapter$instantiateItem$1.onResourceReady$25390db0 (ImageViewAdapter.java:88)
com.bumptech.glide.request.GenericRequest.onException (GenericRequest.java:547)
com.bumptech.glide.load.engine.EngineJob.handleExceptionOnMainThread (EngineJob.java:183)
com.bumptech.glide.load.engine.EngineJob.access$200 (EngineJob.java:22)
com.bumptech.glide.load.engine.EngineJob$MainThreadCallback.handleMessage (EngineJob.java:204)
android.os.Handler.dispatchMessage (Handler.java:98)
android.os.Looper.loop (Looper.java:154)
android.app.ActivityThread.main (ActivityThread.java:6776)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1496)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1386)'

I also attached Proguard mapping file.
com.towneers.www.ui.adapter.ImageViewAdapter$instantiateItem$1 -> hsa:
    com.towneers.www.ui.adapter.ImageViewAdapter this$0 -> a
    android.widget.ProgressBar $progressBar -> b
    88:88:boolean onException$6f56094(java.lang.Exception,java.lang.Object,com.bumptech.glide.request.target.Target) -> a
    1090:1091:boolean onException$4d4a0d67(java.lang.Exception,com.towneers.www.core.glide.HoianImage,com.bumptech.glide.request.target.Target):90:91 -> a
    1090:1091:boolean onException$6f56094(java.lang.Exception,java.lang.Object,com.bumptech.glide.request.target.Target):88 -> a
    88:88:boolean onResourceReady$25390db0(java.lang.Object,java.lang.Object,com.bumptech.glide.request.target.Target) -> a
    1095:1096:boolean onResourceReady$19e372f5(android.graphics.Bitmap,com.towneers.www.core.glide.HoianImage,com.bumptech.glide.request.target.Target):95:96 -> a
    1095:1096:boolean onResourceReady$25390db0(java.lang.Object,java.lang.Object,com.bumptech.glide.request.target.Target):88 -> a
    88:88:void <init>(com.towneers.www.ui.adapter.ImageViewAdapter,android.widget.ProgressBar) -> <init>

A: According to the Glide docs the parameter e (the Exception) might be a null. In your Kotlin implementation however the parameter is marked as non-optional. And this causes a (runtime) crash when the method gets called with a null.
Fix in this case would be to change the signature of the onException function to:
override fun onException(e: Exception?, model: HoianImage, target: Target<Bitmap>, isFirstResource: Boolean): Boolean

Note the questionmark added.
Kotlin makes all paramters non-optional when implementing interfaces/methods. It only adds the ? when the method in the Java interface has a @Nullable annotation on it. It happens quite a lot when implementing Java/Android interfaces in Android.


text:
Q: Fast method for Nth Squarefree number (using mathematica) I am trying to compute Nth Squarefree numbers using Mathematica. What I am trying to utilize is the SquareFreeQ[i] function.
Here is my solution :
NSqFree[N_] :=
 For[n = 1; i = 1, n <=  N + 1,
  If[SquareFreeQ[i], If[n == N, Print[i] ] n++] i++]
But I am supposed to compute NSqFree[1000000000] but seems like my approach is taking for ever. Any faster method ?
Thanks,
ADDED:
Here an exactly identical topcoder question and the corresponding editorial for the same.

A: You have to us the Inclusion-Exclusion principle: suppose you want to find the number of square free numbers up to $N$, then from $N$ you have to substract the number of integers divisible by the square of a prime, but then you have to add any multiple of the square of the product of two discinct primes and so on, in formulas the number looked for is
$$ N - \sum_{p^2 \le N} \left\lfloor\frac{N}{p^2}\right\rfloor + \sum_{p^2q^2 \le N} \left\lfloor\frac{N}{p^2q^2}\right\rfloor - \sum_{p^2q^2r^2 \le N} \left\lfloor\frac{N}{p^2q^2r^2}\right\rfloor + \cdots -\cdots $$
using the moebius $\mu$ function you can write this last formula as
$$ \sum_{n \le \sqrt{N}} \mu(n) \left\lfloor\frac{N}{n^2}\right\rfloor $$
I don't know how to write this in mathematica but it should take a negligible fraction of the time it takes your current method.

A: You won't do a billion (if I counted the zeros right) loops any time soon, so you need a better approach.  Wikipedia has an approximation under the section Distribution of square-free numbers.  So you could start with $10^9 \pi^2/6$ and calculate how many below that are square-free, then correct from there.  You will need to use inclusion/exclusion, but there are only about 40,000 to consider.

A: I'm not an expert of number-theoretic algorithms, but it seems to me that you can employing the Chinese Remainder Theorem to obtain a decent first stab at a "sieving" algorithm.

*

*Use several registers r[p], each storing a residue modulo p2 for some prime p. Define such a register for various small primes p ∈ {2, 3, 5, ... , P} for some suitably large prime P. You will use these to represent an integer R, such that R ≡ r[p] (mod p2). You shouldn't need too many such registers to faithfully represent even reasonably large non-negative numbers (the registers can uniquely determine any integer from 1 to 22 × 32 × 52 × ... × P2).

*Whenever you wish to increment R, increment each of the registers r[p] as well. If R is square-free, none of these registers will be zero modulo the square of the appropriate prime. For sufficiently small integers N, you can even characterize N as being square-free if none of these residues are zero. Put another way, the more registers r[p] you maintain, the larger the range of square-free numbers you can automatically detect using these registers.
Suppose that you want to test for square-freeness up to some upper limit N. What do you need to test square-freeness using nothing but registers such as I've described? What you need is for any composite number less than N to have a prime factor from the list of registers that you maintain; that is, you need registers for each of the primes up to √N.
If you're going to iterate through all integers anyway, you can discover the list of primes that you need to characterize square-freeness at the same time by the Sieve of Erasthotenes, and construct the list of residues modulo squares-of-primes as you go. Any time you find a new prime P, so long as P2 < N, add P to the list of primes for which you maintain registers and initialize a register for residues modulo P2.
As Ross suggests in his answer, you can use results on the distribution of square-free numbers to obtain an upper bound for the Nth square-free number (it should grow more slowly than N ln(N) or so, in any case). This gives you an upper bound on the number of registers that you have to maintain as you search for square-free integers.
From this, you should actually be able to show a polynomial-time asymptotic upper bound on the runtime of your procedure.

A: I think that your method can be improved by sieving: if $n$ is not squarefree you don't need to check any of its multiples. Start with a reasonable estimate (like the one Ross Millikan gave) and sieve like you would do in a prime sieve.
Is this viable? I don't know! I can't program in Mathematica, but later today I'll try to implement this in Python.


text:
Q: Azure Web App - Request Timeout Issue I have and MVC5 web-app running on Azure. Primarily this is a website but I also have a CRON job running (triggered from an external source) which calls a URL (a GET Request) to carry out some house keeping.
This task is asynchronous can take up to and sometimes over the default timeout on Azure of 230 seconds. I'm regularly getting 500 errors due to this.
Now, I've done a bit of reading and this looks like it's something to do with the Azure Load Balancer settings. I've also found some threads relating to being able to alter that timeout in various contexts but I'm wondering if anyone has experience in altering the Azure Load Balancer timeout in the context of a Web App? Is it a straightforward process?

A:
but I'm wondering if anyone has experience in altering the Azure Load Balancer timeout in the context of a Web App?

You could configure the Azure Load Balancer settings in virtual machines and cloud services.
So, if you want to do it, I suggest you could deploy web app to Virtual Machine or migrate web app to cloud services.
For more detail, you could refer to the link.
If possible, you could try to optimize  your query or execution code.

A: This is a little bit of an old question but I ran into it while trying to figure out what was going on with my app so I figured I would post an answer here in case anyone else does the same.
An Azure Load Balancer (created via ANY means) which mostly comes along with an external IP Address — at least when created via Kubernetes / AKS / Helm  — has the 4 min, 240 second idle connection timeout that you referred to.
That being said there are two different types of Public IP Addresses — Basic (which is almost always the default that you probably created) and Standard.  More information on the docs: https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-standard-overview
You can modify the idle timeout see the following doc: https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-tcp-idle-timeout
That being said changing the timeout may or may not solve your problem.  In our case we had a Rails app that was connection to a database outside of azure.  As soon as you add a Load Balancer with a Public IP all traffic will EXIT that public IP and be bound by the 4 minute idle timeout.
That's fine except for that Rails anticipates that a connection to a Database is not going to be cut frequently — which in this case happens ALL the time.

We ended up implementing a connection pooling service that sat between our Rails app and our real database (called PGbouncer — specific to Postgres DBs).  That service monitored a connection and re-connected when the timer was nearing the Azure LB timeout.

It took a little while to implement but in our case it works flawlessly.  You can see some more details over here: What Azure Kubernetes (AKS) 'Time-out' happens to disconnect connections in/out of a Pod in my Cluster?
The longest timeout you can set for a Public IP / Load Balancer is 30 minutes.    If you have a connection that you would like to utilize that runs idle longer than that — then you may be out of luck.  As of now 30 mins is the max.


text:
Q: How to find solution this system of PDEs?
\begin{align} \frac{\partial}{\partial x}\psi &=-h\psi+ie^{-it}\phi &&& (1) \\
\frac{\partial}{\partial x}\phi&=h\phi+ie^{it}\psi &&& (2) \\
\frac{\partial}{\partial t}\psi&=\left(-h-\frac{i}{2}\right)\psi-he^{-it}\phi &&& (3) \\
\frac{\partial}{\partial t}\phi&=\left(h+\frac{i}{2}\right)\phi-he^{it}\psi &&& (4)
\end{align}

Solution of eqs $(1)$-$(4)$ is,
$$\psi=i\left(C_1e^A − C_2e^{−A}\right)e^{− \frac{i}{
2}t}$$
$$\phi=\left(-C_1e^{-A} + C_2e^{A}\right)e^{\frac{i}{
2}t}$$
where
$$C_1 =
\frac{\left(h − \sqrt{h^2 − 1}\right)^{1/2}}
{\sqrt{h^2 − 1}}, \qquad C_2 =
\frac{\left(h + \sqrt{h^2 − 1}\right)^{1/2}}
{\sqrt{h^2 − 1}}$$ and $$A =
\sqrt{h^2 − 1}\big(x + iht\big)$$
How to find these solutions? Anyone can help?


text:
Q: Register views with regions depending on the user rights in Silverlight We have a module class which implements the IModule interface and it has only one method Initialize() in which we register our views.
Is it possible to register these views after successful login?
I want to prohibit the registration of several views depending on the current user. But the user logs on after the module initialization.
Is there a way to provide a callback where Prism can evaluate if the registration is active? Or do I have the chance to disable registrations of the Region Manager? Any other ideas?
Thanks

A: The easiest way to communicate among multiple modules (or even within) in Prism is using the EventAggregator. Here is what I would do:

*

*Create a CompositePresentationEvent for UserLoginEvent that takes relevant parameter regarding the user

*Publish the event using IEventAggregator when the user successfully logs in

*On your module initialize, subscribe to the UserLoginEvent, in the handler register the appropriate views

*Repeat the above, but opposite, for UserLogout if desired.

In your infrastructure lib:
public class UserLoginEvent : CompositePresentationEvent<User> { }

Then in your module:
public class YourModule : IModule
{
    private readonly IUnityContainer container;
    private readonly IRegionManager regionManager;
    private readonly IEventAggregator events;

    public YourModule(IUnityContainer container, IRegionManager manager, IEventAggregator events)
    {
        this.container = container;
        this.regionManager = manager;
        this.events = events;
    }

    public void Initialize()
    {
        ....
        events.GetEvent<UserLoginEvent>().Subscribe(RegisterUserViews);
    }

    private void RegisterUserViews(User u)
    {
            // check user permissions
            // register and create views using container, regionManager
    }
}

In whatever module / code your user logs in... I assume you can get the IEventAggregator (similar to above) and then do something like:
OnUserLogin(User u)
{
    eventAggregator.GetEvent<UserLoginEvent>().Publish(u);
}

Hope this helps! if a user logs out, then you may want to store references to your views in your module and remove them on a UserLogoutEvent which would work like the above code but just doing the opposite.


text:
Q: Another exception was thrown: Null check operator used on a null value!!1 I tried to change the password in app with flutter (Firebase) but it give me and error Another exception was thrown: Null check operator used on a null value. so can someone help me fix this one.
do I need to add something to check null or remove something.
 class ChangingPasswordScreen extends StatefulWidget {
  static const routeName = '/ChangingPasswordScreen';
  //late final String? email;
  //final User user;

  //ChangingPasswordScreen({required this.user});

  @override
  State<StatefulWidget> createState() {
    return _ChangingPasswordState();
  }
}

class _ChangingPasswordState extends State<ChangingPasswordScreen> {
  final _formKey = GlobalKey<FormState>();

  var newPassword = " ";

  final newPasswordController = TextEditingController();

  @override
  void dispose() {
    newPasswordController.dispose();
    super.dispose();
  }

  final currentUser = FirebaseAuth.instance.currentUser;

  changePassword() async {
    try {
      await currentUser!.updatePassword(newPassword);
      FirebaseAuth.instance.signOut();
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => SigninScreen(),
        ),
      );
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Your Password has been changed'),
        ),
      );
    } catch (error) {}
  }

ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    setState(() {
                      newPassword = newPasswordController.text;
                    });
                    changePassword();
                  }
                },
                child: Text(
                  'Change Password',
                  style: TextStyle(fontSize: 18.0),
                ),
              ),

A: In,
await currentUser!.updatePassword(newPassword);

make sure that currentUser is not null before using !. ! indicate that the variable will never be null.
Try something like this,
if(currentUser != null){
  try {
      await currentUser!.updatePassword(newPassword);
      FirebaseAuth.instance.signOut();
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => SigninScreen(),
        ),
      );
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Your Password has been changed'),
        ),
      );
    } catch (error) {
      print("Error thrown : $error");
    }
}

Note: Never leave a catch block empty. Log the error while debugging. Handle the error properly. If you leave a catch block empty, you'll never know if it throws an Exception or not.