text:
Q: Concentration without first moment The weakest concentration inequality I know of is markov's inequality:
$$\mathbb P (X \geq t) \leq \frac{\mathbb E X}{t}$$
where $X$ is a nonnegative random variable with first moment $\mathbb E X$ and $t > 0$. Of course, this bound assumes that the first moment exists.
Is there a weaker and still useful concentration inequality than the markov inequality? Does it even make sense to talk about concentration when the first moment does not exist?
For example in the specific case of a cauchy, I know that the measure concentrates around $0$, but I don't know of a useful bound on the measure far away from this concentration point that applies to general random variables without finite first moments.
EDIT: naively, I could imagine the existence of finite "partial moments" implying weaker inequalities. By partial moments I mean: $\mathbb E X^p$ for $p < 1$ (although I dont think negative $p$ could give us concentration type properties).

A: On $\mathbb{R}$ (and Polish spaces in general) all probability measures are tight, so some kind concentration inequality always exists and can be derived directly by the tightness property. (See https://en.wikipedia.org/wiki/Tightness_of_measures)
I would also add that for any bounded function $f:\mathbb{R}\rightarrow \mathbb{R}$ and any ranom variable $X$ on $\mathbb{R}$ it always holds that $\mathbb{E}f(X) < \infty $.
If $f$ is also strictly increasing then we can always use Markov's inequality to derive the concentration bound
$$ P(X>f^{-1}(t))\leq \frac{\mathbb{E} f(X)}{t}.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Labelling individual data points gnuplot Just trying to get used to gnuplot. I searched a few pages on this site looking for the answer, read the documentation (4.6), and still haven't found the answer. say I have a data file like this:
0.0 0
1.0 25
2.0 55
3.0 110
4.0 456
5.0 554
6.0 345

and I want to label all the data points on the plot. How do I do this? I tried this suggestion plot 'exp.dat' u 1:2 w labels point offset character 0,character 1 tc rgb "blue" but it didn't work. It gave me a Not enough columns for this style response. I'm sure it's something I'm doing but I'm not sure what. Any help would be appreciated. Thanks.

A: I think you are missing strings for labels. You can do
flabel(y)=sprintf("y=%.2f", y)
plot '-' u 1:2:(flabel($2)) w labels point offset character 0,character 1 tc rgb "blue"
0.0 0
1.0 25
2.0 55
3.0 110
4.0 456
5.0 554
6.0 345


text:
Q: How to restore/import an Oracle database from dmp file? I've recently received the dump file of the soon to be migrated Oracle Database. I've installed Oracle 10g and now I need to restore the original database.
Can anyone give me a step by step procedure for how to restore it from the *.dmp file ?

A: It depends what you are trying to do but one short answer is:
imp system/password@sid file=(filename) log=imp.log fromuser=(existing user) touser=(new user)

The last 3 here: log, fromuser, touser are optional.  You might give some more details about what you are doing if that doesn't help...

A: It depends on the type of export (dump) that was done from the original database.  Oracle does four types of exports (called modes):

*

*Full

*User

*Table(s)

*Tablespace(s)

Assuming that a Full export was done, you'd do something like:
SET ORACLE_SID=dbsid
imp system/manager FULL=y FILE=database.dmp LOG=import.log STATISTICS=recalculate

Having said that, you should read through the Oracle documentation on imp.

A: Keep in mind a .dmp file could mean it was exported using exp or expdp. Run imp help=y or impdp help=y if you run into any issues.

A: I usually only restore the schemas that I want:
imp userid=SYSTEM/ART@cscdap1 fromuser=MDSBI touser=MDSBI grants=y indexes=y commit=y ignore=y buffer=10240000 file=MDSBI.dmp log=imp_MDSBI.log
imp userid=SYSTEM/ART@cscdap1 fromuser=MDS_GRS touser=MDS_GRS grants=y indexes=y commit=y ignore=y buffer=10240000 file=MDS_GRS.dmp log=imp_MDS_GRS.log
imp userid=SYSTEM/ART@cscdap1 fromuser=ODM touser=ODM grants=y indexes=y commit=y ignore=y buffer=10240000 file=ODM.dmp log=imp_ODM.log
imp userid=SYSTEM/ART@cscdap1 fromuser=ODIWORK touser=ODIWORK grants=y indexes=y commit=y ignore=y buffer=10240000 file=ODIWORK.dmp log=imp_ODIWORK.log
imp userid=SYSTEM/ART@cscdap1 fromuser=ODIMASTER touser=ODIMASTER grants=y indexes=y commit=y ignore=y buffer=10240000 file=ODIMASTER.dmp log=imp_ODIMASTER.log
imp userid=SYSTEM/ART@cscdap1 fromuser=EPADMRT touser=EPADMRT grants=y indexes=y commit=y ignore=y buffer=10240000 file=EPADMRT.dmp log=imp_EPADMRT.log
imp userid=SYSTEM/ART@cscdap1 fromuser=OEMUSER touser=OEMUSER grants=y indexes=y commit=y ignore=y buffer=10240000 file=OEMUSER.dmp log=imp_OEMUSER.log
imp userid=SYSTEM/ART@cscdap1 fromuser=HERNA236 touser=HERNA236 grants=y indexes=y commit=y ignore=y buffer=10240000 file=HERNA236.dmp log=imp_HERNA236.log
imp userid=SYSTEM/ART@cscdap1 fromuser=MAURYAKO touser=MAURYAKO grants=y indexes=y commit=y ignore=y buffer=10240000 file=MAURYAKO.dmp log=imp_MAURYAKO.log
imp userid=SYSTEM/ART@cscdap1 fromuser=SAWANTRO touser=SAWANTRO grants=y indexes=y commit=y ignore=y buffer=10240000 file=SAWANTRO.dmp log=imp_SAWANTRO.log
imp userid=SYSTEM/ART@cscdap1 fromuser=ABDERHOB touser=ABDERHOB grants=y indexes=y commit=y ignore=y buffer=10240000 file=ABDERHOB.dmp log=imp_ABDERHOB.log
imp userid=SYSTEM/ART@cscdap1 fromuser=CHECK_DB touser=CHECK_DB grants=y indexes=y commit=y ignore=y buffer=10240000 file=CHECK_DB.dmp log=imp_CHECK_DB.log
imp userid=SYSTEM/ART@cscdap1 fromuser=SABATAJA touser=SABATAJA grants=y indexes=y commit=y ignore=y buffer=10240000 file=SABATAJA.dmp log=imp_SABATAJA.log


text:
Q: How to compare the values $\sqrt 2$ and $\ln(3).$ How to compare the values $\sqrt 2$ and $\ln(3)?$ I know only $\ln(x)<x$ and $\sqrt{x}<x$. Please help. Thanks.

A: With simple numerical calculation we can show $\ln(3)< \frac75<\sqrt2$.
First calculate $e^{7/5}$ using the series expansion for exponential function.
Taking just three terms of the series: $e^{7/5}> 1+ 7/5 + 7^2/(2!5^2)=169/50>3$
This shows natural log for 3 is less than 7/5.
Now $7^2/5^2=49/25<2$ And we are done.

A: The trick is to look at $f(x) = \sqrt{x} - \ln(1+x)$.
Note that for $x = 1$,
$$1 - \ln(2) > 0$$
This is true since $\ln(x)$ is an increasing function and $1 < 2 < e$ implies
$$0 = \ln(1) < \ln(2) < \ln(e) = 1$$
Now look at the derivative
$$f'(x) = \frac{1}{2\sqrt{x}} - \frac{1}{x+1}$$
We would like to show that $f'(x) \ge 0$ for $x > 1$, which means $f(x)$ is increasing and must therefore be positive for $x > 1$ (since it is already positive at $x=1$ per above).
Consider the following equivalent inequalities (when $x > 1$):
$$\begin{eqnarray}
\frac{1}{2\sqrt{x}} - \frac{1}{x+1} &\ge& 0\\
\frac{1}{2\sqrt{x}} &\ge& \frac{1}{x+1}\\
x + 1 &\ge& 2\sqrt{x}
\end{eqnarray}$$
For the last inequality, $1+1 = 2 = 2\sqrt{1}$ and for $x > 1$, taking the derivatives agains shows that the left side grows at a rate of $1$ and the right side grows at the rate of $\frac{2}{2\sqrt{x}} = \frac{1}{\sqrt{x}} < 1$ when $x > 1$.
Thus the last equivalent inequality holds for $x > 1$, which implies $f'(x) \ge 0$ for $x > 1$ which implies $f(x)$ is positive for $x > 1$. In particular, $f(2) = \sqrt{2} - \ln(3) > 0$. Therefore $\sqrt{2} > \ln(3)$.

A: By the Cauchy-Schwarz inequality
$$ \log(3) = \int_{0}^{2}\frac{dx}{1+x}\leq \sqrt{\int_{0}^{2}\frac{dx}{(1+x)^2}\int_{0}^{2}dx}=\frac{2}{\sqrt{3}}\tag{1}$$
and trivially $\frac{2}{\sqrt{3}}<\sqrt{2}$, hence $\color{red}{\log(3)<\sqrt{2}}$.
The same approch shows that for any $t>0$ we have
$$ \log(t+1) < \frac{t}{\sqrt{t+1}}\tag{2} $$
$$ \log(t+1) < \frac{2\sqrt{t+1}-2}{(t+1)^{1/4}}\tag{3} $$
and the inequalities are pretty tight if $t$ is close to zero.
For instance, $(3)$ immediately proves $\color{red}{\log(4)<\sqrt{2}}$.

Addendum. A nice alternative is provided by Beuker-type integrals. We have $\log(3)=\int_{0}^{1}\frac{4\,dx}{4-x^2}$ and
$$ \int_{0}^{1}\frac{4x^4(1-x^2)^4}{4-x^2}\,dx = 1296\log(3)-\frac{109632}{77}\tag{4}$$
is bounded between $0$ and $\frac{1}{40}$. It follows that $\log(3)\approx \frac{2284}{2079}=[1; 10, 7, 14, 2]$ is clearly less than $\sqrt{2}=[1;2,2,2,2,\ldots]$, by using the typical notation for continued fractions.

A: "Argument" 1
Compute: $\sqrt{2}\approx 1.41421356237$ (source) and $\ln(3) \approx 1.09861228867$ (source)
There's no way floating point arithmetic is that inaccurate, so the desired inequality is true by direct computation. :)
But beware floating point arithmetic when you desire high levels of precision!
$python
>>> .1 + .2 == .3
False
>>> .1 + .2
0.30000000000000004

Argument 2
Surely we can do better than a black box calculator. Motivated by how a calculator might carry out a direct computation, we argue via numerical approximation ...
As the exponential function is monotone, the desired comparison is equivalent to comparing $e^{\sqrt{2}}$ to $3$. The number $3$ is easy to compute, so we focus on the left side of the equation. From the calculator, we suspect that $e^\sqrt{2} > 3$, so we are led to truncate the exponential series:
\begin{align*}
e^\sqrt{2} &= 1 + \sqrt{2} + \frac{1}{2!}\sqrt{2}^2 + \frac{1}{3!}\sqrt{2}^3 + \cdots \\
&\geq 1 + \sqrt{2} + \frac{1}{2}\sqrt{2}^2 \\
&= 2 + \sqrt{2} \\
&> 2 + 1 \\
&= 3
\end{align*}

Argument 3
Motivated by graphing the functions:

The square root starts ahead of the logarithm and doesn't look back -- it not only is greater, its rate of increase is also greater, and so we can reason from their derivatives.
Let $F(x) = \sqrt{x}$ and $G(x) = \ln(1+x)$. Notice that both functions are smooth on $(0,\infty)$ and have
$$F(x) = \int_0^x\frac{1}{2\sqrt{t}}\ dt$$
and
$$G(x) = \int_0^x \frac{1}{t+1}\ dt $$
Now observe that
$$ 2\sqrt{t} \leq t+1 $$
with equality achieved at $t=1$, as $2\sqrt{t}$ is concave down and the function $t\mapsto t+1$ is the equation of the tangent line of $2\sqrt{t}$ at $t=1$.
Therefore $\frac{1}{2\sqrt{t}} \geq \frac{1}{t+1} > 0$ for all $t>0$. As integrating positive functions preserves inequality, we have $F(x) \geq G(x)$ for all $x>0$. In particular, $F(2) \geq G(2)$, so $\sqrt{2}\geq \ln(3)$.

A: Here's another series argument:
Use the fact that $\sqrt{1+x} = 1 + \frac{x}{2} - \frac{x^2}{8} + \frac{x^3}{16} -\cdots$ and $\ln(2+x) = \ln 2 + \frac{x}{2} - \frac{x^2}{8} + \frac{x^3}{24} \cdots$. The first expansion is obtained by successfully differentiating $(1+x)^n$ and substituting $0$ with $n = \frac{1}{2}$.
Then $\sqrt{2} - \ln 3$ equals:
$$\left(1 + \frac{1}{2} - \frac{1}{8} + \frac{1}{16} \cdots \right) - \left(\ln2
 + \frac{1}{2} - \frac{1}{8} + \frac{1}{24} \right)$$
$$=\frac{49}{48} - \ln 2$$
and approximating $\ln 2$ as $1 - \frac{1}{2} + \frac{1}{3} - \frac{1}{4} = \frac{7}{12}$, we have:
$$\frac{49}{48} - \frac{7}{12} = \frac{7}{16} $$
The Lagrange error bound for $\sqrt{1+x}$ is:
$$|R_n| ≤ \frac{|1/16|(1-0)^4}{4!} \Rightarrow |R_n| ≤ \frac{1}{384} (\approx 0.0026)$$
and the Lagrange error bound for $\ln(1+x)$ is:
$$|R_n| ≤ \frac{|1/24|(1-0)^4}{4!} \Rightarrow |R_n| ≤ \frac{1}{576} (\approx 0.0017)$$
Meanwhile, the maximum error for approximating $\ln 2$ to order $x^4$ is:
$$|R_n| ≤ \frac{|-1/4|(1-0)^5}{5!} \Rightarrow |R_n| ≤ \frac{1}{480} (\approx 0.0021)$$
In the worst possible scenario, adding up all these errors gets nowhere near $\frac{7}{16}$. Therefore $\sqrt{2} - \ln 3 > 0$ and $\sqrt{2} > \ln 3$.

A: We have $\exp(\sqrt 2)= \sum\limits_{n=0}^{+\infty} \frac{(\sqrt 2)^n}{n!}$, then, $\exp(\sqrt 2) \geq 1+\sqrt 2 + \frac{(\sqrt{2})^2}{2}=2+\sqrt 2  > 3$, then $\sqrt 2  > \ln 3$.


text:
Q: jQuery UI autocomplete add selected item's description to a text field I have the following for an autocomplete text box which works fine:
 $('#material_number').autocomplete({
     source: function(request, response) {
         $.ajax({
             url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
             dataType: "json",
             data: {
                 search: request.term,
                 maxRows: 10
             },
             success: function(data) {
                 response(data);
                 console.log();
                 //need to append material_description to a textbox here
             }
         })
     }
 });

What i am trying to to is output the material_description value returned to a textbox called txtMaterialDescription. I have looked at different examples on this site but unable to get it to work. So when the user selects a part number from the autosuggest list, the description field populates the part number description. Can anyone help me out and point me in the right direction please?
many thanks as always.
JC

A: You need to trap the focus or select event:
focus: function(event, ui) {
    $("#textbox").val(ui.item.someProperty);
}

Now, if your JSON data consists of objects that look like {label: ..., value: ..., someProperty: ...} then you can write:
source: function(request, response) {
    $.ajax({
        url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
        dataType: "json",
        data: {
            search: request.term,
            maxRows: 10
        },
        success: response
    });
}

Otherwise, you can always transform your data using jQuery.map:
source: function(request, response) {
    $.ajax({
        url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
        dataType: "json",
        data: {
            search: request.term,
            maxRows: 10
        },
        success: function(data) {
            response($.map(data, function(item) {
                return {
                    label: item.productName,
                    value: item.productCode,
                    someProperty: item.productDescription + item.productPrice
                }
            }));
        }
    });
}

A: you can use focus option and load details for a focused item like
   focus: function(event, ui) {
            $(this).val(ui.item.label);

 //do ajax call here  for currently focused element
  // and on sucesss you can do the following

  //add your detail description here
            $("#tags").empty();
            $("#tags").append("Detailed for "+ui.item.label);

            return false;
        },

For a detailed explanation you can look here -jquery autocomplete example


text:
Q: Message : Element is not reachable by keyboard How can I solve this problem on Python Selenium : Element is not reachable by keyboard ??
I couldn't use the send_keys("xxx")

A: I would advise you to launch screen in full mode :
driver.maximize_window()

and then use ActionChains like below :
ActionChains(driver).move_to_element(driver.find_element_by_xpath("//input[@name='instance/header/number' and @datatype='string' and @onkeyup='handleOnChange(this, event);']")).send_keys("XXXX").perform()

you will need to import the below for actions chain  :
from selenium.webdriver.common.action_chains import ActionChains


text:
Q: Refresh tokens by example using Angular and Spring Boot I am designing out an app that would have an Angular frontend and Spring Boot (Java) backend.
I was considering (but not married to) the prospect of JWT-based authentication:

*

*User logs in with username and password and submits a form; this form POSTS to, say, /auth/sign-in

*A Spring Security filter checks to see if the username and password are valid, and if so, generates a JWT with a reasonable (say, 15 minute) expiry and returns the JWT as a response header

*Angular client then reuses this JWT until it expires, at which point, Spring Security will send back a specific 400-level error code which will prompt the Angular frontend to redirect the user to the login page and log back in

This is pretty straightforward to implement, but will be a bad UX for my users (if they have to log back in every 15 minutes).
Instead I'm thinking of something along these lines:

*

*Maintain an in-memory cache of some kind mapping each unique user ID to the last activity timestamp (a timestamp representing the last activity they were doing; basically the last time that user did anything in the app that resulted with a call to the backend being made) --> userActivityMap : Map<User,Date>

*Every time the user (via the Angular client) does anything in the app that prompts Angular to make a call to the backend, this user activity map is updated with the current timestamp

*User logs in with username and password and submits a form; this form POSTS to, say, /auth/sign-in

*A Spring Security filter checks to see if the username and password are valid, and if so, generates a JWT with a reasonable (say, 15 minute) expiry and returns the JWT as a response header

*Angular client then reuses this JWT until it expires, at which point, the Spring Security filter that detected it as being expired subsequently consults the user activity map. If the user has been active within the last, say, 15 minutes, then a new JWT "refresh token" is generated for the user and sent back to the Angular client with a specific 400-level error code

*The Angular client sees this specific error code and knows to pluck the refresh token off the error response, use the value of that token as the main access token/JWT moving forward, and retries the same command with the new (refreshed) access token

I think I could get this to work, but in my Google searches to find what others have done I was surprised to see a million beginner-level "how to" articles but nothing really concrete for this use case. What are typical solutions for this given stack and the specific scenario at hand? Is my solution close to generally-accepted best practices or did I miss the mark considerably? Thanks!

A: It sounds like you're reinventing the wheel a bit here.
JWT authentication has a well-documented "protocol" already defined for this. When the user initially logs in, you provide both a bearer token and a refresh token. The bearer token is the short-living token you've already mentioned, the refresh token is a longer-living token used to get a new bearer token when the current one expires.
How you handle the refresh is up to you; you can go for a "better to ask forgiveness than permission approach" or a "look before you leap" approach. The former being waiting for a request to fail with an unauthorised status code, and then requesting a new bearer token and retrying the request. The latter being checking the exp claim of the bearer token either on an interval or before each request, and requesting a new token when you're within a specified threshold of the expiration time.
JWT authentication is a fairly loose concept, you can implement the client and server sides in a way that meets your requirements, but sticking to a bearer + refresh token approach is definitely recommended.
Whether you cache the refresh token or save it in a database is up to you. Keep in mind, caching introduces a lot of complexity when it comes to blacklisting refresh tokens for recently blocked users.
There are third-party solutions available such as AWS Cognito that you could use. They're far from perfect, but I would consider all options available if I were you.


text:
Q: JS from a JS Fiddle not working in browser test I have been trying to implement this cool little Expand/Collapse js function I discovered on JS Fiddle, but can't get it to work in a browser test. Could anyone offer a suggestion on what needs to be corrected?
Probably should know this, but as I'm new to Javascript I am stuck. Thanks for your time.
Here's all the code as I've currently set it up:
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<link rel="stylesheet" href="css/teststyle.css">

Expand

This is just some random content.

This is just some random content.

This is just some random content.

This is just some random content.

CSS
@charset "utf-8";
/* CSS Document */

.container {
    width:100%;
    border:1px solid #d3d3d3;
}
.container div {
    width:100%;
}
.container .header {
    background-color:#d3d3d3;
    padding: 2px;
    cursor: pointer;
    font-weight: bold;
}
.container .content {
    display: none;
    padding : 5px;
}

JS
// JavaScript Document

$(document.ready()());
    $(".header").click(function () {

    $header = $(this);
    //getting the next element
    $content = $header.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //execute this after slideToggle is done
        //change text of header based on visibility of content div
        $header.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});

A: The way you've created your "document.ready" function is not correct.
You can use the correct way:
$(document).ready(function() {
     // here goes your code
});

Or much simples (like my example below):
$(function() {
    // here goes your code
});

Try to change your Javascript file to this:
$(function() {
    $(".header").click(function () {
        $header = $(this);

        //getting the next element
        $content = $header.next();

        //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
        $content.slideToggle(500, function () {
            //execute this after slideToggle is done
            //change text of header based on visibility of content div
            $header.text(function () {
                //change text based on condition
                return $content.is(":visible") ? "Collapse" : "Expand";
            });
        });
    });
});

A: Your document ready wan't called/nested correctly. Try the following:
$(document).ready(function() {
  $(".header").click(function () {

    $header = $(this);
    //getting the next element
    $content = $header.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //execute this after slideToggle is done
        //change text of header based on visibility of content div
        $header.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

  });
});

A: It's your js call to $(document).ready. Change your code to:
$(document).ready(function () {
    $(".header").click(function () {
        $header = $(this);
        //getting the next element
        $content = $header.next();
        //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
        $content.slideToggle(500, function () {
            //execute this after slideToggle is done
            //change text of header based on visibility of content div
            $header.text(function () {
                //change text based on condition
                return $content.is(":visible") ? "Collapse" : "Expand";
            });
        }); rantFormViewModel.wireEvents();
    });
});

and everything will work like you want it to.


text:
Q: Print 'hashtags' from JSON to CSV file using Python I'm a beginner using the following code:
f = open("singletweetwithtimezone.json", "r")
tweet_text = f.read()

import json

tweet_json = json.loads(tweet_text)

g = open("Singletweetcsvoutput.csv", "w")

g.write(tweet_json["created_at"]+"\t")
g.write(tweet_json["user"]["time_zone"]+"\t")
g.write(tweet_json["entities"]["hashtags"]["text"])

g.close()
f.close()

The writing works, except for the hashtags. I want it to write the text 'messi' in the CSV file, but I can't figure out what I'm doing wrong, due to a lack of knowledge. I get the following error:
g.write(tweet_json["entities"]["hashtags"]["text"])
TypeError: list indices must be integers, not str". "

The JSON tree is shown in the image i've added:
what the tree looks like
Anyone who can help me out?
RAW JSON code:
{"created_at":"Sun Apr 23 21:04:13 +0000 2017","id":856252394233106432,"id_str":"856252394233106432","text":"RT @11FC_FR: Et \u00e0 la fin ... #Messi \n\ud83d\ude0d https:\/\/t.co\/uiyTnJJiKd","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":1628829458,"id_str":"1628829458","name":"LK20","screen_name":"KeevinGruny","location":null,"url":null,"description":"\u26bd\ufe0f\u26bd\ufe0f","protected":false,"verified":false,"followers_count":903,"friends_count":209,"listed_count":39,"favourites_count":7328,"statuses_count":59480,"created_at":"Sun Jul 28 21:50:55 +0000 2013","utc_offset":10800,"time_zone":"Athens","geo_enabled":true,"lang":"fr","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/854838667428466688\/jE52U_LU_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/854838667428466688\/jE52U_LU_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/1628829458\/1492857072","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Sun Apr 23 20:38:37 +0000 2017","id":856245950544838660,"id_str":"856245950544838660","text":"Et \u00e0 la fin ... #Messi \n\ud83d\ude0d https:\/\/t.co\/uiyTnJJiKd","display_text_range":[0,25],"source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":2617563403,"id_str":"2617563403","name":"11FootballClub","screen_name":"11FC_FR","location":"3, All\u00e9e Cassard - NANTES","url":"http:\/\/www.11footballclub.com","description":"11FootballClub est un concept store unique et une boutique en ligne soign\u00e9e. Actus foot, nouveaut\u00e9s produits, promos et jeux concours","protected":false,"verified":false,"followers_count":49693,"friends_count":24561,"listed_count":54,"favourites_count":350,"statuses_count":1268,"created_at":"Fri Jul 11 15:21:20 +0000 2014","utc_offset":-25200,"time_zone":"Pacific Time (US & Canada)","geo_enabled":true,"lang":"fr","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"A16E1E","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/648580532322836480\/2lodFucd_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/648580532322836480\/2lodFucd_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/2617563403\/1443468740","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":155,"favorite_count":92,"entities":{"hashtags":[{"text":"Messi","indices":[16,22]}],"urls":[],"user_mentions":[],"symbols":[],"media":[{"id":856245937915793408,"id_str":"856245937915793408","indices":[26,49],"media_url":"http:\/\/pbs.twimg.com\/media\/C-H_JNnXkAApCFh.jpg","media_url_https":"https:\/\/pbs.twimg.com\/media\/C-H_JNnXkAApCFh.jpg","url":"https:\/\/t.co\/uiyTnJJiKd","display_url":"pic.twitter.com\/uiyTnJJiKd","expanded_url":"https:\/\/twitter.com\/11FC_FR\/status\/856245950544838660\/photo\/1","type":"photo","sizes":{"small":{"w":680,"h":460,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":1200,"h":812,"resize":"fit"},"large":{"w":2048,"h":1386,"resize":"fit"}}}]},"extended_entities":{"media":[{"id":856245937915793408,"id_str":"856245937915793408","indices":[26,49],"media_url":"http:\/\/pbs.twimg.com\/media\/C-H_JNnXkAApCFh.jpg","media_url_https":"https:\/\/pbs.twimg.com\/media\/C-H_JNnXkAApCFh.jpg","url":"https:\/\/t.co\/uiyTnJJiKd","display_url":"pic.twitter.com\/uiyTnJJiKd","expanded_url":"https:\/\/twitter.com\/11FC_FR\/status\/856245950544838660\/photo\/1","type":"photo","sizes":{"small":{"w":680,"h":460,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":1200,"h":812,"resize":"fit"},"large":{"w":2048,"h":1386,"resize":"fit"}}}]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"fr"},"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"Messi","indices":[29,35]}],"urls":[],"user_mentions":[{"screen_name":"11FC_FR","name":"11FootballClub","id":2617563403,"id_str":"2617563403","indices":[3,11]}],"symbols":[],"media":[{"id":856245937915793408,"id_str":"856245937915793408","indices":[39,62],"media_url":"http:\/\/pbs.twimg.com\/media\/C-H_JNnXkAApCFh.jpg","media_url_https":"https:\/\/pbs.twimg.com\/media\/C-H_JNnXkAApCFh.jpg","url":"https:\/\/t.co\/uiyTnJJiKd","display_url":"pic.twitter.com\/uiyTnJJiKd","expanded_url":"https:\/\/twitter.com\/11FC_FR\/status\/856245950544838660\/photo\/1","type":"photo","sizes":{"small":{"w":680,"h":460,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":1200,"h":812,"resize":"fit"},"large":{"w":2048,"h":1386,"resize":"fit"}},"source_status_id":856245950544838660,"source_status_id_str":"856245950544838660","source_user_id":2617563403,"source_user_id_str":"2617563403"}]},"extended_entities":{"media":[{"id":856245937915793408,"id_str":"856245937915793408","indices":[39,62],"media_url":"http:\/\/pbs.twimg.com\/media\/C-H_JNnXkAApCFh.jpg","media_url_https":"https:\/\/pbs.twimg.com\/media\/C-H_JNnXkAApCFh.jpg","url":"https:\/\/t.co\/uiyTnJJiKd","display_url":"pic.twitter.com\/uiyTnJJiKd","expanded_url":"https:\/\/twitter.com\/11FC_FR\/status\/856245950544838660\/photo\/1","type":"photo","sizes":{"small":{"w":680,"h":460,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":1200,"h":812,"resize":"fit"},"large":{"w":2048,"h":1386,"resize":"fit"}},"source_status_id":856245950544838660,"source_status_id_str":"856245950544838660","source_user_id":2617563403,"source_user_id_str":"2617563403"}]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"fr","timestamp_ms":"1492981453842"}

A: Start by printing the type of each different node in the response. The error that you see is caused by the fact that you are trying to access everything in the response as it was the key of a dictionary. Thing is that hashtags, from the screenshot, could be an array, hence needs to be accessed as:
tweet_json['entities']['hashtags'][0]['text']

Hashtags contains an array, in this case the length of the array is 1 so you'd access with [0], but since the  length of these arrays is variable you should add a check for length and then do a loop a little like below. I like to use dictwriter from the csv library even if for this is an over kill, it can be used to go through several tweets.
import csv
import json

with open('.../input.json','r') as inputfile:
    tweet= inputfile.read()

tweet_json = json.loads(tweet)

with open('.../output.csv', 'w') as csvfile:
    fieldnames = ['created_at', 'user', 'hashtags']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    #extract all info that you want to write
    created_at = tweet_json['created_at']
    #selecting the screen_name of the user rather than id
    user = tweet_json['user']['screen_name']
    hashtags = tweet_json['entities']['hashtags']
    #creating an empty string for the hashtags in the array
    hashes = list()
    for hashtag in hashtags:
        text = hashtag['text']
        #append to hashes listed_count
        hashes.append(text)
    #stringify the list and write to file (will be ugly)
    writer.writerow({"created_at":created_at, "user":user,"hashtags":str(hashes) })


text:
Q: Mismatch between /reputation and epic badge tracker There is a mismatch between what /reputation shows and my badge tracker for 'epic':
days represented 1269
rep cap was reached via rep from upvotes *only* on 42 days
earned at least 200 reputation on 45 days
earned 36 reputation from suggested edits
Meanwhile, the next badge tracker for epic shows 44/50:

This appears to be caused by a user who had voted on a post of mine that was deleted (I saw a 'deleted user -10' show up in my rep history a bit ago).
So, in /reputation, it shows:
-- 2016-02-10 rep +200  = 47281
-- 2016-02-11 rep +215  = 47496

while the reputation log on the site shows:

The reason that I'm a bit below 200 was that I down voted several answers at 22:27.

However, the reputation (and thus badge tracking) hasn't caught up with the reputation that wasn't assigned after the deleted user's vote was removed.

You can see 21:34 down vote rep getting that rep 'back' with the 21:40 upvote (limited to +1 because of the rep cap).
However, the 22:27 down votes weren't 'recovered" with the 22:39 up vote to reset it back to 200 rep cap for the day, and thus a mismatch between the reputation cap information on /reputation and displayed for the epic badge tracking.  I believe that this is from a user being deleted who had upvoted a post that day, and the removal process isn't properly recalculating the reputation for the purposes of badge tracking.
I will note the possibility that I've confused all of this and /reputation and the epic badge tracker are looking different things, but if that is the case, then there's still a bug (just that this isn't the underlying cause).


text:
Q: How do I configure Outlook 2011 (mac) to display contact pictures when you read email? On Outlook 2008 and 2010 (Windows) I appreciated the show contact picture on emails but I was not able to find the same feature on Outlook 2011 on OS X.
Clicking on contact name to see the picture is not a solution, I am looking for a solution that would not require me to do an additional click.


text:
Q: Replace text in textarea using Javascript I need to replace all the matches of a regular expression till the caret position in a textarea using Javascript.
For example, if the text in the textarea is: "6 students carry 2 books to 5 classes" and the cursor
is placed on books and the regular expression is /\d/, the numbers 6 and 2 should be replaced by, say, 4.
I know the replace function and I know how to get the caret position, but how do I solve this problem?
Thanks for any help in advance!

A: textareaClicked = function(e){
    var pos = e.target.selectionStart;
    var beforeSelection = e.target.innerHTML.slice(0,pos);
    var afterSelection = e.target.innerHTML.slice(pos);
    var newHTML = beforeSelection.replace(/\d/g,4) + afterSelection;
    e.target.innerHTML = newHTML;
    e.target.setSelectionRange(pos,pos);
};

document.getElementById('foo').onclick=textareaClicked;

see it in action in this jsfiddle.

A: There is probably a more elegant way, but I would just copy the text from the text area, split the string into two substrings at the caret position (which you said you know how to find), do the replace on the first substring and then concatenate it with the second substring. Copy it back into the text area making sure to update the caret position appropriately.


text:
Q: Verification of map scale A map provider says on its webpage that the ground resolution (respectively pixelsize) is 0.2m x 0.2m.
The WMTS-Capabilities document states on the highest zoom level (ows:Identifier 16) a scale denominator of 267.When considering the standard pixel size of 0.28mm we have everything to calculate the map scale through:
pixelSpan = scaleDenominator × 0.28 10-3 / metersPerUnit(crs);
where:
metersPerUnit(Webmercator) => 1
pixelSize => 0.07

The calculated ground resolution of 0.07m is slightly off the 0.2m.
The unit of Web Mercator is one meter which leads to one meter per unit, right?
But where did I get wrong?
When loading the map in QGIS and zooming in to the maximum and then measured the pixel size I also arrived at 0.07 meters.


text:
Q: Do break operators turn while loop conditions from True to False? Check out this very basic while loop in Python:
while True:
    response = input("Say something: ")
    if response == 'bye':
        break
    if response != 'bye':
        continue

This script prompts the user for input. If the user would like to say hello (or really just about anything), the loop will continually prompt the user for a new response until the user finally enters: "bye". If the answer is "bye", the loop breaks.
My million dollar question for all of you: For the purpose of while loops in general, is it safe to say that the break statement turns a while condition from True to False, therefore exiting the loop?
I realize that lines 5 and 6 really aren't necessary because even without them the loop would continue to perform as I described above. I added the continue statement to demonstrate the distinction between break (turning the while condition to False) and 'continue' (allowing the while condition to remain True).
In case I need to refer back to the source or origin of this question, I got this idea from Andrei Neagoie's Udemy course content for "Complete Python Developer in 2019" (Section 4: Lecture 71: "While Loops 2").

A: break does not alter the values in any variables, but it simply ends the loop.  You can check it out by using another variable to control the loop like this:
other_variable = "whatever"
while other_variable == "whatever":
    response = input("Say something: ")
    if response == 'bye':
        break
    if response != 'bye':
        continue
print(other_variable)

A: Similar to the way that C language handles break and continue, Python will jump to outside of the loop escope when it reaches the break statement and, when it reaches a continue statement, it will jump back to the loop's test expression.


text:
Q: Very slow computation on a Dataframe based on previous rows I am calculating the RSI value for a stock price where a previous row is needed for the result of the current row. I am doing it currently via for looping the full dataframe for as many times there are entries which takes a lot of time (executing time on my pc around 15 seconds).
Is there any way to improve that code?
import pandas as pd
from pathlib import Path

filename = Path("Tesla.csv")
test = pd.read_csv(filename)
data = pd.DataFrame(test[["Date","Close"]])
data["Change"] = (data["Close"].shift(-1)-data["Close"]).shift(1)
data["Gain"] = 0.0
data["Loss"] = 0.0
data.loc[data["Change"] >= 0, "Gain"] = data["Change"]
data.loc[data["Change"] <= 0, "Loss"] = data["Change"]*-1
data.loc[:, "avgGain"] = 0.0
data.loc[:, "avgLoss"] = 0.0
data["avgGain"].iat[14] = data["Gain"][1:15].mean()
data["avgLoss"].iat[14] = data["Loss"][1:15].mean()

for index in data.iterrows():
    data.loc[15:, "avgGain"] = (data.loc[14:, "avgGain"].shift(1)*13 + data.loc[15:, "Gain"])/14
    data.loc[15:, "avgLoss"] = (data.loc[14:, "avgLoss"].shift(1)*13 + data.loc[15:, "Loss"])/14

The used dataset can be downloaded here:
TSLA historic dataset from yahoo finance
The goal is to calculate the RSI value based on the to be calculated avgGain and avgLoss value.
The avgGain value on rows 0:14 are not existent.
The avgGain value on row 15 is the mean value of row[1:14] of the Gain column.
The avgGain value from row 16 onwards is calculated as:
(13*avgGain(row before)+Gain(current row))/14

A: 'itertuples' is faster than 'iterrows' and vectorized operations generally performs best in terms of time.
Here you can calculate average gains and losses (rolling averages) over 14 days with the rolling method with a window size of 14.
%%timeit
data["avgGain"].iat[14] = data["Gain"][1:15].mean()
data["avgLoss"].iat[14] = data["Loss"][1:15].mean()

for index in data.iterrows():
    data.loc[15:, "avgGain"] = (data.loc[14:, "avgGain"].shift(1)*13 + data.loc[15:, "Gain"])/14
    data.loc[15:, "avgLoss"] = (data.loc[14:, "avgLoss"].shift(1)*13 + data.loc[15:, "Loss"])/14

1.12 s ± 3.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
data['avgGain_alt'] = data['Gain'].rolling(window=14).mean().fillna(0)
data['avgLos_alt'] = data['Gain'].rolling(window=14).mean().fillna(0)

1.38 ms ± 2.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

data.head(15)

Using vectorized operations to calculate moving averages is approximately 10 times faster than calculating with loops.
However note that, there is also some calculation error in your code for the averages after the first one.


text:
Q: How can I see the full command Ant uses in the Java task? I'm having some trouble with a <java> task not executing the way I expect it to and want to see the actual text of the command ant is calling on the command line so I can check to see if it is what I expect. Is there a way to do this?
Trying to Google for how to do this is very frustrating since all I get is a lot of information about how to set the command line arguments that get passed in ant. I am already doing that, but want to know that what's getting executed it what I expect before I start digging into other possible issues.

A: You can run ant in debug mode using:
    ant -d
It should dump all the information you needed in this context.

A: $ ant -verbose -debug ...

should display the command used (and much more).


text:
Q: ng-options not displaying or linking objects I have three entities: Project, Customer and Reference
A Project has two selection fields: Customer and Reference.
In the Customer object there are multiple References.
Therefore a Reference is only available for selection when a Customer with References is selected.
My problem: I only either get the Reference selection to work, or the initial Customer loading, not both.
On loading a Project with this the Customer is showed properly in the select field:
<select id="customer" ng-model="selectedProject.customer"
        ng-options="customer.id as customer.name for customer in customers | orderBy:'name'">
    <option value="">keine Angabe</option>
</select>

But no References are shown, even though the selected Customer has some.
<select id="reference" ng-model="selectedProject.reference"
        ng-options="reference.name for reference in selectedProject.customer.references track by reference.id">
    <option value="">keine Angabe</option>
</select>

If I change the Customer selection to this, the References are shown, but the Customer selection field is empty when loading a Project:
<select id="customer" ng-model="selectedProject.customer"
        ng-options="customer.name for customer in customers | orderBy:'name' track by customer.id">
    <option value="">keine Angabe</option>
</select>Project

How do I get both working?

EDIT
  I got both working by doing this:

ng-options="customer as customer.name for customer in customers | orderBy:'name'"

And overwriting the id with the object on Project selection:
$scope.selectedProject.customer = $scope.getCustomer($scope.selectedProject.customer);

But now a new problem occurs, I can't save the project anymore as it expects a reference, not the customer object.


text:
Q: Where shall I put the AutoMapper configuration? I have AutoMapper mappings, which look like this:
Mapper.Initialize(cfg =>
    {
        cfg.CreateMap<Person, PersonViewModel>();
        cfg.CreateMap<Order, OrderViewModel>();
    });

I am trying to figure out where to put this code in an MVC application.  There are two options:
1) Composition Root
public class CompositionRoot : IWindsorInstaller
    {
      //Castle Windosr configuration goes here
      //Call to AutoMapper configuration class here
    }

2) Global.asax
Questions like this suggest it: Where to place AutoMapper.CreateMaps?
My gut is telling me to put it in the Composition Root, however everywhere I read tells me to put it in the Global.asax.

A: If you take a look in Global.asax at Application_Start. You can already see things like RouteConfig.RegisterRoutes etc. These typically call static methods on classes in the App_Start folder. I usually add a class called AutoMapperConfig with a static method called Configure. I then add this to the list in Gloabl.asax. See below:
void Application_Start(object sender, EventArgs e)
{
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    ModelBindersConfig.Configure();
    DevExpressConfig.Configure();
    AutoMapperConfig.Configure();
}

A: In the past I have registered them as part of a static call from Global.asax. However, the static Mapper.Map methods are being deprecated so I've recently created a static class to setup the configuration mappings. I then call this within the composition root of my application to register the IMapper object that I can then take as a dependency in any classes.
E.g.
public static class AutoMapperConfig
{
  public static MapperConfiguration ConfigureMapping()
  {
    return new MapperConfiguration(cfg =>
    {
      cfg.CreateMap<Person, PersonViewModel>();
      cfg.CreateMap<Order, OrderViewModel>();
    });
  }
}

Using Castle Windsor you could do something like:
container.Register(
  Component.For<IMapper>()
    .UsingFactoryMethod(() => AutoMapperConfig.ConfigureMapping().CreateMapper())
    .LifeStyle.Singleton);


text:
Q: jQuery divide elements and add class I want to count my li-elements in my navigation and divide them into four classes to get them an individual border-color.
It should look like:

Of course I want it dynamically with jQuery.
I've tried:
$('#navbar li').each(function(i) {
    $(this).addClass('className-' + i);
});

but that code count all li-elements in my ul..
Thank for help!

A: You can store those Classes in an array & assign a class to each li element based on the remainder of element's index when divided by 4 (i%4).

var classNames=['red','yellow','green','blue'];
$('li').each(function(i) {
    $(this).addClass(classNames[i%4]);
});
.red{
  color:red;
  }
.yellow{
  color:yellow;
  }
.green{
  color:green;
  }
.blue{
  color:blue;
  }

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten


text:
Q: Service factory not working I inject this into my controller module:
var services = angular.module('services', []);

services.factory('jsonManager', ['$http', function($http) {

return{
  loadData: loadData
}

function loadData(){
   $http({
     method: 'GET',
     url: 'data/2015_data.json'
}).then(function successCallback(response) {
    return response.data;
  }, function errorCallback(response) {
    return response.err;
  });
}

}]);

... and it doesn't work! I'm using it on the controller like this, check it out:
var ctrls = angular.module('controllers', ['services']);

ctrls.controller('overviewController', ['jsonManager', '$scope',

function(jsonManager, $scope){

$scope.load = function(){
  var datos = jsonManager.loadData();
  console.log(datos);
  $scope.gastos = datos.gastos.data;
  $scope.ganancias = datos.ganancias.data;

}

I omitted some code from my controller; the scope objects work properly. The problem is, that I get an error that tells me that "datos" is undefined at lines 55 and 56. Why does this happen?

A: The $http service returns a promise, so you need to use then(successCallback, errorCallback) to resolve the promise.
service
var services = angular.module('services', []);
services.factory('jsonManager', ['$http', function($http) {
    var loadData = function(){
        $http({
            method: 'GET',
            url: 'data/2015_data.json'
        });
    return {
        loadData: loadData
    };
}]);

controller
var ctrls = angular.module('controllers', ['services']);
ctrls.controller('overviewController', ['jsonManager', '$scope', function(jsonManager, $scope){
    $scope.load = function(){
        var datos = jsonManager.loadData().then(function(res) {
            console.log(res.data);
            $scope.gastos = res.data.gastos.data;
            $scope.ganancias = res.data.ganancias.data;
        }, function(err) {
            console.log(err);
        });
    };
}]);

A: $http is asynchronous and
console.log(datos);
$scope.gastos = datos.gastos.data;

is run before jsonManager.loadData(); return it's value
Use callbacks or a promises
function loadData(callback){
   $http({
     method: 'GET',
     url: 'data/2015_data.json'
}).then(function successCallback(response) {
    callback(null, response.data);
  }, callback);
}

$scope.load = function(){
  var datos = jsonManager.loadData(function(err, datos){
    console.log(datos);
    $scope.gastos = datos.gastos.data;
    $scope.ganancias = datos.ganancias.data;
  });
}

A: It is asynchronous, so one way would be to force it to resolve in $scope.load like this:
$scope.load = function(){
  var datos = jsonManager.loadData().then(function(results){return results;});
  console.log(datos);
  $scope.gastos = datos.gastos.data;
  $scope.ganancias = datos.ganancias.data;


text:
Q: Ajax call aborted before redirect I have an issue with which I am stuck :
I have an html file which has few hyperlinks on it, on clicking on any of those hyperlinks
, a dynamic url is generated and user is redirected to that dynamically created URL.
Now I am trying to make an ajax call on click of those hyperlinks before it is redirected, but
it fails, and firebug show aborted ajax request.
Am i not doing in correct way ? why is it getting aborted ?
Thanks in advance

A: As I see you are already told moving to a new location aborts everything. I want to add that you need to keep in mind that if you do something like:
//hyperlinkclick function
{

   $.ajax({
      ... });

   window.location = 'somewhere under the rainbow ... ';
}

This doesnt mean your ajax call has been executed before the relocation! Ajax call is async, so if you want to relocate after the call is complete you can either set the relocating line in the success callback of the ajax call or you can use it as promise:
var call = $.ajax({ ... });
call.done(function() {
   window.relocate = "the middle of nowhere";
}

A: When you click a hyperlink that will trigger a url change, aborting everything. If you try to do something on the click of that hyperlink it will be aborted, due to the browser moving to a new location. To successfully run an ajax before actually moving to the url, you would have to do something like this:

document.querySelector('a').addEventListener('click', function (event) {
  event.preventDefault();
  doMyAjaxThing(function () {
    location.href = event.currentTarget.getAttribute('href');
  });
});

A:     //hyperlinkclick function
    {

       $.ajax({
  success: function addgetdata(returns) {
       window.location = 'somewhere under the rainbow ... ';
}
          ... });

    }

You need to use the ajax method in your hyperlinkclick function, so when you click it, it will raise the ajax function first. and you put the redirection yin your ajax success function, so when the ajax is finished, it will redirect to the new url.
yours,
Ivan


text:
Q: Functional derivative identity Is my proof of the following identity correct?

Let the functional $F[\Psi(\xi);x,y]$ be the inverse of the functional
$G[\Psi(\xi); x, y]$ in the following sense:
$\displaystyle \int dz F[\Psi(\xi);x,z] G[\Psi(\xi); z, y] = \delta(x- y), \quad \forall \Psi(\xi) \qquad (1)$
Why is the following identity true:
$\displaystyle \frac{\delta F[\Psi(\zeta);x,y]}{\delta \Psi(z)} = -\int d\xi d\eta F[\Psi(\zeta);x,\xi]\frac{\delta G[\Psi(\zeta); \xi, \eta]}{\delta \Psi(z)}F[\Psi(\zeta);\eta,y] \qquad (2)$

Proof:
Changing the dummy variables in (1) we have:
$\displaystyle \int d\xi F[\Psi(\zeta);x,\xi] G[\Psi(\zeta); \xi, \eta] = \delta(x - \eta)$
Taking the variation of the previous equation and multiplying by $F[\Psi(\zeta);\eta,y]$ we obtain:
$\displaystyle \int d\xi \Bigg\{ \frac{\delta F[\Psi(\zeta);x,\xi]}{\delta \Psi(z)}G[\Psi(\zeta); \xi, \eta]F[\Psi(\zeta);\eta,y] \\\displaystyle+ \frac{\delta G[\Psi(\zeta); \xi, \eta]}{\delta \Psi(z)}F[\Psi(\zeta);x,\xi]F[\Psi(\zeta);\eta,y]\Bigg\} = 0$
which integrated with respect to $\eta$ yields:
$\displaystyle \int d\xi \frac{\delta F[\Psi(\zeta);x,\xi]}{\delta \Psi(z)}\delta(\xi - y) + \int\int d\xi d\eta F[\Psi(\zeta);x,\xi]\frac{\delta G[\Psi(\zeta); \xi, \eta]}{\delta \Psi(z)}F[\Psi(\zeta);\eta,y] = 0$
where we have made use of (1) once again. Using the sifting property of the delta funcion leads to the desired result.

A: The first identity can be written as $FG=I,$ where $I$ is the identity kernel. We also assume that $GF=I.$ Taking derivatives of both sides gives $(FG)' = 0,$ i.e $F'G+FG'=0,$ leading to $F'G=-FG'.$ Multiply both sides with $F$ from the right to get $F'GF=-FG'F,$ i.e. $F'=-FG'F$ since $GF=I.$


text:
Q: Cómo puedo activar el evento Click de un boton que esta dentro de un videoView? alguien que me pueda decir como puedo hacer que un boton pueda ser usado mientras se está reproduciendo un video en un videoView. Lo que necesito es que ese boton permanezca invisible hasta el final del video. Cuando el video termine que el boton aparezca y pueda ser presionado. El problema es que aunque lo presione no ocurre nada.
Código java:
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
    {
        @Override
        public void onCompletion(MediaPlayer mp)
        {
            if(Capitulo != 0)
            {
                btnSiguienteCapitulo.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        ReproductorVideo.this.finish();

                        Intent siguienteCapitulo = new Intent(ReproductorVideo.this, ReproductorVideo.class);

                        siguienteCapitulo.putExtra("Capitulo",Capitulo + 1);
                        siguienteCapitulo.putExtra("Temporada",Temporada);
                        siguienteCapitulo.putExtra("Serie",nombreSerie);

                        startActivity(siguienteCapitulo);
                    }
                });
            }
        }
    });

Tengo entendido que OnCompletionListener se activa al terminar el video, pero el boton no funciona y no se porque, les agradecería su ayuda.
Pd: Ya probé usando un Toast y si lo muestra, pero el boton no hace nada.

A: El boton va a funcionar en el momento que definas el listener, eso va a ocurrir cuando se cumplan 2 situaciones:
1)Que el video termine de reproducirse, debes asegurarte que no ocurra un error antes de esto.
2)La variable Capitulo debe ser diferente a 0.
Tu implementacion no es comun ya que podrias crear un metodo para realizar el Intent:
private void iniciaIntent(){
  ReproductorVideo.this.finish();

                        Intent siguienteCapitulo = new Intent(ReproductorVideo.this, ReproductorVideo.class);

                        siguienteCapitulo.putExtra("Capitulo",Capitulo + 1);
                        siguienteCapitulo.putExtra("Temporada",Temporada);
                        siguienteCapitulo.putExtra("Serie",nombreSerie);

                        startActivity(siguienteCapitulo);
}

y mandarlo ejecutar al dar click en el boton y cuando termina el video.
btnSiguienteCapitulo.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                       iniciaIntent();
                    }
                });

