INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Asymmetric Key Systems?
I understand the basic system of public vs. private keys and how if I want to send a person something, I need their public key and they decrypt with their private key, but what kind of logical mechanisms are at play so that a private key can decrypt what a public key encrypted? For example, say I wanted to write my own asymmetric key system. How would I go about generating these keys in pairs and how would I implement them?
I know there's not just one way to do it, but I am just trying to wrap my head around any way of doing it.
|
All these systems are based on mathematics. Check out
<
it goes through the math.
At one point I actually understood that stuff ;)
To generate the keys, you would need some extremely large prime numbers (for them to be useful in practice, you can do it with 7 and 11 if you want, but thats not so secure).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "encryption asymmetric"
}
|
Melf's Acid Arrow and Bonus damage
Due to some _Lucky Dice_ (the soulmeld) from _Magic of Incarnum_ book, I am getting +1 generic bonus damage (a luck bonus).
This seems to quite clearly apply to the initial damage of Acid Arrow, but how does this work with the repeating acid damage?
1. The repeating damage is not augmented at all.
2. The repeating damage is augmented with the _Lucky Dice_ bonus the caster had when the spell was cast.
3. The repeating damage updates its damage bonus to the caster's current _Lucky Dice_ bonus, every round.
|
With each swift action you use to activate _lucky dice_ , you can gain a +1 bonus to damage rolls made before the beginning of your next turn. That includes the damage roll you make for _acid arrow_ ’s lingering damage. So the answer to your question is 3, each damage roll receives a bonus based on _lucky dice_ at the time it was rolled. You don’t get to “bake in” the _lucky dice_ bonus, extending it for the duration of your _acid arrow_ spell, but you do get the bonus.
Please note that _acid arrow_ is a pretty weak spell, and _lucky dice_ are a **very** weak soulmeld. Neither comes recommended.
|
stackexchange-rpg
|
{
"answer_score": 3,
"question_score": 2,
"tags": "dnd 3.5e, spells, meldshaping"
}
|
Simulate localization in a Android device with debug mode
I connect my tablet android galaxy 2 to my pc for debug my application with eclipse, it runs good but I am trying to simulate the location in a google map that I included into my app.
I try with gps android simulator and seems that it connect to the port (8600 in my case) it sends the location but nothing happens. And for example with the port 5554 says that it can't connect.
After that, I tried with telnet: `telnet localhost 8600` but it did nothing, it did like a "clear" in console.
I have search on internet but I didnt found an answer.
I checked:
1. manifest: `<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />`
2. Android device settings to enable simulate location.
I am very frustated with it because I need it. Thanks for your replys.
|
There's an app called Fake GPS on Play Store which might help. See this question.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, eclipse, debugging, mocking, android debug"
}
|
How to use a regex to find combined words with period delimiters?
I am trying to find all instances of words separated by period delimiters.
So for example, these would be valid:
word1.word2
word1.word2.word3
word1.word2.word3.word4
Valid letters of words are those composed of `a-zA-Z0-9-`. And so on. I tried `[\w.]*` but this does not appear to be accurate.
|
You can use the following:
[a-zA-Z0-9]\w+(?:\.\w+)+
See DEMO
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, regex"
}
|
Possible to re-use a Fragment instance across multiple Activities?
If I add a `Fragment` instance to `Activity` `A` as follows...
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, myFragment, "MY_FRAGMENT_TAG")
.commit();
... And then I start `Activity` `B` on top of `Activity` `A`. Is it possible (?) to get a handle on the previously committed `Fragment` instance in `Activity` `B` something as follows...
getSupportFragmentManager()
.findFragmentByTag("MY_FRAGMENT_TAG");
... This returns `null` so I wonder if this is possible using the approach above or otherwise??
|
It is not possible, you can use Fragments only in its FragmentActivity.
In SDK doc, it says A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. **A Fragment is closely tied to the Activity it is in, and can not be used apart from one.** So, you can't.
Please read the reference document: <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "android, android fragments, android fragmentactivity, android support library"
}
|
Reading data from USB Printer in C#
I have a CUSTOM PLUS II USB printer that I need to send and receive status information.
I am able to send commands to the printer using the WritePrinter method using winspool but can't read the response. I can't find a single working example of the ReadPrinter method.
This is the main example I have used for writing data: <
I have tried to contact CUSTOM but get no response from them. Any other way to read from a USB printer would also be helpful.
|
It is called Bidi Communication. The SDK topic starts here. Beware for the rough ride, this is not friendly. Especially not in C#, these are COM interfaces without a type library.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#"
}
|
Vertex group is not moved by bone (only overlapping vertices seem to move)
I have bones for the forefoot (Element.005) and the heel (Element.006) of a foot:
 appear to be moving. The heel stays where it is.
Can somebody explain why this is the case? Many thanks!
 &= \sum_{n=0}^{\infty} \left( \sum_{k=0}^{n} {n \choose k} a_k \right)\\\ &= \sum_{n=0}^{\infty} \left( \sum_{k=0}^{n} {n \choose n-k} a_k \right) \end{align} This looks like the product of two generating functions $A(x)$ ( for $a_n$ ) and $C(x)$. Hence the given sequence $b_n$ is an convolution of two $a_n$ and some $c_n$.
