INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Conditional expectation of Poisson r.v. $X$ given $X$ is even?
We have a random variable $X$ that is poisson distributed with $\lambda$.
We wish to show:
$$E[X\mid X \text{ is even}]=\lambda \frac{1-e^{-2\lambda}}{1+e^{-2\lambda}}$$
So far, I have that
1. $P(X \text{ is even})=\frac{1+e^{-2\lambda}}{2}$
2. $P(X\text{ is odd})=\frac{1-e^{-2\lambda}}{2}$ and that
3. $E[X]=\lambda$ for the Poisson distribution.
I am struggling because I'm not completely sure how these pieces fit together. Conditional expectation is still a little fuzzy to me. Any hints/solutions are appreciated. | Treat $X\mid X \text{ is even}$ as a random variable. What is its pmf? $$P(X=k\mid X \text{ is even})=0$$ if $k$ is odd (obviously) and for $k$ even $$P(X=k \mid X\text{ is even})=\frac{P(X=k, X \text{ is even})}{P(X \text{ is even})}=\frac{P(X=k)}{P(X \text{ is even})}=\frac{2e^{-λ}λ^k}{k!(1+e^{-2λ})}$$ So
\begin{align}E[X \mid X \text{ is even}]&=\sum_{k=0}^{+\infty}kP(X=k \mid X \text{ is even})=\sum_{k\text{ is even}}^{+\infty}k\frac{2e^{-λ}λ^k}{k!(1+e^{-2λ})}\\\\[0.2cm]&=\frac{2}{1+e^{-2λ}}\sum_{k\text{ is even}}^{+\infty}\frac{e^{-λ}λ^k}{(k-1)!}\\\\[0.2cm]&=\frac{2λ}{1+e^{-2λ}}\sum_{k\text{ is even}}^{+\infty}\frac{e^{-λ}λ^{k-1}}{(k-1)!}\\\\[0.2cm]&=\frac{2λ}{1+e^{-2λ}}\sum_{k\text{ is odd}}^{+\infty}\frac{e^{-λ}λ^{k}}{k!}=\frac{2λ}{1+e^{-2λ}}\cdot P(X \text{ is odd})\\\\[0.2cm]&=\frac{2λ}{1+e^{-2λ}}\cdot \frac{1-e^{-2λ}}{2}=λ\frac{1-e^{-2λ}}{1+e^{-2λ}}\end{align} | stackexchange-math | {
"answer_score": 4,
"question_score": 3,
"tags": "probability theory, conditional expectation, poisson distribution"
} |
Some activities stay open in the "android history" when starting a new one
So when I open a certain activity, the main activity stays in the "android history" and it looks like this, now there are two instances of the app:
 and stays with only one instance