video.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
    {
        @Override
        public void onCompletion(MediaPlayer mp)
        {
            if(Capitulo != 0)
            {
             iniciaIntent();
            }
        }
    });

En este ejemplo creas el listener del boton no importando si se completa el video o si Capitulo !=0, esto para que siempre funcione el clic del boton.


text:
Q: Django group by field and get all items related to that particular field I'm using Django 3.1.1 and I've got a News model which has a field called source_name.
class News(models.Model):
    title = models.CharField(max_length=350)
    content = RichTextField(blank=True, null=True)
    link = models.URLField(max_length=500, unique=True)

    # Source
    source_name = models.CharField(max_length=100)

I want to group each news by source_name and for each source i want to get all the news.
News(title='test',source_name='AAA',...)
News(title='test-1',source_name='AAA',...)
News(title='test-2',source_name='AAA',...)
News(title='test-B',source_name='BBB',...)
News(title='test-B1',source_name='BBB',...)

In the html template I want to get the following output
- AAA
  -test
  -test-1
  -test-2
- BBB
  -test-B
  -test-B1

It would be so easy if I could the following loops:
{% for source in source_names %}
    {{ source }}
    {% for news in source %}
        {{news.title}}
    {% endfor %}
{% endfor %}

How can I achieve the above descriped output in the django template?
Thanks