If now I can find $c_n$, and a closed form for $C(x)$ (which I believe exists), the sequence $a_n$ can be found since $$A(x) = \frac{B(x)}{C(x)}$$
* * *
**My question:**
I am unable to find the sequence $c_n$. I tried using $c_k = {n \choose k}$ but I am quite sure that it is incorrect.
|
Here we are looking for so-called _binomial inverse pairs_. To show the relationship we multiply exponential generating functions (egfs). Let $A(x)=\sum_{n\ge0}a_{n}\frac{x^n}{n!}$ and $B(x)=\sum_{n\ge0}b_{n}\frac{x^n}{n!}$ egfs with $B(x)=A(x)e^x$. Comparing coefficients gives the following
> _Binomial inverse pair_ \begin{align*} B(x)&=A(x)e^x&A(x)&=B(x)e^{-x}\\\ b_n&=\sum_{k=0}^{n}\binom{n}{k}a_k&a_n&=\sum_{k=0}^{n}\binom{n}{k}(-1)^{n-k}b_k \end{align*}
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "generating functions"
}
|
Using Entity Framework, how do I specify a sort on a navagation property?
I have two tables: [Category], [Item]. They are connected by a join table: [CategoryAndItem]. It has two primary key fields: [CategoryKey], [ItemKey]. Foreign keys exist appropriately and Entity has no problem pulling this in and creating the correct navigation properties that connect the entity objects.
Basically each category can have multiple items, and items can be in multiple categories. The problem is that the order of items is specified per category, so that a particular item might be third in one category but fifth in another.
In the past, I have added a [Sequence] field to the join table and modified the stored procedure to handle it. But since Entity is replacing my stored procedures, I need to figure out how to make Entity handle the sequence.
Any suggestions?
|
`EntityCollection`s are unordered. You can read about this here. The workaround, when you need an ordered list, is to project onto a POCO presentation model or DTO:
var q = from c in Context.Categories
select new CategoryPresentation
{
Key = c.Key,
Items = from ci in c.CategoryAndItems
orderby ci.SequenceNo
select new ItemPresentation
{
Key = ci.Item.Key,
// etc.
},
// etc.
};
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, database, entity framework"
}
|
delete memory automatically allocated by assignment of a literal
char *str = "hi";
delete [] str;
I wonder why we can't free memory by delete operator? I'm getting an exception 'Runtime error', when doing this.
`char *str = "hi";` automatically allocates memory and writes string in it.
So delete operator should work, or am I wrong with this assumption?
|
> I wonder why we can't free memory by delete operator?
You don't need to in this case!
> `char *str = "hi";` automatically allocates memory and writes string in it.
No it doesn't! This all happens at compile time (and should even leave you a warning).
You didn't allocate `str`, you assigned a pointer to a `const char*` literal (the compiler is allowed to place wherever the implementation wants to), thus you can't delete it.
Dynamic allocation as managed with `new()` and `delete` would mean something like
char* str = new char[3];
strncpy(str,"hi",3);
// ...
delete [] str;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": -3,
"tags": "c++"
}
|
ruby convert array into function arguments
Say I have an array. I wish to pass the array to a function. The function, however, expects two arguments. Is there a way to on the fly convert the array into 2 arguments? For example:
a = [0,1,2,3,4]
b = [2,3]
a.slice(b)
Would yield an error in Ruby. I need to input `a.slice(b[0],b[1])` I am looking for something more elegant, as in `a.slice(foo.bar(b))` Thanks.
|
You can turn an `Array` into an argument list with the `*` (or "splat") operator:
a = [0, 1, 2, 3, 4] # => [0, 1, 2, 3, 4]
b = [2, 3] # => [2, 3]
a.slice(*b) # => [2, 3, 4]
### Reference:
* Array to Arguments Conversion
|
stackexchange-stackoverflow
|
{
"answer_score": 130,
"question_score": 109,
"tags": "ruby, arrays, function, arguments"
}
|
Why does North Korea test their nuclear weapons underground?
When the U.S. and the Soviet Union were testing their nuclear bombs during the Cold War, they did the testing above ground. Why does North Korea test their nuclear weapons below ground, and how is it even possible to test a nuclear weapon underground?
|
# Why?
We now understand that nuclear explosions produce fallout, especially ground bursts. That was only partly understood in the early years, and there was a war on. It is much smarter to test deep underground, especially if one has nothing the size of Nevada or Kazakhstan.
# How is it possible?
The effects will differ when there is an underground burst, but North Korea is **not** trying to investigate the effects of a ground burst or air burst. Those are known well enough for their purpose in open literature. What North Korea wants is to prove that they can cause a nuclear explosion -- that can be done underground.
It is an interesting question if North Korea has a weaponized warhead or "only" something the size of a room, but it would be stupid to assume that their warheads are not weaponized.
|
stackexchange-politics
|
{
"answer_score": 17,
"question_score": 1,
"tags": "united states, north korea, nuclear weapons, soviet union"
}
|
a simpler test for normality given skewness, kurtosis and autocorrelation and size of time series
I typically do a JB (Jarque Bera) test and DW (Durbin Watson) tests for check for normality given skewness, kurtosis and autocorrelation of the data. However this requires a CHI distribution table lookup and some calculation. I was wondering if there is a simple less accurate test that I can do on the data to check if it is normal or not?
Secondly How do I numerically test for I.I.D ?
|
There are simple visual tests for normality and i.i.d.
To test for nomality, simply look at the distribution of the observations and overlay the normal density function as in the following chart:
!enter image description here
The blue line represents the normal distribution. The black bars are from the histogram representing the empirical distribution. Clearly the data is leptokurtotic is skewed to the right.
To test whether the data is i.i.d., simply partition the data set into different periods and plot the frequency distribution:
!enter image description here
Notice the distribution has shifted from Period 1 to Period 2 -- therefore this data is not i.i.d.
|
stackexchange-quant
|
{
"answer_score": 0,
"question_score": 3,
"tags": "time series, normal distribution, testing"
}
|
Looping a section of code with different variables in python?
I am designing a quiz which has to save three different scores to a file. How would I loop this and are you able to change the variable names? For example, the first time it loops, score1, then score2 then score3.
Thanks For the help in advance
|
You can use a dictionary, with the three values indexed with keys, and change a variable who contains the current key's name.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -5,
"tags": "python, loops, variables"
}
|
Report builder field with mutiple values separated by a colon
I'm new to report builder and I'm trying to something like this:
Part A:
serialNum,serialNum,serialNum,serialNum,serialNum...
Part B
serialNum,serialNum,serialNum,serialNum,serialNum...
. . for all the parts in an invoice
Another choice would be in columns Part A
serialNum serialNum serialNum serialNum serialNum
serialNum serialNum serialNum serialNum serialNum
Does anybody how to achive this or something similar with Report Builder?
|
Create a tablix (white color) with the a row group on part values with two rows. On the first row you will display the part value
Create a tablix (blue color) with a column group on serial values. Delete the row group and hide the detail.
Now drag the tablix(blue color) with the column group on the 2nd row of the tablix (white color) with the row group.
;'>cell3</td></tr>")
My problem is that if I wanted the message box to say "hello", I can't get it to work because of the quotes, any ideas?
It's a quote within a quote within a quote and my brain is melting.
Thanks for any help in advance.
|
try putting a backslash \ before the quotes around the word hello (for example).
you can programmatically do that if it works out for you when hardcoded... but let's see if it helps you first.
the following answer also suggests how to programmatically replace all quotes in your string with escaped quotes, so you don't have to hard code them:
How do I replace a double-quote with an escape-char double-quote in a string using javascript?
sample:
str.replace(/"/g, '\\"');
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "javascript, html"
}
|
How to find the limit of a matrix $P^n = UD^nU^{-1}$ where $D$ is a diagonal matrix of eigenvalues and $U$ a matrix of eigenvectors?
If we have a matrix where $P = UDU^{-1}$, where $D$ is a diagonal matrix of real eigenvalues that are less than or equal to 1, and $U$ is the corresponding matrix of eigenvectors, how can we show that the limit of $P^n = UD^nU^{-1} \to u_1v_1'$, where $u_1$ is the column vector for $U$ and $v_1$ is the row vector of $U^{-1}$?
|
From your notation and tags we can surmise that you are dealing with a transition matrix $P$ for a Markov chain. A typical situation in this context is that $1$ is an eigenvalue with multiplicity $1$ and that all other eigenvalues are less than $1$ in modulus. Your result follows immediately under those conditions as explained by user7530.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, probability, markov chains"
}
|
Geometric meaning of derivative of a complex valued function
I know that a derivative of a real valued function at a point measures the slope of the tangent at that point. I am wondering what could be the geometric meaning of derivative of a complex valued function at a certain point?
|
The geometric meaning of having $f'(z_0)=0$ is that, if you consider the graphs of $\operatorname{Re}f$ and of $\operatorname{Im}f$, then the graph is smooth near $z_0$ and its tangent planes there are horizontal.
On the other hand, asserting that $f'(z_0)=c\neq0$ means that $f$ maps a tiny circle near $z_0$ ($t\mapsto z_0+re^{it}$, with $t\in[0,2\pi]$), seen as a point that moves once clockwise around $z_0$, starting tat $z_0+r$, into a small circle near $f(z_0)$, whose radius is the radius $r$ of the original circle times $\lvert c\rvert$ and whose initial point is about $f(z_0)+cr$. Actually, this circle is very close to $t\mapsto f(z_0)+cre^{it}$ and, in particular, if you see it as a point that moves around $f(z_0)$, it moves once and clockwise.
That's why the conjugation is differentiable nowhere: it reverses the orientation of the movement of the point around $f(z_0)$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, complex analysis"
}
|
Fedora - Python import selinux cannot find selinux_current_policy_path
When I run any python script that does `import selinux` (such as `system-config-users`) I get the following error:
ImportError: /usr/lib64/python2.7/site-packages/selinux/_selinux.so: undefined symbol: selinux_current_policy_path
I think it must be something that I uninstalled at one time. But I don't have a clue what to install to fix it.
How do I fix it/What packages do I need to install?
|
You didn't say which FC you're running, there was a bug in libselinux recently. Run `yum update libselinux` to update your version.
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linux, fedora, python, fedora 17"
}
|
ifstream does not completely read whole data
I'm trying to read a file block by block. Blocksize is 64Byte. But some bytes are left.
Example: I have a 360 Byte file and read the data in 64byte blocks, so I need 6 times a 64 byteblock to get all data.
typedef unsigned char uint1;
ifstream is(path.c_str(), ifstream::in | ifstream::binary);
uint1 data[64];
int i = 0;
while (is.read((char*)data, 64)) {
i++;
}
cout << i << endl;
But I only get 5 times a completely filled 64-Byte Block. How to get the remaining Bytes??
|
360 is not divisible by 64, which means that the last block will not be read in its entirety. Consulting suitable documentation shows that reading such an incomplete block sets both `eofbit` and `failbit` on the stream from which you're reading, which means the condition in your `while` loop will evaluate to `false` for the last block. But the read _did_ actually happen and _the data is stored correctly._
You might want to check the value of `gcount()` after the last read:
while (is.read((char*)data, 64)) {
i++;
}
if (is.gcount() > 0) {
i++;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c++, byte, ifstream"
}
|
Non-WWW site redirects to WWW explicitly?
I recently moved my NodeJS app to a new Openshift server.
Visiting www.lsmsaSGO.com works as expected. Visiting lsmsaSGO.com seems to redirect explicitly to www.lsmsaSGO.com in the URL bar. I do not want this behavior.
I have another site set up almost identically which will use non WWW domains if the user types elsealabs.com, but will use WWW domains if the user types www.elsealabs.com. This is the desired behavior for lsmsaSGO.com.
Do I need the page rule in the final image? Can anyone help or offer some advice on how to obtain this behavior?
 from `lsmsasgo.com/<anything>` to `www.lsmsasgo.com/<anything>`. What happens if you delete that? Or change the www to xyz? The xyz page won't load, but you should see the redirect change from lsmsasgo.com -> www.lsmsasgo.com to lsmsasgo.com -> xyy.lsmassgo.com, which will tell you it is that setting.
