qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
124,191 | I'm on the academic job market this season for a position in a STEM field. I've had one on-campus interview and may receive an offer from this school within the next week or so. I've also had Skype interviews with a few other schools, but haven't received any on-campus invites from them. (The Skype interviews occurred about 3 weeks ago.)
At this point, should I let these schools know that I've had an on-campus interview? Or is it safe to assume that I've been rejected by them if I haven't received a campus invite already? | 2019/02/01 | [
"https://academia.stackexchange.com/questions/124191",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/103883/"
] | Don't make assumptions. Nearly everywhere will let you know when you are no longer under consideration. You may or may not be high on their list. You could be high and they are just dithering. But they would rather make it definite, just to avoid fruitless communication.
But it is probably a mistake to tell them you've had an interview, as it may confuse them about your interest. Wait until you have an acceptable offer before you notify them.
Trying to "nudge" them in your favor could work either way, if it has any effect at all. It is a risky thing to do. Nudging might be worthwhile if you are juggling multiple offers. | A general advice in any job search (academia or civilian world or NFL) is to let the other parties know when things have become competitive. It doesn't guarantee you get something done with the other parties. But it will often move things along. Especially if you are a good candidate and are likely to come off the market.
Be gracious about it (just wanted to let you know that I am moving down the path with X...would love to interview with you, T.) But don't hide your light under a bushel. At the end of the day, both sides are seeking to create an auction. Make sure you do the small things you can to make an auction for you.
Edit: Just looked at Buffy's comment. Yes, an offer is much more powerful and deserving of a nudge. I would still consider if you can do the nudge (gently) with less than an offer. In particular, if you think things will move fast with the other party and you won't have a lot of time to shop an offer. Judgment call, but my gut feel is power for the people. |
52,926,235 | I ran into this problem where I have h6s and when you hover over them, the background turns grey (opacity: 0.25;) and when you hover out, the background turns transparent again. Then, when you click on it, the background turns grey and stays that way. For some reason, when I hover over a different h6, the background doesn't turn grey.
```js
$(document).ready(function() {
var topic_list = {
0: "HOMEPAGE",
1: "WHAT HYDROMETEOROLOGICAL BIOHAZARDS ARE",
2: "WHEN AND WHERE THIS HAPPENED",
3: "OUR IDEAS",
4: "PROS AND CONS",
5: "OUR DETAILED ESSAY ON HYDROMETEOROLOGICAL BIOHAZARDS",
6: "CREDITS AND REFERENCES"
};
for (i in topic_list) {
$("#" + topic_list[i].split(" ").join("_")).hide();
}
$("#HOMEPAGE").show()
for (var i in topic_list) {
var element = document.createElement("h6");
var node = document.createTextNode(topic_list[i]);
$(element).append(node);
$("#header").append(element);
element.className = "topics";
element.id = topic_list[i].split(" ").join("_") + "_directory";
}
$(".topics").click(function() {
for (var i in topic_list) {
if (this.id == topic_list[i].split(" ").join("_") + "_directory") {
$("#" + topic_list[i].split(" ").join("_")).fadeIn();
$("#" + topic_list[i].split(" ").join("_") + "_directory").css("background", "rgba(128, 128, 128, 0.25)")
} else {
$("#" + topic_list[i].split(" ").join("_")).fadeOut();
$("#" + topic_list[i].split(" ").join("_") + "_directory").css("background", "transparent")
}
}
});
$("#directory_link").click(function() {
$("#WHAT_HYDROMETEOROLOGICAL_BIOHAZARDS_ARE").fadeIn();
for (var i in topic_list) {
if (topic_list[i].split(" ").join("_") != "WHAT_HYDROMETEOROLOGICAL_BIOHAZARDS_ARE") {
$("#" + topic_list[i].split(" ").join("_")).fadeOut();
}
}
});
});
```
```css
* {
font-family: Montserrat, Trebuchet MS;
}
body {
margin: 0px;
background: white;
}
h1 {
position: relative;
margin: 0px;
padding: 20px;
color: white;
text-align: center;
}
h6:hover {
background: rgba(128, 128, 128, 0.25);
}
h6 {
position: relative;
text-align: center;
margin: 0px;
padding: 20px;
color: white;
display: inline-block;
transition: 0.4s;
}
header {
background: #1d29c4;
}
#header {
background: #202dd9;
text-align: center;
}
div {
position: absolute;
}
p {
position: relative;
margin: 20px;
font-size: 18px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<header>
<h1>HYDROMETEOROLOGICAL BIOHAZARDS</h1>
</header>
<header id="header"></header>
<div id="HOMEPAGE">
<p><i><b>sfdfdsasafd
</b></i></p>
<p>afdsdfsfdsa</p>
<p><i>asdfdsfafds</i></p>
<p>sdfadfsdfs</p>
<p>asdf <em>asf</em> <i id="directory_link">sfdadfas</i>? ...</p>
</div>
<div id="WHAT_HYDROMETEOROLOGICAL_BIOHAZARDS_ARE">what</div>
<div id="WHEN_AND_WHERE_THIS_HAPPENED">when where</div>
<div id="OUR_IDEAS">ideas</div>
<div id="PROS_AND_CONS">procon</div>
<div id="OUR_DETAILED_ESSAY_ON_HYDROMETEOROLOGICAL_BIOHAZARDS">a</div>
<div id="CREDITS_AND_REFERENCES">cred</div>
``` | 2018/10/22 | [
"https://Stackoverflow.com/questions/52926235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8268036/"
] | The style you set in function override the style you set in css
[](https://i.stack.imgur.com/9FTVn.png)
To prevent override do not set color :
`$("#" + topic_list[i].split(" ").join("_") + "_directory").css("background", "")`
(It's better than use `!important` in css)
```js
$(document).ready(function() {
var topic_list = {0: "HOMEPAGE", 1: "WHAT HYDROMETEOROLOGICAL BIOHAZARDS ARE", 2: "WHEN AND WHERE THIS HAPPENED", 3: "OUR IDEAS", 4: "PROS AND CONS", 5: "OUR DETAILED ESSAY ON HYDROMETEOROLOGICAL BIOHAZARDS", 6: "CREDITS AND REFERENCES"};
for (i in topic_list) {
$("#" + topic_list[i].split(" ").join("_")).hide();
}
$("#HOMEPAGE").show()
for (var i in topic_list) {
var element = document.createElement("h6");
var node = document.createTextNode(topic_list[i]);
$(element).append(node);
$("#header").append(element);
element.className = "topics";
element.id = topic_list[i].split(" ").join("_") + "_directory";
}
$(".topics").click(function() {
for (var i in topic_list) {
if (this.id == topic_list[i].split(" ").join("_") + "_directory") {
$("#" + topic_list[i].split(" ").join("_")).fadeIn();
$("#" + topic_list[i].split(" ").join("_") + "_directory").css("background", "rgba(128, 128, 128, 0.25)")
} else {
$("#" + topic_list[i].split(" ").join("_")).fadeOut();
$("#" + topic_list[i].split(" ").join("_") + "_directory").css("background", "")
}
}
});
$("#directory_link").click(function() {
$("#WHAT_HYDROMETEOROLOGICAL_BIOHAZARDS_ARE").fadeIn();
for (var i in topic_list) {
if (topic_list[i].split(" ").join("_") != "WHAT_HYDROMETEOROLOGICAL_BIOHAZARDS_ARE") {
$("#" + topic_list[i].split(" ").join("_")).fadeOut();
}
}
});
});
```
```css
* {
font-family: Montserrat, Trebuchet MS;
}
body {
margin: 0px;
background: white;
}
h1 {
position: relative;
margin: 0px;
padding: 20px;
color: white;
text-align: center;
}
h6:hover {
background: rgba(128, 128, 128, 0.25);
}
h6 {
position: relative;
text-align: center;
margin: 0px;
padding: 20px;
color: white;
display: inline-block;
transition: 0.4s;
}
header {
background: #1d29c4;
}
#header {
background: #202dd9;
text-align: center;
}
div {
position: absolute;
}
p {
position: relative;
margin: 20px;
font-size: 18px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="icon" type="image/x-icon" href="">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<header>
<h1>HYDROMETEOROLOGICAL BIOHAZARDS</h1>
</header>
<header id = "header"></header>
<div id = "HOMEPAGE">
<p><i><b>sfdfdsasafd
</b></i></p>
<p>afdsdfsfdsa</p>
<p><i>asdfdsfafds</i></p>
<p>sdfadfsdfs</p>
<p>But, what <em>are</em> <i id = "directory_link">hydrometeorological biohazards</i>? ...</p>
</div>
<div id = "WHAT_HYDROMETEOROLOGICAL_BIOHAZARDS_ARE">what
</div>
<div id = "WHEN_AND_WHERE_THIS_HAPPENED">when where
</div>
<div id = "OUR_IDEAS">ideas
</div>
<div id = "PROS_AND_CONS">procon
</div>
<div id = "OUR_DETAILED_ESSAY_ON_HYDROMETEOROLOGICAL_BIOHAZARDS">a
</div>
<div id = "CREDITS_AND_REFERENCES">cred
</div>
</body>
</html>
``` | Your code could use some touch-ups, but I used what you wrote.
Try this:
```
$(".topics").click(function(e) {
// Set an "active" class for an active state
$(".topics").removeClass("active");
$(this).addClass("active");
for (var i in topic_list) {
if (this.id == topic_list[i].split(" ").join("_") + "_directory") {
$("#" + topic_list[i].split(" ").join("_")).fadeIn();
} else {
$("#" + topic_list[i].split(" ").join("_")).fadeOut();
}
}
});
``` |
28,631 | When i change any data into salesforce code using eclipse and trying to save that then eclipse takes too much time but when i am doing this thing in sandbox it will get saved , deployed and synchronized quickly .
Is there any way to decrease the delay between saving , deploying and synchronizing the code to server using eclipse or any other tool?
 | 2014/02/24 | [
"https://salesforce.stackexchange.com/questions/28631",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/4895/"
] | If you are only changing client-side resources for VF development, remember, you can reference those from anywhere. You shouldn't be inlining your JS or CSS anyway, so while you're fine-tuning, why not stick them in your own content server, edit them there, and then the refresh is immediate.
I've done this two ways.
One is to run a local static web server and reference it in my VF pages via localhost. This obviously only works if you are writing and testing on the same machine as the server. There was a [good blog article](http://blogs.developerforce.com/developer-relations/2013/05/instantly-reloading-visualforce-static-resources.html) on this in the developerforce blogs not too long ago.
The other is to serve static content from a public web server. I've typically done this with a heroku instance. There is a small lag while you push to your heroku repo, but nothing like waiting for your test code to run.
**BUT**
The reason we force you to run tests is so you don't screw up your production system! As has been said, all development should be done in a sandbox or developer edition org then pushed to production after thorough testing. So I would still suggest these techniques, but in reality you should be doing them in a system that is ring-fenced from your production org. | Hurrey !!!! I got the solution to this problem.
You can save the pages , components , css etc through salesforce enviornment.
Here are the Steps -->
1. Go to login.salesforce.com
2. Type your creadentials and logged into the SF.
3.Click on the name top corner , right hand side and click setup option.
4.click develop , here all the static resources, components etc are listed .
1. just click on any static resources, components click edit button there on the upper side.
e.g.
```
Develop --> Pages --> xyz.page --> edit -->(after changes)--> quick save --> save (finally)
```
it will not take too much time.
*Note : For Apex Classes you need to change into Sandbox or Dev org after testing you can deploy onto server through eclipse and it will take time.* |
7,664 | I have worked out some poor code to achieve the goal of 3D Delauney triangulation(random points in E3), but the time consuming is huge, and when five points are exactly (or nearly due to the round-off error) on one sphere, my code can not handle this situation properly.
I use the basic data-structure which is a list of tetrahedrons and a list of points and a list of relationship of tetrahedrons with their neighborhood.
The algorithm is incremental insertion.
Can somebody tell me which kinds of data-structures and algorithm should i prefer to? Can quad-edge data-structure be used in the situation ? When I read papers about this topic,I find that maybe this data-structure is not suitable for 3D application(strictly speaking, not suitable for 3D manifold application?I just know what is manifold yesterday, Please help me...). Is divide-conquer a better algorithm?
Thanks! | 2013/06/14 | [
"https://scicomp.stackexchange.com/questions/7664",
"https://scicomp.stackexchange.com",
"https://scicomp.stackexchange.com/users/4557/"
] | This is implemented in qhull which is available from scipy (python). If you cannot use these implementations directly for some reason, the explanations of the data structures in the docs might be helpful.
<http://www.qhull.org/>
<http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html#scipy.spatial.Delaunay> | The data structure in 3D is pure algebraic.
What you need to have is the following arrays:
* `Vertex` `V`: the vertices' coordinates for the mesh, a $(\# \text{ of vertices}) \times 3$ array, with each column being $x$-, $y$- and $z$-coordinates, and the row index corresponds to the index of that vertex.
* `Element to Vertex` `E2V`: the tetrahedral element to the vertex numbering, a $(\# \text{ of tetrahedra}) \times 4$ array. Each row represents a tetrahedron, and each column on that row is the index vertex(row number of this specific index in `V`) of that tetrahedron.
* `Face to Vertex` `F2V`: triangle faces to the vertex numbering, with a $(\# \text{ of faces}) \times 3$ array. Each row represents a face, and each column on that row is the index vertex(row number of this specific index in `V`) of that face.
* `Edge to Vertex` `F2V`: edge to the vertex numbering, with a $(\# \text{ of edges}) \times 2$ array. Each row represents an edge, and each column on that row is the index vertex(row number of this specific index in `V`) of that edge.
*First two are necessary data structure*, all other array can be generated from the first two using algebraic operations. Other notable arrays are `Element to Edge`, `Face to Edge`, `Vertex to Element`(the elements sharing a vertex), `Face to Element`(the elements sharing a face), `Edge to Face`(the faces sharing an edge), etc.
The implementation of 3D Delaunay triangulation does not sound as trivial as the other answer said. Depends on your software of interest, I may update my answer more. |
39,031,893 | I have a table that looks like this:
```
id name date
1 prabhat 22-12-1989
2 Ashok 20-12-1978
3 prabhat 22-12-1986
4 Ashok 20-12-1974
5 prabhat 22-12-1889
6 Ashok 20-12-1900
```
And I want to change the name from prabhat --> Ashok and Ashok--> prabhat in a single query
Thanks. | 2016/08/19 | [
"https://Stackoverflow.com/questions/39031893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3505302/"
] | One clever trick here would be to self-join your table on the `name` columns matching the names `prabhat` on one table and `Ashok` on the other (or vice-versa). Then you can simply do a single `SET` to update the value.
```
UPDATE yourTable t1
INNER JOIN yourTable t2
ON (t1.name = 'prabhat' AND t2.name = 'Ashok') OR
(t1.name = 'Ashok' AND t2.name = 'prabhat')
SET t1.name = t2.name
``` | If you do select, it is easy:
```
SELECT id, `date`,
if (name = 'prabhat', 'Ashok', if (name = 'Ashok', 'prabhat', name)) AS name
FROM tab
```
If you update, you need to use a temp-value (which does not exist in the tab.name)
```
-- check if temp name exists
SELECT count(*) FROM tab WHERE name = 'NON-EXIST-temp-name';
UPDATE tab SET name = 'NON-EXIST-temp-name'
WHERE name = 'prabhat';
UPDATE tab SET name = 'prabhat'
WHERE name = 'Ashok';
UPDATE tab SET name = 'Ashok'
WHERE name = 'NON-EXIST-temp-name';
```
After I answered, I found Tim also comes up with a clever answer, if you are not logically strong, probably try this straight forward method |
34,085,616 | I have a code for extracting date from a text (format = mm-dd-yyyy) using regular expressions.
**Note**: The text is obtained using OCR on a bill image. So, the expected date format is mm-dd-yyyy but it can be any random text as it is obtained using OCR.
```
import re
date_reg_exp = re.compile('\d{2}[-/.]\d{2}[-/.]\d{4}') #works for mm-dd-yyyy
matches_list=date_reg_exp.findall(test_str)
for match in matches_list2:
print match
```
If I have a string `'This is a text extracted from OCR 09-11-2015'` the above code works and results the Date as output `'09-11-2015'`. But, if I have a string `'This is o text extractud fram OCR 09-11-201 5'` or `'This is o text xtractud fram OCR 09-11-201'` or `'This is o text xtractud fram OCR O9-11-201'` it fails. How to I write a code for such scenario where it also picks up the nearest match. | 2015/12/04 | [
"https://Stackoverflow.com/questions/34085616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5196647/"
] | There are several ways you could implement approximate matching with regular expressions. The most "theoretically straightforward" approach would most probably require you to perform an [edit-distance](https://en.wikipedia.org/wiki/Edit_distance)-like [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) computation over the regexp's [DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton).
This being a fairly tricky algorithm to code, there are not too many implementations of it lying around. The most famous is known as [Agrep](https://en.wikipedia.org/wiki/Agrep) (technically, the `agrep` tool implements several algorithms, but is most known, among other things, for the fuzzy regexp matching).
Brief googling by this keyword comes up with [this library](https://github.com/laurikari/tre/), which seems to have Python bindings and might be exactly what you need. | **This is not what the title demands**
but might turn up useful for your scenario as you mentioned Levenshtein distance.
```
from dateutil.parser import parse
s = 'This is o text xtractud fram OCR O9-11-201'
parse(s, fuzzy=True)
datetime.datetime(201, 9, 11, 0, 0)
```
Dateutil offers a fuzzy datetime parser.
This works for `'09-11-201'` but won't work for `'09-11-201 5'` |
173,302 | I've got a 9G backup from a dead Solaris machine (SS20) that I'm trying to mount via lofi in Solaris. It won't mount the entire image file and I'm not sure how to discover the partition layout so as to split it again with dd.
Am I better off just finding an appropriate sized thumb drive and going that route? | 2010/08/22 | [
"https://serverfault.com/questions/173302",
"https://serverfault.com",
"https://serverfault.com/users/51980/"
] | Are you currently running Solaris on a SPARC machine or an x86 based one ? In the latter case, there is no way to mount the filesystem on it as the format is architecture dependant. | I'm not sure about Solaris, but with Linux there's a `-o loop` option. Could you try that and see if it works? If it doesn't, then edit your question and tell us what error message it's giving. |
42,639,269 | I am so close. I am trying to create a form that will upload a file to my Dropbox, and I can get it to work using a file on the server with the code here:
```
$path = 'render.png';
$fp = fopen($path, 'rb');
ch = curl_init('https://content.dropboxapi.com/2/files/upload');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);curl_close($ch);
echo $response;
```
I was sure this would work, but nope.....
```
$fp = fopen($_FILES['file'], 'rb');
```
Anyone have a quick fix for this? | 2017/03/07 | [
"https://Stackoverflow.com/questions/42639269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7669770/"
] | You need to duplicate `@group.users`:
```
group_members = @group.users.dup
```
This way `group_members` won't point to the original object, which will later be destroyed.
You can also wrap this in a transaction in case `@group` doesn't destroy:
```
group_members = @group.users.dup
if @group.transaction do
@group.destroy
notify_to_group_members group_members
end
flash[:success] = t "flash.delete_success", record: Group.name
else
flash[:danger] = t "flash.delete_fail", record: Group.name
end
``` | You have different ways to do this, but a "Rails like way to accomplish this is by using callbacks. The before\_destroy callback occurs right after any validation and before the actual destroy happens.
You could do this in your model (assuming you are using ActiveRecord):
```
class Group < ActiveRecord::Base
# Add a before destroy callback
# This will be called just before the group (and the dependent members are destroyed)
before_destroy :notify_to_group_members
# Rest of your methods
private
def notify_to_group_members
members.each do |member|
message = Aws::Sns::GeneratePayload.call I18n.t("company.push_messages.group.delete"),
action: :delete, type: :group, device: member.device
Aws::Sns::PublishToEndpoint.delay.call member, message
end
end
end
```
And then your controller would be "dry" as the notification logic is in the Group model.
```
class Admin::GroupsController < Admin::BaseController
before_action :load_group
def destroy
group_members = @group.users
if @group.destroy
flash[:success] = t "flash.delete_success", record: Group.name
else
flash[:danger] = t "flash.delete_fail", record: Group.name
end
binding.pry
redirect_to admin_company_management_groups_path
end
private
def load_group
@group = Group.find_by_id params[:id]
end
end
```
This way, you are sure that your members are being notified and that the group is deleted. |
2,022,936 | This is an exercise in my Analysis book that I find difficult. Suppose that {$a\_n$} is the Fibonacci sequence, and $b\_n=\frac{a\_{n+1}}{a\_n}$. Prove that {$b\_n$} converges to the Golden Number.
First, of course, one has to prove that {$b\_n$} does converge. I think since $a\_n$ is increasing, and $a\_{n+1}-a\_n>a\_n-a\_{n-1}$, {$b\_n$} is decreasing. Now since both the numerator and denominator are positive, {$b\_n$} is bounded below by $0$. That means {$b\_n$} must converge.
Now how to prove that {$b\_n$} actually converges to $\frac{1+\sqrt5}{2}$ I don't know. I tried taking limits of $b\_{n+1}$ and $b\_n$ but that got messy and didn't seem to lead anywhere.
How do I solve this?
Thanks in advance. | 2016/11/20 | [
"https://math.stackexchange.com/questions/2022936",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/378977/"
] | **Hint**. By setting
$$
I=\int\frac{\cos(x)\:dx}{2\cos(x)+3 \sin(x)}\quad J=\int\frac{\sin(x)\:dx}{2\cos(x)+3 \sin(x)}
$$ One may observe that
$$\begin{cases}
2 I+3J=\displaystyle\int 1\:dx \\
3 I-2J=\displaystyle \int\frac{(2\cos(x)+3 \sin(x))'}{2\cos(x)+3 \sin(x)}\:dx
\end{cases}
$$
Can you take it from here? | Hint:
Let $$2\sin x+3\cos x=A(3\sin x+2\cos x)+B\cdot\dfrac{d(3\sin x+2\cos x)}{dx}$$ |
52,986,966 | ```
if (col.gameObject.tag == "Enemy"){
transform.position = new Vector3(-9.5f, -4f, 0f)};`
```
In this program whenever the player touches an object called "enemy" it is supposed to "die", before removing the semi-colon, it "died" to anything it touched, now I removed it dies to nothing. Anyone know how to to make it die to only "enemy". | 2018/10/25 | [
"https://Stackoverflow.com/questions/52986966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9492366/"
] | Formik author here...
`setError` was [deprecated in v0.8.0](https://github.com/formium/formik/releases/tag/v0.8.0) and renamed to `setStatus`. You can use `setErrors(errors)` or `setStatus(whateverYouWant)` in your `handleSubmit` function to get the behavior you want here like so:
```js
handleSubmit = async (values, { setErrors, resetForm }) => {
try {
// attempt API call
} catch(e) {
setErrors(transformMyApiErrors(e))
// or setStatus(transformMyApiErrors(e))
}
}
```
**What's the difference use `setStatus` vs. `setErrors`?**
If you use `setErrors`, your errors will be wiped out by Formik's next `validate` or `validationSchema` call which can be triggered by the user typing (a change event) or blurring an input (a blur event). Note: this assumed you have not manually set `validateOnChange` and `validateOnBlur` props to `false` (they are `true` by default).
IMHO `setStatus` is actually ideal here because it will place the error message(s) on a separate part of Formik state. You can then decide how / when you show this message to the end user like so.
```
// status can be whatever you want
{!!status && <FormError>{status}</FormError>}
// or mix it up, maybe transform status to mimic errors shape and then ...
{touched.email && (!!errors.email && <FormError>{errors.email}</FormError>) || (!!status && <FormError>{status.email}</FormError>) }
```
Be aware that the presence or value of `status` has no impact in preventing the next form submission. Formik only aborts the [submission process if validation fails](https://formik.org/docs/guides/form-submission). | **This what you're looking**
```
setErrors({ username: 'This is a dummy procedure error' });
``` |
2,347 | I do `C-a` `C-k` `C-k` to kill the entire line point is on.
If I want to *copy* the line instead of killing it, I can hit `C-/` `C-/`
right after typing the sequence above.
Alternatively, I can do `C-a` `C-SPC` `C-n` `M-w`.
**Is there a faster way to kill or copy the entire line point is on?** | 2014/10/19 | [
"https://emacs.stackexchange.com/questions/2347",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/504/"
] | You can use `kill-whole-line` to kill the entire line point is on. Position of point does not matter. This command is bound to `C-S-DEL` by default.
You can also instruct `kill-line` (bound to `C-k`) to kill the entire line by setting the *variable* `kill-whole-line` to a non-`nil` value:
```el
(setq kill-whole-line t)
```
Note that point has to be at the beginning of the line for this to work.
---
Then there are **these two gems** (via [emacs-fu](http://emacs-fu.blogspot.de/2009/11/copying-lines-without-selecting-them.html)):
```el
(defadvice kill-region (before slick-cut activate compile)
"When called interactively with no active region, kill a single line instead."
(interactive
(if mark-active
(list (region-beginning) (region-end))
(list (line-beginning-position) (line-beginning-position 2)))))
(defadvice kill-ring-save (before slick-copy activate compile)
"When called interactively with no active region, copy a single line instead."
(interactive
(if mark-active
(list (region-beginning) (region-end))
(message "Copied line")
(list (line-beginning-position) (line-beginning-position 2)))))
```
With these in place you can kill or copy the line point is on with **a single keystroke**:
* `C-w` kills the current line
* `M-w` copies the current line
Note that if there is an active region, `kill-region` and `kill-ring-save` will continue to do what they normally do: Kill or copy it.
---
### Porting `slick-cut` and `slick-copy` to new advice system
Emacs 24.4 introduces a [new advice system](https://emacs.stackexchange.com/q/3079/504). While `defadvice` [still works](https://emacs.stackexchange.com/a/3087/504), there is a chance that it might be deprecated in favor of the new system in future versions of Emacs. To prepare for that, you might want to use updated versions of `slick-cut` and `slick-copy`:
```el
(defun slick-cut (beg end)
(interactive
(if mark-active
(list (region-beginning) (region-end))
(list (line-beginning-position) (line-beginning-position 2)))))
(advice-add 'kill-region :before #'slick-cut)
(defun slick-copy (beg end)
(interactive
(if mark-active
(list (region-beginning) (region-end))
(message "Copied line")
(list (line-beginning-position) (line-beginning-position 2)))))
(advice-add 'kill-ring-save :before #'slick-copy)
``` | This is a modification of the answer by itsjeyd – currently the highest voted answer, and one I have used for years. However, it has issues: The adviced version of `kill-ring-save` would sometime fail because the mark is not set (typically in a new buffer), and even when it did work, the cursor did a strange dance after use of the function to copy a single line. After some digging, it dawned on me that this happens because `kill-ring-save` calls `indicate-copied-region` after it has done its work, but as point and mark do not match the copied region, `indicate-copied-region` marked the wrong region.
Enough said. Here is a solution that remedies this:
```
(define-advice kill-ring-save
(:before-while (beg end &optional region) slick)
(or mark-active
(not (called-interactively-p 'interactive))
(prog1 nil
(copy-region-as-kill
(line-beginning-position) (line-beginning-position 2))
(message "Copied current line"))))
```
There is nothing wrong with itsjeyd's advice on `kill-region`. Here is a variant of it anyhow, stylistically more consistent with the above:
```
(define-advice kill-region
(:around (kill-region beg end &optional region) slick)
(if (or mark-active (not region))
(funcall kill-region beg end region)
(funcall kill-region
(line-beginning-position) (line-beginning-position 2))
(message "Killed current line")))
```
**Note** that if `transient-mark-mode` is not turned on, these advices do nothing. |
2,981,512 | I do not understand the process that is required in order to find the max and min values of $|z|$ in $|z-2-i|=1$. My textbook implies to use inspection which I find a bit confusing.
I tried to sketch out the curve but I have little idea on where the minimum and maximum values are.
[](https://i.stack.imgur.com/bqk4Z.png)
Personally, I find A and B to be the intuitive places to check for a minimum, but they don't seem to be the right answers.
Additionally, I am conflicted between C or D (D which is somewhere between $(2,2)$ and C on the circle) is the maximum value. It seems like it could swing either way. Could you pelase explain intuitively how I should determine where the max and min are? | 2018/11/02 | [
"https://math.stackexchange.com/questions/2981512",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/321912/"
] | The minimal value of $\lvert z\rvert$ is reached at the point $P$ of the circle which is closest to the origin and the maximal value of $\lvert z\rvert$ is reached at the point $Q$ of the circle which is furthest from the origin. These points are$$P=2-\frac2{\sqrt5}+\left(1-\frac1{\sqrt5}\right)i\text{ and }Q=2+\frac2{\sqrt5}+\left(1+\frac1{\sqrt5}\right)i$$respectively.
[](https://i.stack.imgur.com/cyWeV.png) | Regarding those 4 points, you can do a direct computation.
$$|A|= \sqrt{1^2+1^2} = \sqrt2\approx 1.4\\ |B|= 2\\|C|=\sqrt{1^2+3^2}=\sqrt{10}\approx 3.16
\\|D|=| 2+i + e^{i\pi/4}| = \sqrt{\left (2 + \frac{1}{\sqrt2}\right )^2+ \left (1 + \frac{1}{\sqrt2}\right )^2} \approx 3.2$$ |
59,413,022 | Experiencing an issue with a program that finds the greatest out of three numbers and displays it. I think that I don't link the two files properly. Can somebody point out what I'm doing wrong and why it doesn't work? Thanks in advance.
The code is written in two separate files - .html and .js.
The code:
```js
let pressedKey = getElementById("button");
pressedKey.addEventListener("click"function() {
let num1 = Number(document.getElementById("num1").value);
let num2 = Number(document.getElementById("num2").value);
let num3 = Number(document.getElementById("num3").value);
if (num1 > num2 && num1 > num3) {
window.alert(num1 + " is the greatest!");
} else if (num2 > num1 && num2 > num3) {
window.alert(num2 + " is the greatest!");
} else {
window.alert(num3 + " is the greatest!");
}
});
```
```html
<html>
<head>
<meta charset="UTF-8">
<title>Greatest number of 3.</title>
</head>
<body>
<h1>Calculate the greatest of three numbers!</h1>
<hr color="cyan">
<br> Enter number one: <input type="text" id="num1"></input><br> Enter number two: <input type="text" id="num2"></input><br> Enter number three: <input type="text" id="num3"></input><br>
<hr color="cyan">
<button id="button">OK</button>
<script src="greatestNumber.js"></script>
</body>
</html>
``` | 2019/12/19 | [
"https://Stackoverflow.com/questions/59413022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12566049/"
] | You are using `getElementById` alone. You need to call it from `document`. So: `document.getElementById`. Also, in your `pressedKey.addEventListener` you are missing a comma. Finally, in your html, you are closing your `input` elements with `</input>`. `input` is a void element and does not need a closing tag. See this post for more details: <https://stackoverflow.com/a/13232170/7919626>
You can find these errors yourself using the developer tool(F12) on any browser. I would suggest you learn how to use them to find the errors easily next time.
Here's the final working solution:
```js
let pressedKey = document.getElementById("button");
pressedKey.addEventListener("click", function() {
let num1 = Number(document.getElementById("num1").value);
let num2 = Number(document.getElementById("num2").value);
let num3 = Number(document.getElementById("num3").value);
if (num1 > num2 && num1 > num3) {
window.alert(num1 + " is the greatest!");
} else if (num2 > num1 && num2 > num3) {
window.alert(num2 + " is the greatest!");
} else {
window.alert(num3 + " is the greatest!");
}
});
```
```html
<html>
<head>
<meta charset="UTF-8">
<title>Greatest number of 3.</title>
</head>
<body>
<h1>Calculate the greatest of three numbers!</h1>
<hr color="cyan">
<br> Enter number one: <input type="text" id="num1" /><br> Enter number two: <input type="text" id="num2" /><br> Enter number three: <input type="text" id="num3" /><br>
<hr color="cyan">
<button id="button">OK</button>
<script src="greatestNumber.js"></script>
</body>
</html>
``` | ```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Greatest number of 3.</title>
<div id="numberList"></div>
</head>
<body>
<h1>Calculate the greatest of three numbers!</h1>
<hr color="cyan">
<br>
Enter number one: <input class='num' type="text" id="num1"></input><br>
Enter number two: <input class='num' type="text" id="num2"></input><br>
Enter number three: <input class='num' type="text" id="num3"></input><br>
<hr color="cyan">
<button id="button">OK</button>
</body>
<script>
let pressedKey = document.getElementById("button");
pressedKey.addEventListener("click", function(){
let numElements = document.getElementsByClassName('num');
let nums = [];
for(var i = 0; i < numElements.length; i++) {
nums[i] = numElements[i].value;
}
console.log(nums.sort(function(a, b){return b-a}));
});
</script>
</html>
``` |
64,478,268 | For testing purposes we have PS script to deploy our ARM templates to testing Resource Group.
```
$ctx = New-AzStorageContext -StorageAccountName $storageAccountName -UseConnectedAccount
$sasToken = New-AzStorageContainerSASToken -Context $ctx -Name $containerName -Permission r -ExpiryTime (Get-Date).AddHours(1)
$toDeploy = "app1", "app2"
foreach ($template in $toDeploy) {
$templateUri = "${containerUrl}/${template}.json${sasToken}"
$templateParameterUri = "${containerUrl}/${template}.parameters.Integration.json${sasToken}"
$templatePostUri = "${containerUrl}/${template}.Post.json${sasToken}"
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroup `
-TemplateUri $templateUri `
-TemplateParameterUri $templateParameterUri `
-Mode Incremental `
-DeploymentDebugLogLevel All `
-Name "TestDeployment" `
-Verbose
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroup `
-TemplateUri $templatePostUri `
-Mode Incremental `
-DeploymentDebugLogLevel All `
-Name "TestDeploymentPost" `
-Verbose
```
It works for 2 out of 3 developers. When one of us is executing this an error is displayed saying that link to template is invalid. ARM cannot download it.
```
Error: Code=InvalidContentLink; Message=Unable to download deployment content from
| 'https://ourstorage.blob.core.windows.net/user-testing/app1.json?SAS_TOKEN_HERE'. The tracking Id is '386e7670-1863-4c85-9484-8a27d2dd0760'.
```
But when we copy it to browser we can download it. All 3 of us. For some reason only ARM cannot download it. When storage account is configured with public access and we remove SAS token from links it works from this dev's machine. So looks like some issue with SAS token generation from one machine. But why is this SAS token ok for us (3 devs) but invalid for ARM? | 2020/10/22 | [
"https://Stackoverflow.com/questions/64478268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/679340/"
] | wrap your ListView.builder with Container provide a height to it.
like for your code-
```
child: Stack(
children: [
Container(
height: 100.0,
child: ListView.builder(
itemCount: tasks.length,
shrinkWrap: true ,
itemBuilder: (context, index) => ListTile(
title: Text(tasks[index].name),
),
),
),
FloatingActionButton(
onPressed: () {
setState(() {
hide = !hide;
});
},
),
],
),
``` | you can just wrap `ListView` with an `Expanded` widget
```
Stack(
children: [
Expanded(
child: ListView.builder(
itemCount: tasks.length,
shrinkWrap: true ,
itemBuilder: (context, index) => ListTile(
title: Text(tasks[index].name),
),
),
),
)
``` |
42,460,667 | I have a `command-line` program that its first argument `( = argv[ 1 ] )` is a regex pattern.
`./program 's/one-or-more/anything/gi/digit-digit'`
So I need a regex to check if the entered input from user **is correct or not**. This regex can be solve easily but since I use [c++](/questions/tagged/c%2b%2b "show questions tagged 'c++'") library and [`std::regex_match`](http://en.cppreference.com/w/cpp/regex/regex_match) and this function **by default** puts **begin** and **end** assertion (`^` and `$`) at the given string, so the **nan-greedy** quantifier is ignored.
Let me clarify the subject. If I want to match `/anything/` then I can use `/.*?/` but `std::regex_match` considers this pattern as `^/.*?/$` and therefore if the user enters: `/anything/anything/anyhting/` the `std::regex_match` still returns **true** whereas the input-pattern **is not correct**. The `std::regex_match` only returns **true** or **false** and the expected pattern form the user can only be a text according to the pattern. Since the pattern is various, here, I can not provide you all possibilities, but I give you some example.
**Should be match**
```
/.//
s/.//
/.//g
/.//i
/././gi
/one-or-more/anything/
/one-or-more/anything/g/3
/one-or-more/anything/i
/one-or-more/anything/gi/99
s/one-or-more/anything/g/4
s/one-or-more/anything/i
s/one-or-more/anything/gi/54
and anything look like this pattern
```
---
Rules:
1. delimiters are `/|@#`
2. `s` letter at the beginning and `g`, `i` and 2 digits at the end are optional
3. `std::regex_match` function returns **true** if the entire target character sequence can be match, otherwise return **false**
4. between first and second delimiter can be **one-or-more** `+`
5. between second and third delimiter can be **zero-or-more** `*`
6. between third and fourth can be **g** or **i**
7. At least **3** delimiter should be match `/.//` not less so `/./` should not be match
8. [ECMAScript 262](http://www.ecma-international.org/publications/standards/Ecma-262.htm) is allowed for the pattern
---
**NOTE**
* May you would need to see may question about `std::regex_match`:
[std::regex\_match and lazy quantifier with strange
behavior](https://stackoverflow.com/questions/42422778/stdregex-match-and-lazy-quantifier-with-strange-behavior)
* I no need any C++ code, I just need a pattern.
* Do not try `d?([/|@#]).+?\1.*?\1[gi]?[gi]?\1?d?\d?\d?`. It fails.
* My attempt so far: [`^(?!s?([/|@#]).+?\1.*?\1.*?\1)s?([/|@#]).+?\2.*?\2[gi]?[gi]?\d?\d?$`](https://regex101.com/r/3SC0l8/6)
* If you are willing to try, you should put `^` and `$` around your pattern
---
If you need more details please comment me, and I will update the question.
Thanks. | 2017/02/25 | [
"https://Stackoverflow.com/questions/42460667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4643584/"
] | You have an extra newline between the command `echo` and the string that you are telling the shell to echo, which is what is causing your error message.
But you are also sending interactive commands to `sfdisk`, which is not an interactive tool. Your code appears to be based on the top of [this article](http://xmodulo.com/how-to-run-fdisk-in-non-interactive-batch-mode.html), which @GregTarsa linked in his comment, but that is sending those commands to *fdisk*, not *sfdisk*. (You are also missing another newline between the `l` and `w` fdisk commands.)
The *sfdisk* program is designed to take a text description of the desired partitioning layout and apply it to a disk. It doesn't expect single-letter commands on input; it expects its input to look like this:
```
# partition table of /dev/sda
unit: sectors
/dev/sda1 : start= 2048, size= 497664, Id=83, bootable
/dev/sda2 : start= 501758, size=1953021954, Id= 5
/dev/sda3 : start= 0, size= 0, Id= 0
/dev/sda4 : start= 0, size= 0, Id= 0
/dev/sda5 : start= 501760, size=1953021952, Id=8e
```
Which is less generic than the `fdisk` commands, since it requires actual block numbers, but much easier to use (and for someone reading your script to understand), since you're not trying to remote-control an interactive program by `echo`ing commands to it.
If you *are* going to remote-control an interactive program from the shell, I recommend looking into [`expect`](http://www.tcl.tk/man/expect5.31/expect.1.html) instead of doing blind `echo`s.
Also, in general, if you are trying to print multiline data, `echo` is probably not the way to go. With lines this short, I would reach for `printf`:
```
printf '%s\n' n p l "" "" w | fdisk "$i"
```
But the more generally useful tool is the here-document:
```
fdisk "$i" <<EOF
n
p
l
w
EOF
``` | A newline terminates a command. If you want to pass a multiline argument to `echo`, you need to move your quote. For example:
```
for i in $hdd; do
echo "n
p
1
w
" | sfdisk $i
done
```
It would probably look better to write:
```
for i in $hdd; do printf 'n\np\n1\n\nw\n' | sfdisk $i; done
```
A third option is to use a heredoc:
```
for i in $hdd; do
sfdisk $i << EOF
n
p
1
w
EOF
done
``` |
49,960,934 | I need to count the number of dupes in an array, but I'm constrained to only using arrays, no HashSets or ArrayLists.
Here are example inputs with their expected outputs:
```
numDuplicates(new double[] { }) --> 0
numDuplicates(new double[] { 11.0 }) --> 0
numDuplicates(new double[] { 11.0, 11.0, 11.0, 11.0 }) --> 3
numDuplicates(new double[] { 11.0, 11.0, 11.0, 11.0, 22.0, 33.0, 44.0, 44.0, 44.0, 44.0, 44.0, 55.0, 55.0, 66.0, 77.0, 88.0, 88.0 }) --> 9
numDuplicates(new double[] { 11.0, 22.0, 33.0, 44.0, 44.0, 44.0, 44.0, 44.0, 55.0, 55.0, 66.0, 77.0, 88.0 }) --> 5
```
This is the code I have, but it counts duplicates after each number, returning an inflated count, i.e. {11.0, 11.0, 11.0, 11.0} returns 6 instead of 3:
```
public static int numDuplicates (double[] list) {
int dupCount = 0;
for (int i = 0; i < list.length; i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[i] == list[j]) {
dupCount++;
}
}
}
return dupCount; //TODO1: fix this
}
```
Note: I'm new on Stack, I tried searching thoroughly but couldn't find an array duplicate question that had similar input/output to mine, but I'm sorry if someone has already asked this. | 2018/04/21 | [
"https://Stackoverflow.com/questions/49960934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9680116/"
] | Simple fix:
```
public static int numDuplicates (double[] list) {
int dupCount = 0;
for (int i = 0; i < list.length; i++) {
for (int j = i + 1; j < list.length; j++, i++) { // HERE it is
if (list[i] == list[j]) {
dupCount++;
}
}
}
return dupCount;
}
```
What I did was to increment `i` in addition to `j`. What this did was to start `i` at the place where `j` stopped. The reason I thought to do that was because you said it was returning an inflated count, so I figured it must be because you are doing too many counts and that was exactly what was happening.
`i` was always following in increments of `1` rather than increments of the `size of the last duplicate counts` found, so it was always repeating counts.
As to how the `j++, i++` works - it is just a series of expressions. Java allows you to separate expressions that evaluate to the same type, using a comma.
---
As per the comments, you can remove the outer loop:
```
public static int numDuplicates (double[] list) {
int dupCount = 0;
for (int i = 1; i < list.length; i++) {
if (list[i] == list[i - 1]) {
dupCount++;
}
}
return dupCount;
}
``` | You could use another array like so:
```
public static int numDuplicates(double[] list) {
double[] duparray = new double[list.length];
int dupCount = 0;
for (int i = 0; i < list.length; i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[i] == list[j] && !(list[i] == duparray[i])) {
duparray[i] = list[i];
dupCount++;
}
}
}
return dupCount;
}
``` |
51,902,363 | I added a progress bar to my screen. I want it to be centered horizontally in my container, but I want to move it to the bottom of my screen. How do I edit the third line to change its position?
```
func addControls() {
progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Default)
progressView?.center = self.view.center
view.addSubview(progressView!)
}
``` | 2018/08/17 | [
"https://Stackoverflow.com/questions/51902363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10229471/"
] | It will only clear the element in the index *right after* the last element in the original list, so in the first example the list is empty, hence it nullifies the element at index zero (the first element which is `"1"`).
In your last example, it just happens that the last element is the one right after the last element in the original list. Knowing that the last scenario wouldn't really help in determining the size of the list because it *did* allowed null values.
But if the list did not allow null (e.g. [immutable lists introduced in Java 9](https://docs.oracle.com/javase/9/docs/api/java/util/List.html#immutable)), then this is useful because in case you're looping over the returned array, **you would not want to process the extra elements**, in which case you can stop the iterator at the first null element. | Code of toArray(T[] a) of (for instance) ArrayList is quite clear:
```
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
```
If input array's size is bigger than this list's (which means that we can copy all the list's content into this array because it's length is big enough), then the next element reference in the array after all lists content copied (actually the index equal to the size of the list) will be set to point to null. |
56,030,927 | I am getting an array in PHP as:
```
Array
(
[1] => 2019
[2] => 5
[3] => 7
[4] => 0
)
```
where [1] is always the year, [2] is always the month and [3] is always the date.
How can I convert this array to `date("Y-m-d")` format? | 2019/05/07 | [
"https://Stackoverflow.com/questions/56030927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/777505/"
] | Assuming this data input:
```
$data = [null, 2019, 5, 7, 0];
```
Using DateTime
```
$dt = new DateTime(sprintf( "%04d-%02d-%02d", $data[1], $data[2],
$data[3]));
echo $dt->format('Y-m-d') . "\n";
```
Using Sprintf
```
// use this if you really trust the data
$dt = sprintf( "%04d-%02d-%02d", $data[0], $data[1], $data[2]);
echo $dt . "\n";
```
Using Carbon
```
// Carbon is a fantastic Date and Time class -> https://carbon.nesbot.com/
$dt = \Carbon\Carbon::create($data[0], $data[1], $data[2], 0, 0, 0);
echo $dt->format('Y-m-d') . "\n";
``` | You might simply use concat and join them into a string:
```
$arr = array(
"1" => "2019",
"2" => "5",
"3" => "7",
"4" => "0",
);
$datetime_format = $arr["1"] . "-" . $arr["2"] . "-" . $arr["3"];
var_dump($datetime_format);
```
### Output
```
string(8) "2019-5-7"
```
If you wish to have a 4-2-2 format, this might work:
```
$arr = array(
"1" => "2019",
"2" => "5",
"3" => "7",
"4" => "0",
);
$datetime_format = '';
foreach ($arr as $key => $value) {
if ($key == "4") {break;}
echo strlen($value);
if (strlen($value) >= 2) {
$datetime_format .= $value;
} elseif (strlen($value) == 2) {
$datetime_format .= $value;
} elseif (strlen($value) == 1) {
$datetime_format .= "0" . $value;
} else {
echo "Something is not right!";
}
if ($key <= "2") {$datetime_format .= '-';}
}
var_dump($datetime_format);
```
### Output
```
string(10) "2019-05-07"
``` |
71,127,608 | I would like to repeat an API call which returns a Promise, conditionally using rxjs.
The API method receives an id which will be changed on every call by adding a counter prefix to it. The calls will be repeated until the data met some condition or the counter reach to a specific number X. How it can be done using rxjs?
API method:
`fetchData(id):Promise<data>`
try 1: fetchData(id)
try 2: fetchData(id\_1)
try 3: fetchData(id\_2) | 2022/02/15 | [
"https://Stackoverflow.com/questions/71127608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18213593/"
] | You can use concatMap to ensure only one call is tried at a time. `range` gives the maximum number of calls because `takeWhile` will unsubscribe early (before the range is done) if a condition is/isn't met.
That might look like this:
```ts
// the data met some condition
function metCondition(data){
if(data/*something*/){
return true;
} else {
return false
}
}
// the counter reach to a specific number X
const x = 30;
range(0, x).pipe(
concatMap(v => fetchData(`id_${v === 0 ? '' : v}`)),
takeWhile(v => !metCondition(v))
).subscribe(datum => {
/* Do something with your data? */
});
``` | I know you've specified using rxjs, however you've also specified that `fetchData()` returns a `promise` and not an `observable`. In this case I would suggest using `async` and `await` rather than rxjs.
```js
async retryFetch() {
let counter = 0;
while (counter++ < 20 && !this.data) {
this.data = await this.fetchData(counter);
}
}
```
You can put whatever you want in the conditional.
Even if your api call returned an observable, I would still suggest wrapping it in a promise and using this very readable solution.
The stackblitz below wraps a standard `http.get` with a promise and implements the above function. The promise will randomly return the data or undefined.
<https://stackblitz.com/edit/angular-ivy-rflclt?file=src/app/app.component.ts> |
26,784,319 | I want to split a large text file into single words as I need to shuffle the letters of each word.
```
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
```
This is show I read in the textfile with text and gives an output of:
```
[This is Line One. , This is Line Two. , This is Line three. , End.]
```
How do I split this into {This, is, Line, One} etc?
I tried
```
aryLines.split("\\s+");
```
but it doesnt work as aryLines is a array... | 2014/11/06 | [
"https://Stackoverflow.com/questions/26784319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3952463/"
] | I want to offer a more modern solution using `DispatchGroup`.
Usage example 1:
```
var urlRequest = URLRequest(url: config.pullUpdatesURL)
urlRequest.httpMethod = "GET"
urlRequest.httpBody = requestData
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let (data, response, error) = URLSession.shared.syncRequest(with: urlRequest)
```
Usage example 2:
```
let url = URL(string: "https://www.google.com/")
let (data, response, error) = URLSession.shared.syncRequest(with: url)
```
Extension code:
```
extension URLSession {
func syncRequest(with url: URL) -> (Data?, URLResponse?, Error?) {
var data: Data?
var response: URLResponse?
var error: Error?
let dispatchGroup = DispatchGroup()
let task = dataTask(with: url) {
data = $0
response = $1
error = $2
dispatchGroup.leave()
}
dispatchGroup.enter()
task.resume()
dispatchGroup.wait()
return (data, response, error)
}
func syncRequest(with request: URLRequest) -> (Data?, URLResponse?, Error?) {
var data: Data?
var response: URLResponse?
var error: Error?
let dispatchGroup = DispatchGroup()
let task = dataTask(with: request) {
data = $0
response = $1
error = $2
dispatchGroup.leave()
}
dispatchGroup.enter()
task.resume()
dispatchGroup.wait()
return (data, response, error)
}
}
```
As a bonus, if you need to, you can easily implement a timeout. To do this, you need to use
`func wait(timeout: DispatchTime) -> DispatchTimeoutResult` instead of
`func wait()` | Be careful with synchronous requests because it can result in bad user experience but I know sometimes its necessary.
For synchronous requests use NSURLConnection:
```
func synchronousRequest() -> NSDictionary {
//creating the request
let url: NSURL! = NSURL(string: "exampledomain/...")
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
var error: NSError?
var response: NSURLResponse?
let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
error = nil
let resultDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
return resultDictionary
}
``` |
22,911 | As an IT guy I cannot avoid the observation that the states "30-30" and "40-40", "deuce", have the same outgoing transitions in the state machine "tennis game": From both scores a two point difference is necessary to win the game, and the state machine degenerates to a machine with three states (advantage for either of the two players, or deuce). Likewise, "30-40" and "40-30" is "advantage" for the respective leader.
My son and I therefore started calling "30-30" "deuce" and "30-40"/"40-30" "advantage", first jokingly, and now as a matter of routine. As with traditional counting, a win requires scoring at least four times and being two scores ahead.
This habit does not change the game, right?
Edit to address closing as dup: The alleged duplicate is an entirely different question. It asks in effect why we don't count 1, 2, 3 instead of 15, 30, 40 but does not address the fact that there is no logical distinction between 30-30 and 40-40 (or 2-2 and 3-3, for that matter). | 2019/08/07 | [
"https://sports.stackexchange.com/questions/22911",
"https://sports.stackexchange.com",
"https://sports.stackexchange.com/users/17828/"
] | Deuce connotes that both players have scored their maximum per game without winning the game. Calling 30-30 'deuce' does not reflect this. Similarly, using 'advantage' before true deuce has been attained does not indicate that both players have scored their game max without winning the game. | With regard to "40-40": in court tennis (aka real tennis), when the handicap system is used "40-all" is called instead of "deuce" because the next point will win the handicapped game. In non-handicap play, as in lawn tennis, one needs to win by two points, so "deuce" (derived from deux (two)) is called to indicate this. |
427,707 | What's the origin of the expression "peanut gallery"? When was it first used? I know there is a similar expression in Spanish "gallinero", I wonder if they are equivalent. | 2018/01/23 | [
"https://english.stackexchange.com/questions/427707",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/9625/"
] | According to the OED, "peanut gallery" is an informal American term that originally referred to a location in a theater:
>
> the top gallery in a theatre or cinema, usually the location of the cheapest seats and hence regarded as the most vocal or rowdy section of the audience
>
>
>
(I have never heard the term used to refer to a specific part of a theater, but this definition is still listed in some modern dictionaries, so it's apparently still in use.)
According to [World Wide Words](http://www.worldwidewords.org/qa/qa-pea1.htm), the reason it's called a *peanut* gallery is that:
>
> A significant difference between the American and British theatres is that American patrons ate peanuts; these made wonderful missiles for showing their opinion of artistes they didn’t like.
>
>
>
The earliest citation for the expression in the OED is 1876:
>
> As a bid for applause from the political pit and peanut gallery it was a masterpiece.
>
> The Mountain Democrat (Placerville, California)
>
>
>
The earliest I have been able to find (with Google Books) is 1874:
>
> ... but, concluding that we could see nothing worth seeing from this position, in what we would call the "peanut gallery" at home, we respectfully declined the proposal.
>
> [Europe Viewed Through American Spectacles](https://books.google.com/books?id=Xl3o-NK_xPcC&pg=PA53)
>
>
>
A search of newspapers brought up a slightly earlier result:
>
> ...he thought he would buy a ticket admitting him to the peanut gallery.
>
> [*Delaware state journal.* (Wilmington, Del.), 31 May 1873.](http://chroniclingamerica.loc.gov/lccn/sn84026836/1873-05-31/ed-1/seq-4/)
>
>
>
[Merriam Webster](https://www.merriam-webster.com/dictionary/peanut%20gallery), on the other hand, lists 1867 as the year of first known use (but has no specific citation). | Whatever it may be now, 'peanut gallery' seems to have started as a thin veneer laid over more overtly racist names for segregated seating. The earliest use I could find of the specific phrase exposes the agenda:
>
> It is useless for us to repeat our praises of Johnny Thompson, Billy Reeves, and others of the company, as negro delineators; they "out Herod Herod," and put the darkies in the "peanut gallery" fairly to the blush.
>
>
> [*The Times-Picayune*, New Orleans, Louisiana, 16 Jan 1867](https://www.newspapers.com/image/26666596/?terms=%22peanut%2Bgallery%22) (paywalled).
>
>
>
(The "out Herod Herod" in the quoted paragraph alludes to Shakespeare's use of the phrase in *Hamlet*, where it means "to outdo Herod in cruelty, etc.". Here it is probably used in a weakened sense, that is, "they are more outrageous than Herod".)
In isolation, the use of 'peanut gallery' in *The Times-Picayune* of 1867 might be considered incidental to the skin tones of those seated there; it is not in isolation, however. The same section of seats was commonly called the 'negro gallery' (from at least 1853 to the mid-1900s), the 'nigger gallery' (from at least 1860 to the mid-1900s), and the 'nigger seats' (from at least 1833). For example, this early use of 'nigger seats' lays the practice and terminology bare:
>
> **DIALOGUE.**
>
> The following dialogue, says the N. E. Galaxy, occurred on the morning of the first discussion between Messrs. Wright and Finley, at Park-street meeting house:
>
> 'A very respectable and well-dressed colored man had taken a station in a distant corner of the gallery. A colonizationist came up to him, and the following dialogue ensued.
>
> *Colonization.* You must not remain here.
>
> *Color.* Where shall I go?
>
> *Colonization.* Up there. [*Pointing to a large martin box,* commonly called *nigger* seats, the *Liberia* of every church.]
>
> *Color.* Where is Mr. Simpson's pew; he invited me to take a seat in it, whenever I should come here.
>
> *Colonization.* Mr. Simpson has no pew.
>
> *Color.* Doesn't he come here to meeting.
>
> *Colonization.* Yes.
>
> *Color.* Well; has he no pew to sit in?
>
> *Colonization.* Yes; but he hires it.
>
> *Color.* Well, Sir, will you be so good as to show it to me.
>
> *Colonization.* No, you can't go there, but you may go into the other gallery. [*Pointing to the opposite side.*]
>
>
> The seat to which this colored man, whose character would dignify nine out of ten whites in this city, was so arbitrarily driven, was similar to that which he had first taken.
>
>
> [*The Liberator*, Boston, Massachusetts, 29 Jun 1833](https://www.newspapers.com/image/35036554/?terms=%22nigger%2Bseats%22) (paywalled).
>
>
>
Note that the 'martin box' was so called because of its elevation and distance from the pulpit or stage, compared to other seating areas. Note also that "Liberia" in the dialog alludes to "a West African state founded in 1822 as a settlement for freed black slaves from the United States" ([*OED*](http://oed.com/)). And note finally that a 'colonizationist' was an "adherent or advocate of colonization; *spec[ifically]* (in *U.S. Hist.*) an advocate of the colonization of Africa by emancipated slaves and free black people from America, as a solution to the slavery question" (*OED*).
---
I suppose the Spanish *gallinero* is roughly equivalent in some senses to contemporary senses of 'peanut gallery'. Colloquial use of *gallinero*, especially in the UK, emphasizes the elevation of seating in theaters by refering to the spectators as "gods". Similarly, the 'peanut gallery' is today known for the rowdy and noisy behavior of its occupants, and *gallinero* in colloquial use refers to the noise and bedlam of the madhouse. The literal sense of *gallinero*, however, is "henhouse" or "coop". |
41,877,041 | I am checking for a config value to be set, if it is I want to redirect to a child route. if not just display as usual. The code does update the URL as expected but then gets into an infinite loop.
`index.js`
```
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, browserHistory, IndexRoute } from 'react-router'
import App from './modules/App'
import About from './modules/About'
import Map from './modules/Map'
import Maps from './modules/Maps'
import Home from './modules/Home'
import { settings } from './appconfig.js';
function checkDefaultFloor(){
if (settings.floorUrl){
console.log( settings.floorUrl);
browserHistory.push('/maps/'+ settings.floorUrl);
}
}
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/maps" component={Maps} onEnter={checkDefaultFloor}>
<Route path="/maps/:mapName" component={Map}/>
</Route>
<Route path="/about" component={About}/>
</Route>
</Router>
), document.getElementById('app'))
```
[](https://i.stack.imgur.com/w8Kia.png) | 2017/01/26 | [
"https://Stackoverflow.com/questions/41877041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236989/"
] | I had a similar problem. The solution was to implement what Shubham Khatri, suggested. However, an important point I originally missed was to attach the onEnter callback to an IndexRoute. I'm using standard JavaScript objects to define my routes. This is what I needed to do:
```js
{
path: '/',
indexRoute: {
onEnter: (nextState, replace) => replace('some-route')
},
childRoutes: [...]
}
```
I would bet that there was a similar problem with the OP's JSX code. It likely should have been like this (although I haven't tested this):
```js
function checkDefaultFloor(nextState, replace, callback){
if (settings.floorUrl){
console.log( settings.floorUrl);
replace(`/maps/${settings.floorUrl}`)
}
callback();
}
```
```js
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/maps" component={Maps}>
<IndexRoute onEnter={checkDefaultFloor}/>
<Route path="/maps/:mapName" component={Map}/>
</Route>
<Route path="/about" component={About}/>
</Route>
</Router>
``` | You `browserHistory.push()` statement is making it to go in an endless loop since the route is nested insided your `map` route. You need to make use of `replace` function and `callback` like.
```
function checkDefaultFloor(nextState, replace, callback){
if (settings.floorUrl){
console.log( settings.floorUrl);
replace(`/maps/${settings.floorUrl}`)
}
callback();
}
``` |
73,907,515 | I'm trying to understand as what can be done in order to enable cross platform communication with Microsoft Teams. I've researched but there is nothing from Microsoft that talks on this subject or even didn't find anything on Google. However, this is what is possible with Facebook messenger. I've created an application which can communicate with FB messenger by means of `webhook`.
I've an API, which is configured in FB app (ref: <https://developers.facebook.com/docs/messenger-platform/webhooks#verification-requests>). Microsoft does talk about `outgoing webhook`, but that's for BOT conversation not real time communication. Could anyone assist? | 2022/09/30 | [
"https://Stackoverflow.com/questions/73907515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4776754/"
] | You have to use `concat_ws`
```
from pyspark.sql.functions import concat_ws
df = df.withColumn('joined_column',concat_ws('',df.p1, df.p2, df.p3, df.p4))
``` | you can use below code. If you will check your schema, the data in those columns may not be integer. You need to convert p1 to p4 as integer type
```
from pyspark.sql.types import IntegerType
df = df \
.withColumn("p1" , df["p1"].cast(IntegerType())) \
.withColumn("p2", df["p2"].cast(IntegerType())) \
.withColumn("p3" ,df["p3"].cast(IntegerType())) \
.withColumn("p4" , df["p4"] .cast(IntegerType()))
import pyspark
from pyspark.sql import functions as sf
df = df.withColumn('joined_column',sf.concat(sf.col('p1'),sf.col('p2'),sf.col('p3'),sf.col('p4')))
display(df)
``` |
2,540,109 | I'm brand new to java, coming from a ruby world. One thing I love about ruby is the very terse syntax such as ||=.
I realize of course that a compiled language is different, but I'm wondering if Java has anything similar.
In particular, what I do all the time in ruby is something like:
```
someVar ||= SomeClass.new
```
I think this is incredibly terse, yet powerful, but thus far the only method I can think of to achieve the same thing is a very verbose:
```
if(someVar == null){
someVar = new SomeClass()
}
```
Just trying to improve my Java-fu and syntax is certainly one area that I'm no pro. | 2010/03/29 | [
"https://Stackoverflow.com/questions/2540109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74389/"
] | I think the best you could do is the ternary operator:
```
someVar = (someVar == null) ? new SomeClass() : someVar;
``` | This looks like you could add a method to SomeClass similar to
```
public static someClass enforce(someClass x) {
someClass r = x.clone();
if(r == null){
r = new SomeClass();
}
return r;
}
```
And call it like
```
someVar = SomeClass.enforce(someVar);
``` |
266,486 | I am trying to write out a png file from a java.awt.image.BufferedImage. Everything works fine but the resulting png is a 32-bit file.
Is there a way to make the png file be 8-bit? The image is grayscale, but I do need transparency as this is an overlay image. I am using java 6, and I would prefer to return an OutputStream so that I can have the calling class deal with writing out the file to disk/db.
Here is the relevant portion of the code:
```
public static ByteArrayOutputStream createImage(InputStream originalStream)
throws IOException {
ByteArrayOutputStream oStream = null;
java.awt.Image newImg = javax.imageio.ImageIO.read(originalStream);
int imgWidth = newImg.getWidth(null);
int imgHeight = newImg.getHeight(null);
java.awt.image.BufferedImage bim = new java.awt.image.BufferedImage(imgWidth,
imgHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB);
Color bckgrndColor = new Color(0x80, 0x80, 0x80);
Graphics2D gf = (Graphics2D)bim.getGraphics();
// set transparency for fill image
gf.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));
gf.setColor(bckgrndColor);
gf.fillRect(0, 0, imgWidth, imgHeight);
oStream = new ByteArrayOutputStream();
javax.imageio.ImageIO.write(bim, "png", oStream);
oStream.close();
return oStream;
}
``` | 2008/11/05 | [
"https://Stackoverflow.com/questions/266486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The build in imageio png writer will write 32bit png files on all the platforms I have used it on, no matter what the source image is. You should also be aware that many people have complained that the resulting compression is much lower than what is possible with the png format. There are several independent [png libraries](http://www.catcode.com/pngencoder/) available that allow you to specify the exact format, but I don't actually have any experience with any of them. | I found the answer as to how to convert RGBA to Indexed here: <http://www.eichberger.de/2007/07/transparent-gifs-in-java.html>
However, the resulting 8-bit png file only has 100% or 0% transparency. You could probably tweak the IndexColorModel arrays, but we have decided to make the generated file (what was an overlay mask) into an underlay jpg and use what was the static base as the transparent overlay. |
569,357 | is it possible to clear all textboxes in HTML by calling a javascript function ? | 2009/02/20 | [
"https://Stackoverflow.com/questions/569357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65415/"
] | I think
```
$("input:text").val("");
```
Should work with jQuery. | Old post..but, with jquery for example:
```
$("input[type=text],textarea,input[type=email]").val('');
``` |
37,150,417 | I am using a tab bar controller and I wonder if there is a way to check which tab is being clicked?
If the user clicks on the "account" tab and is not logged in I want to redirect to a full screen modal login screen instead of the account VC. | 2016/05/10 | [
"https://Stackoverflow.com/questions/37150417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2636197/"
] | You can do it in your custom UITabBarController or somewhere, and override the 'didSelectItem' function.
```
import UIKit
class TabbarViewController: UITabBarController {
override func viewDidLoad() {
}
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
print("Selected Index :\(self.selectedIndex)");
}
}
``` | UITabBarDelegate's didSelectItem |
22,574,698 | I am using below PHP function in Behat Mink to check the Email column values are in ascending or descending order.But the problem is its always fails.I just want to check if the subject or From of Email column in all rows are in ascending and descending order.Is there are any other way to do this?
```
public function ValidateColumnSorting($Column, $order) {
$nodes = // Logic goes to retrieve all rows subject or from column value
if (strcasecmp($order, "asc") == 0)
{
for ($i = 1; $i < $sizeof($nodes); $i++)
{
if (strcasecmp($nodes[$i], $nodes[$i - 1]) >= 0)
{
print_r("Row " . $i - 1 . " val is " . $nodes[$i - 1]);
}
else if (strcasecmp($nodes[$i], $nodes[$i - 1]) < 0)
{
throw new Exception($Column . " column ascending sort order failed.".$nodes[$i] . " is less than " . $nodes[$i - 1]);
}
}
}
else
{
for ($i = 1; $i < $sizeof($nodes); $i++)
{
print_r($Column . " column row " . $i . " value is " . $nodes[$i]);
if (strcasecmp($nodes[$i], (string) $nodes[$i - 1]) <= 0) {
print_r($Column . " of Email is same");
} else if (strcasecmp($nodes[$i], $nodes[$i - 1]) > 0) {
throw new Exception($Column . " column descending sort order failed." . $nodes[$i] . " is greater than " . $nodes[$i - 1]);
}
}
}
}
``` | 2014/03/22 | [
"https://Stackoverflow.com/questions/22574698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2212566/"
] | You can wrap the svg element with a div element, and set styles to the div element, then enlarge the svg size enough to render whole graphic.
```
<div style="overflow:visible; margin-left:121px; margin-top:39px; height:206px; width:327px;">
<svg height="206px" width="500px">
<path d=" M 244.3,102.7 A 82.3,52 0,0 0,82.3 102.7 L 1.3,102.7 A 163.3,102.7 0,0 1,325.3 102.7 L 325.3,102.7 365.8,102.7 284.8,153.3 203.8,102.7 244.3,102.7 L 244.3,102.7 " x="1.5" y="1.5" style="fill:#92d050; stroke-width:3; stroke:blue; "></path>
</svg>
</div>
``` | `document.getElementsByTagName("path")[0].getBBox()` will get the bounds of the path (x, y, width, height) you can use those to set the `<svg>` element width and height. |
9,998,832 | I'm creating an array of view controllers, adding them to a UINavigation Controller, and then presenting them modally.
I cannot however set the text to the "back" button in each view to anything other than the word "back".
This is the code:
```
//The View Controllers and Array
VC1 *vc1 = [[VC1 alloc] initWithNibName:@"VC1" bundle:nil];
VC2 *vc2 = [[VC2 alloc] initWithNibName:@"VC2" bundle:nil];
VC3 *vc3 = [[VC3 alloc] initWithNibName:@"VC3" bundle:nil];
NSArray * viewControllers = [NSArray arrayWithObjects:vc3, vc2, vc1, nil];
// Create the nav controller and set the view controllers.
UINavigationController* theNavController = [[UINavigationController alloc]
initWithRootViewController:vc3];
[theNavController setViewControllers:viewControllers animated:NO];
// Display the nav controller modally.
[self presentModalViewController:theNavController animated:YES];
```
I have tried the following in the init of each VC:
```
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @"Acknowledge Briefings Read";
self.navigationItem.backBarButtonItem = barButton;
```
... but it does not work. Any ideas? Many thanks.
Also, related, I'd ideally like to navigate the stack in a "forwards" direction. Is this possible using a navigation controller? | 2012/04/03 | [
"https://Stackoverflow.com/questions/9998832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1128354/"
] | You can't do anything view-wise in the init. You need to wait for viewDidLoad (or willAppear or didAppear), since nothing has been drawn in init (in the case of the nav controller, the previous item will be affected).
Here is what I do (in viewDidLoad):
```
UIBarButtonItem *doneButon = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed)];
[self.navigationItem setRightBarButtonItem:doneButon];
``` | The back button test is automatically set to the title attribute of the UIViewController that is on the top of the stack. So in the viewDidAppear or viewDidLoad of each view controller set self.title to the text you want to appear in the "Back" button when a new view is pushed onto the stack. |
111,305 | I have a phd student that is very smart. They had a small baby a few months before starting the PhD in a foreign country and then moved to do the PhD with their family in the UK.
It has been 7 months now and the PhD student is not performing well. We have weekly meetings and I try hard to guide and help (more than I normally do). The student sometimes disappears for 1-2 weeks without answering emails and comes back offering no excuse rather vague "family-issues". The funding is fixed for 3 years without the possibility of extending or freezing. Also, the uni is rigid on students submitting at 3 years. We have discussed several times and I have suggested asking the university for help. Didn't happen yet.
At the end of the first year, PhD students have a mini-viva called transfer. The examiner is another professor from the department. With the current work, failure is almost certain, unless I appeal to that professor on behalf of the student (which I've never done before, I find it morally wrong, and don't even know if it would work).
On academic performance, the situation is clear, the student would fail. I only find myself in dilemma because of the family situation (small baby, new country, no relatives, low salary). The official guidelines state my suggestion should only be based on the academic performance. This is advisory since the examiner will make the final decision. Nevertheless, how can I do this knowing the student will lose their funding and visa and have to go back with their family? | 2018/06/16 | [
"https://academia.stackexchange.com/questions/111305",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/42952/"
] | Have you communicated with the student clearly about the situation? It's easy to softball negative news so they might not realize just how dire their situation is. Sit them down and straightforwardly tell them that their options are ask for help or get sent home soon, like you have in this post.
Currently, since you (and the future examiner) have no insight into the reasons for the low performance, you have no indications that it would get any better soon or that the student would be capable of catching up in time to defend their thesis. Therefore the transfer is working as intended: to catch these cases early so that the student does not waste another two years to no end. It will feel harsh in the moment, but it is not in the student's best interest to stretch out their failure for another two years (I imagine they don't feel great about their work either).
If they can explain what went wrong, establish a plan for stopping it from happening in the future, and demonstrate improvement by the time of the deadline, only then would I consider pleading for leniency with the examiner or administration. Essentially, inspire yourself from standard management techniques and put the student on a performance improvement plan. | The previous answers are excellent, and so I'd like to only add that it is worthwhile putting things in text. In case you have an in-person "heart to heart" in which you lay out the options and have a discussion with the student, sit down later on and summarize the discussion in an email that you send to the student. If you want to do it the other way around, that's fine as well -- sometimes a student needs to see written down and have time to digest something before they understand the gravity of the situation.
I suggest this for two reasons:
* For some students, especially if English is not their first language and/or if they come from cultures where the culture is so that they say "yes" and nod to everything a professor says, having things written down provides a different level of reality than just hear someone say something. It also gives them a way to go over it again a couple of times to really understand what you are saying, if necessary with a dictionary.
* For you, it gives you something you can point at if push eventually does come to shove. You can now reference an email or memo that can be looked at and that has a concrete date, in case you need to write the student about not performing the tasks you had laid out previously, or if you are asked by administration later on if you can back up your claim that the student has consistently underperformed.
I've been in your situation before, and at the time put the student on academic probation for two semesters after having struggled with the student for a year or more. That got her attention, and in the end she wrote an excellent thesis, independently and on a topic of her own choice. I admit that that was one of the worst things I had to do as a PhD adviser -- our students are our kids too, in some sense. But at the same time, dragging them along is also not a solution: they need to pull themselves out by their bootstrap, because (i) we can't just give them a degree, and (ii) there is a better student somewhere who could be admitted if we let students who don't do well go. |
1,137 | I've recently been trying to 'install' stuff a lot less on my Windows machine (I hate installers - I need to know where programs put stuff...), choosing to use portable or standalone versions of applications instead.
I put them all in a 'Programs' dir on a drive separate from my Windows partition, so whenever I reinstall, I have all my applications available with minimal effort and on the plus side, I get a nice clean setup.
Applications like Office and Creative Suite still require me to go through a horribly long installation process where a thousand random libraries and tools are thrown across my system.
Why do Windows apps still need installing? Why can't we just drag Photoshop to a folder à la OSX and just have it work? Does anyone else focus on portable apps, or am I just being OCD about the whole thing? | 2009/07/15 | [
"https://superuser.com/questions/1137",
"https://superuser.com",
"https://superuser.com/users/551/"
] | [XCOPY deployment](http://en.wikipedia.org/wiki/XCOPY_deployment) was announced by Microsoft as *the* way of the future a couple years ago. Still nothing :)
Meantime, you might be interested in PortableApps.com platform. | Great question, I asked a [related question](https://stackoverflow.com/questions/498598/self-installing-application-or-separate-installer) on Stack Overflow a while ago.
The answer often seems to be "because that's how we've done it in the past". Sorry but that doesn't wash with me.
A few others have said the main reason is due to the registry. If you are talking about a device driver or some other COM component etc, then yes this may be necessary, but not for GUI applications such as Word processors or spreadsheets.
It's quite possible to write an application that either checks on start-up for required registry settings, and prompts the user for them / uses defaults. Or, as many protable apps currently do, jst let the user know that OS integration is currently limited because you are running in portable mode.
Installers often also have a lot of "knowledge" about how the application works. Then when the application changes, you often have to update the installer too. This is a classic cause of bugs/problems I've seen in my time programming.
It's the one size fit's all approach. |
5,200,758 | I want to unit test a user component which use custom events. when doing this without using VS Unit test Framework debug.assert succeed, when doing the same thing with VS Unit Test Framework, assert fails this is illogical so I want to debug while doing Unit test with VS framework. But It seems I can't because code never pause at debug point that I set.
So is there a way to force it to pause at debug point in that case ?
Update: I mean not in the Test Project itself but in the Targeted Project while running the Test Project. | 2011/03/05 | [
"https://Stackoverflow.com/questions/5200758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310291/"
] | The answer by P. Campbell is not exactly right. If you start debugging a project (such as a WCF services site), it is impossible to start any unit tests, debug mode or not. The options to do so are simply grayed out in Visual Studio 2012.
This means you simply cannot debug out-of-process code from a unit test. You can only debug code that was directly called in process by the unit test.
This is a major problem in VS2012 that they need to fix now. | In VS2015, select:
>
> Test->Debug->All Tests
>
>
>
Or you can highlight a specific test in the editor and select
>
> Test->Debug->Selected Tests
>
>
> |
3,747 | Often times I hear the argument that marriage is between a man and a woman, God made them male and female, (adam and eve not adam and steve ..etc).
My question is for those who do not fit into the gender boxes we like people to fit into.
In fact there are many variations of gender between the poles xmale, heterosexual, masculine
and xfemale, heterosexual, feminine.
For the sake of specificness we will drop the heterosexual part and look a little closer at just the gender aspect.
What happens when a physical check shows one sex/gender and a chromosome test shows another?
"it would seem a simple case of checking for XX vs. XY chromosomes to determine whether an athlete is a woman or a man, it is not that simple. Fetuses start out as female, and the Y chromosome turns on a variety of hormones that differentiate the baby as a male. Sometimes this does not occur, and XX people with two X chromosomes can develop hormonally as a male, and XY people with an X and a Y can develop hormonally as a female."
<http://www.nytimes.com/2009/08/22/sports/22runner.html?em>
Stories like Santhi Soundaragjan, who after gender testing failed as a female and was stripped of her Olympic medal. Her condition was possibly "Androgen Insensitivity Syndrome (AIS). This condition includes the existence of a 'Y' chromosome in phenotypic females (typically only associated with a male genotype) and results in an inability to respond to Androgens. This unresponsiveness leads to a female body without female internal sex organs. Although the body produces testosterone, it does not react to the hormone." from <http://www.taipeitimes.com/News/sport/archives/2009/06/11/2003445882> (The failed test even led to a suicide attempt)
There is more...amidst the many varying conditions that fall somewhere inbetween, there are those who are born with both genders, the hermaphrodite.
Where do these people fit into normal Christian male/female scenarios? Do they have room for them? | 2011/10/02 | [
"https://christianity.stackexchange.com/questions/3747",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/810/"
] | As with many of these questions, some of the answer is already in the question. You've termed occurrences like this "conditions" - in other words, deviations from the general norm. As with other medical conditions they are a result of The Fall. So the line you quote is correct, God created male and female, very clearly and distinctly.
So, how do people affected by these conditions fit into the "normal Christian scenarios" of male and female? Well firstly there's nothing explicitly Christian about recognising that the norm is to be male or female. Secondly, as we both have already pointed out, these are medical conditions, so I would suggest they warrant expert medical attention. Thirdly my understanding is that in most cases there is a "leaning" towards one gender or the other that can help to establish which gender a person really is.
Finally, your last question, "do they [Christians] have room for them [people with these type of conditions]?" Of course. Anyone and everyone has the potential to become a Christian and should be welcome in Church. There should be a note of caution taken here though. Many people, inside and outside the church, find these issues very confusing and may struggle to react in the way they perhaps should. Some may be overly curious, others may find such a condition distasteful and not want to confront it. Nobody is unwelcome but not everyone will necessarily be able to express that. And that's ok, the church is made up of all kinds of people, not all of whom will see eye to eye all the time. | As for hermaphrodites, the Bible isn't clear. it's simply not addressed. My wife and I have discussed this a few times, and my personal answer is "I don't know. But I know they can be saved, just like anyone else. so I'm not going to focus on their sexuality, but rather on whether or not they've accepted Christ. Once saved, they will have their own relationship with God, and their own indwelling of the Holy Spirit to guide them. I would have the same response for those who show one sex/gender based on physical attributes, but a different result based on chromosomes.
As for varying of degrees on gender based on whether a person "feels" male or female, the idea of "gender boxes" is a very new concept. I don't buy it. Just thinking something is true or wanting something to be true doesn't make it true.
But ***again***, whether you're on my side of the fence or the other, their sexuality ***isn't the important thing***. Homosexuality may be a sin, but the Bible is clear that ***no one sin is any more serious than another***. ([Matthew 5:19](http://www.biblegateway.com/passage/?search=Matthew%205:19&version=NIV), [James 2:10](http://www.biblegateway.com/passage/?search=James%202:10&version=NIV)) Everyone is damned whether straight, gay, black, white, kind, mean, giving, greedy, because all of us have sinned in one way or another.
EVERYONE is condemned ([John 3:18](http://www.biblegateway.com/passage/?search=John%203:18&version=NIV)) unless we accept the free gift of salvation, which comes through the Grace of God, by faith in our Lord, Jesus Christ. The free gift is available to all of the people in all of the situations you gave. It's simply up to them to accept or reject it. |
63,170,026 | I got one text with two columns (via column-count property) and I'd like to target the second column only so I can apply a red color on it for example. How can I do it, in CSS or Javascript ?
I know I could go through the creation of two containers instead so I would just have to manipulate the second div, but in my case I need to put all the text in one div.
HTML :
```
<div>Auxerunt haec vulgi sordidioris audaciam, quod cum ingravesceret penuria commeatuum, famis et furoris inpulsu Eubuli cuiusdam inter suos clari domum ambitiosam ignibus subditis inflammavit rectoremque ut sibi iudicio imperiali addictum calcibus incessens et pugnis conculcans seminecem laniatu miserando discerpsit. post cuius lacrimosum interitum in unius exitio quisque imaginem periculi sui considerans documento recenti similia formidabat. <br/>Hanc regionem praestitutis celebritati diebus invadere parans dux ante edictus per solitudines Aboraeque amnis herbidas ripas, suorum indicio proditus, qui admissi flagitii metu exagitati ad praesidia descivere Romana. absque ullo egressus effectu deinde tabescebat immobilis.</div>
```
CSS
```
div{
column-count:2;
}
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63170026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13729628/"
] | Bad news - it is not possible, maybe someday.
I understand you want to split the text colour, you have a reason and an idea... if any trick or workaround works - go ahead!
Or maybe your intended goal can be achieved by changing the background? Different colour for each column?
```
.gradient{ background: linear-gradient( to left, lightblue, white, pink);}
```
One more thing - if it is a text block it should be a `<p>` not `<div>` - for blind people screen readers it is important | You can do it like this, it not select directly the second line but it works :
```css
.col:not(first-line) {
color:green;
}
.col:first-line{
color:black;
}
```
```html
<div class="col">Auxerunt haec vulgi sordidioris audaciam, quod cum ingravesceret penuria commeatuum, famis et furoris inpulsu Eubuli cuiusdam inter suos clari domum ambitiosam ignibus subditis inflammavit rectoremque ut sibi iudicio imperiali addictum calcibus incessens et pugnis conculcans seminecem laniatu miserando discerpsit. post cuius lacrimosum interitum in unius exitio quisque imaginem periculi sui considerans documento recenti similia formidabat. <br/>Hanc regionem praestitutis celebritati diebus invadere parans dux ante edictus per solitudines Aboraeque amnis herbidas ripas, suorum indicio proditus, qui admissi flagitii metu exagitati ad praesidia descivere Romana. absque ullo egressus effectu deinde tabescebat immobilis.</div>
``` |
1,280 | Steven Pinker in "The Language Instinct" claims that there is strong psychological evidence for the existence of a sharp age cutoff for the ability to acquire a flawless foreign accent (I may dig up the exact reference, if needed). In other words, there is a fairly narrow age threshold (around 20-odd years) below which exposure to a foreign accent is more or less sufficient to acquire it and above which it's physiologically impossible. Has this phenomenon been confirmed or refuted by any systematic study? | 2012/01/14 | [
"https://linguistics.stackexchange.com/questions/1280",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/673/"
] | One of the reasons the feral children data are difficult to assess is that the brains of these children are often underdeveloped or have developed differently because they weren't stimulated with language at a young age. (For a more scientific explanation of the how of this, see Curtiss et al 544-545+.) As I mentioned in my comment to Askalon, while that data supports the idea that there is a critical period for acquiring a faculty for language, it doesn't say much about what factors influence how successful you will be in acquiring native-like competence in a second language. Although age is often speculated to be a factor in acquiring native competence, estimates on the cutoff have ranged from as low as 3-4 to as high as puberty.
**Infant Studies of Phoneme Perception**
An important question to keep in mind is, why should skill in acquiring a new phonological system decrease because of age? Most cognitive abilities get remarkably better with age, assuming typical development. Of course, there are obvious factors like motivation (generally not as high for L2 learners), phonological interference, or different method of acquisition (generally by analytical study and reflection than immersion for L2 learners), but the biggest theory seems to be currently that it is because, while young infants are like a phonological tabula rasa, after exposure to their native language, they narrow their focus to only pay attention to the contrasts which differentiate meaning -- what are traditionally called phonemes. They lose the ability to learn how to produce and differentiate any sound.
Even very young children show decreased sensitivity to contrasts not present in their native language. For example, Hindi has many contrasts that English doesn't, for example differentiating aspirated and unaspirated stops like [pʰal] and [pal]. Werker and Tees (1984) trained infants to expect a reward (a little puppet show) when they heard aspirated syllables (this is called a conditioned head turn technique). Then, they tested them, playing aspirated and unaspirated stops and measuring how often the infants turned at the appropriate times. If they failed to turn after hearing an aspirated stop, this was counted as a miss, and if they turned after hearing an unaspirated sound, this was counted as a false alarm. At 6-8 months, infants scored well -- they had fewer than 2/10 misses or false alarms -- while those in the 10-12 month group did remarkably poorly -- approximately only 2/10 correct hits. I cannot find the citation, but I have heard vocalic categories are cemented even earlier. And keep in mind that this is before these infants are even babbling!
**Immigrant and Foreign Language Learner Studies**
There *have* been studies looking at the acquisition of foreign language by people of varying ages, or by immigrants with varying age-of-arrival, and some (Johnson and Newport 1989) support the idea of a critical period and others (Snow and Hoefnagel-Höhle 1978) do not. It is important to note that these studies often look at both knowledge of grammar and pronunciation and I have unfortunately not found any studies specifically related to accent -- though I will add them if I come across them. These studies generally rely on a battery of tests to assess grammatical competence (e.g. grammaticality judgments) and native speakers to rate the degree of the subjects' accent. In general, it seems that a critical period for phonology is much more supported than a critical period for grammar -- acquisition of grammar is much more linked to cognitive ability in adults, although in young children, cognitive ability has no effect (e.g. Flege et al 1999, DeKeyser 2000).
**Conclusion**
So yes, there does seem to be evidence for a cutoff in acquiring native-like phonology, from immigrant studies and SLA studies backed up by infant perception studies. What I would take from this, though, is that in addition to lost competence in implicit learning mechanisms, when we already have one language to work with, we will rely more on overt analysis and comparison to learn a foreign language. And while grammars are very good at detailing correct syntax and morphology, they are often abysmally poor and lazy at instructing learners in pronouncing and distinguishing foreign phonemes. (This is because they are often not written by linguists.) Add to that the fact that having an accent is not terribly stigmatized (but poor grammar is) and it's no surprise that L2 learners will often not develop a great accent.
* [The Linguistic Development of Genie](http://www.jstor.org/stable/412222)
Author(s): Susan Curtiss, Victoria Fromkin,
Stephen Krashen, David Rigler and Marilyn Rigler
Source: Language, Vol. 50,
No. 3 (Sep., 1974), pp. 528-554 Published by: Linguistic Society of
America Article
* [The Critical Period for Language Acquisition: Evidence from Second
Language Learning](http://www.kennethreeds.com/uploads/2/3/3/0/2330615/article.pdf)
Author(s): Catherine E. Snow and Marian
Hoefnagel-Höhle
Source: Child Development, Vol. 49, No. 4 (Dec.,
1978), pp. 1114-1128 Published by: Blackwell Publishing on behalf of
the Society for Research in Child Development
* [Critical period effects in second language learning: The influence
of maturational state on the acquisition of English as a second
language](http://www.sciencedirect.com/science/article/pii/0010028589900030)
Author(s): Jacqueline S Johnson, Elissa L Newport,
Source: Cognitive Psychology, Volume 21, Issue 1, January 1989, Pages
60-99, ISSN 0010-0285, 10.1016/0010-0285(89)90003-0.
* [Age Constraints on Second-Language Acquisition](http://www.sciencedirect.com/science/article/pii/S0749596X99926384)
Author(s): James Emil Flege, Grace H. Yeni-Komshian, Serena Liu
Source: Journal of Memory and Language,
Volume 41, Issue 1, July 1999, Pages 78-104
* [The Robustness of Critical Period Effects in Second Language Acquisition](http://journals.cambridge.org/action/displayAbstract?fromPage=online&aid=67465).
Author(s): Robert M. DeKeyser
Source: Studies in Second Language Acquisition, 22 , 2000, pp 499-533 | I believe that the existance of a cut off period is imposible to measure due to the large number of factors affecting language accuisition. As an English language teacher and a person who has very near native competence in a foreign language, I believe that older people are less likely to achieve native competence in pronunciation because to mimick a native accent perfectly, in the majority of cases, would necessitate presenting oneself as having a different identity to that you have been raised with.
Children are less concerned about changing their identity than adults are and will more willingly mimick a native accent.
That is why they aquire native pronunciation much more efficiently - and the same is true for adults who are not shy or ashamed to assume a different identity - they also master foreign accents. |
18,540,987 | I am developing my first Flask application (with sqlite as a database). It takes a single name from user as a query, and displays information about this name as a response.
All working well, but I want to implement typeahead.js to make better user experience. Typeahead.js sends requests to server as user types, and suggests possible names in dropdown. Right now I'm searching the database with `select * from table_name where name like 'QUERY%'`. But this of course is not so fast as I would like it to be - it works, but with noticable input lag (less or around a second I suppose).
In order to speed up things I looked at some memory caching options (like Redis or memcached), but they are key-value store, therefore I think do not fit my needs. I think *possible* option would be to make list of names (["Jane", "John", "Jack"], around 200k names total), load it into ram and do searches there. But how do I load something in memory in Flask?
Anyway, my question is: What is the best way to make such search (by first few letters) faster (in Python/Flask)? | 2013/08/30 | [
"https://Stackoverflow.com/questions/18540987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672932/"
] | Basically `show_double(value)` passes the `value` defined in the main function to `show_double(number)` function which is expecting a number to receive as an argument
```
def main():
value = 5
show_double(value) # Function Call
# The show_double function accepts an argument
# and displays double its value
def show_double(number): # Function defination
result = number * 2
print result
#call main function
main()
``` | main function calls the `show_double()` passing the argument value.
Then value is doubled inside function and returned |
6,575,975 | Suppose I want www.example.com/profile to redirect a user to his or her profile page. So what I want to do is match "/profile" to "users#show" but also let the controller know who the current user is. Is there any way I can set params[:id] or params[:user\_id] to session[:user\_id] in the routes file? I know this might not be the best way to accomplish what I want to accomplish. I just want to know if it's possible, and how to do it if it is. | 2011/07/04 | [
"https://Stackoverflow.com/questions/6575975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629474/"
] | Route '/profile' to 'users#show', then set the params value to the session value if it is not already set. You can't set this in your routes file, but you can do it in the controller.
Routes:
```
match '/profile' => 'users#show
```
Controller:
```
class UserController < ApplicationController
def show
params[:id] ||= session[:user_id]
@user = User.find(params[:id)
end
end
```
You'll want to do some extra checking in your controller to make sure your user actually is who they say they are in the session, I assume you are using some sort of authentication library. | If you want to accomplish this, you shouldn't let it appear in your routes at all.
It should remain:
```
match "/profile" to "users#profile"
```
Because you have the information in session, you only have to fetch it in your controller.
```
User.find(session[:user_id])
```
The best is to put a `before_filter` checking whether or not the user is logged so that you won't face an error because the session is nil. |
8,073,427 | I know I can use data in files to drive unit test, for example data inside a csv or xml file.
For example:
```
[TestMethod]
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.CSV",
"Data.csv",
"Data#csv",
DataAccessMethod.Sequential)]
public void TestData() {}
```
I would like to know if there is a way that, instead of using a file, I can use a data structure that's already in memory to drive the tests.
Something like:
```
// this structure has the data to use in the unit test
var DataList = new List<string>();
[TestMethod]
[DataSource(
"Microsoft.VisualStudio.TestTools.DataSource.IEnumerable",
"DataList",
"DataList",
DataAccessMethod.Sequential)]
public void TestData() {}
``` | 2011/11/10 | [
"https://Stackoverflow.com/questions/8073427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622363/"
] | If it's in memory, my preference would be to not use DataSource, but use a T4 template to auto generate your unit tests instead. This way, you will only write the test once, but in the results for the test run, you will see an entry for each of the input you tested. Add this .tt file to your test project.
```
<#@ template debug="false" hostspecific="true" language="C#v3.5" #>
<#@ assembly name="System.Core.dll" #>
<#@ assembly name="System.Data.dll" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#@ output extension=".cs" #>
<#
List<string> DataList = AccessInMemoryData();
#>
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestProject1
{
[TestClass]
public class UnitTest1
{
<# foreach (string currentTestString in DataList) { #>
[TestMethod]
public void TestingString_<#= currentTestString #>
{
string currentTestString = "<#= currentTestString #>";
// TODO: Put your standard test code here which will use the string you created above
}
<# } #>
}
}
``` | I don't think you can do that with the `[DataSource]` attribute, but you can do a more or less the same thing manually.
Load your data in a method decorated with `[AssemblyInitialize]` or `[ClassInitialize]`. Then rewrite your tests to loop over the data. Unfortunately this way you will end up with a single test instead of separate results per test run. |
29,897,685 | I have spent a few days looking and have been unable to find a solution, most example deal with spring boot and gradle, I am only using spring mvc and maven.
If I remove the springfox-swagger-ui dependency the app runs fine and the following return JSON as expected http:\\localhost:8080\restful\v2\api-docs?group=restful-api
For some reason my spring application is failing to pass the swagger-ui.html and it gives the same response if I set an index.html
I have tried adding:
1. Welcome list files in the web.xml
2. Resource Handlers
3. Default Servlet Handling
None worked.
App Config
----------
```
package au.com.speak.restful.spring;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "au.com.speak.restful.api" })
public class AppConfig extends WebMvcConfigurerAdapter {
// ========= Overrides ===========
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}
// ========= Beans ===========
@Bean(name = "localeResolver")
public LocaleResolver getLocaleResolver() {
return new CookieLocaleResolver();
}
@Bean(name = "messageSource")
public MessageSource getMessageSources() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("/WEB-INF/resources/properties/error", "/WEB-INF/resources/properties/validation");
messageSource.setCacheSeconds(0);
return messageSource;
}
}
```
Swagger Config
--------------
```
package au.com.speak.restful.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket restfulApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("restful-api")
.select()
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"My Apps API Title",
"My Apps API Description",
"My Apps API Version",
"My Apps API terms of service",
"My Apps API Contact Email",
"My Apps API Licence Type",
"My Apps API License URL"
);
return apiInfo;
}
}
```
The code I have is as follows:
web.xml
-------
```
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>example restful api</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>contextClass</param-name>
<param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
au.com.speak.restful.spring.AppConfig
au.com.speak.restful.spring.PropertyConfig
au.com.speak.restful.spring.SecurityConfig
au.com.speak.restful.spring.ServiceConfig
au.com.speak.restful.spring.PersistenceConfig
au.com.speak.restful.spring.SwaggerConfig
</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.xml</param-value>
</context-param>
<!--
Reads request input using UTF-8 encoding
-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--
Apply Spring Security Filter to all Requests
-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--
Handles all requests into the application
-->
<servlet>
<servlet-name>model</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>*</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>model</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
```
Error
-----
```
2015-04-27 23:03:47,805 INFO - Loading XML bean definitions from ServletContext resource [/swagger-ui.html]
2015-04-27 23:03:47,811 ERROR - Context initialization failed
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 2 in XML document from ServletContext resource [/swagger-ui.html] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 7; Element type "html" must be declared.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4913)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5200)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1618)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1399)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:828)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$240(TCPTransport.java:683)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$1/1746485750.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 7; Element type "html" must be declared.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1906)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:742)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1363)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$ContentDriver.scanRootElementHook(XMLDocumentScannerImpl.java:1292)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3138)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:76)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:429)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:391)
... 66 more
``` | 2015/04/27 | [
"https://Stackoverflow.com/questions/29897685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4837799/"
] | Fixed by adding the following into the AppConfig.
```
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
``` | I encountered this error because of a version mismatch between `springfox-swagger2` and `springfox-swagger-ui`, versions of the two dependencies have to be the same.
```
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
``` |
17,891,932 | I'm shopping for an open-source framework for writing natural language grammar rules for pattern matching over annotations. You could think of it like regexps but matching at the token rather than character level. Such a framework should enable the match criteria to reference other attributes attached to the input tokens or spans, as well as modify such attributes in an action.
There are three options I know of which fit this description:
* [GATE Java Expressions over Annotations (JAPE)](http://gate.ac.uk/sale/tao/splitch8.html#chap%3ajape)
* [Stanford CoreNLP's TokensRegex](http://nlp.stanford.edu/software/tokensregex.shtml#Mail)
* [UIMA](http://uima.apache.org/) [Ruta](http://uima.apache.org/ruta.html) ([Tutorial](http://uima.apache.org/gscl13.html#gscl.tutorial))
* [Graph Expression (GExp)](http://code.google.com/p/graph-expression/)\*
**Are there any other options like these available at this time?**
*Related Tools*
* While I know that general parser generators like [Antlr](http://www.antlr.org/) can also serve this purpose, I'm looking for something which are more specifically tailored for natural language processing or information extraction.
* [UIMA](http://uima.apache.org/) includes a [Regex Annotator](http://uima.apache.org/d/uima-addons-current/RegularExpressionAnnotator/RegexAnnotatorUserGuide.html) plugin for declaring rules in XML, but appears to operate at the character rather than high-level objects.
* I know that this kind of task is often performed with statistical models, but for narrow, structured domains there's benefit in hand-crafting rules.
\* With GExp 'rules' are actually implemented in code but since there are so few options I chose to include it. | 2013/07/26 | [
"https://Stackoverflow.com/questions/17891932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317110/"
] | Your error is not the generics. They are workable. Your error is in:
```
itor.add(t);
```
You don't add objects to an iterator.
You add them to the list. The iterator can only enumerate and iterate over them. Use
```
this.t.add(t);
```
I'd rename the list to `tList` and change the code to:
```
private List<T> tList;
private Iterator<T> itor;
public GenericBox()
{
t = new ArrayList<T>();
itor = tList.listIterator();
}
public void insert(T t)
{
tList.add(t);
}
```
and so on... | `Iterator<T>` does not have an `add<T>(T)` method. You probably meant to call `this.t.add(t);` instead of `itor.add(t);`. |
9,871 | I have a "basic statistics" concept question. As a student I would like to know if I'm thinking about this totally wrong and why, if so:
Let's say I am hypothetically trying to look at the relationship between "anger management issues" and say divorce (yes/no) in a logistic regression and I have the option of using two different anger management scores -- both out of 100.
Score 1 comes from questionnaire rating instrument 1 and my other choice; score 2 comes from a different questionnaire. Hypothetically, we have reason to believe from previous work that anger management issues give rise to divorce.
If, in my sample of 500 people, the variance of score 1 is much higher than that of score 2, is there any reason to believe that score 1 would be a better score to use as a predictor of divorce based on its variance?
To me, this instinctively seems right, but is it so? | 2011/04/22 | [
"https://stats.stackexchange.com/questions/9871",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/4054/"
] | A few quick points:
* Variance can be arbitrarily increased or decreased by adopting a different scale for your variable. Multiplying a scale by a constant greater than one would increase the variance, but not change the predictive power of the variable.
* You may be confusing variance with reliability. All else being equal (and assuming that there is at least some true score prediction), increasing the reliability with which you measure a construct should increase its predictive power. Check out this discussion of [correction for attenuation](http://en.wikipedia.org/wiki/Correction_for_attenuation).
* Assuming that both scales were made up of twenty 5-point items, and thus had total scores that ranged from 20 to 100, then the version with the greater variance would also be more reliable (at least in terms of internal consistency).
* Internal consistency reliability is not the only standard by which to judge a psychological test, and it is not the only factor that distinguishes the predictive power of one scale versus another for a given construct. | A simple example helps us identify what is essential.
Let
$$Y = C + \gamma X\_1 + \varepsilon$$
where $C$ and $\gamma$ are parameters, $X\_1$ is the score on the first instrument (or independent variable), and $\varepsilon$ represents unbiased iid error. Let the score on the second instrument be related to the first one via
$$X\_1 = \alpha X\_2 + \beta.$$
For example, scores on the second instrument might range from 25 to 75 and scores on the first from 0 to 100, with $X\_1 = 2 X\_2 - 50$. The variance of $X\_1$ is $\alpha^2$ times the variance of $X\_2$. Nevertheless, we can rewrite
$$Y = C + \gamma(\alpha X\_2 + \beta) = (C + \beta \gamma) + (\gamma \alpha) X\_2 + \varepsilon = C' + \gamma' X\_2 + \varepsilon.$$
**The parameters change, *and the variance of the independent variable changes*, yet the predictive capability of the model remains unchanged**.
In general the relationship between $X\_1$ and $X\_2$ may be nonlinear. Which is a better predictor of $Y$ will depend on which has a closer linear relationship to $Y$. Thus **the issue is not one of scale** (as reflected by the variance of the $X\_i$) but has to be decided by the relationships between the instruments and what they are being used to predict. This idea is closely related to one explored in a recent question about [selecting independent variables in regression](https://stats.stackexchange.com/q/9590/919).
There can be mitigating factors. For instance, if $X\_1$ and $X\_2$ are discrete variables and both are equally well related to $Y$, then the one with larger variance *might* (if it is sufficiently uniformly spread out) allow for finer distinctions among its values and thereby afford more precision. *E.g.*, if both instruments are questionnaires on a 1-5 Likert scale, both are equally well correlated with $Y$, and the answers to $X\_1$ are all 2 and 3 and the answers to $X\_2$ are spread among 1 through 5, $X\_2$ might be favored on this basis. |
9,705,810 | If i set a sharedpreference in one activity, why does the other one has different preferences? context changed? (but i se use application context!)
Here is my code
```
MyApp appState = ((MyApp)this.activity.getApplicationContext());
appState.setDittaSelezionata( (int) itemId);
```
....
```
MyApp appState = ((MyApp)this.getApplicationContext());
int ditta_id_selezionata = appState.getIdSomething();
```
And
```
public class MyApp extends Application implements Parcelable {
private SharedPreferences getSharedPrefs()
{
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//SharedPreferences settings = this.getSharedPreferences(MyApp.PREFS_NAME, this.MODE_PRIVATE);
return settings;
}
public int getIdSomething() {
SharedPreferences settings = this.getSharedPrefs();
return settings.getInt("ditta_id_selezionata", 0);
}
public void setDittaSelezionata(final int ditta_selezionata) {
SharedPreferences settings = this.getSharedPrefs();
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ditta_id_selezionata", ditta_selezionata);
// Commit the edits!
editor.commit();
}
```
...
How can i make global preferences that are shared among all activities android 3.2? is there something android provides or i have to code a save to file/open to file and add it for each activity onStop() / onCreate() ? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9705810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/579646/"
] | You can't. Create a new bitmap context. You can transfer the old one's contents to the new one by creating an image from it (`CGBitmapContextCreateImage`) and then drawing that image into the new context. | A Core Graphics context doesn't have “bounds”. It has a coordinate system, with essentially infinite extent. You can, for example, do `CGContextFillRect(gc, CGRectInfinite)`.
A bitmap context has an underlying bitmap, and each pixel in the bitmap is mapped to a well-defined region in the context's coordinate system. (The region is always a parallelogram.)
The initial mapping, when you create a bitmap context, maps the pixels (collectively) to the rectangle `CGRectMake(0, 0, width, height)`.
If you want to change this mapping, change the context's *current transform matrix* (CTM). For example, if you want to map the pixels to the rectangle `CGRectMake(-50, -50, 100, 100)`, do this:
```
CGContextScaleCTM(gc, width / 100.0f, height / 100.0f);
CGContextTranslateCTM(gc, -50, -50);
``` |
21,566,437 | I have read a csv file using,
```
with open('test.csv', newline='') as csv_file:
#restval = blank columns = - /// restkey = extra columns +
d = csv.DictReader(csv_file, fieldnames=None, restkey='+', restval='-', delimiter=',', quotechar='"')
```
I would like to iterate through the created dictionary to find blank values within the csv.
I have tried:
```
for k, v in d.items()
#Do stuff
```
However I get the error: **AttributeError: 'DictReader' object has no attribute 'items'**
Is it right in saying that the values stored in **d** is a dictionary of dictionaries?
Coming from C# I would have stored the csv in a multidimensional array with a nested for loop to iterate through the values. Unfortunately I'm still new to Python - any help + explanations will be appreciated! | 2014/02/05 | [
"https://Stackoverflow.com/questions/21566437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2242977/"
] | You have to first iterate over the dict getting each row, and then iterate over the items in each row:
```
for row in d:
for k, v in row.items():
# Do stuff
``` | We also can try:
```
with open('test.csv', newline='') as csv_file:
#restval = blank columns = - /// restkey = extra columns +
d = csv.DictReader(csv_file, fieldnames=None, restkey='+', restval='-', delimiter=',', quotechar='"')
data = list(d)
for row in data:
for key,val in row.items():
print(key)
print(val)
``` |
268,159 | Is there any way to disable the `CTRL`+`Z` (Undo) shortcut in Windows Explorer? Alternatively, is there a way to have Windows Explorer "forget" its undo history?
The reason I ask is that you may have done some file operations in Explorer (copying, renaming, etc.), and perhaps you don't reboot for days or longer (choosing to hibernate instead). The problem is that if you accidentally hit `CTRL`+`Z` one or more times (often mistaking which application you have in the foreground; using a dual-monitor setup will increase that likelihood), you may be undoing something that was done ages ago without realizing what happened.
Even if you do realize what has happened, you may not remember what the last several operations were that you did potentially days ago. As far as I can tell, there is no "Redo" function in Windows Explorer to save you. I can imagine scenarios in which this mistake could cause lots of problems.
If the shortcut can be disabled, it would at least force you to use the `Edit > Undo` menu item before doing something stupid. Otherwise if the undo history could be periodically cleared, that would prevent some very old operations from being undone.
**Addendum:** For those interested in implementing this, I created an [AHK](http://www.autohotkey.com/ "AutoHotkey") file that runs silently (the [`#NoTrayIcon`](http://www.autohotkey.com/docs/commands/_NoTrayIcon.htm "#NoTrayIcon") option) from my Windows Startup folder. Besides some other useful shortcuts I incorporated, this is what it looks like:
```
#NoTrayIcon
SetTitleMatchMode RegEx
return
; Disable Ctrl+Z shortcut in Windows Explorer
;
#IfWinActive ahk_class ExploreWClass|CabinetWClass
^z::return
#IfWinActive
```
If you prefer feedback instead of `CTRL`+`Z` simply doing nothing, play a default sound or use `MsgBox` to cause a dialog to appear.
```
#IfWinActive ahk_class ExploreWClass|CabinetWClass
^z::
;Uncomment the feedback option you prefer below
;SoundPlay *-1
;MsgBox Ctrl+Z has been disabled.
return
#IfWinActive
``` | 2011/04/08 | [
"https://superuser.com/questions/268159",
"https://superuser.com",
"https://superuser.com/users/41575/"
] | I wrote a program in C to disable both the Undo and Redo shortcuts, since both can lead to accidents.
The program can be found at <http://purl.org/net/dweundo> .
It has an installer which, if you want, adds a shortcut in the Start Menu 'Startup' folder, so the program starts when you log on. | This AutoHotKey script catches Explorer windows, as in other answers, but also the Desktop:
```
#IfWinActive ahk_class CabinetWClass ; Explorer
^z::
#IfWinActive ahk_class ExploreWClass ; Explorer (legacy)
^z::
#IfWinActive ahk_class Progman ; Desktop
^z::
#IfWinActive ahk_class WorkerW ; Desktop shown by Win+D
^z::
MsgBox Ctrl+Z has been disabled.
return
#IfWinActive
```
Still, I think the best solution is to use the program written by Jelle Geerts (see [his anwser](https://superuser.com/questions/268159/disable-ctrlz-shortcut-or-clear-undo-history-in-windows-explorer#683987)). |
15,015,821 | In iOS, is there a relationship between run loop and display refresh? If so how? | 2013/02/22 | [
"https://Stackoverflow.com/questions/15015821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66814/"
] | Please note that your `echo $(( 22/7 )) | bc -l` actually makes bash calculate 22/7 and then send the result to bc. The integer output is therefore not the result of bc, but simply the input given to bc.
Try `echo $(( 22/7 ))` without piping it to bc, and you'll see. | `scale` variable determines number of digits after decimal separator
```
$ bc
$ scale=2
$ 3/4
$ .75
``` |
114,330 | [Steve Vai does vibrato by circling his finger around the note like he's giving it a massage.](https://www.youtube.com/watch?v=wuRS_hQLLRg). He says that this somehow makes the note go flat as well as sharp.
I can't hear it. I try to do it on my guitar and can't hear it. Is this even possible? Unless you change increase the length or decrease the tension on the string neither of which you can do if your fingers are on a fret playing a note. | 2021/05/10 | [
"https://music.stackexchange.com/questions/114330",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37013/"
] | You *can* make the note go a little flat by pushing it forward, since you do decrease the tension on the speaking length of the string. Test it yourself with a tuner and see how flat you can get the notes. It's easier to push the notes flat on larger strings and on wound strings. Now, it can be quite difficult to do, and it's certainly debatable whether circular vibrato pushes the notes flat enough to make a practical difference. | Using the same motion as classical guitarists the note becomes *slightly* sharper as the finger rolls to the back of the fret - closer to the guitar's nut. I'd argue that yes, the pitch changes, and does go flatter (minimally) when the finger is closest to the bridge, but that's semantics. Since the *correct* note ought to be when the fret is fingered just behind the fretwire, its pitch alters, but the opposite way! Otherwise the string stats out of tune.
Against that, the actual bending of the string - laterally - will increase the pitch far more effectively, and somewhat negates any other pitch change. |
12,432,060 | Hi I have this Demo: <http://jsfiddle.net/SO_AMK/BcFVv/>
I am trying to show only 1 Div at a time instead of all three. I want it so a certain div will only show when itss button is pressed.
As you can see it shows all of the Divs at the start. The buttons work fine.
QUESTION: How do I hide Divs 2 and 3 from the start? | 2012/09/14 | [
"https://Stackoverflow.com/questions/12432060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486934/"
] | ID's should be named with a leading letter before the digit.
"ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("\_"), colons (":"), and periods (".")." (W3C) | Try this:
```
$('#pages div').not('[id=1]').hide();
```
jsFiddle: <http://jsfiddle.net/wqtT5/> |
351,780 | I am a team lead at an IT company with 5 years of experience.
Recently, me and my team have reached a maturity level where we all realize that we do not give back enough to the community. We are starting to make contributions (issues, pull requests, improvements) to open source projects or libraries that we use.
We (like most developers I guess) have gained huge benefits on the awesome community on Stack Overflow. But now, it's time to give back.
My questions are:
* What drives you to be active and not passive on Stack Overflow?
* How would you motivate/organize your team so that they would have the same drive?
I was thinking about organizing maybe workshops after work hours on certain days and stay as a team and answer questions. Or maybe see it as a constructive competition of who gathers the most points. | 2017/07/06 | [
"https://meta.stackoverflow.com/questions/351780",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/4239642/"
] | >
> * What drives you to be active and not passive on Stack Overflow?
>
>
>
The growth opportunities.
I've used Stack Overflow to learn and teach for about as long as I've been developing for iOS. My motivations have evolved over time, but they went something like this:
1. This is new and pretty cool.
2. This is new and pretty cool and I can learn things by asking questions.
3. This isn't new anymore, but it's still pretty cool and I can learn things by asking ***and*** answering questions.
It's gratifying when I'm able to thoroughly and accurately answer a question about a technology that's relatively new to me. The badges and the points don't hurt either. :)
>
> * How would you motivate/organize your team so that they would have the same drive?
>
>
>
The way to make someone want to do something is to help them see the value in it. That of course depends on why you value that thing. If your value is "giving back," then you want to convince your team that answering questions on Stack Overflow is a good way to give back.
I don't know if I like the idea of an organized workshop *as a time for answering questions.* I'd think a specific block of time (45 minutes daily or weekly) for people to answer questions on their own would be a less pressurized way for individuals to contribute.
Another way to motivate your team may be to take advantage of the badging system for some motivation. I'm not sure how I feel about public awards, but depending on your team dynamic, you might let the team know when someone earns a gold or silver badge in a particular technology. | I am using Stack Overflow for some time now. But just recently I understood that there are questions that I can also answer even though it may be a simple edit in an existing answer or a comment to improve an existing answer. While looking for answers I am now trying to share my knowledge and I am really enjoying it. Thank you community.
So the most important thing that drives me to come to Stack Overflow is to find answers when I am stuck with errors when coding. But now I also come to see if there are any questions that I can answer to help others. I am still learning so maybe there is not much that I can do at the moment. But I will try my best to help the community. |
38,006 | What does *for grins* mean in the following?
>
> If the web service says the values are valid, the underlying fields
> are updated. If it says the values are invalid, it sets up error
> messages for the fields. **For grins**, on an invalid return, it also
> validates the level number itself.
>
>
> | 2011/08/15 | [
"https://english.stackexchange.com/questions/38006",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/833/"
] | "For grins" is typically used as another way of saying "for amusement purposes". | A more common English expression is "for fun." Not for a serious purpose.
Also, "for laughs," or "for kicks." |
67,850,966 | I have given a string consistent of only numbers .
**Example**
```
let inputString = "1234";
```
Question
--------
I have to write a function which will return the string except first even number if any present
**Example Output**
```
"134"
```
**Example Code**
```
let inputString = "1234";
function palindromeRearranging(inputString) {
/// code
}
console.log(palindromeRearranging(inputString));
// output is "1234"
```
What I have Tried
-----------------
```js
let inputString = "1234"
function palindromeRearranging(inputString) {
let arr = inputString.split("");
arr = arr.filter((w)=>{return w % 2 !== 0 })
return arr.join("")
}
console.log(palindromeRearranging(inputString))
```
But it is returning a string of all odd nos.
please explain what I am doing wrong and how can I achieve my goal.
Thank you for staying with me . | 2021/06/05 | [
"https://Stackoverflow.com/questions/67850966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16138106/"
] | Use a regular expression and match (only once) and remove any character that is `02468`.
```js
const palindromeRearranging = inputString => inputString.replace(
/[02468]/,
''
);
console.log(palindromeRearranging("1234"));
``` | Also, you can use [.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) to get the first element which satisfies condition:
```
let inputString = "1234"
function palindromeRearranging(inputString) {
let arr = inputString.split("");
const found = arr.find(element => element % 2==0);
return arr.join("").replace(found,'')
}
console.log(palindromeRearranging(inputString))
``` |
854,762 | So I am trying to use this formula here and is giving me some trouble.
If I just substitute $6000$ into the formula, the answer is approximately $1500$.
But the number of primes under $6000$ is clearly half that. How do you use this formula properly? | 2014/07/02 | [
"https://math.stackexchange.com/questions/854762",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/161346/"
] | $\pi(x)$ is the prime counting function, it gives the exact amount of primes below $x$
$$\pi(6000)=783$$
The formula provided is an approximation, so it gives:
$$\frac{6000}{\log\_e 6000}=\frac{6000}{8.699514748}=689.69364083$$
While about $100$ from the actual answer, this is pretty accurate. It will increase in accuracy as $n$ goes to $\infty$
When you calculated the formula, you used $\log\_{10}$ and not $\log\_e$, that's why your value was so long from the actual value. | I'm not sure that you used teh wrong base of logarithm, because when I treid it with base 10 log, I got 1588, which I would have rounded off to 1600.
Whit the natural logarithm, the answer is 690, which is off by almost a hundred. I am reminded of the frivolous tehorem of arithmetic: "almost all integers are very large." Legendre probly knew that $\pi(6000) = 783$, so he thought that the formula was $\pi(n) \approx \frac{n}{\log n - 1.08366}$, and indeed that gives 788, which is far closer. But if you keep going higher and hihger, you'll probably revise that 1.08633 number until at some point you realize you dont even need it. So you strike it out and you get $$\left.\lim\_{n \to \infty} \pi(n) \middle/ \frac{n}{\log n}\right. = 1$$ |
5,992,929 | I have a class that references a background image (and I don't want to upgrade to using imagebundles) so I need to print the "base module url" before my image url. How can I achieve this?
```
background: #BDE5F8 url("image/info.png") no-repeat 2px center;
``` | 2011/05/13 | [
"https://Stackoverflow.com/questions/5992929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43671/"
] | You could always add a static function somewhere:
```
public static String getBackgroundUrl(){
return com.google.gwt.core.client.GWT.getModuleName() + "/images/background.png";
}
```
And in your CSS
```
@eval BG_URL com.yourclass.getBackgroundUrl();
.myBackground { background-url:BG_URL; }
``` | Including images in your ClientBundle really is the way to go. But then again, you've already mentioned that you're not going to do that.
Instead, consider using a [value function](http://code.google.com/webtoolkit/doc/latest/DevGuideClientBundle.html#Value_function) to get the value of `GWT.getModuleBaseURL()`:
```
.something {
background: #BDE5F8 value('com.google.gwt.core.client.GWT.getModuleBaseURL', '/info.png') no-repeat 2px center;
}
``` |
63,528,474 | An example of simple nested for loop:
```js
for (let i=0; i<=2; i++) {
for (let j=0; j<=1; j++){
console.log("i is: " + i);
console.log("j is: " + j);
console.log("---");
}
}
```
Nested for loop with delay:
```js
for (let i=0; i<=2; i++) {
for (let j=0; j<=1; j++){
task(i,j);
}
}
function task(i,j) {
setTimeout(function() {
console.log("i is: " + i);
console.log("j is: " + j);
console.log("---")
}, 1000 * i);
}
```
**NOW MY QUESTION IS**
How can I delay each loop seperately.
Current output (ignore the "---"):
**i, j, delay, i, j, delay, ...**
Desired output (ignore the "---"):
**i, delay, j, delay, i, delay, j, delay ...**
I tried things like below (but its returning a complete wrong output)
```js
for (let i=0; i<=2; i++) {
for (let j=0; j<=1; j++){
taski(i);
taskj(j)
}
}
function taski(i) {
setTimeout(function() {
console.log("i is: " + i);
}, 1000 * i);
}
function taskj(j){
setTimeout(function() {
console.log("j is: " + j);
}, 1000 * j);
}
``` | 2020/08/21 | [
"https://Stackoverflow.com/questions/63528474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9357872/"
] | You could use `Promise` and `async/await` to handle sequential call
```js
function taski(i) {
return new Promise(function (resolve) {
setTimeout(function () {
console.log("i is: " + i)
resolve()
}, 1000 * i)
})
}
function taskj(j) {
return new Promise(function (resolve) {
setTimeout(function () {
console.log("j is: " + j)
resolve()
}, 1000 * j)
})
}
async function execute() {
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 1; j++) {
await taski(i)
console.log("delay")
await taskj(j)
console.log("delay")
}
}
}
execute()
```
---
### Reference:
* [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
* [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) | You could try to to an asynchronous approach with async/await:
```js
function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
(async function() {
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 1; j++) {
await taski(i);
await taskj(j);
}
}
}())
async function taski(i) {
await sleep(1000 * i);
console.log("i is: " + i);
}
async function taskj(j) {
await sleep(1000 * j);
console.log("j is: " + j);
}
``` |
25,647,752 | I want DIR to loop through all the arguments (with space and ""). But this code do not recognize, "cd ef" as one. Dividing them into two.
How can I do that?
```
#test.sh
echo Number of arguments: $#
if [ $# -eq 0 ]
then
echo "No arguments"
DIR=.
else
DIR="$*"
fi
echo DIR =$DIR
for arg in $DIR;
do
echo $arg;
done
```
Command
```
#bash test.sh ab "cd ef"
```
Output, Number of arguments: 2
But, enumerating 3 elements in the loop as `ab, cd`, and `ef`.
I know, I can do,
```
for arg in "$*";
```
But that not the solution in this case. Can I use DIR for this purpose?
The platform is OSX Mavericks shell. | 2014/09/03 | [
"https://Stackoverflow.com/questions/25647752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312627/"
] | You need to use an *array*, not a regular scalar variable, for this purpose -- and `"$@"`, not `$*`:
```
if (( $# )); then
dirs=( "$@" )
else
dirs=( . )
fi
for dir in "${dirs[@]}"; do
...
done
```
See also [BashFAQ #5](http://mywiki.wooledge.org/BashFAQ/005). | If you don't actually need a variable `DIR`, you can use a form of parameter expansion:
```
echo "DIR=${@:-.}"
for dir in "${@:-.}"; do
...
done
``` |
3,384,917 | Let $E \subseteq \mathbb R$ and $f : \mathbb R \rightarrow \mathbb R$. Show that $f(\overline{E}) \subseteq \overline{f(E)}$.
I've seen similar questions on stackexchange, but answers are using metric spaces and topology concepts I have't learned. This is from a real analysis intro class.
I'm thinking that given $g \in f(\overline{E})$, if I can show $\exists f\_n \in f(E)$ s.t $f\_n \rightarrow g$ where $g \in f(E)$ also, uniformly, then by definition of uniform convergence and definition of closure set, it implies $f(\overline{E}) \subseteq \overline{f(E)}$? Seems complicated | 2019/10/08 | [
"https://math.stackexchange.com/questions/3384917",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/604375/"
] | You are confusing some terms. If $y\in f(\overline E)$, then there exists $x\in\overline E$ with $f(x)=y$. As $x\in\overline E$, there exists $\{x\_n\}\subset E$ with $x\_n\to x$. Using that $f$ is continuous,
$$
f(y)=f(\lim x\_n)=\lim f(x\_n)\in\overline{f(E)}.
$$ | Let $e \in \overline{E}$, so $f(e)$ describes an arbitrary point of $f(\overline{E})$. You can write $e$ as the limit of some sequence. (Why?)
Check the images of that sequence under $f$. How can you now conclude that $f(e) \in \overline{f(E)}$? |
10,969,415 | here is my code
```
<div class='content'>
<div class='div1'>content</div>
<div class='div2'>content</div>
</div>
```
```css
.content { width:300px;}
.div1 { float:left;width:200px;}
.div2 { float:left;width:100px;}
```
in some case I need to set `display:none` for `div2`. is it possible to set `.div1` width to full-size of `.content` ( 300px ) | 2012/06/10 | [
"https://Stackoverflow.com/questions/10969415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191220/"
] | So long as you only need to add or remove the second div, the easiest solution is to only make that second div a float, and place it within the first, non-floated div, like so: <http://jsfiddle.net/Tb89A/> .
Just remove the comments on the display:none to see it in action. | Try to add class (for example, `hidden`) to `div2` when you set `display: none` and then set `fullwidth` do `div1` (in which you define `width: 300px`). Finally, you can go with jQuery and conditionals:
```
if($('.hidden').length()) {
$('.div1').addClass('fullwidth');
}
```
Of course you may want to change those class names to more specific ones.
I can't think of any different solution, since CSS doesn't allow conditional statements. |
1,591,836 | I'm trying to store a shortened date (mm/dd/yyyy) into a DateTime object. The following code below is what I am currently trying to do; this includes the time (12:00:00 AM) which I do not want :(
```
DateTime goodDateHolder = Convert.ToDateTime(DateTime.Now.ToShortDateString());
```
Result will be 10/19/2009 12:00:00 AM | 2009/10/20 | [
"https://Stackoverflow.com/questions/1591836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/175057/"
] | You only have two options in this situation.
1) Ignore the time part of the value.
2) Create a wrapper class.
Personally, I am inclined to use option 1. | You'll always get the time portion in a DateTime type.
```
DateTime goodDateHolder = Convert.ToDateTime(DateTime.Now.ToShortDateString());
```
will give you today's date but will always show the time to be midnight.
If you're worried about formatting then you would try something like this
```
goodDateHolder.ToString("mm/dd/yyyy")
```
to get the date in the format that you want.
This is a good resource [msdn-dateformat](http://msdn.microsoft.com/en-us/library/az4se3k1.aspx) |
5,316,172 | I basically have a `Money` value type, which consists of `Amount` and `Currency`. I need to map multiple `Money` values into a table, which has multiple fields for amount, but only one currency. In order words, I have the table:
```
Currency Amount1 Amount2
===============================
USD 20.00 45.00
```
Which needs to be mapped to a class with 2 Money values (which can logically never have different currencies):
```
class Record
{
public Money Value1 { get; set; }
public Money Value2 { get; set; }
}
struct Money
{
public decimal Amount { get; set; }
public string Currency { get;set; }
}
```
(Example is a bit simplified)
The table schema cannot be changed. I'm happy to implement an `IUserType`, if needed, but I cannot figure out how to access the `Currency` column for both values.
How do I map this using NHibernate ? | 2011/03/15 | [
"https://Stackoverflow.com/questions/5316172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13627/"
] | What about changing your classes like this?
```
class Record
{
public MoneyCollection Money { get; set; }
}
class MoneyCollection
{
public MoneyCollection(string currency, params decimal[] amount1) { /*...*/ }
public decimal[] Amount { get; private set; }
public string Currency { get; private set; }
public Money[] Money
{
get
{
return Amount.Select(x => new Money(Currency, x)).ToArray();
}
}
}
class Money
{
public Money(decimal amount, string currency ) { /* ... */ }
public decimal Amount { get; private set; }
public string Currency { get; private set; }
}
```
Now you can write a user type for `MoneyCollection`.
Note: You need to make sure that the `MoneyCollection` has a constant number, or at least a maximal number of values, because you need to map it to a constant number of columns. Check this in the class itself. | I know it is a few years late - but I have a solution.
```
private decimal _subTotal;
private decimal _shipping;
private CurrencyIsoCode _currency;
public virtual Money SubTotal
{
get { return new Money(_subTotal, _currency); }
set
{
_subTotal = value.Amount;
_currency = value.CurrencyCode;
}
}
public virtual Money Shipping
{
get { return new Money(_shipping, _currency); }
set
{
_shipping = value.Amount;
_currency = value.CurrencyCode;
}
}
```
**Mapping:**
```
Map(Reveal.Member<Basket>("_subTotal")).Column("SubTotal");
Map(Reveal.Member<Basket>("_shipping")).Column("Shipping");
Map(Reveal.Member<Basket>("_currency")).Column("Currency");
``` |
19,188 | I wonder if Tolkien ever explained why Gandalf insisted that Bilbo should go with the dwarves on their journey to reclaim Erebor. Gandalf didn't know about the One Ring and Gollum at that time. Did Gandalf foresee something or was he just thinking that Bilbo would be crucial for defeating Smaug (which Bilbo in the end of course was)? | 2012/06/26 | [
"https://scifi.stackexchange.com/questions/19188",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/7048/"
] | There is no explicit answer, but in the Hobbit, the following passage occurs:
>
> "Of course there is a mark," said Gandalf. "I put it there myself. For very good reasons. You asked me to find the fourteenth man for your expedition, and I chose Mr. Baggins. Just let any one say I chose the wrong man or the wrong house and you can stop at thirteen and have all the bad luck you like, or go back to digging coal." He scrowled so angrily at Gloin that the dwarf huddled back in his chair; and when Bilbo tried to open his mouth to ask a question, he turned and frowned at him and stuck out his bushy eyebrows, till Bilbo shut his mouth tight with a snap. "That's right," said Gandalf. "Lets have no more argument. I have chosen Mr. Baggins and that ought to be enough for all of you. If I say that he is a Burglar, a Burglar he is. or will be when the time comes. There is a lot more in him than you guess, and a deal more than he has any idea about himself. You may (possibly) all live to thank me yet. Now Bilbo, my boy, fetch a lamp, and let's have a little light at this."
>
>
>
So the dwarves wanted another member for their journey, and Gandalf thought Bilbo would fit (presumably a full-sized man or elf would be out of place among the dwarves). Bilbo was a relative of a slightly 'less respectable' group of hobbits - the Tooks, who were known to be adventurous. | Because Bilbo asked him to go (or at least Gandalf believed so)!
>
> "All the same I am pleased to find you remember something about me.
> You seem to remember my fireworks kindly, at any rate, land that is
> not without hope. Indeed for your old grand-father Took's sake, and
> for the sake of poor Belladonna, I will give you what you asked for."
>
>
> "I beg your pardon, I haven't asked for anything!"
>
>
> "Yes, you have! Twice now. My pardon. I give it you. In fact I will go
> so far as to send you on this adventure. Very amusing for me, very
> good for you and profitable too, very likely, if you ever get over
> it."
>
>
> |
34,431,249 | I want to remove the "kibana" loading text from the iframe of kibana dashboards. Any pointers on which file i can change for this. | 2015/12/23 | [
"https://Stackoverflow.com/questions/34431249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089557/"
] | I think that using br tag is always a bad idea. Try using paragraphs, css padding, css margin, hr. Try avoiding br because it's not [semantic](https://en.wikipedia.org/wiki/Semantic_Web) and using the proper tag in your site "helps the search" engines to "understand your site" | Try using this where you want the blank space:
```
```
If you want multiple blank spaces, then repeat the code successively like this:
```
```
etc. |
3,542,518 | It is possible have a bunch of web apps running in one windows azure small compute instance?
I am looking at using Azure as a place to sit a bunch of projects (web apps) that are in dev and non-production ready. Some are actually moth-balled, but I'd like to have an active instance of them somewhere. I don't want to pay for separate compute hours for each app, that is just sitting there 90 % of the time.
The other option I am considering to get a shared hosting account for these projects. | 2010/08/22 | [
"https://Stackoverflow.com/questions/3542518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135202/"
] | It depends on what you mean by Windows Azure instance.
A single Azure Account can hold multiple services and deployments. Deployment (at the moment of writing) could hold multiple Worker and Web Roles (essentially projects).
A single Web Role can be deployed in multiple deployment instances.
Given all that, you can **easily host multiple web applications in a single Windows Azure Account or even a single deployment**.
If you are interested in minimizing costs and keeping multiple test web apps under a single web role instance it gets tricky - you'll need to bring them together into a single project and deploy at once.
Note: last scenario might see drastic improvements rather soon, so Windows Azure is a rather safe bet. | Azure may not be the best for this use case - one VM allows only one app and all other options are somewhat complicated to implement (like having multiple apps in one web role or on-demand deploying and tearing down - also note that Azure charges for the clock hour, so I am not sure what happens if you bring up an instance, bring it down and then bring it up again within an hour).
Another cloud provider, like rackspace or Amazon might be better, you could create Windows VMs and host your apps on IIS as you would on a normal server. Only advantage in this case would be easier provisioning of that server and no infrastructure management (you still have to manage OS and other dependencies though, unlike Azure). |
1,405,245 | How would I be able to track all changes to my database?
I need a way to find out exactly what changes I made to the database so that I can make the same changes on another server.
For example, if I added a new field in one of the tables, I would like to know what field that was so that I could add that same field to another database. | 2009/09/10 | [
"https://Stackoverflow.com/questions/1405245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The steps people usually go through when facing these problems are:
1. Change the development db in whatever way is needed at the time.
2. Ready to deploy a new version of the application - realize the production database needs to be updated as well while retaining the data.
3. Dump the production and development schema, manually diff the schema creation scripts. Bang head against wall. Write change scripts that updates the production database.
4. Realize the change scripts needs to be written from the start when updating the development database instead of willy-nilly add and change stuff.
5. Find a naming scheme for versioning those change scripts so any installation can be updated from a given version to a newer version.
6. place the DB creation and change scripts in source control.
Make sure you're not repeating 1-3 every time, but get around to do 4-6 so you don't have to repeat 1-3 every time. | A non-automated but useful way to keep track of changes to a db is with the [MySQL Query Browser](http://dev.mysql.com/downloads/gui-tools/5.0.html). It keeps a history of all operations you run while using it. This makes assembling a change script very straightforward.
Obviously, this is not a solution if you're looking to replicate all changes made by all users. But if you are just looking to keep a set of changes in the correct order and avoid retyping them, it works pretty well. |
18,878,163 | I am plotting data as described in a previous Stackoverflow question:
[gnuplot 2D polar plot with heatmap from 3D dataset - possible?](https://stackoverflow.com/questions/18792461/gnuplot-2d-polar-plot-with-heatmap-from-3d-dataset-possible)
Mostly it is working well for me, and I am down to some small details. One of these is how to exert control over the contour line colors and linewidths. There are lots of posts on the web regarding using `set style increment user` followed by definition of user style via `set style line 1 lc rgb "blue" lw 2` etc. In theory this was supposed to force splot to plot lines using the newly defined styles. I tried it and it did not work. In addition, when I went to the help pages through my gnuplot install, I discovered that this usage is deprecated with my version (Version 4.7 patchlevel 0 last modified 2013-07-25). It was recommended to use set linetype instead, which changes the characteristics of the gnuplot line style permanently for the current invocation of gnuplot. Killing and restarting gnuplot restores the default linetype characteristics.
Next, I restarted gnuplot, regenerated the plot without redefining any line style or type for the contour lines. When I looked at my plot, I could see that the line colors start with cyan, then purple, then blue (e.g. like line types 5,4,3 or 14,13,12, etc.). It seems as if the line types are going BACKWARDS through the available styles. OK, I thought, I can just change those and live with the odd behavior. However, after issuing multiple set linetype commands that changed all of these line types to something that would be obviously different (I verified these by running the `test` command, the contour lines on the plot still had the same color and line width as before. I can't seem to figure out what linetype is being used for the contour lines, so I can't change the appropriate linetype.
Perhaps this odd behavior is a result of the contour line being of type `set cntrparam levels increment -6,-6,-24` and the negative values and/or negative going increment are causing some unpredictable behavior?
I'd like to know how I can know what line type will be used for contour lines in this plot, and whether that will change if the number of lines used to build the surface plot change. For instance, the plot shown below uses 13 "lines" to generate the surface using `set pm3d map`. So let's say N=13 lines - is there a rule that is obeyed for the first contour linetype?. For instance, will I always be sure that the contour line style will start at N=14? I'd to know what line type will be used for the first and subsequent contour lines when the number of "lines" in my input data will vary.
The bottom line is that I need to apply certain style to the contour lines used for each contour level. I want to consistently use the same style for each level when the input data changes. The plot will always use the same set of contour levels: -6, -12, -18, and -24. The plot data will always have a maximum "z" coordinate of about 0 and decrease from there.
Gnuplot commands are shown below. The dataset for this plot can be downloaded here:
<http://audio.claub.net/temp/new_test.dat>
```
reset
set terminal pngcairo size 800,800
set output '3d-polar.png'
set lmargin at screen 0.05
set rmargin at screen 0.85
set bmargin at screen 0.1
set tmargin at screen 0.9
set pm3d map interpolate 20,20
unset key
set multiplot
# plot the heatmap
set cntrparam bspline
set cntrparam points 10
set cntrparam levels increment -6,-6,-24
set contour surface
#set style increment user #NOTE: the commented out lines do not seem to affect color or width of the the contour lines no matter what number I use for the linetype
#set linetype 8 lc rgb "blue" lw 2
#set linetype 9 lc rgb "black" lw 1
#set linetype 10 lc rgb "orange" lw 1
#set linetype 11 lc rgb "yellow" lw 1
set palette rgb 33,13,10 #rainbow (blue-green-yellow-red)
set cbrange [-18:0]
unset border
unset xtics
unset ytics
set angles degree
r = 3.31 #This number is Log10(max frequency) - Log10(min frequency) of the polar frequency grid
set xrange[-r:r]
set yrange[-r:r]
set colorbox user origin 0.9,0.1 size 0.03,0.8
splot 'new_test.dat'
# now plot the polar grid only
set style line 11 lc rgb 'black' lw 2 lt 0
set grid polar ls 11
set polar
set logscale r 10
set rrange[10:20000]
unset raxis
set rtics format '' scale 0
#set rtics axis scale
set rtics (20,50,100,200,500,1000,2000,5000,10000,20000)
do for [i=-150:180:30] {
dum = r+0.15+0.05*int(abs(i/100))+0.05*int(abs(i/140))-0.05/abs(i+1)
set label i/30+6 at first dum*cos(i), first dum*sin(i) center sprintf('%d', i)
}
set label 20 at first 0, first -(log(20)/log(10)-1) center "20"
set label 100 at first 0, first -(log(100)/log(10)-1) center "100"
set label 200 at first 0, first -(log(200)/log(10)-1) center "200"
set label 1000 at first 0, first -(log(1000)/log(10)-1) center "1k"
set label 2000 at first 0, first -(log(2000)/log(10)-1) center "2k"
set label 10000 at first 0, first -(log(10000)/log(10)-1) center "10k"
set label 20000 at first 0, first -(log(20000)/log(10)-1) center "20k"
plot NaN w l
unset multiplot
unset output
```
The plot with no control over the contour lines is shown below. I need to be able to specify line color and width for the contour lines. How?
 | 2013/09/18 | [
"https://Stackoverflow.com/questions/18878163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2719646/"
] | Here is how you can change the line properties of the contour lines. I can't explain why it is that way, I just found out by testing it. Unfortunately, there is no documentation about these details.
The behaviour is as follows (tested with 4.6.3. and 4.7 (2013-07-25 and 2013-09-09), all show the same behaviour):
Default settings
----------------
1. If no `linetype` is specified for `splot`, the surface itself would use `lt 1`. In that case the first contour is drawn with `lt 3`. Yes, the numbering is backwards compared to the specified increment. But you can reverse it by using `set cntrparam levels increment -6,-6,-18` or `set cntrparam levels increment -18,6,-6`
2. The `linewidth` of all contours is the same and also equal to the `linewidth` used for the plotting command, to change it use e.g. `splot 'new_test.dat' lw 3`.
The result (without the thicker lines) is as shown in the question.
Using linestyles
----------------
1. The contours use the `linestyle` with an index by one higher than the one used by the plotting command.
2. You must also define the first `linestyle`, which would be used by the surface. If this style is not defined, the contours fall back to using `linetype`.
3. The `linewidth` is taken from the first `linestyle`, all `lw` settings from the following `ls` are ignored.
Using customized linetypes
--------------------------
1. The contours use the `linetype` with an index by one higher than the one used by the plotting command.
2. All `linetype` must be customized, also the first, the one used by the surface. Otherwise the default settings are used.
3. `lw` same as for `linestyle`.
For testing I used your data and the following stripped down script:
```
reset
set terminal pngcairo size 800,800
set output '3d-polar.png'
set lmargin at screen 0.05
set rmargin at screen 0.85
set bmargin at screen 0.1
set tmargin at screen 0.9
set pm3d map interpolate 20,20
# plot the heatmap
set cntrparam bspline
set cntrparam points 10
set cntrparam levels increment -6,-6,-18
set contour surface
set palette rgb 33,13,10
set cbrange [-18:0]
unset border
unset xtics
unset ytics
set angles degree
r = 3.31
set xrange[-r:r]
set yrange[-r:r]
set colorbox user origin 0.9,0.1 size 0.03,0.8
# load one of the following files:
#load 'linestyle.gp'
#load 'linetype.gp'
splot 'new_test.dat' title ' '
```
The `cbrange` is defined only down to `-18`, so I changed the contour levels accordingly (`-24` wasn't drawn anyway).
The two 'contour settings files', which I use are:
`linetype.gp`:
```
set linetype 1 lc rgb "blue" lw 3
set linetype 2 lc rgb "black"
set linetype 3 lc rgb "orange"
set linetype 4 lc rgb "yellow"
```
`linestyle.gp`:
set style increment user
```
set style line 1 lc rgb 'blue' lw 3
set style line 2 lc rgb 'black'
set style line 3 lc rgb 'orange'
set style line 4 lc rgb 'yellow'
```
Both give the same output image:

To use this for your complete script, just load one of the two files directly before the `splot` command. This gives the output:

After your first question about contours, I was about to submit a bug report, but it turned out to be rather difficult to boil it down to concrete questions. With this question it might be easier. I'll see if I find some time to do this. | I had to refer back to this question when I was again doing some GNUplot plotting, this time in rectangular coordinates, and found that could not recall how to control the line type for contour lines.
I found that the info above is now not quite correct, and I have discovered a way to explain how this works as of GNUplot version 5 patchlevel 3.
There are three things I found to control the contour lines:
1. the 'set cntrparam levels increment' command, and
2. the command 'set style increment user', and
3. the list of line styles (I used the 'set style' command)
It turns out it's a little tricky. Let me give an example or two from my own code:
```
#HOW TO CONTROL LINE COLOR AND WIDTH FOR CONTOUR LINES:
#the number of contour lines and their level is controlled using the 'set cntrparam' command, above
#the 'set cntrparam' has the format 'start,increment,end' for the line positions
#note that the end level is listed at the top of the key/legend for the lines!
#line style 1 is used elsewhere, not for contour lines
#line style 2 is used for the style of the last line (e.g. end, or the last one drawn)
#line styles for other lines begins further down the list of styles and works UPWARDS to line style 2
#example 1: three lines at -40, -30, and -20
# set cntrparam levels increment -20,-10,-40
# set style line 1 lw 0.5 lc "grey30"
# set style line 2 lw 0.5 lc "blue"
# set style line 3 lw 0.5 lc "white"
# set style line 4 lw 0.5 lc "red"
# This results in:
# -20 line color is RED
# -30 line color is WHITE
# -40 line color is BLUE
#
#example 2: four lines at -35, -30, -25, and -20
# set cntrparam levels increment -20,-5,-35
# set style line 1 lw 0.5 lc "grey30"
# set style line 2 lw 0.5 lc "blue"
# set style line 3 lw 0.5 lc "white"
# set style line 4 lw 0.5 lc "red"
# set style line 5 lw 0.5 lc "yellow"
# This results in:
# -20 line color is YELLOW
# -25 line color is RED
# -30 line color is WHITE
# -35 line color is BLUE
```
I'm hoping that others will find this useful and informative. Perhaps Christoph (if he happens to read this thread) can comment, since GNUplot is an evolving tool and he would know about it in detail. |
1,657,409 | This is from Gaughan Ch.2, problem 10. The function $f(x)$ is defined from $(0, 2)$ into $R$. Limit existence is **assumed**. The hint is to choose a subsequence $x\_n$ convergent to $0$ for which $f(x\_n)$ is 'convenient'.
So far I have tried $x\_n=1/n$ and $x\_n=(1/2)^n$, with no luck in either case. Since the latter just ends up looping around to the former in the algebra, I'll explain here what I attempted to do with $x\_n=1/n$.
$$f(x\_n)=(1/n)^{1/n}=n^{-1/n}$$
We always have $0<1/n<1$, so any power or root of $1/n$ is necessarily likewise bounded. Therefore $f$ is bounded above by $1$ and below by $0$. Possible avenues of approach:
1. Is there some $n$ beyond which $f$ is monotonically increasing?
2. Can the subsequence be shown to be Cauchy? (algebraically tedious at best)
3. Back to basics proof by definition of limit.
By graphical inspection, 1. does hold for $n\ge3$, although I have failed in all attempts to prove it. In fact, I get algebraically bogged down in about the same place trying either 1. or 2.
Take $n,m\in Z$ with $0<n<m$. Then $1/m<1/n$, so
$$1/n<(1/n)^{1/n}<(1/n)^{1/m}<(1/m)^{1/m}$$
At least half of which is useless; $1/n$ is going the wrong direction. The middle part isn't much use either, because it's in the middle.
$$|n^{-1/n}-m^{-1/m}|\le\ldots$$
All I can think is to go back to 1. and try induction. But I can't seem to factor the thing at all, so that's unclear. The only convergence herein demonstrated is between my head and the desk. Any suggestions would be appreciated. | 2016/02/15 | [
"https://math.stackexchange.com/questions/1657409",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/314771/"
] | I'm not sure if you function is an injection, and it's quite an ugly function aswell.
Consider this one:
$$
f(x,y)=2^x\cdot 3^y
$$
Use the uniqueness of the prime factorization to prove this is an injection.
---
By the way, with your original argument, you weren't suppose to get that "$x+y=u+v$" but rather $x=u,y=v$: note that if $f(x,y)=x+y$, then certainly $f(x,y)=f(u,v)$ implies $x+y=u+v$, but this is nowhere near an injection. | Here's a way of proving that result that's easier to understand:
$$
\begin{array}{cccccccccc}
1,1 & & 1,2 & \rightarrow & 1,3 & & 1,4 & \rightarrow & 1,5 & & 1,6 & \rightarrow \\
\downarrow & \nearrow & & \swarrow & & \nearrow & & \swarrow & & \nearrow \\
2,1 & & 1,1, & & 2,3 & & 2,4 & & 2,5 & & \cdots \\
& \swarrow & & \nearrow & & \swarrow & & \nearrow \\
3,1 & & 3,2 & & 3,3 & & 3,4 & & 3,5 & & \cdots \\
\downarrow & \nearrow & & \swarrow & & \nearrow \\
4,1 & & 4,2 & & 4,3 & & 4,4, & & 4,5 & & \cdots \\
& \swarrow & & \nearrow \\
5,1 & & 5,2 & & 5,3 & & 5,4 & & 5,5 & & \cdots \\
\downarrow & \nearrow \\
6,1 & & \vdots & & \vdots & & \vdots & & \vdots
\end{array}
$$
There's a first member of $\mathbb N\times\mathbb N$, then a second, then a third, and so on. No matter which member of $\mathbb N\times\mathbb N$ you pick, I know, without knowing which one you picked, that after some finite number of steps, I will reach it by following the arrows. |
6,473,249 | I am trying to upload a movie onto a site and then automatically convert it into .mp4 format from the .mov iPhone format. Is there a php conversion library or tool that would help me do this?
Thanks. | 2011/06/24 | [
"https://Stackoverflow.com/questions/6473249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/766965/"
] | You could try the ffmpeg extension: <http://ffmpeg-php.sourceforge.net/>
Edit:
It turns out that the ffmpeg extension probably won't help you, but you could still use ffmpeg to do the conversion. You are probably better off having a cron job or something similar do the conversions in the background. Just let the user upload the mov file, and then add it to a queue and convert it to mp4 in another process. | Try command :
```
ffmpeg -i movie.mov -vcodec copy -acodec copy out.mp4
``` |
3,061,868 | I try to integrate an existing database file into my Android project.
I follow the instructions on this [blog](http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/). They write that I have to add a table `android_metadata` with a column called locale and put en\_US into it.
I try to figure out what this table is used for. Because my database content is german. Maybe i then should not put en\_US into it? Is this required for localisation of the database content or is the table not needed at all? | 2010/06/17 | [
"https://Stackoverflow.com/questions/3061868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114066/"
] | the metadata table will be generated automatically. if you have content of german try updating the metadata table 'de\_DE'. | The metadata table is required to hold (as its name suggests) meta information about the application. This table is auto-generated in some cases (since api 4 if i remember correctly) but you may want to add it yourself. |
21,280,476 | I'm trying to learn the Eigen C++ library, and was wondering if there is some nice shorthand for initializing dynamic vectors and matrices. It would be really nice to write something like you would using a `std::vector`
```
std::vector<int> myVec = {1,2,3,6,5,4,6};
```
i.e.
```
VectorXi x = {1,2,3,4,7,5,7};
```
The closest (ugly) equivalent I can find involves `Map` . .
```
int xc[] = {2,3,1,4,5};
Map<VectorXi> x(xc,sizeof(xc)/sizeof(xc[0]));
```
What other initialization methods are there? | 2014/01/22 | [
"https://Stackoverflow.com/questions/21280476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276193/"
] | Do like this..
```
$yourstring = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$val = array_pop(explode('/',$yourstring)); // 6.png
``` | You don't need to use regex for this, you can use `substr()` to get a portion of the string, and `strrpos()` to specify which portion:
```
$full_path = "test-e2e4/test-e2e4/test-e2e4/6.png"
$file = substr( $full_path, strrpos( $full_path, "/" ) + 1 );
```
`substr()` returns a portion of the string, `strrpos()` tells it to start from the position of the last slash in the string, and the +1 excludes the slash from the return value. |
18,563 | By signed request I mean something like this (simplified example):
Client creates a sig in his request:
`$sig = hash('sha256', $api_key.$data);` which generates `7409ur0k0asidjko2j` for example. He then sends this to his request: `example.com/api/7409ur0k0asidjko2j`
Now, the receiving server then performs the exact process to perform a match for the sig.
Which is generally more secure, a signed request like this or an HTTP digest auth for the purpose of authenticating requests to an API server? Note we assume SSL is not installed. | 2012/08/12 | [
"https://security.stackexchange.com/questions/18563",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/9317/"
] | If the signature covers the whole request, then integrity is guaranteed. **Request replay is still a potential threat (think: resource abuse).**
With HTTP digest authentication, the request could be modified in transit. **You are at the mercy of a MITM (Man In The Middle) attack.**
Anyway, you should really use TLS provides **transport level security**:
* guaranty of **confidentially of payload**, not just of password or authenticator (but *not* payload size! be careful if payload size can reveal useful information)
* guaranty of **integrity of payload** (but *no* guaranty WRT client IP address!) | Signing of the request might be better, but you should implement it correctly. The hash(key || data) construction is vulnerable to hash length extension attack and should never be used. Here you have good explanation of this subject: [Hash Length Extension Attacks](https://blog.whitehatsec.com/hash-length-extension-attacks/ "Hash Length Extension Attacks"). You should use HMAC for message authentication.
Signing of the request is better than HTTP digest auth, because it could also protect the integrity of data sent in the request. |
53,498,240 | I am trying to migrate a django application from one server to another. The application is working fine on the old server.
On the new server, the application works fine when used using Django's runserver.
To test the django application under uwsgi, I used
```
uwsgi --http :8000 --module mysite.wsgi
```
This opens the django admin page as expected but as soon as I try to login, uwsgi gets a segmentation fault error which is as follows.
Would greatly appreciate if anybody could help understand what this means, and how might I fix this.
---
```
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 15398, cores: 1)
!!! uWSGI process 15398 got Segmentation Fault !!!
*** backtrace of 15398 ***
uwsgi(uwsgi_backtrace+0x35) [0x5569e2f17555]
uwsgi(uwsgi_segfault+0x23) [0x5569e2f17903]
/lib/x86_64-linux-gnu/libc.so.6(+0x35fc0) [0x7f0dd221bfc0]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_cleanup_key_block+0xb) [0x7f0dd0241cab]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_clear+0x16) [0x7f0dd023f5a6]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(tls1_clear+0x9) [0x7f0dd024b219]
/usr/lib/x86_64-linux-gnu/libssl.so.1.1(SSL_new+0x43f) [0x7f0dd2bf376f]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x23969) [0x7f0dd04d6969]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x24fc5) [0x7f0dd04d7fc5]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectPoll+0xb78) [0x7f0dd04c1ba8]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0xfa28) [0x7f0dd04c2a28]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectdb+0x1f) [0x7f0dd04c541f]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x12651) [0x7f0dd0716651]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x133df) [0x7f0dd07173df]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x1fcab2) [0x7f0dd25d9ab2]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x89) [0x7f0dd2645e99]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_CallFunction_SizeT+0x124) [0x7f0dd26468b4]
/home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0xc1a8) [0x7f0dd07101a8]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyCFunction_Call+0x96) [0x7f0dd25f0fe6]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x7940) [0x7f0dd2561f10]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17ba3f) [0x7f0dd2558a3f]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyEval_EvalCodeEx+0x3e) [0x7f0dd25594fe]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x23cc63) [0x7f0dd2619c63]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyObject_Call+0x48) [0x7f0dd26466d8]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x3de5) [0x7f0dd255e3b5]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17ba3f) [0x7f0dd2558a3f]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c11e) [0x7f0dd255911e]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17ba3f) [0x7f0dd2558a3f]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c11e) [0x7f0dd255911e]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x3c95) [0x7f0dd255e265]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x2428a8) [0x7f0dd261f8a8]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x239aa6) [0x7f0dd2616aa6]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x239f6a) [0x7f0dd2616f6a]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x1fcab2) [0x7f0dd25d9ab2]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x89) [0x7f0dd2645e99]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17bee8) [0x7f0dd2558ee8]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyFunction_FastCallDict+0x2c3) [0x7f0dd2558e43]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x131) [0x7f0dd2645f41]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_Call_Prepend+0xcd) [0x7f0dd264666d]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x89) [0x7f0dd2645e99]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x6bb61) [0x7f0dd2448b61]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x1f5f65) [0x7f0dd25d2f65]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x186ff9) [0x7f0dd2563ff9]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyCFunction_FastCallDict+0x13a) [0x7f0dd25f0d6a]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c20c) [0x7f0dd255920c]
/usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492]
*** end of backtrace ***
``` | 2018/11/27 | [
"https://Stackoverflow.com/questions/53498240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395643/"
] | [Pyuwsgi](https://pypi.org/project/pyuwsgi/) can be used instead of building uWSGI from source. It is a wheel, but excludes the SSL plugin so it should workaround the incompatibility. | I have the same problem. It turns out to be caused by the Python package `grpcio (1.34.0)`. Downgrading to `grpcio==1.30.0` solved the problem. This solution is provided by <https://github.com/grpc/grpc/issues/23796>
Using `pipenv` (should be the same with `pip`), my exact commands to fix it were:
```
$ pipenv uninstall grpcio
$ pipenv install grpcio==1.30.0
``` |
2,945,334 | I have a webservice method FetchNumber() that fetches a number from a database and then returns it to the caller. But just before it returns the number to the caller, it needs to send this number to another service so instantiates and runs the BackgroundWorker whose job is to send this number to another service.
```
public class FetchingNumberService : System.Web.Services.WebService
{
[WebMethod]
public int FetchNumber()
{
int value = Database.GetNumber();
AsyncUpdateNumber async = new AsyncUpdateNumber(value);
return value;
}
}
public class AsyncUpdateNumber
{
public AsyncUpdateNumber(int number)
{
sendingNumber = number;
worker = new BackgroundWorker();
worker.DoWork += asynchronousCall;
worker.RunWorkerAsync();
}
private void asynchronousCall(object sender, DoWorkEventArgs e)
{
// Sending a number to a service (which is Synchronous) here
}
private int sendingNumber;
private BackgroundWorker worker;
}
```
I don't want to block the web service (FetchNumber()) while sending this number to another service, because it can take a long time and the caller does not care about sending the number to another service. Caller expects this to return as soon as possible.
FetchNumber() makes the background worker and runs it, then finishes (while worker is running in the background thread). I don't need any progress report or return value from the background worker. It's more of a fire-and-forget concept.
My question is this. Since the web service object is instantiated per method call, what happens when the called method (FetchNumber() in this case) is finished, while the background worker it instatiated and ran is still running?
What happens to the background thread? When does GC collect the service object? Does this prevent the background thread from executing correctly to the end? Are there any other side-effects on the background thread?
Thanks for any input. | 2010/05/31 | [
"https://Stackoverflow.com/questions/2945334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93770/"
] | I feel like testing inside the function is better. If you test outside of the function, you'll have to test everywhere that function could be called (and would cause a lot of duplicate code).
It's nicer to have everything in one place then spread out everywhere. | In this case, I feel that the name of the function implies that something is going to happen to the URL in every case. Someone may want to call `FixURLCosmetics` on a non-GET page and expect something to happen.
I would rename `FixURLCosmetics` to `FixGETURLCosmetics`. Then, throw an exception if it's called on a non-GET page. |
180,690 | I'm working on a software which deals with lots (several millions) of RSA private keys. Keysize is 2048, I'm going to store them in database in PEM format.
I want keys to be encrypted to mitigate risks of hostile access to database. Naturally, applying passphrase with PKCS#8 comes to mind.
However, I'm not sure it is safe to apply **same** passphrase to millions of private keys. If someone gets the database, will it be possible for them to decrypt keys, knowing the fact that same passphrase where used?
If PKCS #8 is not safe in this scenario, what better options I have, given fact that I can use same passphrase (or limited number of them) to encrypt data? | 2018/02/28 | [
"https://security.stackexchange.com/questions/180690",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/171761/"
] | Using a different passphrase for each key means you then have the problem of working out where to keep the passphrases. It is a little better in that the passphrase can be stored separately - and realising (compromising?) the asset requires compromise of both the passphrase and the protected key.
The number of entries you describe rather implies that you will need some automation over bringing the key and the passphrase together (e.g. a html5 application connecting to 2 different services with separate authentication). That is the weak link in the application. But you've not told us anything about the front end of the system. | In the past I made something similar and we decided to add a field to the table that holds the keys in a token. That token was the key of other table, that was in a different database, that holds the passphares of the other. Probably there is a better way but this was enough for us. |
801,201 | I have an ASP.NET WebSite which restarts in every 1-2 hours in a day so sessions and other thing are gone and users are complaning about it, because they open a page and do something for 20 minutes and when they submit it, a nice "we are sorry" page is there.
I don't do anything which restarts the application (changing the web.config, changing the files, or even other buggy things like deleting a folder in App\_Data which normally shouldn't cause a restart).
Can it be related with Server's hardware? It is not much powerful. | 2009/04/29 | [
"https://Stackoverflow.com/questions/801201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89841/"
] | I guess this is [recycling](https://stackoverflow.com/questions/358384/asp-net-recycling-app-pools-indicative-of-larger-problem). | Sounds like the app is being recycled or process is failing.
Check app pool settings <http://msdn.microsoft.com/en-us/library/aa720473(VS.71).aspx>
and event viewer. |
8,262,573 | Im using a timer to call an ajax function that loads in a response from a seperate php page. I want to make it so the content fades out then fades in with the response ever so often.
Here's my code - i can grab the content and make it change just the fading in part im at a loss with.
```
<script type="text/javascript">
window.setTimeout('runMoreCode()',100);
$(document).ready(function(){
$('#refreshRecords').fadeIn(2000);
});
function runMoreCode()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("refreshRecords").innerHTML=xmlhttp.responseText;
$('#refreshRecords').fadeIn('slow');
}
}
xmlhttp.open("GET","NewRecords.php",true);
xmlhttp.send();
setTimeout("runMoreCode()",6000);
}
</script>
```
I have tried to do it with .fadeIn but with no luck. I have linked in the latest jQuery file as well.
Thanks
GCooper | 2011/11/24 | [
"https://Stackoverflow.com/questions/8262573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1064660/"
] | You're going to want to do this:
1. Get new content
2. Fade out old content
3. Swap old content with new content
4. Fade in new content
So you'll want to change your ready state handler to this:
```
// fade out old content
$('#refreshRecords').fadeOut('slow', function (){
// now that it is gone, swap content
$('#refreshRecords').html(xmlhttp.responseText);
// now fade it back in
$('#refreshRecords').fadeIn('slow');
});
```
And I agree Shomz, you should just use JQuery's `$.ajax()` function too. | Try using jQuery's [.ajax](http://api.jquery.com/jQuery.ajax/) method. That way you could apply any jQuery effect just as you get the response (the PHP page you're opening). Should make your work much easier, and your code more readable. Using the old approach is fine if you want to stay with JS and not waste your resources using jQuery, but since you're using jQuery anyway, why not go all the way with it?
One more thing: might seem stupid, but you do have a div with id="refreshRecords" and display set to none, do you? |
223,125 | What would one call a tablet which isn't swallowed?
What verb would be used when taking it?
Would the following phrase be correct?
>
> To suck the secretion of tablet...
>
>
> | 2019/09/05 | [
"https://ell.stackexchange.com/questions/223125",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/92676/"
] | You "suck a *lozenge*" or a *pastille* (British). [Lexico](https://www.lexico.com/en/definition/lozenge) says
>
> **lozenge**
>
> NOUN
>
>
> **1.1** A small medicinal tablet, originally in the shape of a lozenge, taken for sore throats and dissolved in the mouth.
>
>
> *Sucking of lozenges and pastilles produces saliva which lubricates and soothes inflamed tissues and washes infecting organisms off them.*
>
>
>
A **pill** was originally a small, round, solid pharmaceutical oral dosage form of medication. It has become a general term for a medicine taken orally, which can be a tablet, a capsule or a caplet (or when not swallowed, a lozenge). Various types of pill are discussed [in this Wikipedia article](https://en.wikipedia.org/wiki/Tablet_(pharmacy)). | The medical term used in the UK is ***orodispersible.***
[](https://i.stack.imgur.com/QTNpQs.jpg)
This was first introduced in Europe and is now adopted in the USA as well.
Typically, these are uncoated tablets "dissolve" in the mouth without the need to suck or chew them.
<https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3217286/> |
57,214,540 | I have a string like this:
```
myString <- "[0.15][4577896]blahblahblahblahwhatever"
```
I need to extract the number between second brackets.
Currently I am trying to use this:
```
str_extract(myString, "\\]\\[(\\d+)")
```
But this gives me `][4577896`
My desired result would be: `4577896`
How could I achieve this? | 2019/07/26 | [
"https://Stackoverflow.com/questions/57214540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333262/"
] | Here is another version with minimal or no regex
```
qdapRegex::ex_between_multiple(myString, "[", "]")[[2]]
#[1] "4577896"
```
It extracts all the substring between `[` and `]` and we select the value between second bracket. You can convert it into numeric or integer if needed. | An option using `str_extract`
```
library(stringr)
str_extract(myString, "(?<=.\\[)([0-9]+)")
#[1] "4577896"
``` |
34,839,764 | I have a java program (text-based no GUI) that I have written and compiled and uploaded to a server.
I run it with `java -cp myjar.jar mypackage.MyClass` which starts it running processing a datafile with 20,000,000+ entries in it and printing output to `System.out`. I have calculated that it will take a very long time to process the data and I didn't want to have my laptop open for the 10 days of number crunching...
When I log out of my shell however, the process stops.
How can I execute the command and log out without it stopping? What is that even called?
I am using an Amazon Ubuntu EC2 server. I log in using a certificate from Mac OSX with terminal. The server seems to be using a bash shell.
Hope someone can help me out!
Jason. | 2016/01/17 | [
"https://Stackoverflow.com/questions/34839764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5384498/"
] | When you have a template function like
```
template<typename T>
void fun(T & param)
```
if the parameter that is passed is actually `const`, or `volatile`, then in the template instantiation, `T` will also be "cv-qualified" appropriately.
When you put the cv-qualifier in the template function declaration, like so,
```
template<typename T>
void fun(const T & param)
```
then `T` is *not* bound as `const`. But it will be `volatile` if the parameter `volatile`.
It's actually very intuitive -- `T` is the simplest type that will make the function call work, i.e., make the expected type of the function argument match what was passed.
Similarly, if my function is
```
template <typename T>
void fun(T * param)
```
then if I pass it an `int *`, `T` will be bound as `int`.
This is described in great detail in the C++11 standard `[temp.deduct.call](14.8.2.1)`, see part three about the CV-qualifiers:
>
> *[temp.deduct.call] (14.8.2.1)*
>
> (1) Template argument deduction is done by comparing each function template parameter type (call it P) with
> the type of the corresponding argument of the call (call it A) as described below. ...
> (2) If P is not a reference type:
>
> (2.1) — If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is
> used in place of A for type deduction; otherwise,
>
> (2.2) — If A is a function type, the pointer type produced by the function-to-pointer standard conversion (4.3)
> is used in place of A for type deduction; otherwise,
>
> (2.3) — If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction.
>
> (3) If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction. If P is a
> reference type, the type referred to by P is used for type deduction.
>
>
> | Since `cx` and `rx` exhibit the same behavior here, we will use only `cx`.
`cx` is `const int`.
* case of `fun`:
`T&` matches against `const int` so `T` is deduced as `const int`, because `const` is not part of `T &`. The type of `param` is `const int&`.
* case of `fun1`:
`const T&` matches against `const int` so `T` is deduced as `int`, because `const` already is in `const T&`. The type of `param` is `const int&`.
Let's have it all visually horizontally aligned by type match, maybe this is more clear:
```
fun param type: | T | &
receives : | const int |
fun1 param type: | const | T | &
receives : | const | int |
``` |
56,604,387 | I have string like this `2019-06-13 23:37:02.284175`.
I would like to convert this string to unix time epoch.
How can I convert this string to unix timestamp using python?? | 2019/06/14 | [
"https://Stackoverflow.com/questions/56604387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9679298/"
] | No, [the syntax](https://en.cppreference.com/w/cpp/language/range-for) does not allow any more than an *init-statement* (since C++20).
Technically, you can embed additional statements to be performed at the time of iterator comparison and/or incrementation inside *range\_expression*. This can be done by creating a generic wrapper class for containers, implementing its own iterators in terms of the ones of the provided container + additional logic:
```
auto additional_condition = [](auto const& element) { return ...; };
auto increment_statement = []() { ... };
for(auto& element :
custom_iterable(container, additional_condition, increment_statement))
{
...
}
```
But it largely defeats the purpose of the range-based for (simpler syntax). The classic for loop is not that bad.
Let's not forget macros - they probably have the power to:
1. re-implement range-based for
2. add more comma-separated arguments
but let's not use them in this way, either. That would be just rude. | With [range-v3](https://github.com/ericniebler/range-v3) (which should be part of C++20), you might do something like:
```
for (const auto& p : ranges::view::zip(container, ranges::view::ints)) {
doStuff(p.first /* element*/ , p.second /*ID*/);
}
```
[Demo](http://coliru.stacked-crooked.com/a/cfa4b468879eb256) |
12,045,881 | My setup currently looks like this
***application/controllers/register.php***
```
class register_Controller extends Base_Controller
{
public $restful = true;
public function get_index()
{
return View::make('main.register');;
}
}
```
***routes.php***
```
Route::controller(Controller::detect());
Route::any('/', function()
{
return View::make('main.index');
});
Route::any('register',function()
{
return View::make('register.index');
});
```
mydomain.com works.
mydomain.com/index gives a laravel 404
mydomain.com/register gives a standard 404
What's strange is that shouldn't mydomain.com/register give me a laravel 404 error?
[This](https://stackoverflow.com/questions/11791375/laravel-routes-not-working?rq=1) page indicates that WAMP was the cause, but my setup is on a Ubuntu VM running PHP5, Apache2, and mySQL. | 2012/08/20 | [
"https://Stackoverflow.com/questions/12045881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1361802/"
] | With mod\_rewrite on, try setting in apache configurations "AllowOverride All", it fixed it for me. | make sure mod\_rewrite is turned on in Apache (httpd.conf)
Un-comment the following line
```
LoadModule rewrite_module modules/mod_rewrite.so
```
and restart httpd |
1,875,411 | Are there any proofs about Real numbers that have shorter equivalent proofs going through Complex numbers?
Are there proofs about Integers going through Reals, with longer equivalent proofs using pure Integers? | 2016/07/29 | [
"https://math.stackexchange.com/questions/1875411",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/4399/"
] | Many many interesting definite integrals of functions whose indefinite integrals have no closed form are derived using contour integration in the complex plane. Some of these can, however, be derived by far messier work in the real line.
Almost everything involving computational complexity in computer science ends up using the logarithm, which can be defined for only integer arguments if you choose to do so, but whose properties, as a function on the reals, are of great interest and use in complexity analysis. | [Some time ago](https://math.stackexchange.com/q/1721832/26306) I had answered a nice simple question that turned out to be a good example for the Integers/Reals part (I couldn't find simpler discrete proof).
**Problem:**
>
> Let $G = (U \uplus V, E)$ be a connected bipartite graph such that $n\_U = |U| < |V| = n\_V$. Then there exists an edge $\{u,v\} \in E$ such that $\deg(u) > \deg(v)$.
>
>
>
**Discrete proof:**
Sort the vertices such that
\begin{align}
\deg(u\_1) &\geq \deg(u\_2) \geq &\ldots &&\geq \deg(u\_{n\_U}), \\
\deg(v\_1) &\geq \deg(v\_2) \geq &\ldots &&\geq \deg(v\_{n\_V}).
\end{align}
Observe that because there are no isolated vertices in $G$ we have $\deg(v\_{n\_V}) \geq 1$, thus $$\sum\_{i=1}^{n\_U}\deg(u\_i)-\deg(v\_i) > \sum\_{i=1}^{n\_U}\deg(u\_i)-\sum\_{i=1}^{n\_V}\deg(v\_i) = 0.$$
Let $k$ be the smallest natural number with this property, that is,
$$k = \min\Bigg\{k \in \mathbb{N} \ \Bigg|\ \sum\_{i=1}^{k}\deg(u\_i)-\deg(v\_i) > 0\Bigg\}.$$
It follows that
1. $\deg(u\_k) > \deg(v\_k)$, otherwise $k$ would not be the smallest number with the above property.
2. $N\big(\{u\_1,\ldots,u\_k\}\big) \not\subseteq\big\{v\_1,\ldots,v\_k\big\}$, because the sum of degrees in $\{v\_1,\ldots,v\_k\big\}$ is too small to exhaust all the degrees of $\{u\_1,\ldots,u\_k\big\}$.
3. There exists an edge $\{u\_i,v\_j\} \in E$ such that $i \leq k \leq j$.
4. $\deg(u\_i) \geq \deg(u\_k) > \deg(v\_k) \geq \deg(v\_j)$.
**Non-discrete proof:**
Let $$f\big(\{u,v\}\big) = \frac{1}{\deg(u)} - \frac{1}{\deg(v)}.$$
This is a proper definition, because there are no isolated vertices in $G$. Now observe that $$\sum\_{e \in E}f(e) = \sum\_{u \in U}\deg(u)\cdot\frac{1}{\deg(u)} - \sum\_{v \in V}\deg(v)\cdot\frac{1}{\deg(v)}
= |U|-|V| < 0.$$
Therefore, there exists an edge $\{u,v\}$ such that $f\big(\{u,v\}\big) < 0$, but that means $\deg(u) > \deg(v)$.
I hope this helps $\ddot\smile$ |
36,923,923 | I have table **Eli** with 1 million records. When I query the following:
```
Select count(*) from Eli where userId ='my_user'
```
It is taking more than 10 mins to give results. I searched web and found better way to optimize the query from `http://dbatipster.blogspot.com/2009/08/get-row-counts-fast.html`.
How do I utilize the the following query into my above query-
```
SELECT OBJECT_NAME(i.id) [Table_Name], i.rowcnt [Row_Count]
FROM sys.sysindexes i WITH (NOLOCK)
WHERE i.indid in (0,1)
ORDER BY i.rowcnt desc
``` | 2016/04/28 | [
"https://Stackoverflow.com/questions/36923923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2961127/"
] | Without touching on properly building a table, I would use something like this:
```
SELECT COUNT(userID) FROM Eli (NOLOCK)
WHERE userId ='my_user'
```
The `(NOLOCK)` hint allows you to select from the table without other transactions against the Eli table being committed, meaning you're not waiting for other updates and inserts to complete before returning your results. | The easy fix to see improvement would be add an index on the table on the userID, if you intend to use the userID filter very often in your queries. Of course that if userID is the primary key of your table, the index would not be necessary and maybe other ways to improve needs to be checked.
Now, the query you have provided should be applied as this to make it easier for you:
```
SELECT OBJECT_NAME(i.id) [Table_Name], i.rowcnt [Row_Count]
FROM sys.sysindexes i WITH (NOLOCK)
WHERE i.indid in (0,1)
AND OBJECT_NAME(i.id) = 'Eli';
```
The original query you posted listed the row counts for all objects in the database in descending order of the number of rows. |
20,545,881 | I am trying something like this:
```
public function search() {
$criteria = new CDbCriteria;
$criteria->compare('user_details_id', $this->user_details_id);
$criteria->compare('user_type_id', $this->user_type_id);
$criteria->compare('customer_basics_id', $this->customer_basics_id);
$criteria->compare('user_address_id', $this->user_address_id);
$criteria->compare('user_city_id', $this->user_city_id);
$criteria->compare('is_active', $this->is_active);
$criteria->compare('create_dttm', $this->create_dttm, true);
$criteria->compare('update_dttm', $this->update_dttm, true);
// if condition is working
if (isset($_GET['ulip'])) {
$criteria->addCondition(
"customer_basics_id=" . CustomerBasics::getCustomerBasicsId(Yii::app()->session['user_id']), "AND"
);
$criteria->addCondition("user_city_id IS NULL");
// else condition is working
} else {
$criteria->addCondition(
"customer_basics_id=" . CustomerBasics::getCustomerBasicsId(Yii::app()->session['user_id']), "AND"
);
$criteria->addCondition("user_city_id IS NOT NULL");
}
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 10,
),
));
}
```
Here the issue is `if` condition is working fine and showing results according to the condition but else part is not working and it returns nothing. I think `IS NOT NULL` is not working here.
What is the issue ? | 2013/12/12 | [
"https://Stackoverflow.com/questions/20545881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1197047/"
] | **The Main reason.**
In your database table column(user\_city\_id), you have **Empty values** not **NULL values**.
So your query is unable to operate "IS NULL" and "IS NOT NULL" on the corresponding column.
```
1. NULL is Special Data Type.
2. Where as Empty means a string/value which is empty.
```
You can read more [here](https://stackoverflow.com/questions/5615747/what-is-the-difference-between-null-and-empty)
**No need to add operator for first addCondition**
For your information, When you are adding a condition to your criteria, no need to add "AND" operator becoz by default "AND" is the operator in [addConditon](https://github.com/yiisoft/yii/blob/1.1.14/framework/db/schema/CDbCriteria.php#L218). And no use if you add operation for first addCondition, You should add this for your next addConditions if you have any.
```
//AND is not required here as AND is default operation.
//This operator (AND) wont help in first condition.
$criteria->addCondition('condition1=1','AND');
//This bellow condition will be concatenate with above condition so, here operator is required.
$criteria->addCondition('condition2=1','OR');
```
**The Solution is**
I dont like to disturb default search method in my model. **As i'm using MVC Framework, i should follow at least some MVC rules. Otherwise there is no meaning using this MVC.** So, accessing $\_GET stuff in my Model is not good here. so i'm creating a new method in my Model with two parameters.
```
function yourModelMethod($isParamExist,$customer_basics_id)
{
$criteria = new CDbCriteria;
$criteria->condition = "customer_basics_id=$customer_basics_id";
if($isParamExist)
{
$criteria->condition='TRIM(user_city_id) =""';
}
else
{
$criteria->condition='TRIM(return_date) !=""';
}
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
```
Now, I'm using this model method from my controller
```
function actionYourController()
{
$model=new MyModel();
$isParamExist=isset($_GET['ulip']);
$customer_basics_id=CustomerBasics::getCustomerBasicsId(Yii::app()->session['user_id']);
$activeData=$model->yourModelMethod($isParamExist,$customer_basics_id);
$this->render('myView',array('activeData'=>$activeData));
}
```
I hope, it will definitely solve your problem. | Maybe `$criteria->addCondition("user_city_id <> '' ");` solve the probleme because IS NOT NULL interpreted as true and NULL as false. |
10,226,805 | I have below query
```
Select
RPAD(x.QUOTE_ID,20,' ')
from csa_sli_all.T_CONV_XREF_CUST_QUOTE x ,
csa_sli_all.T_CONV_quote q
where q.select_indicator is null and
q.QUOTE_ID = X.QUOTE_ID and
q.HOLD_CODE IN ('CAQ' , NULL )
```
it doesnt give me required result.
I changed last statement to
```
where q.select_indicator is null and
q.QUOTE_ID = X.QUOTE_ID and
(q.HOLD_CODE = 'CAQ' or q.hold_code is null)
```
Now its giving me desired result. My question is
1 can't we use `NULL` in `WHERE IN` clause ?
2 If yes HOW
3 Going by the logic ( not syntax : I know 1st syntax is wrong ) both scenarios will give same answers ? | 2012/04/19 | [
"https://Stackoverflow.com/questions/10226805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1323540/"
] | You cannot use `NULL` in `IN` statements, because `IN` applies the standard `=` operator. This one, of course, fails when comparing `NULL`s.
It's like writing `SELECT NULL = NULL`. Returned value would be `NULL`. | Instead of using a subquery, you'll have to use a join. Say for argument's sake you're using SQL Server, do something like (obviously filling in your fields):
```
SELECT yourField, yourField2
FROM yourTable t1
INNER JOIN yourTable2 t2 ON t1.Id = t2.Id
WHERE t1.field is null
AND (t1.code = 'CAQ' OR t1.code IS NULL)
``` |
1,448,862 | I'm creating RSS reader application. I need to get any linked rss old items. For example some web rss result count is too less. My application check time range is too long. Sometimes loss some news.
How can I get rss old items?
When scrolling down on the google reader,reader shown previous items. | 2009/09/19 | [
"https://Stackoverflow.com/questions/1448862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60200/"
] | try this <http://www.google.com/reader/atom/feed/>{complete url to rssfeed without {} }?n=5000 | Since Google Reader shut down about a year ago, I'd suggest you give a shot at [Superfeedr](http://superfeedr.com/users/) if you're looking for a replacement. |
72,372,940 | I'm using `sed` to obtain a specific string (`0x0296cc83474725ddca19a9feefb3aec3602d9073688a4db6885695320cd2a738`) from an output. This string comes next to `Contract address:`
This is what I'm trying currently.
**UPDATE:** out put has newlines.
```
$ echo $output
```
```
Starknet plugin using the active environment.
Deploying contract.cairo/contract.json
Deploy transaction was sent.
Contract address: 0x0296cc83474725ddca19a9feefb3aec3602d9073688a4db6885695320cd2a738
Transaction hash: 0x3f60551591f6abb9c79044ce15de4260eb169af2931abdc279e73f6428fc12d
Succeeded
```
```
$ ADDRESS=$(echo $output | sed -r "s/.*Contract address: (\w*).*/\1/")
$ echo "Address: $ADDRESS" # This is not working
```
I know how to grab the contract addres using `awk` but for this case I have to use `sed`. | 2022/05/25 | [
"https://Stackoverflow.com/questions/72372940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8842959/"
] | You can use a [parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) to trim the string up to just before the value you want, and then another one to trim from the next whitespace.
```
tail=${output#*Contract address: } # or Contact Hash: if that's what you actually meant
address=${tail%% *}
```
Tangentially, prefer lower case for your private variables; see also [Correct Bash and shell script variable capitalization](https://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization)
`sed` does not portably support `\w` and anyway, using an external process is wasteful when the shell can do this using internal facilities entirely. Your attempt was also flawed in that you should generally [quote your variables](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) unless you specifically require the shell to perform whitespace tokenization and wildcard expansion on the value.
If indeed `$output` contains newlines which were obscured when you `echo`ed it without quoting, then you might want to use
```
tail=${output#*$'\n'Contract address: }
address=${tail%%$'\n'*}
``` | Using `sed`
```
$ address=$(sed -n '/^Contract address: \(.*\)/s//\1/p' <<< "$output")
$ echo "Address: $address"
Address: 0x0296cc83474725ddca19a9feefb3aec3602d9073688a4db6885695320cd2a738
``` |
45,929,449 | I understand that Python is an interpreted language, but the performance would be much higher if it was compiled.
* What exactly is preventing python from being compiled?
* Why was python designed as an interpreted language and not a compiled one in the first place?
Note: I know about `.pyc` files, but those are bytecode, not compiled files. | 2017/08/29 | [
"https://Stackoverflow.com/questions/45929449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8292439/"
] | Python, the language, like any programming language, is not in itself compiled or interpreted. The standard Python implementation, called CPython, compiles Python source to bytecode automatically and executes that via a virtual machine, which is not what is usually meant by "interpreted".
There are implementations of Python which compile to native code. For example, the [PyPy project](http://pypy.org) uses JIT compilation to get the benefits of CPython's ease of use combined with native code performance.
[Cython](http://cython.org) is another hybrid approach, generating and compiling C code on the fly from a dialect of Python.
However, because Python is dynamically typed, it's not generally practical to completely precompile all possible code paths, and it won't ever be as fast as mainstream statically typed languages, even if JIT-compiled. | I think python code can be compiled to some extent but we are unable to compile everything in python before hand. This is due to the loosely typed style of python where you can change variable type anywhere in the program. A modification of Python namely Rpython has much strict style and hence can be compiled completely. |
51,546,329 | My app creates different answers (radio buttons) to select based on what I have in arrays, but I can't figure out how to change the font of these answers. Usually I would just change the font in the layout.xml file, but I only have the radio group there, not the actual buttons.
Here is my code:
```
private void createRadioButton(View view) {
RadioGroup group = (RadioGroup)view.findViewById(R.id.radioGroup);
String[] answers = getResources().getStringArray(R.array.question_1_answers);
for (int i=0;i<answers.length;i++){
String answer = answers[i];
RadioButton button = new RadioButton(getActivity());
button.setText(answer);
group.addView(button);
}
}
```
I wanted to do something like this:
```
Typeface typeface = getResources().getFont(R.font.myfont);
button.setTypeface(typeface);
```
but that requires API 26 and I'm working with API 16 | 2018/07/26 | [
"https://Stackoverflow.com/questions/51546329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8156899/"
] | You can do the following:
```
update x
set d = t.d,
e = t.e,
f = t.f
from (
values
(0,0,0,0,0,0),
(0,0,1,0,0,1),
(0,0,2,0,0,8),
(1,0,2,0,555,8)
) as t(a,b,c,d,e,f)
where x.a = t.a
and x.b = t.b
and x.c = t.c
;
```
Online example: <http://rextester.com/APBVYG17890> | Personally, I recommend a completely different approach. If you created a table that allowed you to crosswalk the values, it would be re-usable, concise, and easy to maintain.
Example:
```
CREATE TABLE t (
a INT
, b INT
, c INT
, d INT
, e INT
, f INT
)
INSERT INTO t (a,b,c,d,e,f) VALUES (0,0,0,0,0,0);
INSERT INTO t (a,b,c,d,e,f) VALUES (0,0,1,0,0,1);
INSERT INTO t (a,b,c,d,e,f) VALUES (0,0,2,0,0,8);
INSERT INTO t (a,b,c,d,e,f) VALUES (1,0,2,0,555,8);
SELECT * FROM t
```
You can simply join to this table on those three values and get the value you want to for d, e, and f. |
223,347 | I feel the gdal WriteArray() is so tedious.First, `Create(file)`,then `prj`, last `WtriteArray(arr)`. Now the problem is how to write many rasters? Because it need to create file first and then write array. How to build a loop for variable `arr`? For example:
now I got some array varaibe r1, r2, r3....
```
driver=gdal.GetDriverByName('GTiff')
outfilename=['r1.tif','r2.tif','r3.tif'......]
for filename in outfilename:
outfile=os.path.join(outpath,filename)
outdataset=driver.Create(outfile,cols,rows,1,3)
geotran=data0.GetGeoTransform()
outdataset.SetGeoTransform(geotran)
proj = data.GetProjection()
outdataset.SetProjection(proj)
outband=outdataset.GetRasterBand(1)
outband.SetNoDataValue(-32768)
outband.WriteArray(r1) #how to build the loop in this line?
outband=None
outdataset=None
print('Done')
``` | 2017/01/05 | [
"https://gis.stackexchange.com/questions/223347",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/87628/"
] | [Rasterio](https://mapbox.github.io/rasterio/) is great, and @sgillies answer is the one to follow if you want a modern python solution. This answer is for the case that you want to use GDAL without the modern wrapper.
If the output images have the same dimensions and footprint, then the best idea might be to use the `CreateCopy` function of `gdal.Driver`. It will create a copy of an existing dataset and retain the geospatial information, no data value, and other metadata. This makes the inner loop only need to create a new dataset and write the array, resulting in much cleaner code.
**CreateCopy only works if the datatype and number of bands are the same in the source and destination datasets.**
```
import gdal
# ...
data0 = gdal.Open('original.tif', gdal.GA_ReadOnly)
driver = gdal.GetDriverByName('GTiff')
# process/create arrays
arrays = {'r1': np.ndarray(), 'r2': np.ndarray(), ...}
# loop through arrays
for name, arr in arrays.items():
ds = driver.CreateCopy(name + '.tif', data0)
ds.GetRasterBand(1).WriteArray(arr)
ds = None
``` | You should loop over the arrays that you have in your memory. I have done this by storing multiple arrays in a dictionary and then looped over the keyes.
for key in arrayDict:
...create rasters
...and write them with outRaster.WriteArray(key).
Or have I missed the point of the question completely. |
56,067,378 | Please note, this question is not about the correctness of this style/convention, only about the use of Boolean operators. Just wanted to mention the style to give context.
Microsoft's [C# Coding Conventions](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions#implicitly-typed-local-variables) states that implicit typing is allowed "for local variables when the type of the variable is obvious from the right side of the assignment."
In the following code:
```
bool x = X();
bool y = Y();
var z = x && y;
```
Does the Boolean operator in the declaration of `z` make its type "obvious"? In other words, is there any situation in C# where `&&` can be used with an `x` and `y` that are not Boolean, and produce a result that is not Boolean? | 2019/05/09 | [
"https://Stackoverflow.com/questions/56067378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3654488/"
] | Yes, it is possible for that to return something that is not a boolean *as long as it can be evaluated as a boolean*.
This requires you to overload the `true` and `false` operators, take this strange type:
```
public class MyStrangeType
{
public static readonly MyStrangeType Strange1 = new MyStrangeType(0);
public static readonly MyStrangeType Strange2 = new MyStrangeType(1);
private int myValue;
public int Value { get { return myValue; } }
private MyStrangeType(int value)
{
myValue = value;
}
public static bool operator true(MyStrangeType x) { return x.myValue == 1; }
public static bool operator false(MyStrangeType x) { return x.myValue != 1; }
public static MyStrangeType operator &(MyStrangeType x, MyStrangeType y)
{
return new MyStrangeType(3);
}
}
```
Now when you do something like this:
```
var result = MyStrangeType.Strange1 && MyStrangeType.Strange2;
```
`result` is **not a boolean** but a `MyStrangeType`.
[Try it out!](https://dotnetfiddle.net/JYA90f)
```
public class Program
{
public static void Main()
{
var result = MyStrangeType.Strange1 && MyStrangeType.Strange2;
Console.WriteLine(result.GetType().FullName);
}
}
```
Outputs:
>
> MyStrangeType
>
>
> | I could maybe misunderstood your question but this maybe could help to you or someone else.
There is "is" operator. You can check a veriable is a type of something.
For example;
var z = x is bool && y is bool; |
27,956,722 | I am trying to call a webjob from asp.net c# page. When I check the log it shows that it run but nothing is in the log except. It should say "Dan's Phone Number is 5551212"
```
[01/15/2015 14:29:18 > 898371: SYS INFO] Status changed to Initializing
[01/15/2015 14:29:20 > 898371: SYS INFO] Run script 'EncodeAsset.exe' with script host - 'WindowsScriptHost'
[01/15/2015 14:29:20 > 898371: SYS INFO] Status changed to Running
[01/15/2015 14:29:20 > 898371: SYS INFO] Status changed to Success
```
Here is my code:
```
public partial class Test : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = @"D:\home\site\wwwroot\app_data\jobs\triggered\EncodeAsset\EncodeAsset.exe";
myProcess.Start();
}
}
class Program
{
// Please set the following connection strings in app.config for this WebJob to run:
// AzureWebJobsDashboard and AzureWebJobsStorage
static void Main()
{
}
public static void Testing([QueueTrigger("queuejobs")]string message)
{
Console.WriteLine("Dan's Phone Number is:", message);
}
}
``` | 2015/01/15 | [
"https://Stackoverflow.com/questions/27956722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1383668/"
] | With a continuous WebJob, the idea is to trigger the function based off an Azure storage queue or blob event, not to directly invoke the function from your client code. Here, you have a `QueueTrigger` annotation, which is listening for new messages on the `queuejobs` queue. To invoke the WebJob function, you need to enqueue a string message on the same queue. To do this, you would do something like the following in your `Button1_Click` handler
(From <http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-queues>):
```
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("queuejobs");
// Create the queue if it doesn't already exist.
queue.CreateIfNotExists();
// Create a message and add it to the queue.
CloudQueueMessage message = new CloudQueueMessage("5551212");
queue.AddMessage(message);
``` | Here's a sample on MSDN which is pretty straightforward. Hope that will help you
<https://code.msdn.microsoft.com/Simple-Azure-Website-with-b4391eeb> |
4,258,623 | I am displaying a dialog with an edittext view. However, the softkeyboard will open only if the user presses inside the editview. So I tried calling an InputMethodManager with the following code.
```
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(dialogField,0);
```
The dialogField is the input field. However, when exactly am I supposed to do this? I tried it in the onStart() method of the dialog, but nothing happens. I also tried requesting the focus for the dialogField before, but that changes nothing.
I also tried this code
```
dialogField.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
public void onFocusChange (View v, boolean hasFocus)
{
if (hasFocus)
{
Main.log("here");
dialogInput.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
/*
InputMethodManager mgr =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(dialogField,0);
*/
}
}
});
```
in both versions. But no soft keyboard would like to appear. The Main.log is just a log, which shows me that the function is actually called. And yes, it is called.
I could get the keyboard with the SHOW\_FORCED flag before the dialog opens. But then it will not close on exit. And I can only do that BEFORE I show the dialog. Inside any callbacks it does not work either. | 2010/11/23 | [
"https://Stackoverflow.com/questions/4258623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/447111/"
] | Awesome question, I was trying to do that too and found a solution.
Using the dialog builder class `AlertDialog.Builder` you will have to invoke the dialog like this:
```
AlertDialog.Builder builder = new AlertDialog.Builder();
AlertDialog dialog;
builder.set...
dialog = builder.create();
dialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
```
This worked fine for me.
Note: you must `import android.view.WindowManager.LayoutParams;` for the constant value there. | Kotlin
------
Here's the tested code.
```
val dialog = AlertDialog.Builder(requireContext()).apply {
setTitle(…)
setView(editText)
setPositiveButton(…)
setNegativeButton(…)
}
val window = dialog.show().window
window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
```
Make sure you access the `window` property from `show()` method. Getting `window` from `create()` method was returning `null` for me, so the keyboard wasn't showing.
Import `AlertDialog` from `androidx.appcompat.app.AlertDialog`.
Import `WindowManager` from `android.view`. |
184,490 | We onboarded a new senior guy recently for a project manager type of role. Based on his past experience and profile/portfolio of work, he is very good. He has handled complex jobs at large orgs in the past.
During the interviews, he was not very "chatty" which is fine. He spoke in measured/considered sentences, and I assumed that was his style.
After starting working, it seems more and more that he actually has difficulties with spoken English. After a recent brainstorming session, he was expected to work on a high level deliverable (like a project plan for example) based on the items discussed in the group session. About a third of the items in his project plan were things never even spoken about in the meeting. Most of these are things that are actually *not* supposed to be part of the product. They are tangentially related (in the sense that there will be a handoff to a third party for further processing) but our product has absolutely nothing to do with it. For example, suppose our product is a product/price comparison site, the actual Action (ecommerce) happens on the ecommerce websites. So the (our) comparison product really does not need to concern itself with things like the cart, order delivery, etc.
Yet, his project plan includes timelines for working on these ecommerce features. So it is obvious that there is significant miscommunication. He hasn't yet spoken much in the couple of sessions he was on - because the project is new to him, and he was expected to mostly listen the first couple of meetings. In one on one calls however, he seems to not have understood much of what is being spoken about unless it is very very clearly laid out.
My hunch is that he was successfully handling the large orgs (including some in the US) because many things are written down clearly and there are people whose job it is to document things. Since this is a small team building new products, not everything is documented in full, and it won't be. We frequently brainstorm on new ideas and the only "notes" or "minutes" of these meetings are very brief and bullet points. Anyone who's been in the meeting, if they were paying attention and participating, will be able to make sense of these notes. These notes are shared with all participants.
Since this is a very senior guy, language training is out of the question. The problem is not the language, it is verbal realtime communication. I also doubt he will readily accept his lack of spoken communication skills. The issue hasn't yet been discussed with him.
I am unsure about letting him go because he is committed and hardworking. But he is also very senior, which means sooner than later he **will** have to take on leadership/management roles. If it were a routine project, it might have been fine. But this involves creating new things from scratch, so oral communication is crucial.
The longer he continues, the harder it will be to fire him. I am almost sure this difficulty in communication will be a long term detriment. He can be assigned a more back-office supervisory kinda role, but the optics of that might cause resentment after another new hire is brought in to do what he expected to be doing.
What are good ways of looking at this problem and addressing it? | 2022/04/29 | [
"https://workplace.stackexchange.com/questions/184490",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/111205/"
] | The first thing you should do is to have a 1:1 with this person and explain what the problem is that you've noticed. Try to do it in as least an accusatory manner as you can. Don't be like "you're not performing well because..." or something like that. Something like "I've noticed you've been having difficulties, because (XYZ reasons). Is there anything I can do to help?". Try to get to the bottom of these issues. Note that, in some cultures, it is frowned upon to admit weakness, so you may have to dig harder than you would like to get to the root of the problem, but it's something you have to do anyway. Don't accept wishy-washy (e.g. "don't worry about it, I can handle it") as an answer. Let him know you're trying to be his friend and help him resolve his issue, not trying to attack him or be discriminatory in some way.
After he tells you what his problem is, then you can determine how to address it. If it turns out to be a language barrier issue, you will have to make a decision of whether to help him overcome the challenge or not. Imo, either option is a valid one, given the resources you have. As a small company, it may be outside of your power/resources to send this person for remedial English studies, which may ultimately mean you need to terminate him. Imo this is a reasonable course of action if necessary. Being able to communicate and be communicated with in an understandable way is as core of a responsibility of an employee as any other responsibility, and being unable to perform one's responsibilities is grounds for termination.
However, before you jump the gun and assume anything, talk to the guy first and determine the source of the difficulty. Perhaps it's not what you think it is and it is something that can be dealt with in a more employment-friendly manner, so start with that. | >
> He hasn't yet spoken much in the couple of sessions he was on - because the project is new to him, and he was expected to mostly listen the first couple of meetings.
>
>
>
So you've made it clear to him that his role in the first few meetings was to listen and learn? *You're telling us you expect more from him, have you told him?*
>
> In one on one calls however, he seems to not have understood much of what is being spoken about unless it is very very clearly laid out.
>
>
>
Is he coming from a total different domain? If so, anyone would have trouble understanding what's going on for a while. It's called ramp up time for a reason. Have you talked to him about this difference yet?
>
> We frequently brainstorm on new ideas and the only "notes" or "minutes" of these meetings are very brief and bullet points. Anyone who's been in the meeting, if they were paying attention and participating, will be able to make sense of these notes.
>
>
>
Is he used to a written first culture? Is your culture a spoken first? Have you talked to him about this yet?
As part of the hiring team, you're invested in his success now. His failure to get up to speed may reflect badly on you. Just hiring someone and expecting that they understand everyone and everything in the company is non-sense.
**You are responsible to get him up to speed now.**
Talk to him more. Ask him about his preferred communication styles. Have lunch with him. Learn about his strengths. Be his friend. He clearly can get things done given the right tools. Give him the tools! |
58,736,319 | I am trying to run react-d3-tree-demo following this README.md at <https://github.com/bkrem/react-d3-tree-demo>
After following the other steps, I got stuck on the second step of trying to run the app locally. The command line returns an error: "'BROWSER' is not recognized as an internal or external command, operable program or batch file," when I try to execute "npm run dev" in the react-d3-tree-demo directory that I cloned from the same repo.
The README.md page instructs to run "npm run dev" in both the react-d3-tree and react-d3-tree-demo directories. I actually got an error when I did that command in the react-d3-tree directory where the command line said the linebreak was incorrect, but I went into the eslintrc.js file and added "'linebreak-style': 0," in the module exports which resolved the error. I've tried turning off my Avast antivirus software which was suggested on another page. Nothing has worked so far.
To reproduce my problem:
Demo:
Clone this repo: git clone <https://github.com/bkrem/react-d3-tree-demo.git>
cd react-d3-tree-demo
Run yarn or npm install OR run bash ./setup.sh and skip to Running locally
React-D3-Tree library:
Inside the react-d3-tree-demo directory, clone the library: git clone <https://github.com/bkrem/react-d3-tree.git>
Run yarn or npm install
Running locally:
Set up 2 terminal windows, one in the react-d3-tree-demo directory, the other in react-d3-tree-demo/react-d3-tree (i.e. the sub-directory into which we cloned the library itself)
Run yarn dev/npm run dev in each
Any changes made to the demo app or the library should now automatically rebuild the library and reload the app with the fresh build (via nodemon).
I expect the react app to open a page at localhost:8000 that looks like this: <https://bkrem.github.io/react-d3-tree-demo/> however, I get a message from the command line that was detailed earlier. I'm not sure why they told me to clone react-d3-tree inside the demo, I'd appreciate any explanation of that also. | 2019/11/06 | [
"https://Stackoverflow.com/questions/58736319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12322549/"
] | There are two fixes i found that works perfectly well
first one :
install cross-env (npm package)`npm install cross-env`
then you change your dev script to
>
> "electron-dev": "concurrently \"cross-env BROWSER=none yarn start\" \"wait-on <http://localhost:3000> && electron .\"",
>
>
>
please note that you also have to install concurrently if not already installed
second one :
install concurrently and run this (on windows though)
>
> "electron-dev": "concurrently \"SET BROWSER=none&&npm run start\" \"wait-on <http://localhost:3000> && electron .\""
>
>
> | i success using cross-env, so try this one:
"dev": "concurrently -k "cross-env BROWSER=none npm start" "npm:electron"",
"electron": "wait-on http://localhost:3000 && electron ." |
27,068,645 | I am trying to fade in three separate lines of text, each one delayed slightly later than the last. I have discovered how to fade a single line, and how to delay a single line, but whatever I try cannot combine the two. All the JS research is for .fadeIn('slow') for button selectors and whatever tried doesn't work with the code below . Any advice appreciated.
```
function showText(id,delay){
var elem=document.getElementById(id);
setTimeout(function(){elem.style.visibility='visible';},delay*1000)
}
window.onload = function(){
showText('delayedText1',1);
showText('delayedText2',2);
showText('delayedText3',3);
showText('delayedText4',4);
}
<h1 id="delayedText1" style="visibility:hidden">First line fades in</h1>
<h1 id="delayedText2" style="visibility:hidden">slightly later this fades in</h1>
<h1 id="delayedText3" style="visibility:hidden">and last this line fades in</h1>
```
<http://jsfiddle.net/k4h94Lob/1/> | 2014/11/21 | [
"https://Stackoverflow.com/questions/27068645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3324665/"
] | If you think you'll be doing more with animation in your project I highly recommend using [Animate.css](https://github.com/daneden/animate.css). Then how about not using JavaScript at all for the delay, and keep it real simple with some CSS?
```
<h1 id="delayedText1" class="animated fadeIn delay-1">First line fades in</h1>
<h1 id="delayedText2" class="animated fadeIn delay-2">slightly later this fades in</h1>
<h1 id="delayedText3" class="animated fadeIn delay-3">and last this line fades in</h1>
```
For example:
```
.delay-1 {
-webkit-animation-delay: 300ms;
-moz-animation-delay: none;
animation-delay: 300ms;
}
.delay-2 {
-webkit-animation-delay: 600ms;
-moz-animation-delay: none;
animation-delay: 600ms;
}
.delay-3 {
-webkit-animation-delay: 900ms;
-moz-animation-delay: none;
animation-delay: 900ms;
}
```
**[Demo JSFiddle](http://jsfiddle.net/occursys/rn4rx46y/)** | Maybe this is what you are looking for: [**DEMO**](http://jsfiddle.net/5fd5zy9r/3)
```
$(document).ready(function () {
$('h1').each(function (line) {
$(this).delay((line++) * 1000).fadeIn();
});
});
```
**UPDATE:** Note that this will work for any number of lines. You can change fade in speed and delay time. |
7,151,016 | I have the following HTML:
```
<div id="myDiv">
<table id="tbl0">
<tr id="tr0" style="display: none;">
<td>
<label id="lbl0"></label>
</td>
</tr>
<tr id="tr1" style="display: none;">
<td>
<label id="lbl1"></label>
</td>
</tr>
<tr id="tr2" style="display: none;">
<td>
<label id="lbl2"></label>
</td>
</tr>
</table>
</div>
```
And the following jquery that sets a row to visible and updates (but fails) the label tag with some text.
```
var myStr = $(this).text();
var myArr = myStr.split(',');
$.each(myArr, function (i) {
// This part works just fine
var tr = $('#myDiv').find("#tr" + i);
tr.css('display', 'inline');
// The label is found, but I can't get jquery to update the text of
// ...it no matter what I try
var lbl = tr.find("lbl" + i);
lbl.val('hello world'); // doesn't work
lbl.text('hello world'); // doesn't work
lbl.html('hello world'); // doesn't work
});
```
So what am I doing wrong here? | 2011/08/22 | [
"https://Stackoverflow.com/questions/7151016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60758/"
] | The error is in this line:
```
var lbl = tr.find("#lbl" + i);
```
You forgot # sign, since you are looking up by ID. | I stumbled upon this thread and while it helped lead me in the right direction I was able to solve a little different way once I found my label by setting the `innerHTML` property on the label element. I was using jQuery.
```
var labels = document.getElementsByClassName('someclassname');
$(labels).each(function (index, element) {
element.innerHTML = 'hello world';
});
``` |
5,656,056 | MySQL runs pretty much all string comparisons under the default collation... except the `REPLACE` command. I have a case-insensitive collation and need to run a case-insensitive `REPLACE`. Is there any way to force `REPLACE` to use the current collation rather than always doing case-sensitive comparisons? I'm willing to upgrade my MySQL (currently running 5.1) to get added functionality...
```
mysql> charset utf8 collation utf8_unicode_ci;
Charset changed
mysql> select 'abc' like '%B%';
+------------------+
| 'abc' like '%B%' |
+------------------+
| 1 |
+------------------+
mysql> select replace('aAbBcC', 'a', 'f');
+-----------------------------+
| replace('aAbBcC', 'a', 'f') |
+-----------------------------+
| fAbBcC | <--- *NOT* 'ffbBcC'
+-----------------------------+
``` | 2011/04/13 | [
"https://Stackoverflow.com/questions/5656056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290213/"
] | This modification of Luist's answer allows one to replace the needle with a differently cased version of the needle (two lines change).
```
DELIMITER |
CREATE FUNCTION case_insensitive_replace ( REPLACE_WHERE text, REPLACE_THIS text, REPLACE_WITH text )
RETURNS text
DETERMINISTIC
BEGIN
DECLARE last_occurency int DEFAULT '1';
IF LENGTH(REPLACE_THIS) < 1 THEN
RETURN REPLACE_WHERE;
END IF;
WHILE Locate( LCASE(REPLACE_THIS), LCASE(REPLACE_WHERE), last_occurency ) > 0 DO
BEGIN
SET last_occurency = Locate(LCASE(REPLACE_THIS), LCASE(REPLACE_WHERE), last_occurency);
SET REPLACE_WHERE = Insert( REPLACE_WHERE, last_occurency, LENGTH(REPLACE_THIS), REPLACE_WITH);
SET last_occurency = last_occurency + LENGTH(REPLACE_WITH);
END;
END WHILE;
RETURN REPLACE_WHERE;
END;
|
DELIMITER ;
``` | In case of 'special' characters there is unexpected behaviour:
```
SELECT case_insensitive_replace('A', 'Ã', 'a')
```
Gives
```
a
```
Which is unexpected... since we only want to replace the à not A
What is even more weird:
```
SELECT LOCATE('Ã', 'A');
```
gives
```
0
```
Which is the correct result... seems to have to do with encoding of the parameters of the stored procedure... |
41,541 | I've used Savage Worlds Plot Point campaigns for successful campaigns (i.e., multiple connected sessions with some coherence to them, where something is accomplished), but don't have any idea how to plan out my own. What do you do when you are creating a campaign (assuming you're not doing some kind of sandbox)?
I'm familiar with the 5x5 method, but I'm still not sure how to come up with the goals/objectives for that. I own "Odyssey", but it's about organizing your campaign once you have all of your ideas. Also, I'm totally open for player input, but I still need to come up with some ideas for different goals, objectives, what's going on, impending dooms, etc.
I'm planning to run a Demon the Descent (new World of Darkness, God Machine) and a Rotted Capes campaign. | 2014/06/27 | [
"https://rpg.stackexchange.com/questions/41541",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3437/"
] | There are Many Approaches
=========================
Ask any group of DMs, ever, and they will each have individual ways of making a campaign. I've listed just a few here. Other people here can and likely will post other methods.
The important part between having a string of adventures featuring recurring individuals and a campaign is the cohesiveness of it all. What you did last adventure affects *this* adventure. This can be achieved in a lot of ways.
Rule Book Guidelines
--------------------
Very, *very* often, system rulebooks come with some suggestions for plots, and what to do as a DM. It seems most of them come down to figuring out a big idea for a plot, and breaking that into individual tasks the adventurers must complete. String these tasks together, and... it's a campaign!
S. John Ross's List
-------------------
S. John Ross has a nice list of RPG plots [here](https://web.archive.org/web/20160426032929/http://www222.pair.com/sjohn/blueroom/plots.htm). While these plots are especially true of individual adventures, they can easily be broadened into a campaign. "Blackmail," "Clearing the Hex," "Don't Eat The Purple Ones," and "Pandora's Box" are all plots he lists that could be a starting point for a campaign.
Basically, you'd choose one as a very large plot, but then introduce sub-plots for individual gaming sessions which help solve the larger plot. This means what happened last session affects what happens this session. For most people, that's the key attribute of a campaign.
The Hero's Journey
------------------
It's just a theory, but [Joseph Campbell](https://en.wikipedia.org/wiki/Hero%27s_journey) came up with the idea that all (good) stories about heroes follow a certain pattern. If you modeled your campaign as a hero's journey, then your players will (most likely) feel pretty heroic and awesome when playing through it.
Some systems are better about this than others, but you could model after the Monomyth (Or Hero's Journey). Extra Credits did a good job of applying it to (video) games [here](https://youtu.be/SWKKRbw-e4U), or you could check out [TED's Hero Journey](https://www.youtube.com/watch?v=Hhk4N9A0oCA) to get a good idea of what this is.
To apply this to roleplaying, you just need to make each segment or task in the hero's journey into an adventure. How will the adventurers experience the call to action? What or who are the threshold guardians? Where and whom do they gain more power from to destroy the shadow? Who or what becomes the shadow?
The Villain's Point of View
---------------------------
Some people like constructing a campaign by simply getting into the mind of their main villain (or BBEG), and figuring out what he/she does. Since the villain creates conflict, what is their overall strategy for accomplishing their goals? Boom, there's a plot! The heroes simply need to figure out what's up with that villain, and neutralize them.
This creates a kind of back-and-forth campaign, where the adventurers do one thing, and then the villain (or her/his lackeys) responds in kind. This allows for gradual buildups in the scale or intensity of the conflict, until they face BBEG and solve it once and for all.
Use Your Character's Motivations
--------------------------------
This kinda feels like cheating sometimes, but just have people make characters, figure out what drives them, and make a campaign out of that. Do you have a kleptomaniac along with a guy who wants revenge on someone? Go steal all the hated person's earthly assets, and make an adventure out of that! Who cares about being creative when you can leverage the creativity of your players? I swear I read this (or something similar) on [the Angry DM's Blog](https://theangrygm.com/?s=Campaign+building), which is just a good resource anyways.
Steal From Other Media
----------------------
Take a plot from any film, book, or TV show you (ideally) really liked. This is more of a social no-no, especially when you get caught. It can still work really well, though, with minimal creativity on your part. Your players may love this or hate this. My players and I hate this sort of thing.
The added danger of this is that your characters may not generally react the same way as the characters in the original. Now you have a great plot that doesn't work anymore. This is why you steal the premise, not the actual entire plot.
The Conflict Approach
---------------------
Get a bunch of cool (conflicting) situations, and throw them together in the same area. This becomes kinda sandbox-y, but makes for an interesting world! This way, there is a conflict, and characters' choices matter.
For example: A dragon wants to take over a nation and cultists want to summon an undead army (maybe as defense against the dragon?). Neither of these things have super great results, but it's a conflict. A conflict your characters can solve, one which will take multiple adventures to do so.
The other variant of this is summarized as follows: unreasonable responses for unreasonable situations. Create an unreasonable situation; clan x wants to destroy clan y, the king's daughter wants to become a dragon-queen, some wizard decided to toy with What-Ought-Not-Be-Toyed-With. Follow that to the (il)logical conclusion, which the adventurers being the ones to fix it. (The adventurers give the unreasonable responses, by the way.)
A Summary
=========
Choose a conflict. One that your characters care about. Diagram how they can solve it, and what needs to be done to do so. Adventures are just these "need to be done to solve the plot" things stuck together, plus whatever else you'll throw in for fun. Link the adventures, and that's a campaign. | Layering
--------
Any plot that players have enjoyed enough to tell stories about later (my personal sign of success), involves **Layering**. I have no idea if this is the correct term for it, but i'm about to describe it, so no harm no foul.
As I use it, Layering is simply creating multiple plots, foes, plans, enemies, allies, in a vacuum and then mapping out the interactions. If you are a visual person, it can help to actually physically map out these connections, on a piece of paper. So then you end up with a scenario where the Endbringers are cooperating with the Witch Queen to destroy the Merchants of the East, hindered by the Dhai (both assassins and holy crusade of the temples versions), and helped by the Convergence of Seasons, the ancient rite that removes magic from the world piece by piece and then returns it. From a short list of things little more than names/concepts (Endbringers, Witch Queen, East India Company, Crusades, Hashishim, Convergence of the Seasons) pulled from all sorts of sources, i've created a half-believable narrative.
Then you create a setting by answering obvious questions about the setup. Why haven't these cool-sounding Endbringers and Witch Queen destroyed some random Merchants? Well, the Merchants rule over a huge area of towns and cities far away from the witch queen and endbringer's seat of power. How do they rule these cities? By money and influence indirectly, probably, or they'd be 'Kings' of the east. Why are the Endbringers and the Witch Queen cooperating? The Witch Queen is a subtle manipulator, and is manipulating the Endbringers. For that matter, who the hell are these Endbringer guys? Well, they sound powerful, and they're being manipulated by a 'Witch Queen', so... they're powerful warriors of darkness from an earlier age, with mutated bodies. And they're called 'Endbringers', so their goal is to destroy the world. So that means the actual enemy of the Merchants of the East is the Witch Queen, and the Endbringers are being used as pawns - whether they're aware of this or not. The Convergence is a time factor which brings the plans of various factions to a head. Time factors are things i've found adding to any plot structure helps handle timing issues for you explicitly, without needing to actually do it all manually and subtly. Who are these Dhai? Why are they helping the Merchants? Well, they're doing it for two different sets of religious reasons - one is seeking to destroy the Endbringers before they destroy the world (temple crusades), the other is trying to guide the Endbringers to a prophesied resolution that 'ends' the world but only so a better one can begin (assassins - it's a strong plot to have people 'allied' who aren't actually on the same team, and where possible, make traditionally evil 'bad guys' have hidden motivations for good - no-one thinks of themselves as a bad guy, everyone has a reason for what they do, although don't overuse this and say everyone is secretly altruistic, people just need reasons, even stuff like 'we're sick of being looked down on by you human scum').
So that's a **Layer**. 5 Individuals (even though 4 of them are factions), 5 Motivations, 2 Conflicts (Merchants + Dhai (temple and sect) vs Endbringers and Witch Queen, Dhai sect assassins vs Everyone). How the PCs are brought into this is the Hook, and separate from campaign building. Campaign-building is just the Grand Story - how the PCs get swept up in it, as descendents of an Endbringer, Temple Assassins, Hired Mercs, or whatever, is up to you.
Additional *metaphysical* **Layers** deal with motivations. They add secret plans or factions to existing Conflicts or Individuals. If you've got this mapped out, it would be an extra paragraph of text underneath each connection between two things. Those don't have to be reversals of existing motivations + secrecy. It can be unrelated things that will blossom into Complications. Like between the Endbringers and the Convergence, you could add 'The Enemy of the Endbringers is still alive, and is the agent of the Convergence, and doesn't want them to succeed'. Etc. Anything related to those relationships, which adds more depth to them.
Additional regular layers comprise a set of new things that are more closely related to each other than the existing things. You create their relationships, and only add relationships between them and the pre-existing stuff in the 'setting building' 'question-answering' phase. Like, a set of individuals that all know each other from childhood, all in different existing factions, would be a new regular **Layer**. A new faction and things opposing it sailing across the sea to invade the continent would be another **Layer**. Etc.
The advantage of the **Layering** system is that you can often add new layers in the middle of games if your existing plotline isn't deep or complex enough - and due to the 'setting building' portion, it won't seem 'weird' or 'out of place' - it will be tied into the existing material. And due to the new material being interlinked with itself, the players will feel like they've stumbled onto a new 'real' thing, another layer of the story or reality, rather than some random stuff the DM threw in due to panic. It links up really well when you introduce sets of linked concepts as a group rather than solitary things and link them later.
The main thing to keep in mind with this system is that you need to keep in mind what the players are going to receive in terms of information. Everything needs to be shades of grey, even if it's presented to the players in-game as black and white. Leave the possibilities of switching sides, of betrayal, of being left holding information important to people that they don't know and having to decide whether to give it to them or not, to the players. Due to all these relationships, people, factions, and secrets that interlinking stuff will create, situations for changing sides or being given damaging information or being left in the lurch etc will happen **organically**. And it's truly wonderful when it does - the stress and difficulty of running a game simply melt away, and you're left to enjoy the story that you haven't even created - you've just let it happen on it's own. |
26,375,793 | I am creating a directive in which I need three values-
1. scrollTop
2. offsetHeight
3. scrollHeight
```
projectModule.directive('scroller', function ($window) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var rawElement = angular.element($window);
angular.element($window).bind('scroll', function () {
var scrollTop = rawElement.scrollTop();
var offsetHeight = rawElement.offsetHeight;
var scrollHeight = rawElement.scrollHeight;
console.log(scrollTop + " ," + offsetHeight + " ," + scrollHeight);
scope.$apply();
});
};
});
```
I can get scrollTop directly by using rawElement.scrollTop() function, but How to get offsetHeight and scrollHeight of that element?
I want to apply that logic-
```
if ((rawElement.scrollTop + rawElement.offsetHeight + 5) >= rawElement.scrollHeight) {
scope.$apply(); //For infinite scrolling
}
```
Thanks in advance. | 2014/10/15 | [
"https://Stackoverflow.com/questions/26375793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2587478/"
] | I would try to make use of `$document` service instead, since you actually need `document.body.scrollHeight` and `document.body.offsetHeight`. So
```
var offsetHeight = $document[0].body.offsetHeight;
var scrollHeight = $document[0].body.scrollHeight;
``` | Can you use getBoundingClientRect if $el is the actual DOM element?
```
var top = $el.getBoundingClientRect().top;
```
[JSFiddle](http://jsfiddle.net/sNLMe/1/)
You could also try using
```
$el.prop('offsetTop')
``` |
40,376,627 | I'm trying to display a UIAlertView after some time (like 5 minutes after doing something in the app). I'm already notifying the user if the app is closed or in a background. But I want to display a UIAlertView while the app is running. I don't want to refresh again and again. After three minutes I have to show some alert like do you want to save or not? | 2016/11/02 | [
"https://Stackoverflow.com/questions/40376627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Use
```
self.perform(#selector(displayAlert), with: nil, afterDelay: 300)
```
where display alert is the function in which you display the alert. | I think there is an alternative best approach for UIAlertView with Custom Delay is You can schedule an local Notification with timeInterval whatever you want. |
5,485,670 | Why does this work?
```
#include <iostream>
#include <string>
using namespace std;
int main(){
string s="a";
if((s=="cm")||(s=="in")||(s=="ft")||(s=="m"))
cout<<s+" Is an illegal value";
else
cout<<"I like "+s;
return 0;
}
```
<http://ideone.com/7pnYh>
but then this doesnt
```
#include <iostream>
#include <string>
using namespace std;
int main(){
string s="a";
if((s!="cm")||(s!="in")||(s!="ft")||(s!="m"))
cout<<s+" Is an illegal value";
else
cout<<"I like "+s;
return 0;
}
```
<http://ideone.com/TXUXA>
The answer i want for both is "I like a" . | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655373/"
] | In your second case `s != "cm"` and of course the first `cout` is printed. To negate the check and the logic to remain the same, do it like this:
```
if((s!="cm")&&(s!="in")&&(s!="ft")&&(s!="m"))
cout<<"I like "+s;
else
cout<<s+" Is an illegal value";
``` | Why should the second one output "I like a"?
Every single one of your conditions in the statement in the second example is true, so it goes into the if branch. Even if only one would be true, it still would go into the if branch, because you are using OR. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.