A: just prepare the data as you want them organized:
source_values = ['a', 'b', 'c']
data = { s: News.objects.filter(source=s) for s in source_values }

and then in the template
{% for source, news_list in data.items %}
    {{source}}
    {% for n in news_list %}
        {{n.title}}
    {% endfor %}
{% endfor %}

A: I managed to fix the issue following this snippet.
grouped = {} #dict
for obj in News.objects.all():
    grouped.setdefault(obj.type, []).append(obj)

and in the template I used:
{% for source, news_list in grouped.items %}
    {{source}}
    {% for n in news_list %}
        {{n.title}}
    {% endfor %}
{% endfor %}


text:
Q: MongoDB set limit to $inc I have database of sports players which contains their "skills". For example football player in database has 14 skills. Each day I simulate training of them so trained skill that day increases by some amount. My collection has over 1.5 million records, so I do bulk update. The problem is that using $inc, it can set value over limit, in my case the skill limit is 100.
How could I set limit to field, so it won't be updated more if it has exceeded its limit?
I have also tried to do skills "fixing" after updating, I mean after training simulation is done, I run script which iterates all players and if it has a field of exceeded value, I make update query to fix it, but making 1.5 million separate queries is kill for the server, so are there any other ways of doing it?
Edit:
increased value has some random values in calculations, so it is not the same for all players.  But the value can be from 0 to 1, rounded to 2nd digit,for example it can be 0.1, 0.2, 0.3.... 1 . So I group players with this value and trained skill and make update to database using operator $in, which contains players ids who train the same skill and their training value is the same