; ", I tried " android:noHistory="true" " , but none of them works.. | Change the launch mode of your activity in your AndroidManifest file:
<activity android:name=".YourActivity" android:launchMode="singleInstance">
Refer to this documentation:
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, debugging, android activity, history"
} |
How to divide rows (instead of columns) of a pandas dataframe by a list with repetition?
I have a dataframe and a list:
df:
| | N_Friends | NFriends_Vacc |
|:-:|:---------:|:-------------:|
| 0 | 6 | 3 |
| 1 | 3 | 1 |
| 2 | 4 | 2 |
| 3 | 5 | 2 |
| 4 | 2 | 1 |
| 5 | 3 | 2 |
l:
l=[2,3]
I'd like to divide each row of the df by the list so that the first element is divided by 2, the second by 3, the third by 2 and so on. The output should look something like this:
df:
| | N_Friends | NFriends_Vacc |
|:-:|:---------:|:-------------:|
| 0 | 3 | 1.5 |
| 1 | 1 | 0.33 |
| 2 | 2 | 1 |
| 3 | 1.66 | 0.66 |
| 4 | 1 | 0.5 |
| 5 | 1 | 0.66 | | You can create a series of same length as the df and divide the dataframe by that,
df.div(np.tile(l, len(df)//len(l)), axis = 'index').round(2)
N_Friends NFriends_Vacc
0 3.00 1.50
1 1.00 0.33
2 2.00 1.00
3 1.67 0.67
4 1.00 0.50
5 1.00 0.67 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "python, pandas"
} |
Asp .net web application is not creating a scripts folder which usually contains bootstrap and jquery scripts
My Visual studio is not automatically making a "scripts" folder whenever I creates a ASP .net web applicationenter image description here | It is due to the project template you selected.
The ASP.NET Core project templates have bootstrap and jQuery removed, which is why you do not see the Scripts folder.
If you choose "traditional" templates which contains `(.NET Framework)` in template name, such as the `ASP.NET Web Application (.NET Framework)` template, then you will see the Scripts folder:
` target the full .NET Framework and behave the same as the pre-.NET Core age. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": ".net, web applications"
} |
Why does one person downloading kill the internet for the rest of the house?
We have 25 megs on the downstream and 2 megs on the upstream. When doing a speed test without anyone downloading (from Usenet, for example), we get the full download and upload.
However, if one person is downloading at max speed (let's say, 3 megs per second), it brings down the internet for the rest of the house, even though we have 25 megs on the download and only 3 are being utilized.
Why is this? Why does throttling it slightly fix this problem?
Thanks | It's the sneaky difference between megabits and megabytes that's killing you. Internet connections are typically rated in megaBITS (Mb), whereas downloads are measured in megaBYTES (MB). To convert between the two, divide by 8:
25Mb downstream / 8 megabits per megabyte = ~3 MB per second | stackexchange-superuser | {
"answer_score": 5,
"question_score": 5,
"tags": "internet, download, troubleshooting, bandwidth"
} |
How do I use an if statement inside the where clause in this sql statement?
select *
from mytable
where (if @key=0
pkey>=0
else
pkey = @key)
`@key` is the value passed in to the stored procedure and `pkey` is a column in `mytable`. | You use `CASE` ( _bit like the way you are trying with`if`_) as below. (DEMO)
select *
from mytable
where pkey = case when @key <> 0 then @key
else Abs(pkey) end | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server, stored procedures"
} |
Elisp function to see a date for next Wednesday
Admitting up front that I am not capable of much Lisp, I have found ways to produce the current date or a number of seconds from a date, but I am looking for a simple equivalent to shell command like `date -d "next wed"` I believe that with the output fed to `(format-time-string ...` I can get what I need. | Emacs's built-in date parser is `parse-time-string` in `parse-time.el`, called by `date-to-time`. It understands English month and weekday names and several combinations of elements in various orders, but not expressions like “next Wednesday”.
The date input formats in the GNU `date` command provided on non-embedded Linux and Cygwin are implemented in the source of the `date` utility, they are not available as a standalone library.
If the GNU `date` utility is available on your system, you can call it. The following snippet returns a time parsed by `date` as a list (SEC MIN HOUR DAY MON YEAR DOW DST TZ).
(let ((human-time "next Wednesday"))
(parse-time-string (with-temp-buffer
(call-process "env" nil t nil "LC_ALL=C" "LANGUAGE=" "date" "-d" human-time)
(or (bobp) (delete-backward-char 1))
(buffer-string))) | stackexchange-emacs | {
"answer_score": 9,
"question_score": 7,
"tags": "time date, parsing"
} |
Windows file attribute change monitor
I need a tool that monitors file changes in a specific folder even at attribute level. Anybody can recommend one? | The best tool found so far is 'Watch 4 Folder', it allows to specify the folder to be monitored and all the status changes on the included files. | stackexchange-serverfault | {
"answer_score": 0,
"question_score": 1,
"tags": "windows, monitoring, files"
} |
What is this light and sound LEGO brick?
I have some sort of light and sound LEGO brick I obtained in an assortment of various brand's bricks. The piece has three black buttons which flash red lights and play different sounds when there are two AA batteries inside the piece. It is genuine LEGO because of the _LEGO_ mark on the studs; however, I can't find a part number on it.
 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".net, rest"
} |
Using openssl_pkcs12_export_to_file()
So I have read the PHP manual (HERE) but I'm not sure if it's does exactly what I think it is supposed to do. I need to convert a PFX certificate to a PEM. My question is, does either the above mentioned method or the openssl_pkcs12_export() method do what I need, or does it simply just export the information of the pkcs12 file?
To complete what I need to do, would I need to use the exec() method and use the appropriate openssl command, such as the one listed below:
openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes | Unless I am mistaken in your needs... You are just slightly off...
pkcs12 -in certificate.pfx -out certificate.pem -clcerts
You may also need to
pkcs12 -in certificate.pfx -out ca-certificate.pem -cacerts
`-clcerts` is only for client certificates
`-cacerts` is for non-client | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, openssl"
} |
delete records based on join result
I have two tables that are joined by an id. Table A is where I define the records. Table B is where I use the definition and add some data. I am doing some data normalization and I have realized that on table B there are some ID that are no longer defined in table A.
If I run this query:
SELECT B.id_cred, A.id_cre from B LEFT JOIN A ON B.id_cred=A.id_cre
I see those records that are NULL on A.id_cre.
I'd like to DELETE from table B those records where the query returns null on table A?
Something like:
DELETE FROM B WHERE id IN (SELECT B.id from B LEFT JOIN A ON B.id_cred=A.id_cre WHERE a.id IS NULL)
but this query throws an error because table B is target and reference at the same time.
> You can't specify target table B for UPDATE in FROM clause
Note that the join query will return 1408 rows so I need to do it in a massive way | Option 1, use `NOT EXISTS`:
delete from B
where not exists (select 1 from A where A.id_cre = B.id_cred)
Option 2, use a `DELETE` with `JOIN`:
delete B
from B
left join A on B.id_cred = A.id_cre
where A.id_cre is null | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "mysql, join"
} |
zsh: permission denied: /Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m MacOS
Python3.6 are installed in /Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m
But `>>python3.6` does not recognize
Try: `>>/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m`
Get: `zsh: permission denied: /Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m` | Install python3.6:
brew unlink python
brew install | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": -1,
"tags": "macos, python 3.6, zsh"
} |
sql getting the minimum and maximum result in same query
From the years table below, how would I be able to get the rows which have the minimum and maximum years? For example, the minimum year in the years table is 1776 and the maximum year is 2021. Therefore, the resulting table should have the row with the year 1776 and the 3 rows with 2021.
**Years** table
+--------+------+
| name | year |
+--------+------+
| name 1 | 1776 |
| name 2 | 1905 |
| name 3 | 2000 |
| name 4 | 2021 |
| name 5 | 2021 |
| name 6 | 2021 |
+--------+------+
Desired result
+--------+------+
| name | year |
+--------+------+
| name 1 | 1776 |
| name 4 | 2021 |
| name 5 | 2021 |
| name 6 | 2021 |
+--------+------+ | Find the `minimum` and `maximum` year and joined it to the main table
SELECT name,year
FROM
(SELECT min(year) AS min_year,MAx(year) AS max_year
FROM years) t1
JOIN years t2 ON t1.min_year = t2.year OR t1.max_year = t2.year
_db<>fiddle_ | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "sql"
} |
Are there types of instrument approaches besides precision and non-precision?
In the 1990s there used to be two basic types of instrument approaches: precision and non-precision. How many different kinds are there now, and what are the differences. | All approaches can still be categorized as a precision or non-precision. Some of the terminology has changed, radar approaches are becoming less common and and GPS approaches are becoming more common, but the fundamentals are the same. Precision approaches still provide glideslope guidance, and non-precision approaches do not.
It may be important to note that many flight computers blur the lines some with GPS approaches. There are approaches where the plate still calls the bottom altitude an 'MDA' (instead of 'DH' or 'DA') as you would in a normal non-precision approach, but the flight computer will generate a custom glide slope to that point. Because this is generated artificially inside your aircraft and not schematically planned by a certified official, this still only qualifies as non-precision.
All in all, if you're trying to pick up instrument flying after a long break, you'll still be good to go with your basic understanding of precision versus non-precision approaches. | stackexchange-aviation | {
"answer_score": 6,
"question_score": 7,
"tags": "instrument flight rules, iaps"
} |
log forging fortify fix
I am using Fortify SCA to find the security issues in my application (as a university homework). I have encountered some 'Log Forging' issues which I am not able to get rid off.
Basically, I log some values that come as user input from a web interface:
logger.warn("current id not valid - " + bean.getRecordId()));
and Fortify reports this as a log forging issue, because the _getRecordId()_ returns an user input.
I have followed this article, and I am replacing the 'new line' with space, but the issue is still reported
logger.warn("current id not valid - " + Util.replaceNewLine(bean.getRecordId()));
Can anyone suggest a way to fix this issue? | Alina, I'm actually the author of the article you used to solve your log injection issue. Hope it was helpful.
Vitaly is correct with regards to Fortify. You'll need to build what Fortify calls a "custom rule".
It will likely be a dataflow cleanse rule. A basic example can be found here: If you own Fortify, there should be a custom rule writing guide in your product documentation.
I don't know what the taint flag you'll use is, but it would look something like "-LOG_FORGING". You would essentially write a rule to remove the log forging "taint" whenever data is passed through your utility method. Fortify will them assume that any data passed through there is now safe to be written to a log, and will not cause log forging. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 12,
"tags": "java, security, logging, fortify, log forging"
} |
sorting rows of a data file with Linux
I would like to sort the lines of a data file (each line idependent from each other) from the first character. For example, if I have a data file
1 0.1 0.6 0.4
2 0.5 0.2 0.3
3 1.0 0.2 0.8
I would like to end with something like
1 0.6 0.4 0.1
2 0.5 0.3 0.2
3 1.0 0.8 0.2
I have tried to do it using the _sort_ command, but it sorts the columns (not the line). Transposing the data file + _sort_ could be also a good solution (I don't know any easy way for transposing datafiles).
Thanks for the help! | Perl to the rescue!
perl -lawne '
print join "\t", $F[0], sort { $b <=> $a } @F[1..$#F]
' < input > output
* `-n` reads the input line by line
* `-a` splits the line on whitespace into the @F array
* `-l` adds newlines to `print`
See sort, join . | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "linux, sorting, row"
} |
Set array within one object equal to array in another object?
Say I have a class called A:
class A{
private:
int myarray[3];
int other;
public:
void setarray(int cell_one, int cell_two, int cell_three);
// ^ Sets values passed to function to elements in myarray
}
And two A objects in my main:
int main(){
A a_one;
A a_two;
a_one.setarray(5,3,6);
}
Is there a way to copy the array in a_one to the array in a_two, without setting the other values equal? | I recommend using `std::array` instead. Then you can implement the copying through simple assignment.
For example you could create a function which returns a (possible `const`) reference to the array, and assign using these functions. Perhaps something like
struct A
{
std::array<int, 3> a;
// Other member variables...
std::array<int, 3> const& get_array() const
{
return a;
}
std::array<int, 3>& get_array()
{
return a;
}
};
// ...
a_one.get_array() = a_two.get_array(); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, arrays, class"
} |
How to refresh properly an ADF TreeTable
I'm working with adf treetables in java, all data is loaded programmatically and one of fields of treetable is an input text component, my problem is when the data is reloaded in the treetable, this field is not refreshed properly because it keeps the previous value (only in the jsf page is not loaded, in backing bean the data is correct), all others fields is reloaded properly, any ideas of what is happen? thanks...
TreeTable image | I have seen this happening when reloading is done though a button having immediate="true" set.
You can try: UIComponent comp = actionEvent.getComponent(); 2 oracle.adf.view.rich.util.ResetUtils.reset(comp); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "jsf, oracle adf"
} |
Do IE Conditional Comments work inline?
Should this work?
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="/minify/css?f=ie8.css<!--[if lte IE 7]>,ie7.css<![endif]--><!--[if lte IE 6]>,ie6.css<![endif]-->" />
<![endif]-->
Apparently nested comments don't work, so what about this?
<link rel="stylesheet" type="text/css" href="/minify/css?f=someotherfile.css<!--[if IE]>,ie8.css<![endif]--><!--[if lte IE 7]>,ie7.css<![endif]--><!--[if lte IE 6]>,ie6.css<![endif]-->" /> | No, conditional comments are not macro-style processing above HTML; they can only go where normal HTML comments can. Comments can't go inside tags.
Therefore:
<!--[if lt IE 7]><link rel="stylesheet" type="text/css" href="/minify/css?f=ie8.css,ie7.css,ie6.css"><![endif]-->
<!--[if (gte IE 7)&(lt IE 8)]><link rel="stylesheet" type="text/css" href="/minify/css?f=ie8.css,ie7.css"><![endif]-->
<!--[if (gte IE 8)&(lt IE 9)]><link rel="stylesheet" type="text/css" href="/minify/css?f=ie8.css"><![endif]-->
(Do you have enough IE-hack rules that a separate stylesheet is warranted, even for IE8? That browser is generally pretty well behaved, as long as it's not in a compatibility mode. If you only have a few rules, this tip might be of use.) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "internet explorer, inline, conditional comments"
} |
Connecting potentiometer with on/off switch to audio board
I have a B10K potentiometer with an on/off switch, trying to connect this to an audio bluetooth board (Dayton Audio KAB-215 2x15W).
My question: The potentiometer has 8 pins an I have a hard time figuring out where to connect the different cables, can't find any suitable diagrams.
To the best of my knowledge I know that I have to run the power and speaker cables through the potentiometer, but in which order?
Any hints or tips is much appreciated!
, typically used for stereo.
The front (nearest to the shaft) and middle plates are the two potentiometers. The middle pins should be the wipers.
The rear two pins are the (probably) push-on-push-off switch.
You should be able to verify all of this with an ohmmeter. | stackexchange-electronics | {
"answer_score": 2,
"question_score": 0,
"tags": "potentiometer, 12v"
} |
Custom UIView subclass add nib subview
I have a custom `UIView` subclass let's call it `CustomViewA` which I init with `initWithFrame:` and add some UIViews programatically (like a UILabel and so on). Now there is need for another view to be added to `CustomViewA` so I created a `nib` which I lay out some GUI elements inside (one being a `UISegmentedControl`)
Now I'm having some issues on how to correctly add this nib as a subview to `CustomViewA`. Do I need to create .h/.m files for the nib? I want CustomViewA to receive the actions when the segmented control changes values. | I finally figured out what was happening. The nib that I added to `CustomViewA` was added outside `CustomViewA`s frame. So apparently when a subview is outside the superview's frame it will not intercept touches. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, xcode, uiview, xib, nib"
} |
Should I parse an integer to string in Java, when not necessary?
I want to append an integer to a string. Is there a difference between doing:
String str = "Number: " + myInt;
and
String str = "Number: " + Integer.toString(myInt);
In other words, should I bother using the `Integer.toString()` method, when not necessary?
**_Edit:_** I am not wondering "How to convert an integer to string", but "if I am required to use a certain method, to convert". | There's no difference. The compiler (Oracle JVM 1.8) transform both snippets to
(new StringBuilder()).append("Number: ").append(myInt).toString();
Personally, I wouldn't use `Integer.toString()` as it adds noise to the code, and that doesn't provide clarity nor readability.
### Edit
I made a mistake on the original answer and described that there would be a minor difference (see the answer history if you want!) | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "java, string, integer"
} |
How to place all menu items inline with logo?
I have one little issue that dont know how to resolve. I inserted links menu into my site in header, and it seems that menu have fixed dimensions, so Login url is going down due to space limitation. i want to place inline with logo. I tryed to adjust via CSS:
.nav-menu-item-7776.menu-item menu-item-type-post_type menu-item-object-page
narrow{
margin-top:-150px;
}
`nav-menu-item-7776` is element for Login URL.
but dont seems to take any effect. Someone to help me with this? | Just update the icon CSS like this:
nav.main_menu>ul>li>a>i {
margin: 0 8px 0 5px;
position: absolute;
top: 38px;
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "css, wordpress"
} |
How to get the number of days of current/last year
I want to find out the number of days from current and last year. I have managed to come up with this code which will give me a starting and ending date.
Then I use `NSDateComponents` to get the number of days for this current year. But what I get is `365`, which means is the number of days from last year.
How can I corectly get the number of days for last and current year ?
func numOfDaysInYear() {
let calendar = NSCalendar.currentCalendar()
var interval = NSTimeInterval(0)
var startOfYear: NSDate?
var endOfYear: NSDate!
calendar.rangeOfUnit(.Year, startDate: &startOfYear, interval: &interval, forDate: NSDate())
endOfYear = startOfYear?.dateByAddingTimeInterval(interval - 1)
let comp = calendar.components(.Day, fromDate: startOfYear!, toDate: endOfYear, options: .MatchFirst)
print(comp.day)
} | endOfYear = startOfYear?.dateByAddingTimeInterval(interval - 1)
gives a date _within_ the current year, and its difference to `startOfYear` is 365 days, 23 hours and 59 seconds, and therefore the result is 365.
What you want is
let startOfNextYear = startOfYear!.dateByAddingTimeInterval(interval)
let comp = calendar.components(.Day, fromDate: startOfYear!, toDate: startOfNextYear, options: .MatchFirst)
print(comp.day)
which gives the correct output `366` for the leap year 2016.
To get results for the previous year, just replace the current data `NSDate()` by a date "one year ago":
calendar.dateByAddingUnit(.Year, value: -1, toDate: NSDate(), options: []) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ios, swift, nsdate"
} |
Why is this for loop not correct?
Visual Studio is telling me that this for loop isn't correct. Error Messages are:
> * type bool unexpected
> * ok is undeclared identifier
> * missing ; before }
>
* * *
infos:
> -recordset.Select return a long -MoveNext a bool
for (size_t i = 0, bool ok = recordset.Select(Adress::getSQLStatement() + "Where A05.recid = %ld", i); ok; ok = recordset.MoveNext(), i++) {
at(i).Save(recordset);
} | It's as **StenSoft** said. But you can define an anonymous structure in the loops first statement, and initialize that.
#include <iostream>
using namespace std;
int main() {
for (struct {size_t i; bool ok;} s = {0, true}; s.ok; ++s.i) {
s.ok = s.i < 10;
cout << s.i;
}
return 0;
}
But IMHO, while it works, it's more trouble than it's worth. Better restructure you code. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "c++, for loop"
} |
JavaScript how to find unique values in an array based on values in a nested array
I have a nested/multi-dimensional array like so:
[ [ **1** , 1, a ], [ **1** , 1 , b ], [ **2** , 2, c ], [ **1** ,1, d ] ]
And I want to filter it so that it returns only unique values of the outer array based on the _**1st**_ value of each nested array.
So from the above array, it would return:
[ [1,1,a] [2,2,c] ]
Am trying to do this in vanilla javascript if possible. Thanks for any input! =) | Here is my solution.
const dedup = arr.filter((item, idx) => arr.findIndex(x => x[0] == item[0]) == idx)
It looks simple and also somehow tricky a bit. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, arrays, set"
} |
Minimal Polynomial and Jordan Basis
Claim: Assume $A:V\rightarrow V$ is an endomorphism with $\dim V=d$. The minimal polynomial of this linear transformation is $m(t)=(t-\lambda)^d$. Choose $v$ such that $(A-\lambda)^{d-1} v\neq 0$. Then, $V$ has basis $B=\\{v, (A-\lambda)v, \cdots, (A-\lambda)^{d-1} v\\}$ such that the representation of $A$ on this basis is in Jordan Forms, e.g.:
\begin{pmatrix} \lambda & 1 &0\\\ 0 & \lambda &1\\\ 0 & 0 & \lambda \end{pmatrix}
I tried to prove this statement by induction. When $d=1$, we get $v$ as the only element in basis $B$, and the corresponding Jordan Form will be a single block consisting of $\lambda$. However, I am not sure how to proceed later. Also, I do not know why the representation of $A$ on this basis is in the Jordan Form when $d\geq 2$.
Any help will be appreciated. | Let $v$ with $(A-\lambda )^{d-1}v\ne 0$. Denote $$ v_i := (A-\lambda)^i v, \quad i=0\dots d-1. $$ Then it holds for $i=0\dots d-2$ $$ A v_i = (A-\lambda) v_i + \lambda v_i = \lambda v_i + v_{i+1}. $$ Hence the $i$-th row of the matrix representation contains $\lambda$ in the $i$-th columns and $1$ in column $i+1$. Pretty much the matrix you asked about.
For $i=d-1$, we have $Av_{d-1} = (A-\lambda)v_{d-1} + \lambda v_{d-1}=\lambda v_{d-1}$, hence the $\lambda$ entry in the lower-right corner. | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "linear algebra, eigenvalues eigenvectors, induction, jordan normal form, minimal polynomials"
} |
How to inform WebStorm's autocomplete about WebGLRenderingContext
I'm working on a project involving WebGL, and using WebStorm to do the development.
One issue with the development flow is that WebStorm isn't able to autocomplete things related to WebGL. In particular, if I annotate a value as being of type `WebGLRenderingContext`
/** @type {!WebGLRenderingContext} */
var gl;
WebStorm complains that WebGLRenderingContext is an unresolved variable. Also it complains about usages of methods on `gl`, warning that it can't find those methods so they may not exist.
My current workaround (besides just turning off the warnings) is to specify a record type like so:
* @type {{
* texParameteri: function,
* TEXTURE_WRAP_T: *,
* ...
* }}
var gl;
But obviously it's a bit silly to be personally listing dozens and dozens of standardized members like this every time I want to use a rendering context. Is there an easier way? | you need to let WebStorm know about WebGL API. Just enable WebGL library in Settings | Languages & Frameworks | JavaScript | Libraries.
It will create/modify the file `.idea/jsLibraryMappings.xml`
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<includedPredefinedLibrary name="WebGL" />
</component>
</project>
See: < | stackexchange-softwareengineering | {
"answer_score": 10,
"question_score": 10,
"tags": "webgl"
} |
Converting evolutionary optimization problem from Excel to Python
I've set up and successfully executed an evolutionary optimization in Excel, and now have a need to convert the problem to Python. `differential_evolution()` in the optimize package would seem to get me there, but doesn't appear to allow for the setting of a constraint such as `x1 < x2` (where `x1` and `x2` are elements of the decision variable vector).
Any suggestions? | You could apply the following trick inside your objective function:
x1 = min(x[1],x[2])
x2 = max(x[1],x[2])
Now `x1 <= x2` automatically holds and you don't need the constraint. (Assuming you can live with `<=` instead of `<`). | stackexchange-or | {
"answer_score": 6,
"question_score": 2,
"tags": "optimization, python, solver"
} |
What is the purpose of .dfm files in C++
I have used C++ in Unix and I am aware of .h and .cpp files, but I have never worked on C++ builder and now I have got a project that contains .cpp, .h and .dfm files. So what is the the purpose of .dfm files and how do we use it?
Thanks in advance. | dfm files describe a form, and typically have an associated cpp file and h file for other aspects of the form's class. They are typically edited using the IDE in C++ Builder. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "c++builder"
} |
Solution to grabbing dynamically created image from another site?
Im having trouble working grabbing a dynamically created image from this service:
<
Im trying to use the same thing in a wordpress site with calls to this server but unsure on a solution.
Can anyone suggest a good way to go about making external calls to this service on the fly and return the image to my own site?
The method they use on their site is different and not compatible due to them hosting the java software on their own system.
Im sure the solution is quite simple im just not sure where to start looking exactly, JS is not my forty, yet. | The solution via jQuery seems to be something of the following.
Sadly there was other issues on the site to prevent it from working that I was unaware of when posting originally.
$(document).ready(function() {
$("#chemicalNameForm").submit(function(e) {
e.preventDefault();
var chemicalName = $("#chemicalName").val();
var url = " + chemicalName + ".png";
$('#results').show();
$("#depiction").attr("src", url);
})
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, wordpress, dynamic"
} |
How to grant the USAGE privilege on all types?
How can I grant the USAGE privilege on ALL TYPES in a schema? For tables and functions we can use `ALL TABLES IN SCHEMA schema_name`, but this isn't supported for types:
GRANT { USAGE | ALL [ PRIVILEGES ] }
ON TYPE type_name [, ...]
TO role_specification [, ...] [ WITH GRANT OPTION ]
I know I can set a default privilege, but in this case I'd already installed an extension with many types before doing that. | We can do this with dynamic sql and psql, Sub out `user1` and `user2` with the name of the user. Feel free to delete either. You may also want only `DOMAIN` or `USER-DEFINED TYPE` adapting this should be pretty simple.
SELECT format(
$$GRANT USAGE ON TYPE %s TO %s;$$,
format('%I.%I.%I', object_catalog, object_schema, object_name ),
grantUser
)
FROM information_schema.element_types
CROSS JOIN (VALUES ('user1'),('user2')) AS t(grantUser)
WHERE object_type IN ('USER-DEFINED TYPE', 'DOMAIN');
Then run
\gexec
You can also run this in a `do` block with `PERFORM` | stackexchange-dba | {
"answer_score": 3,
"question_score": 6,
"tags": "postgresql, permissions, datatypes"
} |
How to Calculate the Possibility of a Straight
I am trying to work out how to calculate the possibility of a straight occurring during the flop.
I have some basic understanding from websites and online videos, but I’m unable to work out some of the following scenarios:
. There 47 cards out not 46.
If you need two cards you cannot make a straight on the turn.
For the river on 567 you could use 8/47 * 8/46 = 2.96% = 1/33.78. This is not exact as you could hit 3 or 9 on the first card and only have 4 outs on the river but then you also have 16 outs for the first. | stackexchange-poker | {
"answer_score": 0,
"question_score": 0,
"tags": "texas hold em, odds"
} |
How much of the manga did the Sankarea anime cover?
I just recently finished Sankarea anime and want to start the manga. How much of the manga did it cover? | The anime seemed to jump around a bit, especially the 12th episode of the anime.
However, till the 11th episode, the **anime mainly covers the manga till Chapter 9** , so you might want to start reading from Chapter 10. | stackexchange-anime | {
"answer_score": 4,
"question_score": 5,
"tags": "sankarea"
} |
How to handle users who don't select answers for their questions
How should SO handle users who don't "maintain" their questions by selecting answers, or remarking newer/better answers as the chosen one?
Many questions...
* Have no answer marked correct, even when one is plainly there
* Are not reviewed by the poster to select a new correct answer
I don't mind taking the time to answer questions, but don't see the point when I don't get "reputation" for doing so since no one reads those questions, and reputation seems to be the point of the site.
I think the "remind to accept an answer" feature is there now, since I just saw it when coming back. I missed it the first time though. | Accepting an answer means putting one's stamp of approval on it as answering your question. I try hard to accept an answer on all of my questions, but I have about 1/3 that were not answered in a way that I felt I could endorse. In one or two cases, I felt like my own answer was the best provided (at a later date), but there is no way to accept your own answer. In some cases, I'm waiting to get more responses.
Not every question gets answered to the OP's satisfaction.
I think there should be a gentle reminder, periodically (that can be turned off) to accept answers to open questions, but it should be left at that. I don't think others should have the ability to accept answers on my behalf.
EDIT: since a while it is possible to accept your own answers. | stackexchange-meta | {
"answer_score": 7,
"question_score": 11,
"tags": "discussion, questions, accepted answer"
} |
PHP - How to set default value of every index of an array
I am having trouble dealing with arrays. PHP throws an error if I access an index of an array which does not exists and It is getting difficult conditioning for every index. Is there any way I could set default value for every index of an array so even if I access a non-existent index of an array then it returns the default set value? | You do _not_ want to set a default value for every index of the array, unless your array is really quite small. It would be a waste of processing and memory.
You can do this:
if (isset($array[$index])) {
$var = $array[$index]; // the index exists
} else {
$var = 'default value'; // the index does not exist
}
// now so something with $var | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, arrays"
} |
What happens to your credit score on prolonged absences from the US?
What happens to your personal credit score when you live overseas for over a decade while only maintaining a checking account and a credit card(used only on the short trips back to US), but no paycheck being deposited into the checking account, no new credit card applications, no rent or mortgage or other loans?
Does it expire altogether, or decay slowly?
Building credit history takes a lot of time; losing it would be a pretty bad side-effect of living overseas. | Neither paycheck deposits or rent are factored into your credit score. Only lines of credit.
If you don't close the credit cards and you use them at least once in a while, then pay off the bill on time your credit should be fine. Can you not use the credit card for an occasional lunch or small purchase it the country you will be staying in?
Not having diverse types of credit can lower your score to some degree, but I wouldn't worry too much about it. | stackexchange-money | {
"answer_score": 17,
"question_score": 13,
"tags": "credit score, credit history, fico score"
} |
Copy file line by line
I have a problem with a loop, what i want to do is copy a file, line by line. I used this code but it in the output file write one more bracket and one line.
void copyStringNewFile(ifstream& inData,ofstream& outData)
{
string x = "";
while (inData)
{
getline(inData, x);
outData << x << '\n';
}
}
Probably i can remove the line:
string x = "";
In the while conditions I've tried a few solution:
while (!inData.eof()) // Works similar to while (inData)
while (inData >> x) // Delete a lot of lines
Thank you so much, and if you can explain where eof can be useful (because in loops it seems useless). | You are not checking the return value of getline(). When it fails, no copy should be made. Btw, you are also depending on a final '\n' in the source file, otherwise you'll have trouble copying the last line.
Here's a form that monitors successful reads properly:
void copyStringNewFile(ifstream& inData, ofstream& outData)
{
char ch;
while (inData >> ch)
{
outData << ch;
}
}
Or if you're ready to use a more advanced form:
void copyStringNewFile(ifstream& inData, ofstream& outData)
{
outData << inData.rdbuf();
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c++, loops, while loop, eof"
} |
java while (resultset.next()) does not return all data in the same column
i need your help. i want the resultset to fetch all data in member_code column, but it's only fetch 1 data. how to fetch all data in member_code using looping? here's my code:
public String membercode() throws SQLException{
String member="";
String sql = "SELECT member_code FROM member";
java.sql.Connection conn = (Connection) koneksi.config();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while(res.next()) {
member = res.getString("member_code");
}
return member;
} | You need to assemble and return a "list". For example:
public List<String> membercode() throws SQLException{
List<String> members = new ArrayList<String>();
String sql = "SELECT member_code FROM member";
java.sql.Connection conn = (Connection) koneksi.config();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while(res.next()) {
member = res.getString("member_code");
members.add(member);
}
return members;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, sql, resultset"
} |
Equalities in C/C++
In C++, the usual way of determining if some value, x, is between two limits is to:
//This is (A)
double x = 0.0d;
double lower = -1.0d;
double upper = +1.0d;
if(x > lower && x < upper){
// Do some stuff
}
But today I discovered by accident that I can do this:
// This is (B)
double x = 0.0d;
double lower = -1.0d;
double upper = +1.0d;
if(lower < x < upper){
// Do some stuff
}
It seems to work fine, but I've never heard of this being done before, with "lower < x < upper". Does this produce executable code as you would expect it to? IE, is (A) equivalent to (B)?
I think a lot of people won't know about this, and I suspect that might be because the compiler interprets (A) differently to (B). It this right? | No, A and B are _not_ equivalent, you cannot do this.
Or, obviously you _can_ (as you discovered) but you're not doing what you think you're doing.
You're evaluating `(lower < x) < upper`, i.e. the value of `lower < x` (which is `false` or `true`, but which convert to `int` for the comparison) is compared to `upper`.
See this table of operator precedence for more information. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 2,
"tags": "c++, c, equality"
} |
SOIC-8 IC input pins small spacing at high voltage
I'm looking at a high common mode voltage difference amp (AD629). The input voltage between the two input pins next to each other will be 150VDC. Normally the pads should be bigger on the PCB than the actual pin size. So between these two pads is at most 0.6mm space.

{
for (std::vector<Model3D*>::reverse_iterator it = mModels->rbegin();it != mModel->rend();it++)
{
Model3D *model = *it;
if (model->GetName() == name)
{
return model;
}
}
}
Thanks for your help!
\--EDIT--
So my goal here is to store all my 3d models (stored in Model3D classes) in a vector, so that i can retrieve it later using the name of the Model3D. Is there maybe a better way to do this? Because it seems like my way is not really good programming... | You are not dynamically allocating any memory. This is static allocation
Model3D *model = *it;
and it will be destroyed when the context block of this variable ends (i.e. when you return from this method). It's only statically allocated pointer.
Dynamically allocation is done with the `new` operator and there isn't any.
Simple rule to check for leaks is to have `delete` for every `new`.
You can check your memory leaks with `valgrind` terminal tool. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c++, pointers, memory, memory leaks"
} |
How to explain exponential plus Gaussian noise
I have some noisy signal. When I substract real (for calibration it is known) or filtered signal I get residuals. When I plot distribution of these residuals I see that it is sum of exponential and Gaussian distributions. Is it possible to speculate about what does it means? Maybe it is common situation? Could you help me with explanation?
# UPDATE:
Blue is RAW signal, red- filtered. :. The prevalence likely arises because the blue signal is much higher frequency than the red, so the blue signal goes through several cycles over any interval where the slower red signal is near a peak/trough. | stackexchange-stats | {
"answer_score": 2,
"question_score": 1,
"tags": "signal processing, filter, noise"
} |
How to display specific div that have image in webview
I've got the following
Document doc = Jsoup.connect("
Elements divs = doc.select("div");
webViewAds.getSettings().setJavaScriptEnabled(true);
for (Element div : divs) {
String html = div.getElementsByClass("majalahpro-core-banner-insidecontent").toString();
String mime = "text/html";
String encoding = "utf-8";
webView.loadData(html, mime, encoding);
}
i want to display this content on my webview, ;
//Loop over it
for (Element link : links) {
// Get its Html
String content = link.html();
}
Enjoy! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, android"
} |
Nix how can I reference a username from users.extraUsers?
I'd like to reference a user in some nix expression. However rather than just setting it to a string value like `bob` I want to reference a user that is already defined in `users.extraUsers` so I assume something like `users.extraUsers.bob.userName`. Is this possible?
The reason for this, is it gives me some extra static guarentee that I'm referencing a user that will exist. | You can make sure a user is defined by looking them up.
$ nix repl '<nixpkgs/nixos>'
Welcome to Nix version 2.3.4. Type :? for help.
Loading '<nixpkgs/nixos>'...
Added 6 variables.
nix-repl> config.users.users.${"root"}.name
"root"
nix-repl> user = "bob"
nix-repl> config.users.users.${user}.name
error: attribute 'bob' missing, at (string):1:1
nix-repl> config.users.users.${user}.name or builtins.throw "You referenced a user `${user}' which was not defined."
error: You referenced a user `bob' which was not defined.
Note that `extraUsers` is just an alias for `users`.
It's not static in the sense that Nix doesn't static checking beyond limited scope checking, but I hope it helps. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "nix, nixos"
} |
Converting a sequence of numbers (not in any data structure) into an array
I have a sequence of numbers that I somehow obtain from an external source, not separated by any commas and not in a data structure, e.g: 1 1.5 120202.4343 58 -2442.5
Where distinct numbers are separated by a space(s).
Is there a way for me to write a program to quickly convert this sequence into a list or numpy array [1, 1.5, 120202.4343, 58 ,-2442.5]. | I'm not sure what you mean by "not in a data structure", that doesn't make much sense. But assuming you have a string, then `numpy` even provides a utility method for this:
>>> import numpy as np
>>> data = '1 1.5 120202.4343 58 -2442.5'
>>> np.fromstring(data, sep=' ')
array([ 1.00000000e+00, 1.50000000e+00, 1.20202434e+05, 5.80000000e+01,
-2.44250000e+03]) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, numpy"
} |
how to handle javascript alerts in selenium using python
So I there is this button I want to click and if it's the first time you've clicked it. A javascript alert popup will appear. I've been using firebug and just can't find where that javascript is located and I've tried
if EC.alert_is_present:
driver.switch_to_alert().accept()
else:
print("no alert")
the above code works if there is an alert box but will throw an error if there is none. even though there is an else statement I've even tried
if EC.alert_is_present:
driver.switch_to_alert().accept()
elif not EC.alert_is_present:
print("no alert")
it throws me this error
selenium.common.exceptions.NoAlertPresentException: Message: No alert is present
how do we get around this? | Use try catch and if the Alert is not present catch `NoAlertPresentException` exception:
from selenium.common.exceptions import NoAlertPresentException
try:
driver.switch_to_alert().accept()
except NoAlertPresentException as e:
print("no alert") | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 6,
"tags": "python, selenium"
} |
Logging a DOM object in a Firefox WebExtension content script prints "<unavailable>"
I'm building a browser extension with the WebExtension API in FireFox. I'm in the middle of writing a content script, and when I pass any DOM object into `console.log`, it is not printed out. Instead, I just get the string `<unavailable>`. Observe:
$ console.log(document);
<unavailable>
However, I can still access the object's properties.
$ console.log(document.baseURI);
Why does this happen, and what does it mean? | That means that the debugger you're using (presumably the add-on debugger in this case) is attached to a different process than the process where the log message was generated (which would be a web content process in this case). The MDN page about debugging discusses this in greater detail: < | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "javascript, firefox, console.log, firefox addon webextensions, browser extension"
} |
Retrieve info from table
I need to retrieve the info of the employees that earn more money than the average wage of their department... we have departments named 10, 20, 30, 40, 50, ... and so goes on. Here I have managed to retrieve what I need for only one department. (40) How can I do it for as many departments as there may be?
This is my Query:
SELECT * FROM EMPLOYEE where (Department_ID='40')and
(
employee_salary >
(select avg(employee_salary) from EMPLOYEE where Department_ID='40')
)
`Datatable`: !data table | Hope this will do,
SELECT emp.* FROM EMPLOYEE emp where emp.employee_salary >
( select avg(employee_salary) from EMPLOYEE new1
where emp.Department_ID=new1.Department_ID
group by Department_ID
) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "sql"
} |
Is SRAM RED AXS Power Meter, 48/35T compatible with Tarmac Pro Disc – SRAM ETAP
I am interested in purchasing specialized "Tarmac Pro Disc – SRAM ETAP" bicycle that comes with "SRAM Force AXS, 48/35T" crankset. I want a crank power meter and want to know if the "SRAM RED AXS Power Meter, 48/35T" is compatible. | Yes they should be compatible - the difference is in the materials/manufacturing: SRAM Tech Support - Difference between Force/Red AXS
However, you can upgrade your Force AXS crankset to have power: SRAM Tech Support - Adding power to Force AXS crankset | stackexchange-bicycles | {
"answer_score": 1,
"question_score": 1,
"tags": "power, specialized bikes"
} |
How can I manually control the collapse button on my wordpress site
I have a problem. This is the site that i was building in x theme in wordpress using cornerstone. The problem is that nav menus where too many and causes a problem on screen width around 980px to somewhere around 1100px and the nav menus go below the brand logo. Is there a way to control that collapse button to trigger when it reached a certain width?
sorry for the win xp thing this is just a test pc for the site
, which seems better.
The question is: **What does it mean by 'splitting it into cases', and why does it work?** Another side question I have is how to differentiate a function that has a modulus somewhere inside it. | $$I=\int_{-2\pi}^{2\pi} xe^{-\mid x\mid}dx.$$
Loosely speaking, you can think about the **definite** integral as the area bounded by the function $xe^{-\mid x\mid}$ and the $x$-axis, **as the variable $x$ moves from $x=-2\pi$ to $x=0$ then from $x=0$ through to $x=2\pi$**. So, intuitively it's not too much of a step to see that $$I=\int_{-2\pi}^{0} xe^{-\mid x\mid}dx+\int_{0}^{2\pi} xe^{-\mid x\mid}dx.$$ Notice in the left integral the $x$ values are only ever negative or zero, and in the right integral the $x$ values are only ever positive or zero, so we can rewrite the whole expression $$I=\int_{-2\pi}^{0} xe^{x}dx+\int_{0}^{2\pi} xe^{-x}dx,$$ since $-|x|=x$ for $x\leq 0$ and $-|x|=-x$ for $x\geq 0$. You can now evaluate the integrals separately to obtain the correct result. Hope this helps. | stackexchange-math | {
"answer_score": 3,
"question_score": 3,
"tags": "calculus, integration, definite integrals, absolute value"
} |
How do i make a htaccess variable optional?
How do i make that the third passed 'get' variable on first line is not mandatory? In other words, page only works if there are 3 'get' variables given, but in my case, i need the third one (e) to be optional. Any ideas?
RewriteRule ^ft/([0-9]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ forum.php?ft=$1&seo=$2&e=$3 [NC,QSA,L]
RewriteRule ^(fc|ft)/([0-9]+)/?$ forum.php?$1=$2 [NC,QSA,L]
RewriteRule ^forums/?$ forum.php [NC,L] | In that case to handle both 2 and 3 variables, try adding 1 more rules in your htaccess Rules file, have your htaccess rules file in following manner.
Please make sure to clear your browser cache before testing your URLs.
RewriteEngine ON
##Newly added rewrite Rule to handle 2 parameters in uri.
RewriteRule ^ft/([0-9]+)/([A-Za-z0-9-]+)/?$ forum.php?ft=$1&seo=$2 [NC,QSA,L]
##Rest of the rules go from here onwards....
RewriteRule ^ft/([0-9]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ forum.php?ft=$1&seo=$2&e=$3 [NC,QSA,L]
RewriteRule ^(fc|ft)/([0-9]+)/?$ forum.php?$1=$2 [NC,QSA,L]
RewriteRule ^forums/?$ forum.php [NC,L] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "apache, .htaccess, mod rewrite, url rewriting, friendly url"
} |
Detect When Flash Loads Remote Item
I have a flash player that loads in some additional features from flash files on other sites... for example, the main flash player on on site1, but it displays an animation that is actually housed on site2.
How can I detect when (and where) the main flash player is going to for information?
Can I trace the network traffic somehow to see this happen? | I've managed to use a product called "Wireshark" to run a network capture and I found the HTTP GET requests in the resulting trace. If you know what you're doing you can probably filter the results a lot better - but luckily for me the colour coding highlighted exactly what I needed in bright green, which saved me having to search through it. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "flash, external dependencies"
} |
FILTER vs CALCULATE DAX Function
Is there a difference between the FILTER and CALCULATE Dax functions?
From what I understand, they produce the same result and are synonymous.
Is this true? | They aren't remotely the same.
FILTER takes a table expression as its first argument and iterates through all the rows of that table checking the condition provided in the second argument. It returns a table.
CALCULATE calculates a scalar expression (first argument) in the filter context determined by the remaining arguments. It returns a single scalar value. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "dax"
} |
Cache flushing doesn't help after manual deletion of entity references
I have a little function that deletes specific entity references directly from database. Because of fact that it bypass the whole entity_load / entity_save system it flushes cache of all entities it affects by itself.
The weird thing is that it doesn't work. The references, while not present in the database, still show up on node view / edit pages.
$affected_users = db_select('field_data_fmu_users_firm', 'su')
->fields('su', array('entity_id'))
->condition('fmu_users_firm_target_id', $user_id, '=')
->execute()->fetchCol();
db_delete('field_data_fmu_users_firm')
->condition('fmu_users_firm_target_id', $user_id, '=')
->execute();
entity_get_controller('user')->resetCache($affected_users);
No special caching module is enabled on the site. | Core has caches. Use the API. If you still do not want to use the API this might be helpful
Is it proper to perform a db_update on an entity table? | stackexchange-drupal | {
"answer_score": 2,
"question_score": -2,
"tags": "caching, entities"
} |
Change table contents to match a query without deleting all rows
I have a table (`tblA`) and a query (`queryB`). The output of `queryB` matches the schema of `tblA`. I want to update `tblA` so that it's contents are equal to `queryB`
An obvious solution to this might be:
TRUNCATE TABLE tblA
INSERT INTO tblA
(queryB)
However, I want to minimise the number of deletes and inserts I do.
There will be three cases with the results from `queryB`:
* In `queryB`, not in `tblA`: Insert
* In `queryB`, in `tblA`: Do Nothing
* In `tblA`, not in `queryB`: Delete
So far I have found the MS SQL's MERGE supports a `[NOT] PRESENT IN TARGET/SOURCE` that would be perfect for this - but have not found an Oracle equivalent.
Is there an elegant way to achieve this? | delete from tblA where
(col1, col2, ...) not in (queryB);
insert into tblA
(queryB) minus (select * from tblA);
* * *
**EDIT :**
You can calculate queryB once if small temporary table will be created (which will contain < 10% of rows of table tblA).
It is assumed that queryB.col1 is never null
create table diff as
select
ta.rowid ta_rid,
tb.*
from tblA ta
full join (queryB) tb
on ta.col1 = tb.col1
and ta.col2 = tb.col2
and ta.col3 = tb.col3
where
ta.rowid is null or tb.col1 is null;
delete from tblA ta
where ta.rowid in (select d.ta_rid from diff d where d.ta_rid is not null);
insert into tblA ta
select d.col1, d.col2, d.col3 from diff d where d.ta_rid is null; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sql, oracle"
} |
gcutil addinstance no longer returns IP address of instance
I just upgraded to gcutil 1.10.0 and I notice that the table that's returned upon completion of addinstance no longer contains the IP address of the instance. I extract that address to use in other scripts so I noticed it was gone immediately.
Looking at gcutil commands, it looks like "listaddresses" should give me the information I'm looking for; however, it returns no entries, just a table header. (The instance is running when I try this.)
So I guess if we're not going to produce the IP address in the output of addinstance anymore, I could use help figuring out how to get the address by a command-line query.
John K. | You can get the address for the instance by using:
gcutil listinstances --columns=all
Alternatively, you can just specify the columns you want. You can get the list of valid columns using:
gcutil help listinstances | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "google compute engine, gcutil"
} |
search in wildcard folders recursively in python
hello im trying to do something like
// 1. for x in glob.glob('/../../nodes/*/views/assets/js/*.js'):
// 2 .for x in glob.glob('/../../nodes/*/views/assets/js/*/*.js'):
print x
**is there anything can i do to search it recuresively ?**
i already looked into Use a Glob() to find files recursively in Python? but the _os.walk dont accept wildcards folders_ like above between nodes and views, and the < docs that dosent help much.
thanks | **Caveat:** This will also select any files matching the pattern anywhere beneath the root folder which is nodes/.
import os, fnmatch
def locate(pattern, root_path):
for path, dirs, files in os.walk(os.path.abspath(root_path)):
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
As os.walk does not accept wildcards we walk the tree and filter what we need.
js_assets = [js for js in locate('*.js', '/../../nodes')]
The locate function yields an iterator of all files which match the pattern.
**Alternative solution:** You can try the extended glob which adds recursive searching to glob.
Now you can write a much simpler expression like:
fnmatch.filter( glob.glob('/../../nodes/*/views/assets/js/**/*'), '*.js' ) | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 6,
"tags": "python"
} |
How to disable webmin start on boot on Ubuntu?
How to disable Webmin starts on boot on Ubuntu 14? Due security reasons, I want to run it manualy when I really will use it. | You can disable Webmin starting at boot from the Webmin interface, in the Webmin Configuration module. At the bottom of the module window is the option to set when Webmin starts. You can invoke Webmin to start via command-line `sudo service webmin start` when configured not to start at boot. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 1,
"tags": "boot, webmin"
} |
how to build 64 bit managed c++ dll in visual studio 2010?
I've got a managed c++ dll, and it builds fine in x86 format. However, when I change the format to x64 in configuration manager, it won't recognize .Net namespaces, like System etc.
What else should I change to be able to build the 64-bit version of the app?
I'll need to be able to build the app for x64 and for x86. | When you changed your project to target x64, the settings that tell the compiler to target the .NET Framework obviously didn't get transferred over.
Check your project's properties to ensure that all of the x64 settings match with the x86 settings.
More specifically, you're looking for the "Common Language Runtime Support" property. On recent versions of Visual Studio, this should probably be set to `Common Language Runtime Support, Old Syntax (/clr:oldSyntax)` for Managed C++.
;
begin
comment on column employees.job_id is 'comment'
end;
/
ora-06550: line 2, column 13:
pls-00103: encountered the symbol "on" when expecting one of the following:
:= . ( @ % ;
begin
execute immediate 'comment on column employees.job_id is ''comment''' ;
end;
/
1 rows affected
_db <>fiddle here_ | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "oracle, plsql, oracle11g, pls 00103"
} |
Uncaught reference error: Function not defined
I have some simple code for one of my first jquery scripts, I'm trying to call it's function but it keeps saying the function doesn't exist! I have check the spelling and I'm sure I had this working before but I have no idea what's changed.
This is my code: <
This is how I'm calling my function:
jQuery(function($){
applyField();
});
Can anyone show me where I went wrong please? | `applyField` isn't defined because jsFiddle wraps your code in an `onload` event handler. So the function is only visible in this event handler.
Choose `"no wrap - in <head>"` in the left menu :
!enter image description here
Alternatively, you could also call your function from this event handler, this would be more coherent.
Note that calling the function isn't enough. If you want your event binding to be effective, change
$(this).on('change', '#apply',function() {
to
$(document.body).on('change', '#apply',function() {
**Demonstration** | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "javascript, jquery"
} |
Why aren't values implicitly convertible to string in C#?
I have some code like:
int value = 5;
MessageBox.Show ( value );
and the `MessageBox.Show` complains saying:
> "cannot convert from 'int' to 'string'"
I seem to remember some cases where values seem to be implicitly converted to string values, but can't recall them exactly.
What's the reason behind this decision that any value isn't implicitly convertible to string values? | `MessageBox.Show()` only accepts a string. When you use something like `Debug.WriteLine`, it accepts a bunch of different object types, including `object`, and then calls `ToString()` on that object. This is probably what you're experiencing. | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 9,
"tags": "c#, .net, string, compiler construction, implicit conversion"
} |
Ubuntu Multiple Monitor Support
I have recently aquired a Dell Inspiron 15R Special Edition (7520) and I am trying to get 2 monitors connected, plus the laptop screen. With a single monitor I can have things working no problem, but when two monitors are connected the 2nd one does not work, it receives no signal. If I swap around the monitors, I can have any combination of two working, even both monitors with no laptop screen.
Is there a way I can have my display extended across all three displays, without having to purchase a $300 Matrox triple head device? | So the answer is no, there is a Hardware limitation to only support two monitors simultaneously.
< | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "ati, xorg, multiple monitors, intel graphics"
} |
What is the preferred way of allocating C++ class member data?
Let's say I have a class that allocates some arbitrary member data. There are two common ways that I have seen used (I know that there are others):
class A
{
public:
A();
~A();
//Accessors...
private:
B *mB;
}
A::A()
{
mB = new B();
}
A::~A()
{
delete B;
}
Versus...
class A
{
public:
//Accessors...
private:
B mB;
}
Assume that A itself will be allocated on the heap by consumer code.
In the general case, which method is preferred? I realize that specific situations really encourage one way or the other, but in absence of those demands, is one way preferred? What are the tradeoffs? | The second is the preferred route. Do not use new / delete unless you specifically need a variable to be on the heap or have a lifetime longer than it's container. C++ value types are easier to manage and have less error cases to worry about IMHO | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 3,
"tags": "c++, memory management"
} |
Ajax request in Chrome extension
I am developing an extenion which makes an ajax request to a web server like this
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 204)
{
//debugger;
alert("Logged in");
flag = 1;
_callBack(xhr, xhr.readyState);
}
}
And here i am able to logged in with status = 204 and now once i logged in i am trying to go for different directory for example www.example.com/index/enter with another ajax request in same extension but could not able to do so. | Are you sure you're expecting the same HTTP response code? It's very likely that the server you're making requests to is sending a different response for a different request URL.
204 No Reponse = there is no response data
200 OK = there is data | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, ajax, google chrome extension, webserver"
} |
Button group overflowing on small viewport
I want to create a group button in a `<td>` element that'll behave the same on both small and large screens.
This is what I currently have.
<div class="btn-group" role="group">
<button type="button" class="edit btn btn-warning btn-sm">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>
</button>
<button type="button" class="delete btn btn-danger btn-sm">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</div>
Here's an screenshot to explain what I mean.
 app in the Apple App Store.
* When it is opened and starts — I fetch a bunch of data.
* If I leave the app (but don’t technically “close” the app from the app switcher), then every time I open the app again, it opens on the same screen (the screen / components persist)
* This happens even if it’s the next day
* Ideally, after some amount of time (hours?) I would like the app to fetch data, but since the previous screen persists and the component is already mounted, I don’t know how to fetch new data
* Obviously if you manually close the app (go to app switcher and swipe up to close app) upon next open it will mount the components and fetch data...
* Is there a setting for the app to “close” on its own after a certain amount of time?
Thanks in advance! | You can use the following tools:
* To detect when the app changes from active to backgrounded: <
* To fetch data in the background: < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "react native, expo"
} |
Change url using rewrite rules in .htaccess
I need your help with an issue I am facing.
I am trying to change the `url` from `domain.com/file.html` to `domain.com/some-text` using **rewrite rules** in .htaccess file. I just need to change the `url string` with no redirection.
How is this possible?
_Notice:_ There is no `some-text` folder inside domain root folder. | Just a simple rules like this should work for you in site root .htaccess:
RewriteEngine On
RewriteCond %{THE_REQUEST} /file\.html[?\s][NC]
RewriteRule ^ /some-test [L,R=301]
RewriteRule ^some-test/?$ file.html [L,NC]
* Apache mod_rewrite Introduction
* Apache mod_rewrite Technical Details | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": ".htaccess, mod rewrite, url rewriting"
} |
Problems with converting a dataset to a Numpy array
I'm traing to convert lines of data into a Numpy array.
This is the first line:
['2013-08-14 00:00:00', '232598', '1.3999999761581', '', '1.1572500056095', '12.302269935608', '51.526794433594', '2.2079374790192', '0.60759371519089', '23.152534484863', '']
Then
import numpy as np
float_data = np.zeros((len(lines), len(header) - 1))
for i, line in enumerate(lines):
values = [ float(x) for x in line.split(',')[1:]]
float_data[i, :] = values
I'm getting: `ValueError: could not convert string to float:` I guess a string whit the value ' ' is the cause of the problem. How can I replace the ' ' with the value 0? | Finally, this worked out for me
import numpy as np
float_data = np.zeros((len(lines), len(header) - 1))
for i, line in enumerate(lines):
laLinea = line.split(',')
for n, k in enumerate(laLinea):
if k == '':
laLinea[n] = '0.0'
laLinea = laLinea[1:]
for x in laLinea:
values = [float(x) for x in laLinea]
float_data[i, :] = values | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, numpy, keras"
} |
IF contains more than one string do "this" else "this"
Trying to make a script that request more info (group Id) if there are SCOM groups with identical names:
function myFunction {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string[]]$ObjectName
)
foreach ($o in $ObjectName) {
$p = Get-SCOMGroup -DisplayName "$o" | select DisplayName
<#
if ($p contains more than one string) {
"Request group Id"
} else {
"do this"
}
#>
}
}
Need help with the functionality in the comment block. | Wrap the value in an array subexpression `@()` and count how many entries it has:
if(@($p).Count -gt 1){"Request group Id"} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "arrays, powershell, if statement, count, scalar"
} |
How to insert text at specified position in google doc using google apps script?
I have document which contains the text. I want to find the word (li) and insert new word by adding new line. I have found the following script that finds the text:
matchPosition = theDoc.getBody().findText("put stuff here").getStartOffset();
theDoc.getBody().editAsText().insertText(matchPosition, "The new stuff");
But this does not work properly because it gives the position of word from the starting line and when we insert a new text it counts position from the start of the document instead of the start of that line. Hope you understand what I am saying.
So to summarize, Is there any way from which we can find the first occurrence of the word anywhere in the document and add a new word on the next line of the found word? | I just found a way to insert text at a specified position:
for (var i = 0; i < paragraphs.length; i++) {
var text = paragraphs[i].getText();
if (text.includes("a href")==true)
{
body.insertParagraph(i, "Test Here")
}
}
This loops through all the paragraphs' text and when it finds the matching word, it adds a new paragraph at the specified position in which you can add your desired word. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "google apps script, google sheets, replace, full text search, google docs"
} |
pysimpleguiweb change hosting port
I'm loving the new **pysimplegui** tools, and have just started exploring the **pysimpleguiweb** port but have quickly hit a roadblock. To actually deploy an application built using the web version, it would be important to be able to control what port number the service was hosted on but it currently looks like it finds a random free port.
Looking through the source code on github I found where the remi server is started, it just specifies port=0.
remi.start(self.MyApp, title=self.Title ,debug=False, address='0.0.0.0', port=0, ...
I guess I can just hack together my own patched version that allows me to specify a port number but I was wondering if there was something obvious I was missing. | I have made changes to PySimpleGUIWeb on the GitHub site. You will need to download the file PySimpleGUI.py file from here to get these changes. The changes expose all of the parameters to the Remi Startup call. In your call to PySimpleGUI.Window, you'll now find these additional named parameters and their defaults:
web_debug=False, web_ip='0.0.0.0', web_port=0, web_start_broswer=True, web_update_interval=.00001
These should give you the level of control you are looking for
These changes have been released to PyPI as PySimpleGUIWeb version 0.11.0. Enjoy! You can get them by doing a pip install:
> pip install --upgrade PySimpleGUIWeb | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "pysimplegui"
} |
How to create a multidimensional array from a one dimensional array in Ruby?
Suppose I have an array:
a=['hello','shivam','how','are','you']
... and I want to make it into a multidimensional array like this below:
[['hello','shivam'],'how',['are','you']]
How do I do this? | def transform ar
[ [ar[0], ar[1]], ar[2], [ar[3], ar[4]] ]
end
this does exactly what you want to do, i cant do more if you dont share the plattern you want it to order... | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -4,
"tags": "ruby, multidimensional array"
} |
How to get Azure webapp config appsettings using Az PowerShell module
For certain reasons I cannot use
az webapp config appsettings list -n appxxx-dfpg-dev4-web-eastus2-gateway-apsvc -g appxxx-dfpg-dev4-web-eastus2
Instead I want to achieve the same result by using Az PowerShell module, is there a way to do so? | You can use this powershell cmdlet Get-AzWebApp.
The sample code:
$myapp = Get-AzWebApp -ResourceGroupName "resource_group_name" -Name "azure_webapp_name"
$myapp.SiteConfig.AppSettings
The test result:
 which work just fine
To make it even more Vim-like I add following:
bind-key -t vi-copy 'v' begin-selection
bind-key -t vi-copy 'y' copy-selection
Which works like Vim's visual select and yank
**Note** : After configuring the file you have to reload it, e.g. with the tmux command `:source ~/.tmux.conf` | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 9,
"tags": "vim, vi, tmux"
} |
How do I convert an array to string using the jinja template engine?
I have an array element called "tags" and would like to convert the array of tags to strings separated by a blank space. But how do you do that in Jinja?
I have tried:
{{ tags|join }} | Actually you are almost there, for join with space, just put it like this:
{{ tags|join(' ') }}
see the jinja docs for more details | stackexchange-stackoverflow | {
"answer_score": 57,
"question_score": 27,
"tags": "python, flask, jinja2"
} |
Why has Ubuntu moved the default mount points?
Why has Ubuntu and many other Linux distributions moved the default mount points from `/media` to `/media/$USER`
Example I plug in a USB drive and it's name is `EXT4-250GB-USB` it used to show up in `/media/EXT4-250GB-USB` but now it shows up in `/media/z/EXT4-250GB-USB`
Why is this and what's the reason behind it? | In fact, Ubuntu as many other Linux distributions have switched to udisks2 which is used for the auto mount feature.
In the new version of udisks, the default mount point is `/run/media/$USER`, but it has been patched by Ubuntu (and some other distributions) to be `/media/$USER` (See this answer from Florian Diesch for more details).
udisks version 2.0.0, which is included in Ubuntu 12.10 doesn't allow you to change the default behaviour which is mounting a file system as non-shared (only accessible by $USER).
Since udisks 2.0.91, it is possible to change the default behaviour so that mounting a file system as shared can be done as before [`/media`] (See this answer from rocko for more details).
The root cause for this change of default behaviour in udisks2 seems clear : the security. It is safer to restrict access to a file system to one particular user instead of giving access to it to all the users of the system. | stackexchange-askubuntu | {
"answer_score": 8,
"question_score": 11,
"tags": "mount, filesystem"
} |
Border radius cutting/image overlapping in Safari
I have looked through a few other questions and answers but still can't get this working in Safari (v 5.1.7).
Here is my code - jsfiddle
.services {
width: 218px;
float: left;
margin-right: 29px;
}
.services img {
border: solid 8px #ccc;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
}
.services a img:hover {
border: solid 8px #333;
-o-transition: all 1s ease 0s;
-ms-transition: all 1s ease 0s;
-moz-transition: all 1s ease 0s;
-webkit-transition: all 1s ease 0s;
transition: all 1s ease 0s;
}
The image is square 218px x 218px, so I'm guessin that has something to do with it, but I wanted it like that so it would look decent enough in older browsers that don't support border radius.
It's probably something simple, but I'm still stuck on this.
Thanks. Al. | Answer from Sitepoint:
Hm, tricky. It works if you put the border on the instead:
Code:
.services {
width: 218px;
float: left;
margin-right: 29px;
}
.services img {
vertical-align: top;
}
.services img, .services a {
border-radius: 50%;
}
.services a {
border: 8px solid #ccc;
display: inline-block;
}
.services a:hover {
border: 8px solid #333;
-o-transition: all 1s ease 0s;
-ms-transition: all 1s ease 0s;
-moz-transition: all 1s ease 0s;
-webkit-transition: all 1s ease 0s;
transition: all 1s ease 0s;
}
You can just use border-radius now, without the vendor prefixes, as all browsers that are going to support it now. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "safari, css"
} |
Should we approve edits that just change "commercial links" to example.com?
According to this, example.com is now the "preferred" example domain and should be used over other domains. Those other domains are blacklisted and aren't allowed in new posts.
Currently, though, there's a user that's going through the posts with "site.com", etc. in them and changing it to example.com. This is often the only change.
I've been rejecting them as too minor, but they often get approved, causing me to second guess myself. Take for example this one.
Should these edits be approved or rejected? | > example.com is now the "preferred" example domain and should be used over other domains.
Well, it's been the "preferred" example domain for well over a decade, predating Stack Overflow by a fair bit.
Regardless, you really don't need a special rule for these. Does the edit make the post better? Easier to understand? Then approve it. Is it making the post _worse?_ Is it pointless busywork on a doomed post? Reject it.
Your example edit wasn't particularly necessary (the URL wasn't hyperlinked) but arguably made a decent post slightly easier to understand. I wouldn't bother making that edit myself unless I was already editing a post, but I wouldn't go out of my way to block it either. | stackexchange-meta | {
"answer_score": 11,
"question_score": 8,
"tags": "discussion, review, suggested edits"
} |
finding min and max from a subset of a list of intervals
Given a list of intervals (shown here with their indexes):
0: 1,3
1: 0,4
2: 5,7
3: 6,9
4: 2,8
And then given an arbitrary in and out from the list indexes, is there a good way to determine the min and max value from the inclusive corresponding intervals?
For example: `0,4` would give you `0,9`. `2,3` would give you `5,9`.
My current solution involves iterating over every interval in range, keeping mins on the in-points and max on the out-points. Wondering if there is a data structure of algorithmic technique I am overlooking to make this faster for when the list of intervals is very long. As the list of intervals does not change, maybe there is some model I can create up front to represent the data differently? | As it can be easily seen that each interval actually indicates a min and a max value.
So the problem becomes: give you 2 arrays, find the min and max value for any specified index ranges.
finding min and max value are similar, so we talk about min here.
First it can be easily done with Segment tree, just as `@Vaughn Cato` said.
and actually we don't need to use a so powerful data structure like `Segment tree`, there's another specific algorithm to solve this, which is called Range Minimum Query.
btw, i've written a post talking about `RMQ`, see < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "algorithm"
} |
How to store table or matrix in Java?
I used to use matrix in octave to store data from data set, in Java how can I do that? Assume I have 10-20 columns and large data, I don't think
int [][]data;
would be the best option. Is nested map the only solution? | Depends on what you need to do. If you know the size of the lists, then an array is definitely ideal since it means you will have instant access (read/write time) to any position in the array, this is very useful for speed.
Maps are better if you dont know the size and it needs to be able to adapt.
And finally, as I discovered in a previous question, if you have a TON of data, and a lot of it will be "0" you might want to also consider using a Sparse Martrix | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "java, performance, data structures, matrix"
} |
Regenerate YML mapping issue in Symfony 2.4
Running a Symfony 2 project, I have recently made a change in my MYSQL database, and I would like to update my schema and model structure inside my symfony project so I can use the new items that are in it.
This is what I try to do from a running instance in production:
php app/console doctrine:mapping:import --force CoreBundle yml
Here is the error I get:
> [PDOException] SQLSTATE[HY000] [2002] Connection timed out
* Core/Bundle exists and was already mapped this way by the past
* Also note that the server is up and running, doing exchanges with the database
* I cannot find a place where to see a more detailed log. Tried to configure the config.yml to add logging for doctrine but it doesn't give me more infos
Thanks in advance | Since I didn't found the source of the problem, I just deployed a new symfony app, connected it to the database and then just generated orm + entities by following the same commands. After that I just copied the /Entity folder and /orm folder and replaced it on my production env. A bit messy but it worked | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, symfony, doctrine, mapping"
} |
HTML5 prevent refresh on submit but allow login save
I have a single page web site with a login. How do I get the browser to prompt to save login details but not refresh the page? I've tried capturing the form submit, which prevents the page refresh, but it also prevents the prompt to save password.
function signOn() {
$(frmSignOn).submit(
function (e) {
var username = $("#iEmail").val();
var password = $("#iPassword").val();
//Do login stuff
e.preventDefault();
}
);
} | Try bellow code to prevent refresh but ask for login save:
$(document).ready(function() {
var frmSignOn=$('form');
$(frmSignOn).bind('submit', $(frmSignOn), function(event) {
var form = this;
event.preventDefault();
event.stopPropagation();
if (form.submitted) {
return;
}
form.submitted = true;
var username = $("#iEmail").val();
var password = $("#iPassword").val();
//Do login stuff
});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, html"
} |
What's the difference between GL_TEXTURE_2D and GL_TEXTURE_EXTERNAL_OES
I'm new to OpenGL ES in android development. I found two types of texture during my study:
1. `GL_TEXTURE_2D`
2. `GL_TEXTURE_EXTERNAL_OES`
I was told that they are not compatible with each other.
I have two questions:
1. What's the difference between them? Are they completely different types of textures?
2. Does `GL_TEXTURE_EXTERNAL_OES` texture has to be `YUV` format? If not, what decides the data format? | > What's the difference between them?
Normal textures are defined, allocated, and managed entirely by OpenGL ES.
External textures are defined and allocated elsewhere, and imported into OpenGL ES in some implementation-defined manner. One common use is for importing YUV video, so external samplers also have to be able to handle color-space conversion and non-standard memory layouts (e.g. multi-plane YUV surfaces).
> Does GL_TEXTURE_EXTERNAL_OES texture has to be YUV format?
No. Some external entity in the system defines the format - it's invisible to the application, and color space conversion is magically handled by the driver stack. Exactly what formats are supported is implementation-defined. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 7,
"tags": "android, opengl es"
} |
how to use NVidia Visual Profiler with OpenCL (on Linux)?
I'm trying to use nvvp to profile opencl kernels. I'm running ubuntu 12.04 64b with a GTX 580 and have verified the CUDA toolkit is working fine (i can run and profile cuda code). When trying to debug my opencl code i get:
`Warning: No CUDA application was profiled, exiting`
Any hints? | nvvp can only profile CUDA applications. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 6,
"tags": "cuda, opencl"
} |
Get index value in python list comprehension (for in preceded with variable)
This syntax is able to define new list above list (or array):
[v for v in ['a', 'b']]
But how to get the index of the list? This doesn't work
[k for k, v in ['a', 'b']]
Expected output
[0, 1] | Probably you have meant indexes, as there are no keys in list. We can get them like this:
indexes = [index for index,element in enumerate(your_list)]
But this isn't really necessary, we can get length of the list and get indexes from it as indexes are from 0 to [length of list]-1:
length = len(your_list)
indexes = list(range(length)) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "python, list, for loop"
} |
How do I control where an R plot is displayed, using python and rpy2?
I'm writing a program in Python. The first thing that happens is a window is displayed (I'm using wxPython) that has some buttons and text. When the user performs some actions, a plot is displayed in its own window. This plot is made with R, using rpy2. The problem is that the plot usually pops up on top of the main window, so the user has to move the plot to see the main window again. This is a big problem for the user, because he's lazy and good-for-nothing. He wants the plot to simply appear somewhere else, so he can see the main window and the plot at the same time, without having to lift a finger.
Two potential solutions to my problem are:
(1) display the plot within a wxPython frame (which I think I could control the location of), or
(2) be able to specify where on the screen the plot window appears.
I can't figure out how to do either. | Plot to a graphics file using `jpeg()`, `png()` or another device, then display that file on your wxWidget. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "python, r, plot, rpy2"
} |
Run a command every 5 minutes and stop it at the end of that time
I have to run NodeJS application which has to run uninterruptedly, but I need to stop it and restart it every 10 minutes. I'm Working on a dedicated Ubuntu 18.04 machine. I have read something about cron but I don't know well how it works. Does it stop the command that was run with it? | You can use forever to run the application, and set up a cron job to restart it in forever every five minutes. As a bonus, forever will also restart it for you if it fails in between cron job executions. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "node.js, linux, ubuntu, cron"
} |
Swift OpenGL es enums
When using Swift to create an OpenGL app I get this error whenever I use OpenGL commands, for example:
glBindRenderbuffer(GL_RENDERBUFFER, self.colorRenderBuffer)
I get an error '`Int32`' is not convertible to '`Glenum`'
Any ideas how to fix this? | Constants like the ones OpenGL uses are imported in Swift as top-level variable declarations instead of enum declarations. Because OpenGL doesn't actually use an enum, you'll have to explicitly construct a `GLenum` with `GL_RENDERBUFFER` as its primitive value:
glBindRenderbuffer(GLenum(GL_RENDERBUFFER), 0) | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "ios, swift, opengl es"
} |
"fastestmirror" like plugin for Ubuntu?
> **Possible Duplicate:**
> How can I get apt to use a mirror close to me?
Are there any plugins for apt like the fastestmirror on e.g.: Fedora?
So that the selected repo mirror for Ubuntu is always fast (because the plugin always uses the fastest server)
Thank you! | There is the option to find the fastest Server in Synaptic. You can also do that by hand in a script. That script would for instances ping all mirrors in the list, selecting the fastest and then edit the sources.list accordingly.
There was a question about this recently. Will look for it. Please stand by.
Edit:
Lenkenstyen's comment answers the gui-part and for newer versions the console part.
As for the console part on older versions of ubuntu you could consulte the link postet earlier in this sentence. | stackexchange-askubuntu | {
"answer_score": 2,
"question_score": 3,
"tags": "apt, repository, mirrors"
} |
Nvidia driver can't run with the newest Kernel
I'm using Ubuntu 14.04.3LTS, I just updated my Kernel to 4.2.0-21 via tty1 but my PC didn't show login screen.I tried :
* Reinstall Nvidia driver 358 (PPA) but it didn't work with new kernel
* Reinstall Nvidia driver 358 (PPA) with old kernel ( 4.2.0-19-generic ) and it's working ok.
How can I fix the problem with new Kernel?
### _If I can provide more information, please don't hesitate let me know!_ | Install supported Nvidia drivers from the official Ubuntu repository by running:
sudo apt-get purge 'nvidia.*'
sudo apt-get install nvidia-352 | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": -1,
"tags": "14.04, nvidia"
} |
How to fade out textarea after copying the value?
I have this basic HTML code:
<textarea id="textarea" cols="30" rows="10">This is sample value</textarea>
How can I fade out the textarea after 1 second after user press `Ctr + C` after selecting or right click and copy the text `This is sample value` in the textarea? | You can use jQuery `copy` event along with `setTimeout` function:
$('#textarea').on('copy', function() {
setTimeout(function() {
$('#textarea').fadeOut();
}, 1000);
});
**FIDDLE** | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery, copy, textarea, fadeout"
} |
Paraxial wave equation solution?
I am looking for a worked solution to the paraxial wave equation, since most sources just say that _clearly_ Gaussians are solutions but they do not explicitly show so.
This equation is equivalent to the TDSE for a free particle, if we replace _z_ by _t_.
$$\frac{\partial^2 \Psi(x,y,t)}{\partial^2 x} + \frac{\partial^2 \Psi(x,y,t)}{\partial^2 y} = 2ik\frac{\partial \Psi(x,y,t)}{\partial t} $$ | The PDE you have written is non other than the heat equation with proportionality constant $\alpha = 2 i k$. Typically it can be solved using Green's function techniques, which you can see on Wikipedia.
In any case, the reason they probably say $\textit{clearly}$ is because you can solve the 1+1-dimensional ($\frac {\partial \Psi} {\partial y} = 0$) equation by using Fourier series and seperation of variables. Fourier series are naturally composed of $\sin$ and $\cos$ functions, i.e, exponentials which resemble Gaussians to some extent. The natural attempt to generalise this to the higher $2+1$ (or $n+1$) dimensional case is then to assume the $\textit{ansatz}$ of a Gaussian and see if it solves it.
Edit: To actually know your Fourier series solution is the Gaussian one is a bit tricky, I'm unsure of the best way to see this except an ad-hoc expansion of your Gaussian and a matching procedure. | stackexchange-physics | {
"answer_score": 1,
"question_score": 2,
"tags": "quantum mechanics, quantum optics"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.