|
stackexchange-superuser
|
{
"answer_score": 7,
"question_score": 4,
"tags": "networking, dns, node.js, vps, cname"
}
|
Wrong partition size during install?
Installed Debian 9.6 in VirtualBox 25GB vhd and partitioning said that:
"Maximum size for this partition is 26.8GB"
"New partion size 26.8GB".
`df` shows 25669860, which seems to be correct.
Where did that extra 1.6GB come during installation?
|
That's because the installer displays the size in decimal gigabytes, whereas other utilities use binary gigabytes.
In bytes, 25 * 2^30 = 26,843,545,600; or, in larger units, 25 GiB = 26.8 GB.
* One binary gigabyte (sometimes called a gibibyte) is 2^30 = 1,073,741,824 bytes.
* One decimal gigabyte is 10^9 = 1,000,000,000 bytes.
(This is an old dilemma. Generally, the prefixes kilo-, mega-, giga-, tera- etc. refer to powers of 10. By abuse of language, it became usual to use them loosely to refer to powers of 2 which have values close to the corresponding powers of 10. Commonly, the binary meaning is almost always meant when speaking of memory capacity; and the decimal meaning is almost always meant when speaking of bandwidth. But for disk storage capacity some utilities default to the decimal meaning, and others to the binary meaning.)
|
stackexchange-unix
|
{
"answer_score": 3,
"question_score": 0,
"tags": "partition, debian installer"
}
|
Prove: Im$\left(\frac{1+re^{i\theta}}{1-e^{i\theta}}\right) = \frac{2r\sin\theta}{1-2r\cos\theta + r^2}$
Prove the identity: $\operatorname{Im}\left(\dfrac{1+re^{i\theta}}{1-e^{i\theta}}\right) = \dfrac{2r\sin\theta}{1-2r\cos\theta + r^2}$
My only lead is to assume $r$ and $\theta$ are real.
Then,
$\operatorname{Im}\left(\dfrac{1+re^{i\theta}}{1-e^{i\theta}}\right) = \dfrac{r\sin\theta + \sin\theta}{\sin^2+(1-\cos\theta)^2}$
|
RTP: $Im\bigg(\dfrac{1+re^{i\theta}}{1-e^{i\theta}}\bigg) = \dfrac{2r\sin\theta}{1-2r\cos\theta + r^2}$=$\frac{2r\sin\theta}{(r-\cos\theta)^2+1-\cos^2\theta}$
$$Im\bigg(\dfrac{1+re^{i\theta}}{1-e^{i\theta}}\bigg) = Im\bigg(\frac{(1+r\cos \theta+ri\sin\theta )(1-\cos\theta +i\sin\theta)}{(1-\cos\theta-i\sin\theta)(1-\cos\theta+i\sin\theta)}\bigg)$$
$$=Im\bigg(\frac{1-\cos\theta+i\sin\theta+r\cos\theta-r\cos^2\theta+r\sin\theta\cos\theta \cdot i +r\sin\theta \cdot i-r\sin\theta\cos\theta\cdot i-r\sin^2\theta}{1-\cos\theta +i\sin\theta -\cos\theta+\cos^2\theta-\cos\theta\sin\theta\cdot i -i\sin\theta +\sin\theta\cos\theta\cdot i +\sin^2\theta}\bigg)$$
$$= \frac{\sin\theta+r\sin\theta}{1-2\cos\theta+\cos^2\theta+\sin^2\theta}$$
$$= \frac{(r+1)\sin\theta}{2(1-\cos\theta)}$$
I don't see how to arrive at the identity from here, could someone comment if they see an error/ way to proceed?
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "complex analysis"
}
|
SWIFT: Remove an item from an array of Structs
I have an array of structs and now I want to create functionality that allows me to remove the struct by index path. I understand that structs are immutable, so any advice on how to solve this issue?
The line of code I was using to solve this was:
arrayOfStruct.removeAtIndex(index)
And this led to the error: Immutable value of type '[Struct]' only has mutating members named 'removeAtIndex'
_[clarifying edit]_
arrayOfStruct is declared within this class as:
var arrayOfStruct: [Struct] {
return (UIApplication.sharedApplication().delegate as! AppDelegate).arrayOfStruct
}
|
You have declared an accessor to your AppDelegate `memes` property as a _computed property_. Read up on the Swift spec -- computed properties are indeed read-only.
However, a read-only _class reference_ can be used as a through-way to a writable structure within.
Probably you're trying to make an accessor that's not as verbose. Your shortcut will need to be:
MemeMe/MemeTableViewController.swift, line 14-16:
var appDel: AppDelegate {
return (UIApplication.sharedApplication().delegate as! AppDelegate)
}
And then whereever you had `self.memes` before replace with `self.appDel.memes`:
MemeMe/MemeTableViewController.swift, lines 31-33:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return appDel.memes.count
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "arrays, swift, struct"
}
|
AWS CodeDeploy :bucket option must not contain a forward-slash (/)
I am kicking off a deployment from aws-cli:
"C:\Program Files\Amazon\AWSCLI\bin\aws.exe" deploy create-deployment --application-name App.Web --deployment-config-name CodeDeployDefault.OneAtATime --deployment-group-name Development-Staging-UAT --region us-west-2 --description "App.Web" --s3-location bucket=app-artifacts/development,bundleType=zip,key=Publish.zip
This does kick off a deploy but end with error in the DownloadBundle section:
:bucket option must not contain a forward-slash (/)
Revision location **s3://app-artifacts/development/Publish.zip**
What am I doing wrong?
|
"C:\Program Files\Amazon\AWSCLI\bin\aws.exe" deploy create-deployment --application-name App.Web --deployment-config-name CodeDeployDefault.OneAtATime --deployment-group-name Development-Staging-UAT --region us-west-2 --description "App.Web" --s3-location bucket=app-artifacts,bundleType=zip,key=development/Publish.zip
Need to removed the /development from bucket and add it part of the key
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "aws cli, aws code deploy"
}
|
SwingWorker get not finishing
I have been using quite some SwingWorkers recently, and had some issues so I tried to create an SCSSE, but that apparently doesn't want to work
static SwingWorker worker;
public static void main(String[] args) {
worker = new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
return "Hello";
}
protected void done() {
System.out.println("I'm done!");
};
};
System.out.println("working");
try {
System.out.println("result: " + worker.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("working finished");
}
when this is executed, it prints "working" and then the script continues to run indefinitely...
|
You never start the `SwingWorker`, so the `worker.get()` method is blocking while it waits for the worker to complete.
You can verify this by adding:
System.out.println("waiting for result");
System.out.println("result: " + worker.get());
If you want the `SwingWorker` to execute then you need to invoke:
worker.execute()
after you create the `SwingWorker`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, swing, swingworker"
}
|
swap memory is almost used ,but processes are running fine.Should i be bothered?
`free -m` on my Linux machine shows that swap memory is almost completely used. However,there is no impact on the system performance. But should i be really bothered? Swap cache also is not used to its fullest? So will this actually impact the performance? Please suggest
**free -k**
total used free shared buffers cached
Mem: 32959100 32786348 172752 0 85096 30303388
-/+ buffers/cache: 2397864 30561236
Swap: 4192956 4188456 4500
**cat /proc/meminfo|grep Swap**
SwapCached: 184012 kB
SwapTotal: 4192956 kB
SwapFree: 11584 kB
**swappiness is 60**
Also we can see that lot of free memory under buffers/cache is available .So why is my swap memory used heavily??How will it effect the performance in future?
|
Judging by the answer to this question on Sever Fault it looks like all your swap file _is_ in use but you are not even remotely coming close to being memory starved.
The buffers/cache line suggests that while you do have 30gb of memory in the disk cache, most of it is ready to be freed when needed. If the larger number was in the "used" column then you would have a large quantity of data waiting to be written to disk.
As it is the fact that it is all just cached data I would suspect you have 2gb of live application data in memory and the rest being used by the disk cache.
It is entirely possible that linux has preemptively pages out all the application data it can, but that the data is still stored in RAM as well. Just because your page file is full does not mean that you have no memory available for the system to use.
To quote the page I linked:
> A Linux system is really low on memory if the `free` value in `-/+ buffers/cache:` line gets low.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linux, memory"
}
|
Error accessing Birthday variable using Watir during gmail sign-up
I am trying to create the gmail account through watir. As part of it while I am trying to select the birthday using div element I am unable to do.
I tried with the below one:
@ie.div(:text,'May').click
My system configurations:
IE-8
Windows-7
|
As @titusfortner indicates, that element cannot be selected/clicked because it is not visible. Using watir-webdriver, this snippet makes the dropdown menu visible so its options can be selected:
b.div(title: "Birthday").when_present.click
b.div(text: "May").when_present.click
That being said, there are two other (read: larger) issues:
1. You won't be able to script your way past the captcha.
2. Google doesn't want you doing this. That's why the captcha is there, and they'll eventually block your IP if you consistently automate/script against them.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ruby, watir, watir webdriver, firewatir"
}
|
Subtracting two dates (including hours and minutes) considering only working time vba or Excel
I need to subtract two dates (including hours and minutes), but I only need to consider working hours. That is, I need to omit lunch time (from 13 to 14 hrs), weekends and hours after 18 hrs and before 9 hrs of the following day, in a working day (from Mo to Fr). Any thoughts? I don't mind if it's an Excel formula or a vba code. I have this formula, but it doesn't omit lunch time:
9*(NETWORKDAYS(initial_time;ending_time)-1)-24*((MOD(initial_time;1)-MOD(ending_time;1)))
|
Here's a possible solution. It assumes an 8 hour work days for all but the start and end date. Also that start date/time is 9:00 or after and end date/time is 18:00 or earlier and that both are on a weekday.
=(NETWORKDAYS(A2,B2)-2)*8+IF(MOD(A2,1)>0.58333,(TIME(18,0,0)-MOD(A2,1))*24,(TIME(18,0,0)-MOD(A2,1))*24-1)+IF(MOD(B2,1)>0.58333,(MOD(B2,1)-TIME(9,0,0))*24-1,(MOD(B2,1)-TIME(9,0,0))*24)
.58333 equates to 14:00. The formula: multiplies networkdays * 8 \+ hours from start date/time until 18:00 subtracting 1 hour if start time is before 14:00 \+ hours from 9:00 until end date/time subtracting 1 hour if end time is after 14:00
Of course this doesn't take any holidays into account.
 {
return mDb.query(YOUR_TABLE, new String[] { RECORD_ROWID,
RECORD_HOUR, RECORD_VALUE }, RECORD_MONTH + "=" + month + " AND " + RECORD_DATE + "=" day,
null, null, null, null);
}
Hope this helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "android, sqlite, sql"
}
|
Count sum of value for each element in coma separated column in R
I have a dataframe such as :
VALUE Names
1 Sp1,Sp2
1 Sp2
2 Sp3,Sp4
4 Sp2,Sp1
And I would like to count for each `df$Names` in coma separated way, the sum of `df$VALUE` and get a new dataframe such as :
Name Sum
Sp1 5
Sp2 6
Sp3 2
Sp4 2
Here is the dataframe in dput format if it can helps:
structure(list(VALUE = c(1L, 1L, 2L, 4L), Names = c("Sp1,Sp2",
"Sp2", "Sp3,Sp4", "Sp2,Sp1")), class = "data.frame", row.names = c(NA,
-4L))
|
We may use `separate_rows` to split the 'Names' column, and then do a group by `sum`
library(dplyr)
library(tidyr)
df1 %>%
separate_rows(Names) %>%
group_by(Names) %>%
summarise(Sum = sum(VALUE))
-output
# A tibble: 4 × 2
Names Sum
<chr> <int>
1 Sp1 5
2 Sp2 6
3 Sp3 2
4 Sp4 2
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "r, dplyr"
}
|
PHP Class Extensions
I was just wondering if the next situation could be possible or not, I've read the PHP Manual documentation, but I would like another perspective because it's not so clear for me.
So I have for example one class:
class SomeClass {
public function someFunction() {
...
}
}
And an extension of it:
class Extension extends SomeClass {
public function someOtherFunction() {
...
}
}
My question is, could I be able to use the public functions inside the classes on both ways, the main class's function inside the extended function and the other way around?
And would I be doing that how?
|
You can use the `public` and `protected`functions of your parent in the extended (child) class:
class Extension extends SomeClass
{
public function someOtherFunction() {
$foo = $this->someFunction(); // from parent class
return $foo;
}
}
When class "Extension" is created, its basically a copy of "SomeClass" which you can modify in the way as you can add new functions or overwrite those of the parent class.
The parent does not know about the Extension (it can be extended multiple times, eg "JSONRequest extends Request", "XMLRequest extends Request"). Calling extended functions from within the parent makes no sense, since the parent class can never know which childs function it should call in such a situation. This type of Inheritance is one of the basic concepts of OOP and clear interfaces.
In other words, no it will never work the other way round. And it should not.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, class"
}
|
Detect that code run by RSpec, Ruby
I would like to be able to know that my code is run under rspec or not. Is this possible?
The reason is that I am loading some error loggers that would be cluttered with deliberate errors (`expect{x}.to raise_error`) during testing.
I have looked at my `ENV` variable, and there is no (apparent) signs of a test environment variable.
|
Add at the beginning of your `spec_helper.rb`:
ENV['RACK_ENV'] = 'test'
Now you can check in your code whether the `RACK_ENV` is test or not.
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 6,
"tags": "ruby, rspec, environment variables"
}
|
API agnostic Vector3, Matrix, etc.?
I'm trying to keep my game logic API-agnostic. In doing so, I don't want to use Unity3D's Vector3 struct, or XNA's, etc. What's the best way to do this? It seems like it would be awfully cast-heavy if I rolled my own Vector3 struct and just wrote implicit converters to the various API implementations.
Is there a best practice for this kind of thing? It's not like I can ask Microsoft, Unity, etc. to have a picnic and adhere to a common interface.
|
It looks like XNA and Unity implementations of `Vector3` are really similar, the main difference being the case of property names. Too bad there's no way to implement extension properties.
What you could do is create a set of extension methods, together with some conditional compilation (`#if UNITY_3_3` or `#if XNA`) and exclusively use those extension methods to retrieve values in your API agnostic code. This would still allow you to pass the Vector3 object unmodified to platform specific code requiring Vector3's without tons of casting.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "c#, xna, unity3d, slimdx, opentk"
}
|
Wifi no icon and can't add wifi in system preferences
I have reinstalled macos high sierra here are some screen shots. , and I was wondering if it was possible to disable colors completely and just draw the wireframes. I use textures on my quads, but when I use this code:
if (Keyboard.isKeyDown(Keyboard.KEY_F1)) {
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
}
if (Keyboard.isKeyDown(Keyboard.KEY_F2)) {
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);
}
It just only draws lines, and then reverts back to a fill mode. However, you can still see the color bleeding through on the lines when in wireframe mode, and I don't want that. Is there any way to remove that so I have just white lines?
|
if (Keyboard.isKeyDown(Keyboard.KEY_F1)) {
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
glDisable(GL_TEXTURE_2D);
}
if (Keyboard.isKeyDown(Keyboard.KEY_F2)) {
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);
glEnable(GL_TEXTURE_2D)
}
Also if you are changing colors anywhere with glColor3f/glColor4f you will want to create a Boolean of whether or not you are in wire frame mode. If you are then at the beginning of each render call, call glColor3f(1, 1, 1).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, opengl, lwjgl"
}
|
What would cause glass to replace calcium carbonate in shells?
Sea creatures have some very pretty shells. Unfortunately, these shells are quite opaque, and much more boring to look at than they could be.
So what if they were made of glass. It’s not unheard of, glass sponges do it already. Unfortunately there are reasons as to why calcium carbonate is the chosen shell material, such as it’s greater durability.
So I want an explanation as to why aquatic creatures would pass on calcium carbonate and go for glass instead. The scenario can be adjusted from the starting point of earth however much is required, but of course less changes are better.
|
Calcium carbonate is dissolved by acidic waters, while glass is more resistant. There is little point in evolving a shell which is dissolved in the very water you live in.
Therefore acidic waters might push the evolution of shell based on silicon dioxide.
|
stackexchange-worldbuilding
|
{
"answer_score": 8,
"question_score": 2,
"tags": "science based, evolution, xenobiology, fauna, ocean"
}
|
How can I create an infinite loop that kills a process if something is found in dmesg?
I need to create a `while` loop that if `dmesg` returns some/any value, then it should kill a determined process.
Here is what I have.
#!/bin/bash
while [ 1 ];
do
BUG=$(dmesg | grep "BUG: workqueue lockup" &> /dev/null)
if [ ! -z "$BUG" ]; then
killall someprocessname
else
break
fi
done
I don't know if instead of `! -z` I should do `[ test -n "$BUG" ]`
I think with -n it says something about expecting a binary.
I don't know if the script will even work because the BUG lockup halts every process, but still there are few more lines in `dmesg` until the computer gets completely borked - maybe I can catch-up and kill the process.
|
Some issues:
* You are running this in a busy loop, which will consume as much resources as it can. This is one instance where `sleep`ing could conceivably be justified.
* However, recent versions of `dmesg` have a flag to follow the output, so you could rewrite the whole thing as (untested)
while true
do
dmesg --follow | tail --follow --lines=0 | grep --quiet 'BUG: workqueue lockup'
killall someprocessname
done
* The code should be indented to be readable.
* It is really strange, but `[` is the same as `test` \- see `help [`.
|
stackexchange-unix
|
{
"answer_score": 12,
"question_score": 8,
"tags": "linux, bash, scripting"
}
|
Quantas imagens posso gravar num campo blob mysql?
Posso gravar várias imagens num só campo `blob`?
Ou terei que criar vários campos? `Imagem1`, `Imagem2` etc... ?
Queria saber se existe alguma maneira para fazer isso sem ter que criar vários campos.
|
Um campo `blob` guarda um conjunto binário de dados. Você pode armazenar mais de uma imagem, se transformar ambas em um único stream de dados antes. Isso tem dois efeitos colaterais imediatos: você precisa saber onde uma imagem começa e a outra termina, e você necessariamente terá um arquivo maior naquele campo.
Isso pode ser útil se você precisar compactar os dados - vários arquivos em um mesmo pacote compactado podem resultar em uma taxa de compactação maior do que vários arquivos em pacotes separados.
No entanto, acredito que o seu problema seja guardar várias imagens sem saber de antemão quantas imagens terá que guardar para cada registro no banco, certo? Nesse caso o ideal é guardar as imagens em outra tabela, com `chave estrangeira` para onde o registro vai ficar.
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "sql, blob"
}
|
What is the difference between PREMIRRORS and SOURCE_MIRROR_URL
Yocto defines two variables: `PREMIRRORS` and `SOURCE_MIRROR_URL` for source mirroring.
What is the difference between both variables?
|
`SOURCE_MIRROR_URL` is used in `own-mirrors.bbclass` to populate `PREMIRRORS`. Thus, using `SOURCE_MIRROR_URL` and `inherit += own-mirrors` is just a shorthand to populate `PREMIRRORS` for all different fetchers (protocols).
See SOURCE_MIRROR_URL in the Yocto Project Reference Manual
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "yocto"
}
|
Image Won't Show - CSS
I am having a weird issue with a CSS bug for mobile / desktop devices.
On mobile, an image for one of my classes won't show up, but the content area for it will.
On desktop, an image for one of my classes will show up, including the content area for it.
This is how I am creating my image:
<div class="image">
<img src="images/image.jpg" alt="" />
</div>
This is what I am doing in my mobile.css file:
.image {
width: 471px;
height: 513px;
float: left;
}
In another one of my files (for iPhone) I am not showing the image so I am doing this:
.image {
display: none;
}
Could that be causing my issue?
|
@media screen and (max-width: 480px) {
.image {
display : none;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "css, image, html, hidden"
}
|
How do you output a line break in the command view in Matlab when running a m-file?
I have a m-file that outputs some calculations basically this:
disp(['Value ', num2str(i)]);
disp(x)
disp(['Number of iterations ', num2str(iter)])
disp('----------')
However this ouputs stuff rather messy in the command view which is really irritating when debugging the code. I would like to add a couple of line breaks to the output in the command window. However I can't seem to find any information about this, as the Matlab documentation is pretty awful. I've tried stuff like disp('\n') and disp(' ') to no avail.
How do you do it? Can it be done?
|
`fprintf('\n')` should do the trick, likewise `disp(' ')`. In general, `fprintf` is more flexible than `disp`. The main advantage of `disp` is that it has some intelligence and knows how to print out complete objects.
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 16,
"tags": "matlab"
}
|
Rearrange arrays order by specific level index
I have been searching this but did not find any solution anywhere. I want to re order my array with a specific index.
Like this:
$scoreboard = array(
'foo' => array(
'score' => 580,
'game' => 'google',
),
'bar' => array(
'score' => 1385,
'game' => 'facebook',
),
'car' => array(
'score' => 750,
'game' => 'tweet',
),
);
And the output should be like this:
$scoreboard = array(
'bar' => array(
'score' => 1385,
'game' => 'facebook',
),
'car' => array(
'score' => 750,
'game' => 'tweet',
),
'foo' => array(
'score' => 580,
'game' => 'google',
),
);
See that the array is rearranged with each item's 'score' index. Any help here?
|
Expanding on on my comment where I suggested to use the uasort function, here is a working sample: <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, arrays"
}
|
Bounded Holomorphic Function - Banach Space?
Can someone, help me in this question, please?
> Let $U\subset\mathbb{C}$ be open set and $H_\infty(U)=\\{f:U\to\mathbb{C}:f\text{ is bounded and homolorphic}\\}$. Show that $H_\infty(U)$ is a closed subset of $C(U)=\\{f:U\to\mathbb{C}\text{ continuous}\\}$, with respect the norm $$ \|f\|=\sup\\{f(x):x\in U\\} $$
This is a random question, of random studies on function analysis, and I don't have a good background in complex variables.
Given a sequence $(f_n)$ in $H_\infty(U)$ that converges to $f\in C(U)$, i would like to prove that the limit commutes with the derivative (or partial derivatives of the real/imaginary parts), hence $f$ satisfies the Cauchy-Riemman conditions, so $f$ is holomorphic.
But, since the derivative operator is not continuous (or is it in these conditions?), this isn't true, and i have no idea what to do...
Any help will be appreciated!
Thanks!
|
This follows from Morera's Theorem:
_Suppose $f: U \to \mathbb{C}$ is continuous and for any triangle $T$ contained in $U$ we have $$\int_T \\! f(z) \, dz = 0.$$ Then $f$ is holomorphic._
(You can find a proof in _Complex Analysis_ by Stein & Shakarchi.)
Now just note that if $f_n: U \to \mathbb{C}$ is holomorphic and $f_n \to f$ uniformly, then for any triangle $T$ in $U$ we have $$\int_T \\! f(z) \, dz = \lim_{n \to \infty} \int_T \\! f_n(z) \, dz = \lim_{n \to \infty} 0 = 0$$ by Cauchy's Theorem.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 4,
"tags": "complex analysis, functional analysis"
}
|
Is there a name for this type of relation?
Let $S$ be a set. Let $\sim$ be a binary relation on $S$. Suppose $\sim$ follows these three rules.
1. $x\sim x$ for all $x\in S$ (reflexivity).
2. If $x\sim y$, then $y\sim x$ for all $x, y \in S$ (symmetry).
3. If $x_1\sim x_2 $, $x_2\sim x_3 $, $x_3\sim \cdots$, then there exists an $n>2$ in the indices of this chain of similarities such that $x_1\nsim x_n$.
I'm trying to capture kind of "partial" or "fuzzy" transitivity. I'm not sure if these are quite the right rules and I'd be happy for anyone to refine them. It reminds me of that children's game, "Whisper Down the Lane", where children in a row whisper a message into each others' ears. Eventually, the final message does not resemble the initial one at all, nor probably a few others.
Update: See comments for modifications on this definition.
|
These rules seem to be inconsistent. For example, $x\sim x\sim x\sim x\cdots$, so the third rule cannot hold in this case.
A relation that seems to meet what you want, on $\mathbb{R}$, is $D_h(x,y)$ where $xD_hy$ if and only if $|x-y|\le h$. It doesn't meet the third condition, but it models the children's game.
|
stackexchange-math
|
{
"answer_score": 8,
"question_score": 2,
"tags": "elementary set theory, terminology, relations"
}
|
Prolog: Create sublist, given two indices
Basically, I need to create a predicate of the form sublist(S,M,N,L), where S is a new list formed from the elements of L between index M and index N, inclusive.
Here's where I've gotten:
sublist([],_,_,[]).
sublist([],M,N,_) :- (M > N).
sublist(S,M,N,L) :- sublist2(S,M,N,L,-1).
sublist2([H|T],St,En,[H2|T2],Idx) :-
(Idx2 is Idx + 1,
St =< Idx2,
En >= Idx2,
H = H2,
sublist2(T,St,En,T2,Idx2);
Idx2 is Idx + 1,
sublist2(T,St,En,T2,Idx2)).
As with all my prolog problems, I feel I'm making it way more complicated than it should be. I've got the base cases right, but anything else evaluates to false. Any advice for this problem, and just general approach to prolog? I understand the language for the most part, but I can't seem to see the simple solutions.
|
Simple solutions follow simple outlook. For lists it's recursion. Recursive programming is simple - just imagine you already have your function, following the given interface/requirements, and so you get to use it whenever you feel like it (but better, in the reduced cases).
sublist(S,M,N,[_A|B]):- M>0, M<N, sublist(S,M-1,N-1,B).
think of it as stating a law of sublists: sublist in a shorter list starts at decreased index.
sublist(S,M,N,[A|B]):- 0 is M, M<N, N2 is N-1, S=[A|D], sublist(D,0,N2,B).
and,
sublist([],0,0,_).
it is exclusive in the second index. tweak it. :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 4,
"tags": "prolog"
}
|
Indicator to see from which function a search string comes
I have a number of functions that create search strings @/
I would like to know from which functions comes the search string.
Is it possible to add an indicator to the search string that doesn't influence the search string but what allows me to check from which function it comes?
p.e. `/[indicator]search string`
|
You can add a regexp _branch_ that never matches, e.g. `/\%$indicator\|search string`
`\%$` is a special Vim atom matching the end of the file. Since that will never match when followed by the indicator text, the first branch (up to `\|`) will never match and therefore can represent your indicator.
Note that you cannot just use the `$` atom, since it matches the end-of-line only at certain places in the regexp, and a literal $ otherwise. (The same applies to other atoms like `^` and `[]`, so only some special Vim atoms (`\%c` is another one) can be used safely. Thanks to ib for pointing this out!)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "string, function, search, vim, indicator"
}
|
No idea how to initialize another value to a variable in a batch file
@echo off
set test=%1
if "%1"=="" (
set test=default
echo %test%
) else (
set test=%1
echo %test%
)
Test:
test.bat
Output:
ECHO is off
Problem: The 'default' string cannot be assigned as a value to variable 'test'. I've found out that test string's value is still %1 which has no value
|
It's the standard batch beginner bug. Percent expansion doesn't work in parenthesis as you expected. It expands when the complete block is parsed, before any of the lines are executed.
So `%test%` is expanded to nothing, the value before it enters the block.
The solution is to use delayed expansion here, as `!test!` will be expanded at execution not parse time.
@echo off
setlocal EnableDelayedExpansion
set test=%1
if "%1"=="" (
set test=default
echo !test!
) else (
set test=%1
echo !test!
)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "batch file"
}
|
Radiative mass generation in QED?
Does self-energy correction leading to a modification in the mass of the electron can be called **radiative mass generation**? In Zee model of radiative neutrino mass generation, the helicity of the neutrino changes but such a thing does not happen in QED self-energy correction because photon cannot change the chirality of the electron. I'm little confused.
|
No. In the electron case the self-energy makes the (bare) mass an ill-defined quantity unless you specify a renormalization scheme.
Usually one takes the dressed electron mass (i.e. the bare mass plus all radiative corrections) to be equal to the measured electron mass in the limit of vanishing external momentum.
All the radiative corrections then do is introduce a dependency of the mass on momentum, an effect that can be measured (although I'm not sure whether it has been measured for the electron since it is so light).
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mass, quantum electrodynamics"
}
|
How to configure dymanic name in spring batches
I have fifteen job configuration in my spring batch project. The jobs are been called from different source. That means I do not have control over the call.
Ten out of fifteen job perform the same task, therefore I want to create a single configuration file and execute all the ten jobs.
My question is :
Is it possible to dynamically change the job name in the configuration file.
|
I created one context file with all the similar job and another file with the common bean definitions. This has helped me in reducing a lot of code works.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "spring, spring batch"
}
|
What is the Microstation keyin for Sychronize Google Earth View for a specific view?
I'm using TerraScan on top of Microstation V8i and I am setting up hotkeys for frequently used commands. I can't find any documentation about the keyins for the Google Earth toolbar, specifically to link the Synchronize GE View button to a specific view (View 1). I know the keyin for this tool is:
googleearth synch
I have followed some keyins with "selview1" or just the number 1 for View 1. Such as:
move up;selview 1
View Previous 1
Does anyone know the keyin to apply the synch google earth to a specific view?
|
I too am trying to figure this out, the best I've come up with is toggling the view off and on before synchronizing. So my key-in for syncing view 1 is: `view toggle 1;view toggle 1;googleearth synch`
this would work too: `view off 1;view on 1;googleearth synch`
|
stackexchange-gis
|
{
"answer_score": 1,
"question_score": 1,
"tags": "google earth, microstation"
}
|
Validating kid in azure jwt token by hard coding the kid
I am getting a azure token and to verify I was checking the **kid** in header by decoding this token from jwt.io and then I hardcoded the kid in my code for future tokens.
Now, after some days the public keys has been changed and the previous kid which I stored in my code is outdated and not matching from the _**<
Can any one help how can I add the kid in my code to verify the token or if I can decode the header of the token directly and verify the kid from _**<
|
If you want to decode the Azure AD JWT token in node application, we can use the package `jwt-decode`.
For example
const jwt_decode = require("jwt-decode");
const token =
"eyJ0eXAiOiJKV1QiLCJhbGc...";
const res = jwt_decode(token, { header: true });
console.log(res);
 then the seed phase has to change then I can recover my wallet with two accounts (two private keys) if I need.