A: You can restrict it by a query document:
db.players.update({skills : {$lt : 100}}, {$inc : {skills : 1}})


text:
Q: Hide Table in Word using VBA I have a series of Tables in a Word document that depending on the situation may need to be filled out. To make the document look clean, I want to allow users to use a check-box to determine if the associated table is relevant or not. On a click of the check-box, the entire table should disappear. I've looked at some solutions available, but none provide consistent results.
I've tried the following:
Sub Hide()

With ActiveDocument.Bookmarks("Test").Range.Tables(1).Range.Font
    If .Hidden = True Then
        .Hidden = False
        Else
        .Hidden = True
   End If
End With
End Sub

I assign the "Test" value to the Table in question. When I run the macro, the Table will disappear.
However, the next step is have the table disappear when clicking the Content Control Check-box. I am not sure how to structure that

A: After much playing around, I got it to work. Posting for others that may want to use this functionality:
Private Sub Test_Checkbox_Click()

If Test_Checkbox.Value = True Then

ActiveDocument.Bookmarks("Test_table").Range.Tables(1).Range.Font.Hidden = True

Else

ActiveDocument.Bookmarks("Test_table").Range.Tables(1).Range.Font.Hidden = False

End If

End Sub

Make sure to use ActiveX Checkbox controls. I used this code several times throughout my Word template and just assigned several different bookmarks


text:
Q: Java RMI: How to pass a POJO I successfully created an RMI service and client. I can call methods and so on. But now I wanted to try the following: I wanted a standard Java object like a LinkedList to be hosted on the service.
Also, I wanted to 'pretend' I already had existing code that uses a LinkedList. What I want is to get a LinkedList that is actually managed by the service, but that I can access locally just like it was a normal LinkedList. On top of that I want to do some minimal logging, like if .add() is called it writes on the server: "Add called".
This is not meant for production, just to help me understand how it works!
So far I've tried a lot of things. The most promising is that I have created a class that extends LinkedList and implements Remote. This class tries to register itself with the Registry in the constructor like this:

  try {
UnicastRemoteObject.exportObject((Remote)this);
   Naming.rebind("theList", (Remote)this);
  }
  catch (Exception e) {
   System.out.println("fail");
   System.out.println(e.getMessage());
  }

I have to do this because I need to extend LinkedList, thus I cannot extend UnicastRemoteObject.
The output I get when I try to run this, on the server side:

fail
Connection refused to host: 192.168.178.27; nested exception is:
 java.net.ConnectException: Connection refused

And on the client side:

java.lang.ClassCastException: MyList_Stub cannot be cast to java.util.LinkedList
 at $Proxy0.createList(Unknown Source)
 at RemoteProgram.main(RemoteProgram.java:27)