Do I right understand this moment? The seed phase will change automatically.
|
> If I create a wallet I get one seed phrase, one account and one private key.
Nearly. You get one seed phrase, but that can translate into multiple private keys, and therefore multiple accounts.
> If I push another private key in my wallet then it has two private keys (two accounts) then the seed phase has to change then I can recover my wallet with two accounts (two private keys) if I need
No - the seed phrase never changes.
* * *
The part you're missing is the idea of HD - hierarchical deterministic - wallets.
An HD wallet starts with a master key, which can be represented by a mnemonic. The master key - and therefore mnemonic - never changes.
From the master key you can then derive child keys, each representing a different account.
Background:
* Anything under the hd-wallets tag
* [External]: The Journey from Mnemonic Phrase to Address
|
stackexchange-ethereum
|
{
"answer_score": 3,
"question_score": 1,
"tags": "wallets, security, private key"
}
|
Episerver Search filter using parent page of Page reference type using UnifiedSearchFor
I have to implement search criteria in episerver. The existing search criteria includes pagetype filter which provides me the search result for the pagetype irrespective of where they are. I need to include another criteria of a parent page which is of type pagereference which basically will filter the pages and return records only which are part of the parent page. kindly advice.
|
Well first if you have the parent page they why not use the ContentLoader instead of a search? Like this:
var loader = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentLoader>();
var children = loader.GetChildren<%pageTypeHere%>(%parent pagereference%);
But if you wish to go with the search option:
query = query.Filter(x => x.Ancestors().Match(%parent pagereference id (so a int)%));
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "episerver, episerver find"
}
|
Intercepting HTTP event using JQuery
I have this JQuery code working however I need to know whether how to actually get the URL executed from the tags selected.
$("link, script, style, a, img").each(function () {
$(this).load(function () {
// get the URL and log it
console.log("Intercepted HTTP Event");
});
});
First thing I need to do it to get the actual URL during the load.
Next thing I may need to do is to actually catch before the load event happens, I mean before an image or link is loaded for example. Also, I need to modify the URL of the event that will be executed, for example, `img` tag has `src="/somewhere/image.png"` I mean, this will cause a `GET /somewhere/image.png` I may need to change it to `GET/otherplace/image.png`
Any ideas how to achive any of these?
|
.attr('src')
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "javascript, jquery"
}
|
App Engine Channel API's Javascript Client Isn't Using my onError Callback
I'm using App Engine's Channel API to maintain a connection between a Chrome extension and an App Engine app. You can see my Channel-related code here: < (The app is open source, so you can check out the repository to get an idea of how it all fits together)
My issue is, for some reason, the 401 error that App Engine throws when a token expires isn't being sent to my onError listener. I've tried just logging the error object from within onError, outside of an if statement, and still got nothing. My conclusion was that onError isn't getting called when a 401 is thrown, as the documentation says it's supposed to.
Has anyone else seen this error? Does anyone else have an idea on how to fix it?
|
I've reproduced this bug and started work fixing it. <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, google app engine, channel api"
}
|
Execute command as administrator to restore mysql database in win7 via CMD
I'm trying to restore a mysql backup in XAMPP - Windows 7 using the following command:
mysqlimport.exe -u username -p password nameOfNewDB < backupFile.sql
The machine I'm working on is attached to a network, so I checked my username using whoami and I got:
rms\johndoe
So I tried:
mysqlimport.exe -u rms\johndoe -p password nameOfNewDB < backupFile.sql
it asks me for the password, after entering it, it says:
**Error: 1045 Access denied for user 'rms/johndow'@'localhost' (using password: YES)**
Then I tried only with johndoe, same error, then I tried using .\admin (I've got the admin password), same error, I also tried .\administrator, admin, administrator and nothing yet.
**Note:** I'm using cmd because the database is very large and I cannot do it using phpmyadmin.
Any suggestion?
Thanks.
|
Try using root as username an the password of your root user.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, windows, cmd"
}
|
How Add TabHost activity which open onclick of button not tab?
I am adding TabHost(it is like iphone) in My application,when click any TabHost Move to other Activity its cool And Tabhost in Botton as usual.But issue is that when I click a button which is on top of Activity Move other Activity in this case TabHost Not Visible on bottom flow is like that
suppose there are 5 tabhost A,B,C,D,E each tabhost have an activity.
case A(click first tabhost):
open Anctivity in that Activity TabHost is present in bottom and there is button on top of this activity.
When click on that button open other Activity but in this case there is no tabhost on the bottom of this activity.But need is that there should be Tabhost anyone suggest me.
|
see this one
<
and this
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android"
}
|
What HDMI cable supports PC display stand-by?
I had my LG display connected to the PC via HDMI for about a year and the display always went to sleep when I shut down my PC and automatically went back on when I turned on the PC. Now I have a new desk and was forced to use a slightly longer HDMI cable (3m vs. 1.8m). With this new cable, when the PC turns off, the display tells me that there is no input signal for about a minute and then turns off completely (status light is off instead of blinking as it was previously with the other cable). When I turn on the PC, I also have to manually turn on the display. Just to be sure, I checked with the old HDMI cable and the old behavior came back, so it's definitely the cable and not something else.
If I have to buy a new HDMI cable, what do I have to look for so that the display turns off and on together with the PC?
|
I simply bought a new HDMI 2.0 compatible cable and everything works as intended now. Wondering what kind of HDMI feature my other cable didn't support.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "graphics card, display, hdmi, desktop computer"
}
|
Regular expression code is not working (Python)
Assume I have a word `AB1234XZY` or even `1AB1234XYZ`.
I want to extract ONLY 'AB1234' or `1AB1234` (ie. everything up until the letters at the end).
I have used the following code to extract that but it's not working:
base= re.match(r"^(\D+)(\d+)", word).group(0)
When I `print base`, it's not working for the second case. Any ideas why?
|
Your regex doesn't work for the second case because it starts with a number; the `\D` at the beginning of your pattern matches anything that ISN'T a number.
**You should be able to use something quite simple for this** \--simpler, in fact, than anything else I see here.
'.*\d'
That's it! This should match everything up to and including the last number in your string, and ignore everything after that.
Here's the pattern working online, so you can see for yourself.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, regex"
}
|
Facing 'refcnt: fd -1 < 0' error when SIGALRM throws exception in perl
My perl script is exiting with error "refcnt: fd -1 < 0" whenever die exception is thrown in SIGALRM handler. How to resolve this issue ?
$ cat ~/alarm_error.pl
$SIG{ALRM}=sub{die};
# Kill the command1 if it runs more than 1s and move on to next command
alarm 1;
my $command1 = 'sleep 100';
open(CMD, "|($command1) < /dev/null");
eval{ close(CMD)};
my $command2 = 'sleep 1';
open(CMD, "|($command2) < /dev/null");
close(CMD);
$ perl ~/alarm_error.pl
refcnt: fd -1 < 0
|
This has been fixed in the development branch of perl (5.31.1), so should appear in 5.32.0 in a month or two's time. From perl5311delta.pod:
> close() on a pipe now preemptively clears the PerlIO object from the IO SV. This prevents a second attempt to close the already closed PerlIO object if a signal handler calls die() or exit() while close() is waiting for the child process to complete. <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "perl"
}
|
Insert data and if already inserted then update in sql
I simply want to insert the data to a SQL database table and if there is some data inserted already then I want to update that data. How can I do this using Java. Kindly help me, and sorry for bad English in advance.
|
Just identify the **unique item** in your data set (like **Id** or a **code** ). Then by using that try to do a **SELECT** query first. If the **Resultset** is empty, do the **INSERT** else try to **UPDATE** the details.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 11,
"tags": "java, sql"
}
|
Removing merged branch commits in git
I was working with git and created an unnecessary situation by accident. This is how my git history looks like:
...a---b-------d---m---e...
\ /
\-c-----/
I would like to remove the branching. It does not matter how. I am not a git expert and tried many things without success. Ideally I would like to have:
a---b---d---m---e
I don't need a lecture on how preserving the history is important. The changes in `c` are not significant enough to be a branch.
|
You can use `rebase` for this. It will essentially reset the branch to a point you specify, then replay commits over the top again the way you tell it to. In this case you'll exclude commit C:
git rebase -i HEAD~5 # 5 is the number of commits back to rebase
# Comment out or delete the line for commit C
# Save/proceed
As you noted, you don't care about preserving the history. This process will change the commit hashes for the commits after C.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "git"
}
|
UIActivityViewController with Text and Mail only
I'd like to create a `UIActivityViewController` with just the text and mail activities. How would I do this? The documentation seems to be fairly sparse in substance.
I'm using the following code to present my `UIActivityViewController`:
NSArray *Items = [NSArray arrayWithObject:@"text"];
UIActivityViewController *ActivityView =
[[UIActivityViewController alloc]
initWithActivityItems:Items applicationActivities:nil];
[self presentViewController:ActivityView animated:YES completion:nil];
Which produces this:
!enter image description here
|
you need to set `setExcludedActivityTypes` like this:-
[ActivityView setExcludedActivityTypes:[NSArray arrayWithObjects:
UIActivityTypeMail,UIActivityTypeCopyToPasteboard,nil]];
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "ios, uiactivityviewcontroller"
}
|
How does iframe . contentWindow . document . execCommand work?
im trying to find out how this text editor work, iv been scanning through the script and can't seem to understand it.
first this is the link for the demo
what i can't understand is when you click the bold button which triggers this
$('.bold', tb).click(function(){ formatText(iframe, 'bold');return false; });
and then it gets send to the formatText function, and thats where i get lost, becuase thiers no mention of adding `<strong></strong>` tags to the text in the textarea, im really curious to know how it works, thanks.
|
function formatText(iframe, command, option) {
iframe.contentWindow.focus();
try{
iframe.contentWindow.document.execCommand(command, false, option);
}catch(e){console.log(e)}
iframe.contentWindow.focus();
formatText is not a default jQuery function. I took the above from the js source of the editor. The first thing it does is focus on the iframe area where your text resides. You're not really typing in a textarea field, but rather in an iframe contentEditable div `<div contentEditable="true"></div>` since textarea does not support rich text editing. The function then issues the contentEditable exexCommand to make the selected text Bold.
You can view a list of all execCommands at <
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "jquery, html, plugins"
}
|
How to use a wildcard in egrep?
Can I use a wildcard '?' in egrep? I just want to print match strings starting with '02' or '03' from Data.
Tried below command, but it doesn't help.
egrep '03/??/16|02/??/16' test
# Data
01/19/16
02/19/16
02/13/16
03/04/16
03/05/16
|
Have you actually looked at the `egrep`'s man page? There is written that `?` specifies that the preceding item is optionally matched at most once (i.e. zero times or once). What you are probably looking for is the `.` pattern which matches exactly one character.
What you need is probably
egrep '03/../16|02/../16' test
or
egrep '(03|02)/../16' test
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "grep"
}
|
Is it true you shouldn't update your global python verision of python on mac?
I know this question been answered else where on Stack, but the many of the questions are from years ago. Just wondering has this changed? I have Mac Catalina v10.15.7.
|
Updating system python can be tricky because some system installed apps may rely on the binary at that prefix.
If you want to install another version of python, just use `miniconda`. It is extremely easy to set up from command line and you can then use multiple environments without disturbing the system.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "python, macos, global"
}
|
Is the function $ f$ differentiable at every point $x$?
Let $ f $ be the function defined as follows: $ f(0) = 1$ and $f(x)= \frac{\sin x}{x} $ if $x \neq 0 $. Show that $ f $ is differentiable at every point $x $ ( at $ 0 $ also! ) and evaluate its derivative.
At first I took $f(x)= \frac{\sin x}{x} $ function and wrote that it is continuous function because
$ \lim_{x\to 0^{+}} $ and $ \lim_{x\to 0^{-}}$ both equals to one.
Now if we discus the graph of $ f(x) $ when $ x \in ( - \infty ; \infty ) $ we will see that the graph is continuous so the function is differentiable.
$$ \begin{cases} f(x) = \frac{\sin x}{x} & x \neq 0 \\\ f(x) = 1 & x = 0 \end{cases}$$
$$ \begin{cases} f^{'}(x) = \frac{x\cos x - \sin x}{x^{2}} \\\ f^{'}(x) = ? \end{cases}$$ is the derivative of $ f(x) $ when $ x = 0 $ $ \rightarrow $ $ f^{'}(x) = 0 $ ?
|
It it exists , $$f^{\prime}(x)=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}=\lim_{h\to 0}\frac{\frac{\sin(x+h)}{x+h}-1}{h}=\lim_{h\to0}\frac{\sin(x+h)-(x+h)}{h(x+h)}$$ and in $x=0$ this is $$=\lim_{h\to 0}\frac{\sin(h)-h}{h^2}=\frac{\not h-\frac{h^3}{3!}+o(h^4)-\not h}{h^2}=-\frac{h}{6}+o(h^2)\rightarrow 0\mbox.$$ This is how i would do it, hope there are no mistakes tho.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "calculus"
}
|
Chaining overloaded + operators
I've been writing a polynomial class and I was overloading operators for it. I managed to (I think) successfully overload the += operator and now I created an external function that uses += for addition just like advised in many sources. It works but I can't chain them for some reason When I try to add polynomials like this
poly a, b, c, d;
a=b+c+d;
I get an error: no matching function for call to 'poly::poly(const poly)'
My += function's main body isn't all that important but that's what it's like:
poly& operator+= (const poly& a){
//implemented +=
return *this;
}
My addition function (outside of the class) looks like this:
const poly operator+ (poly a, const poly & b){
a+= b;
return a;
}
What am I doing wrong here?
|
Your `poly` class is missing a copy constructor of the form `poly(const poly&)`. Note that if you already have a `poly(poly&)` that isn't enough. You need a copy constructor that takes a `const poly&` as a parameter.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c++, class, object, math, overloading"
}
|
Application of Cauchy product rule
Let be $\sum\limits_{j=0}^{\infty}a_j$ and $\sum\limits_{k=0}^{\infty}2^{-k-1}$ two (absolute) convergent series. Then, the Cauchy product rule ( allows us to rearrange as follows:
$\sum\limits_{k=0}^{\infty}2^{-k-1}\sum\limits_{j=0}^{\infty}a_j=\sum\limits_{k=0}^{\infty}\sum\limits_{j=0}^{k}a_j2^{-(k-j)-1}=\sum\limits_{k=0}^{\infty}\sum\limits_{j=0}^{k}2^{j-(k+1)}a_j$.
Hence, $\sum\limits_{k=0}^{\infty}\sum\limits_{j=0}^{k}2^{j-(k+1)}a_j$ converges absolutely.
My tutor said that I mixed up the indices but I don't see where?
|
Adding an intermediate step we obtain \begin{align*} \color{blue}{\sum_{k=0}^\infty 2^{-k-1}\sum_{j=0}^\infty a_j} &=\sum_{n=0}^\infty\sum_{\substack{k+j=n\\\k,j\geq 0}}2^{-k-1}a_j\\\ &=\sum_{n=0}^\infty\sum_{j=0}^n2^{-(n-j)-1}a_j\\\ &\,\,\color{blue}{=\sum_{k=0}^\infty \sum_{j=0}^k2^{j-(k+1)}a_j} \end{align*} in accordance with OPs result. So, the calculation looks fine (+1).
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "real analysis, sequences and series, convergence divergence, solution verification"
}
|
Does this phrase sound natural?
In the context of a game, would the following phrase sound natural in a notification?
**"You drew against your friend. None of you earned bonus points."**
**[Edit:]**
In the context of an e-learning game, where a friend can challenge another, the one who gets more points answering wins the challenge. If they draw, neither of them gets the bonus points. Would the following phrase sound natural in a notification?
**"You drew against your friend. None of you earned bonus points."**
|
Assuming you are talking about a match, combat or fight that ended in a draw, I'd suggest this:
> The match/fight/combat against your friend ended in a draw. Neither of you earned bonus points
The one you suggested is confusing, because reading it you can either understand that a player drew a weapon against a friend, or that there was a combat/match/whatever that ended in a draw.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 0,
"tags": "phrase usage"
}
|
404 header - HTTP 1.0 or 1.1?
Why does almost every example I can find (including this question from about a year ago) say that a 404 header should be `HTTP/1.0 404 Not Found` when we've really been using HTTP 1.1 for over a decade? Is there any reason not to send `HTTP/1.1 404 Not Found` instead?
(Not that it matters all that much... I'm mostly just curious.)
|
The usage of HTTP version can be based on the following factors:
* Your web server support for HTTP 1.0 or 1.1
* The web browser's support for HTTP 1.0 or 1.1
* Your preference as a web developer on which protocol version to use
Modern browsers can support both 1.0 and 1.1 well, and both the client and server will settle for the highest version both can support together. The key differences between the 2 protocol can be found: <
However there's no key differences in the usage of 404 Not Found. However do be consistent for your whole website. i.e. if you use HTTP/1.1, you use it throughout your website.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 23,
"tags": "http, http status code 404, header"
}
|
Workaround for citation inside pdfcomment?
Is there a simple workaround for using citations inside a pdfcomment? Here it is a MWE:
\documentclass{article}
\usepackage{pdfcomment}
\begin{document}
Works \cite{Smith1959}.
Works \pdfmarkupcomment{here}{comment1}
Doesn't work \pdfmarkupcomment{here \cite{Smith1959}}{comment2}.
\begin{thebibliography}{100}
\bibitem{Smith1959}J. Smith, J. Chem. Phys. {\bf 3}, 764 (1935).
\end{thebibliography}
\end{document}
The error message is:
! Argument of \@citex has an extra }.
|
It seems that cite is fragile. However you can do two things:
1. Put `\protect` before `\cite`
\pdfmarkupcomment{here \protect\cite{Smith1959}}{comment2}.
2. Put extra curly braces around `cite`
\pdfmarkupcomment{here {\cite{Smith1959}}}{comment2}.
|
stackexchange-tex
|
{
"answer_score": 7,
"question_score": 2,
"tags": "bibliographies, pdfcomment"
}
|
How to add items to database?
Im trying to add items to my database using C#. I have a database with 2 tables:
"Project Parts"
"Project Table" , in this table there is a column named "Project Name"
but im getting this error:
> There was an error parsing the query. [ Token line number = 1,Token line offset = 21,Token in error = Table ]
Here is the code im using.
private void button1_Click(object sender, EventArgs e)
{
sqlCEC.Open();
//Project_List.Items.Add(new_project_name.Text.ToString());
SqlCeCommand sqlCEcommand = new SqlCeCommand("INSERT INTO Project Table(Project Name) VALUES(@Project Name)", sqlCEC);
sqlCEcommand.Parameters.AddWithValue("@Project Name", new_project_name.Text);
sqlCEcommand.ExecuteNonQuery();
sqlCEC.Close();
}
|
How about?
private void button1_Click(object sender, EventArgs e)
{
sqlCEC.Open();
SqlCeCommand sqlCEcommand = new SqlCeCommand("INSERT INTO Project Table VALUES([@Project Name])", sqlCEC);
sqlCEcommand.Parameters.AddWithValue("@Project Name", new_project_name.Text);
sqlCEcommand.ExecuteNonQuery();
sqlCEC.Close();
}
Because your database objects contains spaces, you need to enclose them with `[]`
My humble advice is, **never** use spaces or other special characters in your tables or your column names.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, database, listbox"
}
|
How to check if &str contains enum in Rust?
I have an enum in Rust like:
enum List {
Rather,
Long,
List,
Of,
Items,
}
And I have a &str which can look like:
let a = "InMyList"
let b = "InMyRather"
let c = "NotContain"
Is there an efficinet way of doing `a.contains(List)`?
I can go through each enum item and do `a.contains(List::Rather) || a.contains(List::Long)` etc. But if the list is long enough, that's a lot of boilerplate code!
|
As you said:
> I can go through each enum item and do a.contains(List::Rather) || a.contains(List::Long) etc. But if the list is long enough, that's a lot of boilerplate code!
So in order to avoid typing many "OR"-checks, which is not only tedious but also error prone, you simply need a way to loop through all the enum variants. Please take a look at the strum crate and also this discussion.
Note: If optimal performance is your goal, regex can be a faster solution than simply looping over the enum variants. Please see Todd's answer and the comments that follow it.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "rust"
}
|
Transparent QLabel in QGraphicsView a good idea?
I'm trying to write a piece of software that allows one to click on a video frame and mark the x,y coordinates of a location in the frame. To design this, I've been wanting to use a QGraphicsView subclass and, on the mouse click event, instantiate a QLabel with a PNG image "target" on where the click occurred.
So far I've gotten everything to work except getting the QLabel to be transparent. All of the info I've found online doesn't seem to work with the latest Qt. Should I totally rethink my design and utilize some sort of integration with painting in Qt? Or is there a way to salvage the QLabel PNG implementation and indeed make the label transparent?
Thanks, \--Dany.
|
QLabel inside QGraphicsView is not a good idea indeed. QGraphicsView was designed to host QGraphicsItems, to display an image you should use QGraphicsPixmapItem.
Embedding QWidget into QGraphicsView has some overhead and was really designed for complex widgets that can't be easily reimplemented in terms of QGraphicItems.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "qt, qgraphicsview, qpixmap"
}
|
Why don't change lvm directory name under in etc directory
Now I have met strange problem in Linux Centos 7.
I would like to test "recreate the device files for LVM volumes". In this case, you can be system crash and lost devices file for lVM. For that, I deleted any volume group device file under /dev/mapper/ directory. And I wanted to rename lvm directory name under /etc directory in which I want to observe again create this directory or no when I wrote "vgmknodes" commands. In this time It gave me Permission denied that I was in system with root user.
# mv /etc/lvm /etc/lvm.old
mv: cannot move ‘/etc/lvm’ to ‘/etc/lvm.old’: Permission denied
What is reason? Why permission denied via root user
Thanks in advance
|
You don't actually need to test that. Those device files are created dynamically as the system runs; typically by udev.
Go to `/etc/udev/rules.d` and you'll probably see a file named something like `11-dm-lvm.rules`. That file is used by udev to create device files such as _/dev/VG/LV_.
Even better, boot another Linux system and then mount, root filesystem somewhere (such as /mnt) and take a look at it's /dev. It will have very few files in it, if anything at all.
|
stackexchange-unix
|
{
"answer_score": 0,
"question_score": 0,
"tags": "centos"
}
|
Indefinite integral problem: $\int_1^\frac{n+1}{1} \frac{(x - [x])^{[x]}}{[x]} dx$
# $ I =\int_1^\frac{n+1}{1} \frac{(x - [x])^{[x]}}{[x]} dx$
my attempt: $I=\int_1^n \frac{(x - [x])^{[x]}{[x]}}\implies\sum_{i=1}^n\int_r^{r+1} \frac{(x-r)^r}{r}dx $
Now by integration I got,
$\implies \left.\frac{(x-r)^{r+1}}{r(r+1)}\right|_{r}^{r+1} +\frac{1}{n(n+1)} \implies \sum_{r=1}^n \frac{1}{r(r+1)} $
* * *
But now I'm stuck at summation, any hints?
|
Here's a standard trick which shows you that the sum telescopes and is thus easy to evaluate: $$\frac{1}{r(r+1)}=\frac{1}r-\frac{1}{r+1}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "calculus, integration, summation, indefinite integrals"
}
|
Ruby : Finding lowest free ID in an ID array
I have an array with different IDs going from 1 to 4000. I need to add some elements in a database with an ID that would go in that array. Since the biggest ID possible is 4000 (which is not that much in my case), I'd like to be able to find the lowest unused ID possible I could use for my new element.
I would know how to do that in C++, but since I'm pretty new in Ruby, I'm asking for help. in C++, I would write a loop in which I would check if array[i] == array[i+1] - 1. If not the case, then the new id would be array[i] + 1.
I have just no idea how to write that in Ruby.
|
array = [1, 2, 3, 5, 6]
(1..4000).to_a.-(array).min
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "ruby, arrays, loops, arraylist"
}
|
How to increase Rome: Total War beyond "Very Hard" settings
Rome Total War was a classic game that I had the pleasure of being introduced to as a teenager on Christmas day. After re-installing this game and playing both the locked and unlockable factions on "Very Hard" I found the battles and campaign scenarios trivial compared to when I was just a kid. Although I have played as every faction, I feel that I could derive more enjoyment from this game if I could find a way to make it more challenging.
Is there a mod(s) or configuration files that I can adjust to make this game truly challenging?
**Note:** At the risk of sounding immodest, I will say that I am a military genius as far as gaming is concerned. I am a grandmaster in Starcraft 2 and have won RTS tournaments and crushed dozens of human opponents at LANs and other organized events. SO BRING ME A CHALLENGE!!!
|
Although the difficult settings modify the aggressiveness of the AI, it does not improve the AI. It just adds income, building speed, attack, defence and moral bonuses to the AI. If you feel it was too easy you can increase the difficult by reducing spending in campaign, or spend less point in allocating troops in skirmish.
Human opponents are more difficult than AI. I suggest you should wait for Total War Rome II or other RTS games and you will have real challenges again.
|
stackexchange-gaming
|
{
"answer_score": 1,
"question_score": 3,
"tags": "mods, rome total war"
}
|
Places Autocomplete always returns Chicago resultas even If lat long is set to other place
I'm using Google places API to check the places nearby and let the user pick one. Everything works fine but I'm having location issues, If I send the longitude and latitude to the api call for a search, for example "McDonalds" I get results in CHICAGO instead of San Francisco...
Any Idea what maybe happening? This is my query:
This is Google's documentation: <
Thanks!
|
You need to define the `radius` to search within.
I used to have a similar problem with results from Chicago so that must be some sort of default area to search in. To search near a location you must supply the `location` and `radius` parameters.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "google maps, location, google places api"
}
|
How do flight arrows affect ranged damage
I'd like to clarify how flight arrows work in Pathfinder:
> Benefit: A flight arrows range increment is 20 feet greater with longbows, 10 feet greater with shortbows.
>
> Drawback: Flight arrows deal damage as if one size category smaller.
I'm assuming this drawback applies to the size category of the bow damage? So a medium longbow now deals 1d6 damage instead of 1d8? I'm basing this off the description of Gravity Bow which says it increases the size and weight of the arrows or bolts fired from the bows.
|
Your assumption is indeed correct, the arrow does damage as though the bow was one size smaller.
|
stackexchange-rpg
|
{
"answer_score": 8,
"question_score": 4,
"tags": "pathfinder 1e, ranged attack"
}
|
Заполнение односвязного списка
Есть структура:
struck tel
{
int info;
tel *next; //указатель на след элемент списка
} *begin, t; //begin- указатель на начало
Функция для формирования списка:
tel* dob(tel *p, int in) {
tel *t = new list; // Захватываем память для элемента
t -> info = in; // Создаём информационную часть
t -> next = p; // Создаём адресную часть
return t;
}
Подскажите пожалуйста, как нужно дописать эту функцию, чтобы она сразу же сортировала элементы по убыванию info.
|
Вам нужно пройтись по списку в предположении, что он уже отсортирован, найти подходящее место для нового элемента так, чтобы список остался отсортированным после вставки, и, конечно, вставить элемент на найденное место.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++"
}
|
Does clipboard get cleared after restart on os x?
Sorry for silly question does OS X clipboared get clear after machine restart?
In the simple way. if i copy text and paste it, when i restart machine will it still be where on clearboard, will i still see it on paste it??
|
Yes it does. If that's a problem then get a clipboard manager.
|
stackexchange-apple
|
{
"answer_score": 1,
"question_score": -1,
"tags": "copy paste"
}
|
How do I write a URL in a comment without making it a link?
I tried to add a comment that included this text:
But it showed up like this:
username@password:www.mysite.com/mypath/
How can I prevent auto-hyperlinking in a comment?
**The magic: (view edit (not source))**
|
Simply use the code `` delimiters
|
stackexchange-meta
|
{
"answer_score": 6,
"question_score": 7,
"tags": "support, status completed, comments, markdown"
}
|
iTextSharp PDF form field validation
Is is possible to add validation to PDF form fields via iTextSharp.
I currently generate a PDF document, fill editable form fields with values from my database and present the document to the user in a webpage.
PdfReader pdfReader = new PdfReader(template);
PdfStamper pdfStamper = new PdfStamper(pdfReader, writeStream);
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("field1", myobj.field1value);
...
pdfStamper.Close();
I'd like to be able to dynamically add validation e.g. numeric field min-max values, or custom JavaScript to the field in this document rendering process. I know this is possible when designing the form in Acrobat, but I can't find any methods/fields for accessing these validation fields through iTextsharp.
|
When looking for answers, please consult the documentation: "iText in Action".
Your question is answered by an example:
* Java: <
* C#:
In this example, some custom JavaScript including a validate() method is added to a field/button. This is the JavaScript: <
The JS added as Additional Action (AA) or as action to a Submit button is identical to the JS one would write for HTML.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, pdf, itext"
}
|
What was the first programming language to have 'printf'?
I'm curious as to which language was the first to literally have a formatted text output procedure called `printf`. A trivial question, sure, but I was prompted to ask by a recent question on ZSPL.
I'll accept a language statement in lieu of a procedure/function/subroutine, but it has to be spelled `printf` (or variants involving upper case, bold, or underlined letters). Other formatted I/O, such as FORTRAN's `FORMAT` facilities, don't count.
I think the answer is Algol68, but that might just be historical ignorance on my part. For what its worth, Algol68 treated a format not as a string but as a unique datatype with its own denotation.
Similar but not quite `printf` arrangements could also be interesting, even if not the specific answer I'm asking for.
|
Having poked around, I feel ready to answer my own question.
The first language to have an actual formatted-print function literally named _printf_ was Algol 68, per the 1973 _Revised Report_ (the original _Report_ in 1968 used _outf_ ).
The format specification for Algol 68 owed IMO something to FORTRAN usage; elements were format directives unless they were specifically identified as literal strings - the inverse of C usage, if you see what I mean. For example, `FORMAT f = $ "the number is " 3d $` (Dollar signs enclose a FORMAT denotation).
An honorary mention goes to BCPL, which had a _writef_ or _writes_ procedure (sources vary in their opinion, and the _BCPL Reference Manual_ describes only the language, not any library), using a standard string for the format, rather than a specialized datatype (Algol [68) or statement type (FORTRAN).
|
stackexchange-retrocomputing
|
{
"answer_score": 20,
"question_score": 13,
"tags": "history, programming"
}
|
Handling stripe with reactJs
I'm trying to handle credit card payments using stripe and reactjs. I'm following the tutorial here < See the get started section. The only problem I have is that I need to submit the credit card form on the component page where the code is (the first page that is created) and not the CheckoutForm page. How do I do that?
I tried doing the following
var elements = useElements();
const card = elements.getElement(CardElement);
const result = await stripePromise.createToken(card);
if (result.error) {
console.dir(result.error.message);
} else {
console.dir(result.token);
}
but I'm not able to use a hook function useElements in a class compomnent.
|
First, the library you've linked to is deprecated, the new version is this one. Since you're using the hooks you must be using the new library already, though.
If you're using Class components, the documentation provides an example of an alternate integration pattern using the `<Elements>` provider and `<ElementsConsumer>` explicitly.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "reactjs, stripe payments"
}
|
How to verify number of function evaluations when profiling R code
When profiling R code with Rprof-type functions we get the time spent in function alone and the time spent in function and callees. However, as far as I know we don't get the number of times a given function was evaluated.
For example, assume I wants to compare two integration functions:
integrate_1(myfunc, from = -Inf, to = Inf)
integrate_2(myfunc, from = -Inf, to Inf)
I could easily see how much time each function takes and where this time was spent, but I don't know how to check how many times myfunc had to be evaluated in each of the integrate functions.
Thanks,
|
One way of implementing Joran's counter method is to use the `trace` function.
For example, first we set the counter to zero. (Assigned in the global environment, for convenience.)
count <- 0
Then set up the trace. Here we set it on the `identity` function (that just returns the value that you input to it).
trace("identity", quote(count <<- count + 1), print = FALSE)
Now whenever `identity` is called, the value of `count` is incremented. `print = FALSE` just stops a message being printed to the console when the function is called.
Let's call the function a few times and inspect the count:
for(i in seq_len(123)) identity(1)
count
## [1] 123
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "r, profiling"
}
|
In LaTeX, is there a way to get long lines along the margins?
I'm working on a report, and some elements are outside the margins (but some are just barely outside the margins). I was wondering: Is there a way to make two vertical lines, one on each side, along the margins so that one can easily see if it goes outside them?
(Googling it, I only found information about margin notes.)
A figure is below:
|report text goes here|
|more text goes also h|ere
|and so on and so fort|h
It would certainly make correcting these kinds of mistakes very trivial. :)
Feel free to post answers that would solve/show this problem in a more "LaTeX-correct" way, if that makes any sense at all.
|
Use the option `draft` in your `\documentclass` statement, e.g.:
\documentclass[12pt,a4paper,draft]{report}
This will produce a litte black box at the end of every overfull line (this is what Johannes Schaub must've been referring to in his comment). This makes it very easy to spot these inconvenient overlong lines ...
Alternatively, you can say `\sloppy` in your preamble. The typesetter will then be less strict on the grey value of your paragraphs and avoid "overfull \hbox"es more often (more frequent linebreaking).
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 1,
"tags": "latex, lines"
}
|
Help understanding $x=y\Rightarrow(x=z\Rightarrow y=z)$
I was reading a proof that opened with the integer axiom of $x=y\Rightarrow(x=z\Rightarrow y=z)$
What would be an accurate statement in English to express this? The "implies" within the first "implies" is kind of confusing to me. I believe the general idea is that if $x$ equals $y$, then if $x$ equals $z$, $y$ also equals $z$.
|
_If $x$ is equal to $y$, then anything equal to $x$ must also be equal to $y$._
|
stackexchange-math
|
{
"answer_score": 11,
"question_score": 5,
"tags": "discrete mathematics, axioms"
}
|
Hide Confirm Form Resubmission PHP
After I submit a form, and I click the back button, the page displays the confirm form resubmission page. Instead of that, I actually just want the browser to display the form itself. It there a way to do that? Here is a part of my code below, and it works except that it will not stop refreshing. I just want it to refresh once when you click the back button.
<meta http-equiv="refresh" content="0">
<form method = 'post' action = 'submitPost.php?section=$section'>
<textarea rows='10' cols='100' name = 'post'></textarea> </br>
<input type = 'submit' value = 'Submit'>
</form>
|
This is a browser security policy - when you want to go back to a page you loaded using the `POST` http verb it will always ask you for confirmation.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, php, forms"
}
|
i want to extract href for the links in this particular website
Can you please help me figure this out? i'm trying to scrape this website < i'm trying to scrape all the links such as < but i can't figure it out
from bs4 import BeautifulSoup
import requests
url = '
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
test = soup.find_all('ul', class_='business-results')
print(test)
|
You can use `#main a` to get all urls:
urls = [url["href"] for url in soup.select("#main a")]
List of dictionaries with key as a text and value as a URL:
urls = []
for url in soup.select("#main a"):
print(url.text, url["href"])
urls.append({url.text: url["href"]})
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, python 3.x, web scraping, beautifulsoup"
}
|
Why Session Variable is not working in PHP?
I am trying to set a session variable but it's not working. Here is what I am doing in Code. Please suggest what's wrong:
## Login-Validator.php
<?php
session_start();
$userName = "test";
$_SESSION['iUsername'] = $userName;
header("Location:
?>
## LoginSuccess.php
<?php
session_start();
$User = $_SESSION['iUsername'];
echo $User;
?>
|
Try this (put a 'exit' after the redirect)
session_start();
$_SESSION['session'] = 'this is a session';
header('location: apage.php');
exit;
read more at @ PHP: session isn't saving before header redirect
If this doesnt work..comment out the redirect and open each page in a different browser tab. Then open Login-Validator.php and then open LoginSuccess.php and check if the session was set. I think it cause by the cookie not setting before the redirect.
Also is Login-Validator.php and LoginSuccess.php on the same domain?
header("Location: /LoginSuccess.php");
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, session variables"
}
|
Can Filebot create subfolders based on artist or title names?
I've used MediaMonkey for music organizing for a long time, but I'm considering Filebot.
My music is organized like so:
Music/{ABC}/{A}/Adele/{Album Title [Release Year]}/01_{Song Title}
So I'm arranging by the first letter of the artist name (grouped into 3's ABC, DEF, GHI...or 0-9 for anything starting with a number or symbol),
then I break that down to the first letter of the artist: A (in this case)
then artist name, album with date, track number with 2 digits_Song Title
Is it possible to do this in Filebot?
|
If you go through all the examples, then you should find all the bits and pieces you need there:
e.g.
Music/{artist[0]}/{artist}/{album} {[y]}/{pi}_{t}
The `{ABC}` part will probably require a bit of code, because your code has to decide which chunk of letters goes into which folder.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "music"
}
|
ion-text-wrap not working inside ion-item and ion-row
In my Ionic 5 app when I am using text inside `ion-item` or `ion-row` with class `ion-text-wrap`, the text is not wapprd. I am trying the following ways.
<ion-item>
<ion-label class="ion-text-wrap">
{{myText}}
</ion-label>
</ion-item>
<ion-item class="ion-text-wrap">
{{myText}}
</ion-item>
;
formData.append("title", document.getElementById("title").value);
formData.append("html",my_html);
var xhr = new XMLHttpRequest();
xhr.open("POST", "
xhr.send(formData);
xhr.onreadystatechange = function() {
// If the request completed, close the extension popup
if (req.readyState == 4)
if (req.status == 200) window.close();
};
The server is supposed to send back a response in JSON format. How do I retrieve and store that in a variable?
|
If the answer is in JSON, you have the result in the responseText attribute.
if (xhr.readyState == 4)
if (xhr.status == 200)
var json_data = xhr.responseText;
For more details, view: XMLHttpRequest
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 11,
"tags": "javascript, html, http post"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.