Thanks in advance!

A: What you are trying to do is very inefficient and not a very good idea. Basically you can send anything in a method invocation that you can serialize. If you want good performance, I would suggest that you only have one remote object that represents your service and acts as a facade for all the services that you need (each remote object results in separate file descriptor, so having lots of remote objects is typically not a good idea). Additionally, if you are frequently adding and removing objects, then sending a message every time you add or remove an element is not really sensible. I would suggest having a single remote object with the following two very simple methods:
LinkedList retrieveLinkedListByName(String);
boolean commitNewVersionOfLinkedListByName(String,LinkedList);

On application startup, you can download the linked list, and then at regular intervals and at application exit, you can send back the linked list. That should be more efficient then using the network every time you add or remove an element to your linked list.  As long as the elements of your LinkedList are serializable, you don't need to do any magic (like extending remote) for it be sent.

A: java.lang.ClassCastException: MyList_Stub cannot be cast to java.util.LinkedList
at $Proxy0.createList(Unknown Source)
at RemoteProgram.main(RemoteProgram.java:27)

LinkedList is a concrete class, RMI works with interfaces so you should be casting to the List interface on the client side.

A: Agree with the other posters, this is a very inefficient design.
As for your exceptions, I don't see know how you can get a 'connection refused' in the server and still be able to run the client. You would need to post the stack trace.


text:
Q: fetching links using re.findall I'm trying to fetch all the links given in a file. All links are enclosed in "" and there are http,https and ftp links. Below is a sample output of the file.
$ cat file

"http://www.google.com" and "http://www.yahoo.com" and "http://www.facebook.com"
"https://1.1.1.1" and "ftp://a.a.a.a"

Below is my python code
In [109]: FILE = open('file','r')

In [110]: data = FILE.read()

In [111]: links = re.findall('"((http|ftp)s?://.*?)"', data)

In [112]: print links

    [('http://www.google.com', 'http'), ('http://www.yahoo.com', 'http'), ('http://www.facebook.com', 'http'), ('https://1.1.1.1', 'http'), ('ftp://a.a.a.a', 'ftp')]

Why the output contains 'http' after the original link. Where did I go wrong?
Can someone please help. I'm using (IPython 2.3.1) in Python 2.7.6

A: Because your regex contain two capturing groups. 1st capturing group captures the whole link where the other captures only the http, ftp part. I suggest you to turn the second capturing group to non-capturing group since re.findall function gives the first preference to capturing groups. If no capturing group is found on the regex, then only it returns the matches.
re.findall(r'"((?:http|ftp)s?://.*?)"', data)

Example:
>>> s = '''"http://www.google.com" and "http://www.yahoo.com" and "http://www.facebook.com"
"https://1.1.1.1" and "ftp://a.a.a.a"'''
>>> re.findall(r'"((?:http|ftp)s?://.*?)"', s)
['http://www.google.com', 'http://www.yahoo.com', 'http://www.facebook.com', 'https://1.1.1.1', 'ftp://a.a.a.a']

A: If all your file looks like that you can split and strip:
lines=""""http://www.google.com" and "http://www.yahoo.com" and    "http://www.facebook.com"
"https://1.1.1.1" and "ftp://a.a.a.a"""

print([x.strip('"') for x in lines.split(" and ")])

['http://www.google.com', 'http://www.yahoo.com', 'http://www.facebook.com"\n"https://1.1.1.1', 'ftp://a.a.a.a']


text:
Q: Easiest way to get the angle of mouse position in WPF relative to the center of a circle I have a circle when mousemove I can get e.GetPosition(this). But how to programmatically get the angle relative to the center of the circle ?
I saw on the internet some sample clocks with binding in XAML. That's not what I want, I want to get the angle value from mouse position relative to the center of a circle.
This is what I tried:
    private void ellipse1_MouseMove(object sender, MouseEventArgs e)
    {

        Point position = e.GetPosition(this);
        double x = position.X;
        double y = position.Y;
        double angle;
        double radians;
        radians = Math.Atan2(y, x);
        angle = radians * (180 / Math.PI);

    }

Angle doesn't seem correct NEVER get 0 nor 90 180.

A: You can use Atan2 http://msdn.microsoft.com/en-us/library/system.math.atan2.aspx.
public static double Atan2(
    double y,
    double x
)

just pass y as delta between your mouse y coord and the center of the circle, and the same for x.
Pay attention that the result is expressed in radiant.if it is a circle and you have X,Y relative to the circle you can pass radius-y,radius-x, if it is an ellipse you can pass height/2-y, width/2-x.

A: OK, the MouseEventArgs expose the function 'GetPosition' which asks for a UI element that will give you the relative mouse position.  This is basically what you want to do.
private void ellipse1_MouseMove(object sender, MouseEventArgs e)
{
  // This will get the mouse cursor relative to the upper left corner of your ellipse.
  // Note that nothing will happen until you are actually inside of your ellipse.
  Point curPoint = e.GetPosition(ellipse1);

  // Assuming that your ellipse is actually a circle.
  Point center = new Point(ellipse1.Width / 2, ellipse1.Height / 2);

  // A bit of math to relate your mouse to the center...
  Point relPoint = new Point(curPoint.X - center.X, curPoint.Y - center.Y);

  // The fruit of your labor.
  Console.WriteLine("({0}:{1})", relPoint.X, relPoint.Y);
}

It seems that from your comments and the rest of the posts that you can handle the actual angle computation part yourself now that you have the right information.  As far as the units are concerned, WPF uses a device independent system of coordinates.  So a circle with a radius of 50 will not necessarily be 50 pixels.  It all depends on your system, screen resolution, etc.  It's all kind of boring, but this will explain some it for you if you are really interested.
http://msdn.microsoft.com/en-us/library/ms748373.aspx

A: Trigonometry can do this for you.
So you will want to use the Arc Tangent to do this (which is found at System.Math.ATan).
You will also need to account for the cases where the angle is a multiple of pi/2 (or 90 degrees).


text:
Q: Frechet Derivative and Convergence of Functionals Let $\Omega\subset\mathbb{R}$ be a bounded interval, $\{u_{n}(t)\}_{n\in\mathbb{N}}$ be a bounded sequence in $H_{0}^{1}(\Omega)$ and define $J[u_{n}(t)] = \frac{1}{2}||u_{n}(t)||_{H_{0}^{1}(\Omega)}^{2}-\frac{1}{p}||u_{n}(t)||_{p}^{p}$ such that $\frac{d}{dt}J[u_{n}(t_{1})] \to 0$ as $n\to\infty$ for $t_{1} \in [0,\infty)$ and $2<p<\infty$.
By the property of Hilbert Space, we can have a subsequence $\{u_{n_{k}}(t_{1})\}_{k\in\mathbb{N}}$ such that $u_{n_{k}(t_{1})}\to v$ weakly in $H_{0}^{1}(\Omega)$.
Let $J'[u_{n}(t_{1})]$ be the Frechet derivative of $J[u_{n}(t_{1})]$. Can I obtain $J'[u_{n}(t_{1})]\to 0$ as $n\to\infty$?
For your information, the functional $J[\,\cdot\,]$ is related to the following semilinear pde ($2<p<\infty$)
\begin{equation*}
\begin{cases}
u_{t} = \Delta u-u+u|u|^{p-2} &\text{ in }\Omega\times(0,\infty)\\
u(\cdot,0) = u_{0} &\text{ in }\Omega\\
u(0,t) = u(b,t)= 0 &\text{ in }(0,\infty)
\end{cases}
\end{equation*}
I am trying to obtain strong convergence in $H_{0}^{1}(\Omega)$ from weak convergence but I need $J'[u_{n}(t_{1})]\to 0$ as $n\to\infty$ in order to do it.
Any help is much appreciated! Thank you very much!


text:
Q: How to write down proof that if $\lim_{x\to \infty}f(x)=\alpha$ then $\lim_{x\to \infty}f'(x)=0$? Let $a, \alpha \in \Bbb{R}$; let $f: (a,+\infty)\to \mathbb{R}$ be differentiable; let $\lim_{x\to \infty}f(x)=\alpha$; let $\beta := \lim_{x\to \infty}f'(x)$. I want to show that $\beta = 0$. Now, the idea is quite clear to me.
If $\lim_{x\to \infty}f(x)=\alpha$ then there is one horizontal assymptote and thus $f$ will get closer to it as $x$ grows. In that case, since it is horizontal, the derivative of $f$ should vanish.
Although the idea is clear I'm not being able to write down this proof. I've tried by contradiction: suppose $\beta > 0$ first. Then since $\lim_{x\to \infty}f(x)=\alpha$, given $\epsilon > 0$ we have $|f(x)-\alpha|<\epsilon$ as long as $x > M$ for some suitable $M\in \mathbb{R}$, $M > 0$.
Now, if we pick $x > M$ and focus on the interval $(M,x)$ there should be $c$, by the mean value theorem, such that
$$f'(c) = \dfrac{f(x)-f(M)}{x-M}.$$
In this way I can introduce the derivative there, but it is computed at a fixed point. Of course if I vary $x$ the $c$ would vary and I believe I could get a contradiction from this, but I'm not finding how to do this properly.
So how can I write down this idea for this proof? How can I get one contradiction from this?

A: Consider (as proposed by David Mitra in the comments)
$$
f(n+1)-f(n)=\frac{f(n+1)-f(n)}{(n+1)-n}=f'(n+\theta_n),\qquad \theta_n\in(0,1)
$$
Now we know that the limits on both sides exist by the assumptions of the statement. The limit on the left is $α-α=0$, the limit on the right $β$ as $c_n=n+\theta_n\to\infty$.

A: Using the additional condition suggested by Paramanand Singh and L'Hôpital (version anything/inf, see the second page):
$$0 = \lim_{x\to\infty}\frac{f(x)}x = \lim_{x\to\infty} f'(x)= \beta.$$


text:
Q: how to adjust textview width based on images downloaded from internet I have a textview and a image view in linear layout with weight assigned. This linear layout is for list items. Problem is sometimes, the URL for image, is giving error, so Picasso library also returns to onError().
For such scenarios, I want that the text view shall occupy complete width instead of what is decided by its weight.
Layout snippet:

    <TextView
        android:id="@+id/content"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Small"
        android:layout_gravity="center_vertical"
        android:layout_weight="5" />
    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/image"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:layout_weight="2"/>
</LinearLayout>

Picasso snippet in Adapter :
Picasso.with(mContext).load(mValues.get(position).getString("imageHref"))
    .into(holder.mImageView, new Callback() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError() {
            holder.mContentView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;

            try {
                 holder.mContentView.setText(mValues.get(position).getString("description"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
});

This doesn't seems to work as the callback comes after some delay, and my textView is already updated with some value for textView width according to layout weight.

A: Try to set visibility GONE when error:
@Override
public void onError() {
  mImageView.setVisibility(View.GONE);
  [...]
}

If it is ListView row then you must set VISIBLE when success:
@Override
public void onSuccess() {
  mImageView.setVisibility(View.VISIBLE);
}

A: You should set the visibility of the ImageView to gone by default, so that the image is not shown and the TextView gets all the space. Only if loading the image has succeeded, set the visibility of the ImageView to visible.
Or you can also do it the other way round and set visibility to gone if loading the image returns an error. This would be better approach if you plan on showing some loading-indicator image while the image is loaded.

A: You can change your textView params like below :
textView.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));


text:
Q: Unable to fetch/bind correct Entity Id in JQuery, always takes first item Id from iteration I have a PartialView where I iterate over a Collection of Entities and display them in a Html Table.
One of the columns of this table has a  with a font awesome class (fa fa-times-circle).
I am setting the "id" property of this  to the "Id" of my object I am iterating. I am setting a HiddenFor helper to get the Id in jQuery but I always get the top item from the HTML table.
When I look at the HTML output all Id's seems fine however when I try to fetch this in jQuery like this:

I always have the top item of the table.
This is how I iterate in my partial view:
foreach (var subscription in Model.Subscriptions)
{
    // tried both HiddenFor & Hidden but same results ... (HiddenFor should be used in my opinion)
    // when iterating all Id's are "good" (Different as they should be)
    @Html.HiddenFor(Model => Model.Subscription.SubscriptionId, new { Value = subscription.SubscriptionId })
    // @Html.Hidden("SubscriptionId", new { Value = subscription.SubscriptionId })

        @subscription.SubscriptionId
        ... some other values ...
         @if (condition)
         {

         }
         else
         {

         }

}

What am I doing wrong? Obviously I want to retrieve the "subscription.SubscriptionId" of the one I clicked in the table but somehow it always takes the top one.
Thank you for any suggestions or answers!

A: It seems to me that you might get like this
var subscriptionId = $(this).attr('id');

Explain:

*

*$('#Subscription_SubscriptionId').val() means: You are getting value from Subscription_SubscriptionId element instead of value of fa fa-times-circle.

*You can read this post of @Owais Alam's answer to know the difference between attr and data in jquery.

Or you can refactor your code like this way
HTML:

Jquery
var subscriptionId = $(this).data('id');


text:
Q: Creating Annotations in Java like Mockito's before In processing I have several functions that change the properties of applet to draw stuff, for instance:
public void resetBackground(PApplet pApplet){
pApplet.fill(175);
pApplet.noStroke();
pApplet.rect(0,0,100,100);
}

But I want these functions to preserve the state of the pApplet after the function call, for that I have something like:
public void resetBackground(PApplet pApplet){
SaveAndRestoreDefaults saveAndRestoreDefaults = new SaveAndRestoreDefaults(pApplet);
// Code that changes state.
saveAndRestoreDefaults.restoreOriginals();
}

Now this works for me but I would like this not to clutter my code here but rather be annotation driven, something like:
@PreserveState
public void resetBackground(){
// code that changes state.
}

I have done a little research on it but it seems to be not an easy task. The googling took me to AOP and I don't want to spend time to learn that. Is there an easier way to achieve the same?
Thanks :)

A: I'd strongly recommend staying in Processing, instead of reaching into the underlying virtual machine API (just because you run it in java, doesn't mean every implementation of Processing has a JVM. Processing.js comes to mind).
Just make a state class and keep track that way:
class SketchState {
  color background_color, stroke_color, fill_color;
  SketchState(color bg, color st, color fl) {
    sketch = s; background_color = bg; stroke_color = st; fill_color = fl;
  }
}

ArrayList<SketchState> stateCache = new ArrayList<SketchState>();

void cacheState() {
  stateCache.add(new SketchState(...));
}

void restoreState() {
  SketchState rest = stateCache.remove(stateCache.size()-1);
  background(rest.background_color);
  stroke(rest.stroke_color);
  fill(rest.fill_color);
}

and add whatever other state aspects you want saved to that class.


text:
Q: How to rename files on Windows using jmeter? I have tried to use OS Process Sampler to rename a file on my desktop, this was my configuration:

*

*Command: ren

*Working directory: Path to desktop

*Command parameter 1: name of the file

*Command parameter 2: the name i want to change to

error on view result tree:
Exception occurred whilst executing system call: java.io.IOException: Cannot run program "ren" (in directory "Working directory i specified"): CreateProcess error=2, The system cannot find the file specified

I can work with any other solution, if it cant be done using OS process sampler
Thanks in advance.

A: You cannot call rename command directly, you need to do it via CMD interpreter like:
cmd /c rename file1 file2

The relevant OS Process Sampler configuration will look like:

One parameter - one line.
Check out How to Run External Commands and Programs Locally and Remotely from JMeter article for more information regarding the different approaches of running 3rd-party apps within the bounds of a JMeter test.

A: You can use BeanShell Sampler to perform this task.

BeanShell is one of the most advanced JMeter built-in components. It
  supports Java syntax and extends it with scripting features like loose
  types, commands, and method closures. If your test case is uncommon
  and implementation via embedded JMeter components becomes tricky or
  even impossible, BeanShell can be an excellent option to achieve your
  objectives.

To perform this first declare Jmeter variables in your Test Plan

After wards Add a Thread Group,BeanShell Sampler,HTTP Request,View Result Tree [preference]
Below Code is the Sample BeanShell Code which I implemented.

try{
int count=0;
String renamedFile = "";
File imageFile;
String image ="E:\\MCMS\\USR1\\issue"+(int) (Math.random()*1000000000)+".PNG";

if(vars.get("counter").equals("A"))
{
imageFile = new File("E:\\MCMS\\USR1\\issue657327357.PNG");
//vars.put("fileName",imageFile.getAbsolutePath());
log.info("First File Identification");
log.info("First File Name : "+imageFile.getAbsolutePath());
vars.put("counter","B");
}
else
{
imageFile = new File(vars.get("nextFile"));
log.info("Next File Iterations");
log.info("Current System file : "+imageFile.getAbsolutePath());
}
File imageFile2 = new File(image);
log.info("System Ram gerated File :"+imageFile2.getAbsolutePath());
log.info("System is giong to replace ram generated file with current system file :");
if (imageFile.renameTo(imageFile2))
{
vars.put("nextFile", ""+imageFile2.getAbsolutePath());
log.info("Conversion successful");
log.info("Assigning the new file name to the jmeter variable");
vars.put("fileName",imageFile2.getAbsolutePath());
log.info(imageFile.getAbsolutePath());
log.info(imageFile2.getAbsolutePath());
}
else
{
log.info("Rename failed");
log.info("I failed but the file in the directory is"+imageFile.getAbsolutePath());
}
}
catch(Exception e){
log.info("Exception Occured"+e);
}

Do note that You cannot use it to be used by many users by just increasing
Number of Threads (users) by the thread group, as jmeter is not implemented that way.
Technically then all threads will try to change one file name at once which it will not work.
The solution to that is create a folder structure for the count of users you trying to perform the test and set the path to each respective folder mapping the thread count.
as illustrated in the below image

A: UPDATE
OS Sampler Config
Here is the config you need to set up in OS Process Sampler
Command : cmd
Command Parameters:
Add each value in a separate row.
/C
ren C:\Test\Oldfilename.txt newfilename.txt
Alternate Solution
Here is the code which renames the file using BeanShell PostProcessor
try {

String oldfile = "C:\\TestingTools\\apache-jmeter-3.2\\apache-jmeter-3.2\\bin\\test.txt";
File file = new File(oldfile);
File newfile = new File("C:\\TestingTools\\apache-jmeter-3.2\\apache-jmeter-3.2\\bin\\test123.txt");

boolean success = file.renameTo(newfile);
if (success)
log.info("file renamed successfully");
}

catch (Throwable e) {
    log.error("Error in Beanshell",e);
}

Output


text:
Q: How to solve the "integer division by zero" problem during the application of opencv? When I use OpenCV in the visual studio with C++ to process an image, it occurs this Exception unhandled problem as follows:
Unhandled exception at 0x00007FF81406F880 (opencv_world455d.dll) in ImageFilterTest.exe: 0xC0000094: Integer division by zero.
my source code is as follows:
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
    // read image
    Mat image = imread("../Images/im092002.jpg");

    //print error message if image is null
    if (image.empty())
    {
        cout << "Could not read image" << endl;
    }
    //apply identiy filter using kernel
    Mat kernel1 = (Mat_<double>(5, 5) << 0, 0, 0, 0, 1, 0, 0, 0, 0);
    Mat identity;
    filter2D(image, identity, -1, kernel1, Point(-1, -1), 0, 4);
    imshow("Orginal", image);
    imshow("Identity", identity);
    destroyAllWindows();

    //blurred using kernel
    //initalize matrix with all ones
    Mat kernel2 = Mat::ones(5, 5,CV_64F);
    kernel2 = kernel2 / 25;
    Mat img;
    filter2D(image, img, -1, kernel2, Point(-1, -1), 0, 4);
    imshow("Original", image);
    imshow("kernel blur", img);
    imwrite("blur_kernel.jpg", img);
    waitKey();
    destroyAllWindows();

}

I have no basis at all to this kind of problem, can any one tell me how to solve this problem?


text:
Q: Python how to store last element in yield iterator? I have the following code:
import zlib

def inflate(infile):
    data = infile.read()
    offset = 0
    while offset < len(data):
        window = data[offset : offset + 2]
        for key, value in zlib_headers.items():
            if window == key:
                decomp_obj = zlib.decompressobj()
                yield key, offset, decomp_obj.decompress(data[offset:])
        if offset == len(data):
            break
        offset += 1

if __name__ == "__main__":
    zlib_headers = {b"\x78\x01": 3, b"\x78\x9c": 6, b"\x78\xda": 9}

    with open("input_file", "rb") as infile:
        *_, last = inflate(infile)

    key, offset, data = last
    start_offset = offset + len(zlib.compress(data, zlib_headers[key]))

    print(start_offset)

Below the function, I'm printing information generated from the iterator. As you can see, I'm doing so for each one, but I only need to do that for the last one. How can I do this? I still need the function to work as a generator using "yield."

A: Based on, you could do something like this. Different from Cleanest way to get last item from Python iterator, you need to unpack the last item as well, since the yield returns 3 values, which are packed into a tuple, because they are assigned to a single variable last:
def inflate():
    """mock function to yield 3 values"""
    for i in range(10):
        yield i, 10 + i, 20 + i

# With unpacking
*_, last = inflate()
marker_index, offset, data = last
print(marker_index, offset, data)

# With for loop
for last in inflate():
    pass
marker_index, offset, data = last
print(marker_index, offset, data)


text:
Q: Run-time error '424' Object required - Unsure what I've written wrong in this code? Sub automated_gr_lookup()
    Dim st As Long
    Dim en As Long
    Dim c1 As Long
    Dim c2 As Long
    Dim iRowAsset As Integer
    Dim table As Range
    Dim tmpRiskID As Variant

    Sheets("Geotechnical Risk Register").Select

    Application.ScreenUpdating = False

    Set assetTbl = Application.Range("M002_") 'Asset table = DES M002
    Set riskTbl = Application.Range("geotechRisks") 'GRR
    Set compiledTbl = Application.Range("CompiledM002") 'Output for M002

    For iRowRisk = 1 To riskTbl.Rows.Count 'loop through risks
        tmpRiskID = riskTbl.Row.Range("Ref No. ID") 'Temporary risk as it gets overridden

        'if assets chainage match risk iRowRisk (4 conditions)
        If (en > c1 And en < c2) Or (st > c1 And en < c2) Or (st > c1 And st < c2) Or (st < c1 And en > c2) Then
            'copy asset row
            assetTbl.Rows(iRowAsset).Copy
            'paste row in compiled
            compiledTbl.Rows(xlEndRow).PasteSpecial xlPasteValues
            'paste risk id in last column of that row
            compiledTbl.Cells(xlEndRow, ColumnH).Value = tmpRiskID
        End If
    Next iRowRisk

End Sub

I'm getting a runtime error 424 on the line tmpRiskID = riskTbl.Row.Range("Ref No. ID") and unsure why? I'm currently trying to assign it to a table heading.

A:
Sheets("Geotechnical Risk Register").Select

This is where problems begin. Where is this worksheet? If it's in whatever workbook happens to be active, then there's run-time error 9 "subscript out of range" waiting to remind you that whatever workbook happens to be active may not necessarily have a worksheet by that name.
If the sheet is in the same workbook that hosts your VBA code, then you don't want "whatever workbook is currently active", but ThisWorkbook - this would already be better:
ThisWorkbook.Worksheets("Geotechnical Risk Register").Select

But, you don't need to .Select anything. Consider:
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Geotechnical Risk Register")

Much better: now we can make member calls against that specific sheet, and we know we're working against the right sheet.
Except, if the sheet exists in ThisWorkbook at compile-time, then it's completely redundant.
Select the sheet module in the VBE's Project Explorer toolwindow (Ctrl+R), then bring up its properties (F4). At the top of the properties list is a (Name) property that's currently probably something like Sheet42 - change that to something more meaningful, say, GeotechRiskRegisterSheet. Now you have a global-scope (project-scope, actually) object variable named GeotechRiskRegisterSheet that you can use anywhere in your VBA project to refer to that particular sheet.
The rest of this answer assumes you've done that. If the sheet isn't in ThisWorkbook, then stick to declaring a local Worksheet variable for it, and pulling the Worksheet object reference from the Workbook.Worksheets collection of the workbook you mean to work with.

Set assetTbl = Application.Range("M002_")

That's assigning to a variable that appears to want to be a local variable, but isn't declared anywhere in the local scope. Application.Range is only slightly better than just Range, and only one level of indirection away from the most-explicit ActiveSheet.Range - but then again, you don't mean to work off whatever the ActiveSheet is, and while tables do defined named ranges and named ranges can be accessed with the Range property, this would be much clearer and absolutely unambiguous:
Dim assetTbl As ListObject
Set assetTbl = GeotechRiskRegisterSheet.ListObjects("M002_")

Same applies to the other two:

Set riskTbl = Application.Range("geotechRisks") 'GRR
Set compiledTbl = Application.Range("CompiledM002") 'Output for M002

Go with:
Dim riskTbl As ListObject
Set riskTbl = GeotechRisksSheet.ListObjects("geotechRisks")

Dim compiledTbl As ListObject
Set compiledTbl = CompiledSheet.ListObjects("CompiledM002")

And then we start looping:

For iRowRisk = 1 To riskTbl.Rows.Count 'loop through risks

If riskTbl is just another Range, then that works. If riskTbl is a ListObject, we can do simpler & faster:
Dim currentRow As ListRow
For Each currentRow In riskTbl.ListRows

And then we get to the run-time error you're asking about:

tmpRiskID = riskTbl.Row.Range("Ref No. ID") 'Temporary risk as it gets overridden

That's error 424 "object required", because riskTbl.Row is a Long integer value: it doesn't have a Range member, so you can't do Range.Row.Range like this. If you're iterating a plain Range with that For iRowRisk loop, then you want that to look something like:
tmpRiskID = riskTbl.Cells(iRowRisk, 12).Value

Where 12 is a hard-coded column index referring to the "Ref No. ID" column. Not ideal, is it? Compare to leveraging the ListObject API:
Dim refIDColumn As Long
refIDColumn = riskTbl.ListColumns("Ref No. ID").Index

tmpRiskID = currentRow.Range.Cells(ColumnIndex:=refIDColumn).Value

If you define the refIDColumn variable outside the loop, every iteration can reuse its value, and as long as the header caption remains "Ref No. ID", the column can be anywhere the user wants it - whereas with a hard-coded column index, if the user inserts a new column, the code breaks.

    'if assets chainage match risk iRowRisk (4 conditions)
    If (en > c1 And en < c2) Or (st > c1 And en < c2) Or (st > c1 And st < c2) Or (st < c1 And en > c2) Then

I'm hoping you have declared and assigned these variables in your actual code - otherwise this conditional expression can't be evaluated reliably, since none of these identifiers have a value. Consider using meaningful names that convey usage intent: en, st, c1, and c2 mean absolutely nothing to anyone that isn't extremely familiar with the thought process of whoever wrote that code. In any case, make sure the top of the module says Option Explicit somewhere.

        'copy asset row
        assetTbl.Rows(iRowAsset).Copy
        'paste row in compiled
        compiledTbl.Rows(xlEndRow).PasteSpecial xlPasteValues
        'paste risk id in last column of that row
        compiledTbl.Cells(xlEndRow, ColumnH).Value = tmpRiskID

I'm not convinced you actually need to involve the clipboard here. Again, consider leveraging the ListObject API - this should work (untested):
    With compiledTbl.ListRows.Add
        .Range.Value = currentRow.Range.Value
        .Range.Cells(ColumnIndex:=compiledRiskIdColumn).Value = tmpRiskID
    End With

Where compiledRiskIdColumn would be declared and assigned before the loop body:
Dim compiledRiskIdColumn As Long
compiledRiskIdColumn = compieldTbl.ListColumns("Risk ID").Index '<~ verify column title


text:
Q: ZF2, I18n and dynamic locale not working anymore after update After finally updating Apache 2.2 -> 2.4 and php 5.4 -> 5.5 translation in view is not dynamic anymore. My app is bilingual with english as fallback.
The locale is set i.e. by user's profile using ::onBootstrap
class Module
{
    public function onBootstrap($events)
    {
    $translator = $events->getApplication()->getServiceManager()->get(
        'translator'
    );

    $authSvc = $events->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');

    $locale = $this->getLocale($authService);

    $translator->setLocale(
        \Locale::acceptFromHttp($locale)
    );

}

After updating Apache and php, translation still works but translation in view uses the default locale from the system. If I put the locale in $this->translate('MY TXT', NAMESPACE, 'en_US') it works but this is not the point. Even after debugging, I could not identify the source of the problem. It worked the way it suppose to do more than 2 years before. Any help is welcome.

A: Found the problem. You have to set translator with locale to the view helper:
public function onBootstrap($events)
{

    ....
    $viewRenderer = $events->getApplication()->getServiceManager()->get('ViewRenderer');

    $plugIn = $viewRenderer->plugin('translate');
    $plugIn->setTranslator($translator, __NAMESPACE__);
    ...
}

Otherwise the locale is taken from the config.global if set there (as in my case). No idea why it worked before for so long...


text:
Q: Numpy way to generate linear operation matrix from a convolution kernel A 2D convolution kernel, K, of shape (k1, k2, n_channel, n_filter) applies on a 2D vector, A, of shape (m1, m2, n_channel) and generates another 2D vector, B, of shape (m1 - k1 + 1, m2 - k2 + 1, n_filter) (with valid padding).
It is also true that for each K, there exists a W_K of shape (m1 - k1 + 1, m2 - k2 + 1, n_filter, m1, m2, n_channel), such that tensor dot of W_K and A is equal to B. i.e. B = np.tensordot(W_K, A, 3).
I am trying to find a pure NumPy solution to generate this W_K from K without using any python loops.
I can see W_K[i,j,f] == np.pad(K[...,f], ((i,m1-i-k1), (j,m2-j-k2)), 'constant', constant_values=0) or simply W_K[i, j, f, i:i+k1, j:j+k2, ...] == K[..., f].
What I'm looking for is almost similar to a Toeplitz matrix. But I need it in multi-dimensions.
Example in loopy code:
import numpy as np

# 5x5 image with 3-channels
A = np.random.random((5,5,3))
# 2x2 Conv2D kernel with 2 filters for A
K = np.random.random((2,2,3,2))

# It should be of (4,4,2,5,5,3), but I create this way for convenience. I move the axis at the end.
W_K = np.empty((4,4,5,5,3,2))
for i, j in np.ndindex(4, 4):
  W_K[i, j] = np.pad(K, ((i, 5-i-2),(j, 5-j-2), (0, 0), (0, 0)), 'constant', constant_values=0)

# above lines can also be rewritten as
W_K = np.zeros((4,4,5,5,3,2))
for i, j in np.ndindex(4, 4):
  W_K[i, j, i:i+2, j:j+2, ...] = K[...]

W_K = np.moveaxis(W_K, -1, 2)

# now I can do
B = np.tensordot(W_K, A, 3)

A: What you want needs a bit of fancy indexing gymnastics but it's not very cumbersome to code. The idea is to create 4-dimensional index arrays that apply the W_K[i, j, i:i+2, j:j+2, ...] part of your second loopy example.
Here's a slightly modified version of your example, just to make sure that some relevant dimensions differ (because this makes bugs easier to find: they would be proper errors rather than mangled values):
import numpy as np

# parameter setup
k1, k2, nch, nf = 2, 4, 3, 2
m1, m2 = 5, 6
w1, w2 = m1 - k1 + 1, m2 - k2 + 1
K = np.random.random((k1, k2, nch, nf))
A = np.random.random((m1, m2, nch))

# your loopy version for comparison
W_K = np.zeros((w1, w2, nf, m1, m2, nch))
for i, j in np.ndindex(w1, w2):
    W_K[i, j, :, i:i+k1, j:j+k2, ...] = K.transpose(-1, 0, 1, 2)

W_K2 = np.zeros((w1, w2, m1, m2, nch, nf))  # to be transposed back
i,j = np.mgrid[:w1, :w2][..., None, None]  # shape (w1, w2, 1, 1)
k,l = np.mgrid[:k1, :k2]  # shape (k1, k2) ~ (1, 1, k1, k2)

W_K2[i, j, i+k, j+l, ...] = K
W_K2 = np.moveaxis(W_K2, -1, 2)

print(np.array_equal(W_K, W_K2))  # True

We first create an index mesh i,j that span the first two dimensions of W_K, then create two similar meshes that span its (pre-moveaxis) second and third dimensions. By injecting two trailing singleton dimensions into the former we end up with 4d index arrays that together span the first four dimensions of W_K.
All that's left is to assign to this slice using the original K, and move back the dimension. Due to how advanced indexing changes behaviour when the sliced (non-advanced) indices in an expression are not all next to one another, this is much easier to do with your moveaxis approach. I first tried to create W_K2 with its final dimensions, but then we'd have W_K[i, j, :, i+k, j+l, ...] that has subtly different behaviour (in particular, different shape).


text:
Q: Remove noise from a binary image I want to get an image only with the grapes and the three circles (red, green, blue).
[I need to remove all the smears].
how can I improve my code for that?
this is my code:
RGB = imread('img_3235.jpg');
GRAY = rgb2gray(RGB);

threshold = graythresh(GRAY);
originalImage = im2bw(GRAY, threshold);

originalImage = bwareaopen(originalImage,250);

imshow(originalImage);

CC = bwconncomp(originalImage); %Ibw is my binary image
stats = regionprops(CC,'pixellist');

this is my image (img_3235.jpg).

and this is the result of my code:

A: An alternative solution is to median filter with an appropriate window size, just after the threshold is applied:
 ...
 originalImage = im2bw(GRAY, threshold);
 originalImage = medfilt2(originalImage,[37 37],'symmetric');
 originalImage = bwareaopen(originalImage,250);
 figure, imshow(originalImage);

A: You can perform a morpholical closing using IMCLOSE.
se = strel('disk', 10); %# structuring element
closeBW = imclose(originalImage,se);
figure, imshow(closeBW);

The closing of A by B is obtained by the dilation of A by B, followed by erosion of the resulting structure by B.