prompt
stringlengths 48
2.37k
| chosen
stringlengths 7
4.28k
| rejected
stringlengths 11
4.44k
|
---|---|---|
Question: This is the current code which fills `skyblue` in the background:
```
var rect=d3.select("svg")
.append("rect")
.attr("width", 1250)
.attr("height", 100)
.style("fill","skyblue");
```
[Example fiddle](http://jsfiddle.net/L77g3r32/)
I want to fill a part of the rectangle(mean of the values being the split) with a different color.
We may do something like this(in html): [fiddle](http://jsfiddle.net/WQ8CG/158/)
How could I do this in d3?
Answer: | You could try to dynamically build a gradient with **"hard" stops** in the SVG's `defs` section and use this gradient on `rect` like this `fill="url(#IdOfYourGradient)"`
What I mean by **hard stops** is to define two stops for the two colors at the position of the boundary.
```
<defs>
<linearGradient id="Gradient1">
<stop class="stop1" offset="0%"/>
<stop class="stop2" offset="50%"/>
<stop class="stop3" offset="50%"/>
<stop class="stop4" offset="100%"/>
</linearGradient>
<style type="text/css"><![CDATA[
.stop1, stop2 { stop-color: red; }
.stop3, stop4 { stop-color: blue; }
]]></style>
</defs>
```
Here's more about [gradients in SVG](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Gradients). | You need to append two `rect` to have one `rect` with two color experience. Like below
```js
var rect = d3.select("svg")
.append("rect")
.attr("width", 100)
.attr("height", 100)
.style("fill", "skyblue");
var rect1 = d3.select("svg")
.append("rect")
.attr("x",100)
.attr("width", 100)
.attr("height", 100)
.style("fill", "red");
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg></svg>
```
**Update**
You need to find the width of `svg`
```
var svgWidth = d3.select("svg").node().getBoundingClientRect().width; //svg width
var rect1Width = svgWidth * 40 / 100; // 40% width of svg for rect1
```
Below is complete example
```js
var svgWidth = d3.select("svg").node().getBoundingClientRect().width;
var rect1Width = svgWidth * 40 / 100;
var rect = d3.select("svg")
.append("rect")
.attr("width", rect1Width)
.attr("height", 100)
.style("fill", "skyblue");
var rect1 = d3.select("svg")
.append("rect")
.attr("x", rect1Width)
.attr("width", svgWidth - rect1Width)
.attr("height", 100)
.style("fill", "red");
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="200" height="100"></svg>
``` |
Question: This is the current code which fills `skyblue` in the background:
```
var rect=d3.select("svg")
.append("rect")
.attr("width", 1250)
.attr("height", 100)
.style("fill","skyblue");
```
[Example fiddle](http://jsfiddle.net/L77g3r32/)
I want to fill a part of the rectangle(mean of the values being the split) with a different color.
We may do something like this(in html): [fiddle](http://jsfiddle.net/WQ8CG/158/)
How could I do this in d3?
Answer: | You need to append two `rect` to have one `rect` with two color experience. Like below
```js
var rect = d3.select("svg")
.append("rect")
.attr("width", 100)
.attr("height", 100)
.style("fill", "skyblue");
var rect1 = d3.select("svg")
.append("rect")
.attr("x",100)
.attr("width", 100)
.attr("height", 100)
.style("fill", "red");
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg></svg>
```
**Update**
You need to find the width of `svg`
```
var svgWidth = d3.select("svg").node().getBoundingClientRect().width; //svg width
var rect1Width = svgWidth * 40 / 100; // 40% width of svg for rect1
```
Below is complete example
```js
var svgWidth = d3.select("svg").node().getBoundingClientRect().width;
var rect1Width = svgWidth * 40 / 100;
var rect = d3.select("svg")
.append("rect")
.attr("width", rect1Width)
.attr("height", 100)
.style("fill", "skyblue");
var rect1 = d3.select("svg")
.append("rect")
.attr("x", rect1Width)
.attr("width", svgWidth - rect1Width)
.attr("height", 100)
.style("fill", "red");
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="200" height="100"></svg>
``` | This is what I finally used:
(This is a derivative of rmoestl's answer)
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="520" height="240" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="Gradient1">
<stop class="stop1" offset="0%"/>
<stop class="stop2" offset="60%"/>
<stop class="stop3" offset="100%"/>
</linearGradient>
<style type="text/css"><![CDATA[
#rect1 { fill: url(#Gradient1); }
.stop1 { stop-color: skyblue; }
.stop2 { stop-color: white; stop-opacity: 1; }
.stop3 { stop-color: blue; }
]]></style>
</defs>
<rect id="rect1" x="10" y="10" width="500" height="200"/>
</svg>
``` |
Question: This is the current code which fills `skyblue` in the background:
```
var rect=d3.select("svg")
.append("rect")
.attr("width", 1250)
.attr("height", 100)
.style("fill","skyblue");
```
[Example fiddle](http://jsfiddle.net/L77g3r32/)
I want to fill a part of the rectangle(mean of the values being the split) with a different color.
We may do something like this(in html): [fiddle](http://jsfiddle.net/WQ8CG/158/)
How could I do this in d3?
Answer: | You could try to dynamically build a gradient with **"hard" stops** in the SVG's `defs` section and use this gradient on `rect` like this `fill="url(#IdOfYourGradient)"`
What I mean by **hard stops** is to define two stops for the two colors at the position of the boundary.
```
<defs>
<linearGradient id="Gradient1">
<stop class="stop1" offset="0%"/>
<stop class="stop2" offset="50%"/>
<stop class="stop3" offset="50%"/>
<stop class="stop4" offset="100%"/>
</linearGradient>
<style type="text/css"><![CDATA[
.stop1, stop2 { stop-color: red; }
.stop3, stop4 { stop-color: blue; }
]]></style>
</defs>
```
Here's more about [gradients in SVG](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Gradients). | This is what I finally used:
(This is a derivative of rmoestl's answer)
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="520" height="240" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="Gradient1">
<stop class="stop1" offset="0%"/>
<stop class="stop2" offset="60%"/>
<stop class="stop3" offset="100%"/>
</linearGradient>
<style type="text/css"><![CDATA[
#rect1 { fill: url(#Gradient1); }
.stop1 { stop-color: skyblue; }
.stop2 { stop-color: white; stop-opacity: 1; }
.stop3 { stop-color: blue; }
]]></style>
</defs>
<rect id="rect1" x="10" y="10" width="500" height="200"/>
</svg>
``` |
Question: I learned that calling an Object's `wait()` method will release the object monitor, if present.
But I have some questions regarding calling `notify()` on this object by another thread:
1. (when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?
2. will the waiting thread wake up, if a 3rd thread called `wait()` on this object?
3. is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)
4. What's happening if `wait()` will be called in the `finalize()` method?
Answer: | 1. That's why you have the `notify()` and `notifyAll()` methods. The former wakes up one thread waiting on the object, the latter wakes up all threads. A waiting thread will not wake up if `wait()` is called in another thread.
2. No.
3. It's only possible to call `thread.holdsLock(obj)` to see if a thread holds the monitor lock on a particular object.
4. Don't call `wait()` in a finalize method. | 2: Not necessarily. `notify()` wakes up *one* of the waiting threads. It might be the original one or the third one.
3: Using `thread.getState()` you can find out if a thread is waiting for an object, but I don't know if you can always find out which object this is, exactly. |
Question: I learned that calling an Object's `wait()` method will release the object monitor, if present.
But I have some questions regarding calling `notify()` on this object by another thread:
1. (when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?
2. will the waiting thread wake up, if a 3rd thread called `wait()` on this object?
3. is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)
4. What's happening if `wait()` will be called in the `finalize()` method?
Answer: | 1. `notify` will wake one thread waiting on the monitor. Unless and until the monitor is unowned, no thread waiting can run; wait() must be called in a synchronized block and so the lock must be held to continue running that block.
2. No guarantees. Call `notifyAll` to give all threads a *chance* to wake.
3. Dunno. You could have the thread set a variable saying it's waiting before it goes to sleep...
4. This is probably a bad idea. Can you come up with a situation where this is necessary? | 1. That's why you have the `notify()` and `notifyAll()` methods. The former wakes up one thread waiting on the object, the latter wakes up all threads. A waiting thread will not wake up if `wait()` is called in another thread.
2. No.
3. It's only possible to call `thread.holdsLock(obj)` to see if a thread holds the monitor lock on a particular object.
4. Don't call `wait()` in a finalize method. |
Question: I learned that calling an Object's `wait()` method will release the object monitor, if present.
But I have some questions regarding calling `notify()` on this object by another thread:
1. (when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?
2. will the waiting thread wake up, if a 3rd thread called `wait()` on this object?
3. is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)
4. What's happening if `wait()` will be called in the `finalize()` method?
Answer: | 1. `notify` will wake one thread waiting on the monitor. Unless and until the monitor is unowned, no thread waiting can run; wait() must be called in a synchronized block and so the lock must be held to continue running that block.
2. No guarantees. Call `notifyAll` to give all threads a *chance* to wake.
3. Dunno. You could have the thread set a variable saying it's waiting before it goes to sleep...
4. This is probably a bad idea. Can you come up with a situation where this is necessary? | 2: Not necessarily. `notify()` wakes up *one* of the waiting threads. It might be the original one or the third one.
3: Using `thread.getState()` you can find out if a thread is waiting for an object, but I don't know if you can always find out which object this is, exactly. |
Question: I learned that calling an Object's `wait()` method will release the object monitor, if present.
But I have some questions regarding calling `notify()` on this object by another thread:
1. (when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?
2. will the waiting thread wake up, if a 3rd thread called `wait()` on this object?
3. is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)
4. What's happening if `wait()` will be called in the `finalize()` method?
Answer: | When you call wait() from a thread, that thread stop executing and it's added to the waitset of the object. When you call notify() from another thread, a random thread from the waitset is waked up, if you call notifyAll() all would be ready to execute.
When you call notify(), the thread is ready to run but it doesnt mean it will be executed inmediately so be careful.
1. It would wake up a thread from the waitset randomly.
2. Youd don't know which one will be waked up first, it doesn't follow any order.
3. Thread.getState()
4. You would produce deadlock. | 2: Not necessarily. `notify()` wakes up *one* of the waiting threads. It might be the original one or the third one.
3: Using `thread.getState()` you can find out if a thread is waiting for an object, but I don't know if you can always find out which object this is, exactly. |
Question: I learned that calling an Object's `wait()` method will release the object monitor, if present.
But I have some questions regarding calling `notify()` on this object by another thread:
1. (when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?
2. will the waiting thread wake up, if a 3rd thread called `wait()` on this object?
3. is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)
4. What's happening if `wait()` will be called in the `finalize()` method?
Answer: | 1. `notify` will wake one thread waiting on the monitor. Unless and until the monitor is unowned, no thread waiting can run; wait() must be called in a synchronized block and so the lock must be held to continue running that block.
2. No guarantees. Call `notifyAll` to give all threads a *chance* to wake.
3. Dunno. You could have the thread set a variable saying it's waiting before it goes to sleep...
4. This is probably a bad idea. Can you come up with a situation where this is necessary? | When you call wait() from a thread, that thread stop executing and it's added to the waitset of the object. When you call notify() from another thread, a random thread from the waitset is waked up, if you call notifyAll() all would be ready to execute.
When you call notify(), the thread is ready to run but it doesnt mean it will be executed inmediately so be careful.
1. It would wake up a thread from the waitset randomly.
2. Youd don't know which one will be waked up first, it doesn't follow any order.
3. Thread.getState()
4. You would produce deadlock. |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | To answer the original question about how to cherry-pick some directories (as commits instead of a brute-force checkout), this is possible. Imagine that `featureA` has diverged from `master` and you want to bring over the `tools/my-tool` commits.
>
> Assuming that you never made any commits that contain both stuff from `/tools/my-tool` and stuff from other directories
>
>
>
This will get you the list of commits to `master` in `tools/my-tool` (that are not already in `featureA`), in reverse-chronological order:
```
git log --no-merges featureA...master tools/my-tool
```
To say it another way:
```
git log --no-merges source_branch...dest_branch my/firstpath my/secondpath [...]
```
To get just the commits you need in chronological order, you need to first reverse the order of the input lines (such as with `tail -r` or `tac`), then isolate the column for the commit hash (such as with `cut`):
```
git log --format=oneline --no-merges featureA...master tools/my-tool \
| tail -r \
| cut -d " " -f 1
```
And to do the whole operation at once, do this:
```
git cherry-pick $(git log --format=oneline --no-merges featureA...master tools/my-tool | tail -r | cut -d " " -f 1)
``` | Note:
* [`git cherry-pick`](http://git-scm.com/docs/git-cherry-pick) is about applying a full commit (or commits) to another branch. There is no notion of "path".
* [`git checkout`](http://git-scm.com/docs/git-checkout) is about updating the working tree (and `HEAD` if no path is specified, effectively switching branches)
```
git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
```
>
> **When `<paths>` or `--patch` are given, `git checkout` does not switch branches**.
>
> It updates the named paths in the working tree from the index file or from a named `<tree-ish>` (most often a commit). The `<tree-ish>` argument can be used to specify a specific tree-ish (i.e. commit, tag or tree) to update the index for the given paths before updating the working tree.
>
>
>
Your `git checkout dev -- tools/my-tool` updates a specific path, but it isn't a "merge" or a "git cherry-pick". |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | Note:
* [`git cherry-pick`](http://git-scm.com/docs/git-cherry-pick) is about applying a full commit (or commits) to another branch. There is no notion of "path".
* [`git checkout`](http://git-scm.com/docs/git-checkout) is about updating the working tree (and `HEAD` if no path is specified, effectively switching branches)
```
git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
```
>
> **When `<paths>` or `--patch` are given, `git checkout` does not switch branches**.
>
> It updates the named paths in the working tree from the index file or from a named `<tree-ish>` (most often a commit). The `<tree-ish>` argument can be used to specify a specific tree-ish (i.e. commit, tag or tree) to update the index for the given paths before updating the working tree.
>
>
>
Your `git checkout dev -- tools/my-tool` updates a specific path, but it isn't a "merge" or a "git cherry-pick". | Jason Rudolph does a great job of summarising this scenario, and the accepted solution in this post:
>
> <https://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/>
>
>
>
This is a good old question, and the above answers did a great job of answering it, but since I recently came across the issue, and his article stated it so concisely I thought I'd share it here. |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | Note:
* [`git cherry-pick`](http://git-scm.com/docs/git-cherry-pick) is about applying a full commit (or commits) to another branch. There is no notion of "path".
* [`git checkout`](http://git-scm.com/docs/git-checkout) is about updating the working tree (and `HEAD` if no path is specified, effectively switching branches)
```
git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
```
>
> **When `<paths>` or `--patch` are given, `git checkout` does not switch branches**.
>
> It updates the named paths in the working tree from the index file or from a named `<tree-ish>` (most often a commit). The `<tree-ish>` argument can be used to specify a specific tree-ish (i.e. commit, tag or tree) to update the index for the given paths before updating the working tree.
>
>
>
Your `git checkout dev -- tools/my-tool` updates a specific path, but it isn't a "merge" or a "git cherry-pick". | You can use `git checkout <from_branch> -- <files_to_bring>`.
I'd do this: `git checkout dev -- tools/my-tool`
Explanation: this tells git to replace/copy files from the branch `dev` and the path `tools/my-tool` to your current branch. |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | Here is the right way to cherry-pick commits from another branch for one folder:
```
git format-patch -k --stdout master...featureA -- tools/mytool | git am -3 -k
```
This will apply the patches to the "tools/mytool" files only, in order.
If you have a merge conflict on any commit, it will pause for you to fix it. `git am --continue` will resume where it left off. | Note:
* [`git cherry-pick`](http://git-scm.com/docs/git-cherry-pick) is about applying a full commit (or commits) to another branch. There is no notion of "path".
* [`git checkout`](http://git-scm.com/docs/git-checkout) is about updating the working tree (and `HEAD` if no path is specified, effectively switching branches)
```
git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
```
>
> **When `<paths>` or `--patch` are given, `git checkout` does not switch branches**.
>
> It updates the named paths in the working tree from the index file or from a named `<tree-ish>` (most often a commit). The `<tree-ish>` argument can be used to specify a specific tree-ish (i.e. commit, tag or tree) to update the index for the given paths before updating the working tree.
>
>
>
Your `git checkout dev -- tools/my-tool` updates a specific path, but it isn't a "merge" or a "git cherry-pick". |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | To answer the original question about how to cherry-pick some directories (as commits instead of a brute-force checkout), this is possible. Imagine that `featureA` has diverged from `master` and you want to bring over the `tools/my-tool` commits.
>
> Assuming that you never made any commits that contain both stuff from `/tools/my-tool` and stuff from other directories
>
>
>
This will get you the list of commits to `master` in `tools/my-tool` (that are not already in `featureA`), in reverse-chronological order:
```
git log --no-merges featureA...master tools/my-tool
```
To say it another way:
```
git log --no-merges source_branch...dest_branch my/firstpath my/secondpath [...]
```
To get just the commits you need in chronological order, you need to first reverse the order of the input lines (such as with `tail -r` or `tac`), then isolate the column for the commit hash (such as with `cut`):
```
git log --format=oneline --no-merges featureA...master tools/my-tool \
| tail -r \
| cut -d " " -f 1
```
And to do the whole operation at once, do this:
```
git cherry-pick $(git log --format=oneline --no-merges featureA...master tools/my-tool | tail -r | cut -d " " -f 1)
``` | Jason Rudolph does a great job of summarising this scenario, and the accepted solution in this post:
>
> <https://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/>
>
>
>
This is a good old question, and the above answers did a great job of answering it, but since I recently came across the issue, and his article stated it so concisely I thought I'd share it here. |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | To answer the original question about how to cherry-pick some directories (as commits instead of a brute-force checkout), this is possible. Imagine that `featureA` has diverged from `master` and you want to bring over the `tools/my-tool` commits.
>
> Assuming that you never made any commits that contain both stuff from `/tools/my-tool` and stuff from other directories
>
>
>
This will get you the list of commits to `master` in `tools/my-tool` (that are not already in `featureA`), in reverse-chronological order:
```
git log --no-merges featureA...master tools/my-tool
```
To say it another way:
```
git log --no-merges source_branch...dest_branch my/firstpath my/secondpath [...]
```
To get just the commits you need in chronological order, you need to first reverse the order of the input lines (such as with `tail -r` or `tac`), then isolate the column for the commit hash (such as with `cut`):
```
git log --format=oneline --no-merges featureA...master tools/my-tool \
| tail -r \
| cut -d " " -f 1
```
And to do the whole operation at once, do this:
```
git cherry-pick $(git log --format=oneline --no-merges featureA...master tools/my-tool | tail -r | cut -d " " -f 1)
``` | You can use `git checkout <from_branch> -- <files_to_bring>`.
I'd do this: `git checkout dev -- tools/my-tool`
Explanation: this tells git to replace/copy files from the branch `dev` and the path `tools/my-tool` to your current branch. |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | You can use `git checkout <from_branch> -- <files_to_bring>`.
I'd do this: `git checkout dev -- tools/my-tool`
Explanation: this tells git to replace/copy files from the branch `dev` and the path `tools/my-tool` to your current branch. | Jason Rudolph does a great job of summarising this scenario, and the accepted solution in this post:
>
> <https://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/>
>
>
>
This is a good old question, and the above answers did a great job of answering it, but since I recently came across the issue, and his article stated it so concisely I thought I'd share it here. |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | Here is the right way to cherry-pick commits from another branch for one folder:
```
git format-patch -k --stdout master...featureA -- tools/mytool | git am -3 -k
```
This will apply the patches to the "tools/mytool" files only, in order.
If you have a merge conflict on any commit, it will pause for you to fix it. `git am --continue` will resume where it left off. | Jason Rudolph does a great job of summarising this scenario, and the accepted solution in this post:
>
> <https://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/>
>
>
>
This is a good old question, and the above answers did a great job of answering it, but since I recently came across the issue, and his article stated it so concisely I thought I'd share it here. |
Question: I've seen different posts on StackOverflow that explain cherry picking a bit, but the comments in their code aren't very specific as to what's a branch and what's a directory. Example `git checkout A -- X Y` doesn't tell me much.
Basically I want this:
* Create new branch `featureA` off of `master`
* Merge directory `/tools/my-tool` from branch `dev` into `featureA`
Answer: | Here is the right way to cherry-pick commits from another branch for one folder:
```
git format-patch -k --stdout master...featureA -- tools/mytool | git am -3 -k
```
This will apply the patches to the "tools/mytool" files only, in order.
If you have a merge conflict on any commit, it will pause for you to fix it. `git am --continue` will resume where it left off. | You can use `git checkout <from_branch> -- <files_to_bring>`.
I'd do this: `git checkout dev -- tools/my-tool`
Explanation: this tells git to replace/copy files from the branch `dev` and the path `tools/my-tool` to your current branch. |
Question: I am working on a webapp and I want to put borders around floating divs which I call faux columns for lack of a better description. I know this is very very basic but for some reason - incompetence maybe - I cannot get this to work
The procedure:
I float two divs left and right. These divs are nested in another div which I want to put a border around.
The code:
```
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>StackOvervlow</title>
<style type="text/css" media="screen">
body {
width: 900px;
}
#wrapper {
border: 2px solid gray;
}
#container {
width: 600px;
float: left;
background-color:#678;
}
#sidebar {
width: 200px;
float: right;
background-color: bisque;
}
#footer {
clear: both;
text-align: center;
}
</style>
</head>
<body>
<div id="header"></div>
<div id="wrapper">
<div id="container">
<p>Placeholder Text.</p>
<p>Placeholder Text.</p>
</div>
<div id="sidebar">
<p>Placeholder Text.</p>
</div>
</div>
<div id="footer">
<p>Some footer stuffs</p>
</div>
</body>
</html>
```
[The outcome...](http://individual.utoronto.ca/igbanam/test.html)
Please explain why the border shows up as a line and does not go around the two enclosed divs as expected. If you could suggest ways to fix this, I'll appreciate that.
Thank you.
Answer: | Simply add:
```
overflow: hidden;
```
to the CSS for `#wrapper`, demo at: [JS Fiddle](http://jsfiddle.net/pPPYR/).
The reason the border collapses to a line is because the floated elements are removed from the document's flow, which means that they essentially occupy no space within their parent element, which, with no contents, collapses. The `overflow: hidden;` causes the parent element to wrap around its children. Though, to be honest, I don't particularly understand *why* that happens.
It's worth having a read of [CSS Floats 101, at A List Apart](http://www.alistapart.com/articles/css-floats-101/) for a refresher/primer on CSS floats, though, for pointers on their behaviour. | When you float the element, it does not take up space the same way as it does when it is inline.
The solution is to put a block level element that has clear both attribute at the bottom:
`<div style='clear:both;'></div>`
See detail here: <http://jsfiddle.net/billymoon/eDqg5/> |
Question: im working with oracle database 11g release 2, and im using apache commons dbutils v1.6, with JDK 8 and tomcat 8.0.30. so im using the QueryRunner and its method and everything works fine if i just concat my variables in text like this
```
query.query ("select * from table where field = '"+value+"'", rsh);
```
lately i have been trying to do the query the proper way using prepared statements but to no avail, every time i bind parameters using the query method
```
query.query ("select ESTREC,LOTE,FECREC from prueba.RECAUDO_ENC where NITREC = ? and ESTREC = ? ORDER BY FECREC DESC", rsh, new Object[]{"1234","PG"});
```
i get this error for no aparent reason
```
java.sql.SQLException: ORA-00942: table or view does not exist
Query: select ESTREC,LOTE,FECREC from prueba.RECAUDO_ENC where NITREC = ? and ESTREC = ? ORDER BY FECREC DESC; Parameters: [1234, PG]
```
im a 100% sure that the table exists, and user has permissions to the table , also if i do the same query concatenating the params in the query it runs just fine, so im looking for reasons behind this behaviour, is there something wrong in the usage of the method?.
also i have read somewhere that there is some problem with BLOB binding using dbutils with oracle, could this be related in someway?
Answer: | Correct query syntax for oracle is:
```
query.query ("select ESTREC,LOTE,FECREC
from prueba.RECAUDO_ENC
where NITREC = :P1 and ESTREC = :P2
ORDER BY FECREC DESC",
rsh, new Object[]{"1234","PG"});
``` | I got the same error with yours.
I think you must be careful the version of jdbc driver.
In my case, I solved the problem changing proper jdbc dirver for me.
I misused the jdbc driver.
I guess you have a jdbc driver version 12 or higher.
Check the version of jdbc driver first in the MANIFEST.MF.
It has following lines
```
....
Implementation-Version: 11.2.0.4.0
....
```
Otherwise, you should have another one for you.
good luck |
Question: im working with oracle database 11g release 2, and im using apache commons dbutils v1.6, with JDK 8 and tomcat 8.0.30. so im using the QueryRunner and its method and everything works fine if i just concat my variables in text like this
```
query.query ("select * from table where field = '"+value+"'", rsh);
```
lately i have been trying to do the query the proper way using prepared statements but to no avail, every time i bind parameters using the query method
```
query.query ("select ESTREC,LOTE,FECREC from prueba.RECAUDO_ENC where NITREC = ? and ESTREC = ? ORDER BY FECREC DESC", rsh, new Object[]{"1234","PG"});
```
i get this error for no aparent reason
```
java.sql.SQLException: ORA-00942: table or view does not exist
Query: select ESTREC,LOTE,FECREC from prueba.RECAUDO_ENC where NITREC = ? and ESTREC = ? ORDER BY FECREC DESC; Parameters: [1234, PG]
```
im a 100% sure that the table exists, and user has permissions to the table , also if i do the same query concatenating the params in the query it runs just fine, so im looking for reasons behind this behaviour, is there something wrong in the usage of the method?.
also i have read somewhere that there is some problem with BLOB binding using dbutils with oracle, could this be related in someway?
Answer: | Correct query syntax for oracle is:
```
query.query ("select ESTREC,LOTE,FECREC
from prueba.RECAUDO_ENC
where NITREC = :P1 and ESTREC = :P2
ORDER BY FECREC DESC",
rsh, new Object[]{"1234","PG"});
``` | This error almost turned us crazy. We don't understand why the solution works but here it is. Just double quote and scape all the columns in the SQL sentence:
```
String sqlStr = "SELECT \"ESTREC\",\"LOTE\",\"FECREC\" " +
"FROM prueba.RECAUDO_ENC " +
"WHERE \"NITREC\" = ? and \"ESTREC\" = ?" +
"ORDER BY \"FECREC\" DESC"
query.query(sqlStr, rsh, new Object[]{"1234","PG"});
```
The funny thing is that we found this error when we added a new constraint to a SELECT sentence. With only one parameter the query would work correctly, but would fail with more than one query param (?). |
Question: im working with oracle database 11g release 2, and im using apache commons dbutils v1.6, with JDK 8 and tomcat 8.0.30. so im using the QueryRunner and its method and everything works fine if i just concat my variables in text like this
```
query.query ("select * from table where field = '"+value+"'", rsh);
```
lately i have been trying to do the query the proper way using prepared statements but to no avail, every time i bind parameters using the query method
```
query.query ("select ESTREC,LOTE,FECREC from prueba.RECAUDO_ENC where NITREC = ? and ESTREC = ? ORDER BY FECREC DESC", rsh, new Object[]{"1234","PG"});
```
i get this error for no aparent reason
```
java.sql.SQLException: ORA-00942: table or view does not exist
Query: select ESTREC,LOTE,FECREC from prueba.RECAUDO_ENC where NITREC = ? and ESTREC = ? ORDER BY FECREC DESC; Parameters: [1234, PG]
```
im a 100% sure that the table exists, and user has permissions to the table , also if i do the same query concatenating the params in the query it runs just fine, so im looking for reasons behind this behaviour, is there something wrong in the usage of the method?.
also i have read somewhere that there is some problem with BLOB binding using dbutils with oracle, could this be related in someway?
Answer: | This error almost turned us crazy. We don't understand why the solution works but here it is. Just double quote and scape all the columns in the SQL sentence:
```
String sqlStr = "SELECT \"ESTREC\",\"LOTE\",\"FECREC\" " +
"FROM prueba.RECAUDO_ENC " +
"WHERE \"NITREC\" = ? and \"ESTREC\" = ?" +
"ORDER BY \"FECREC\" DESC"
query.query(sqlStr, rsh, new Object[]{"1234","PG"});
```
The funny thing is that we found this error when we added a new constraint to a SELECT sentence. With only one parameter the query would work correctly, but would fail with more than one query param (?). | I got the same error with yours.
I think you must be careful the version of jdbc driver.
In my case, I solved the problem changing proper jdbc dirver for me.
I misused the jdbc driver.
I guess you have a jdbc driver version 12 or higher.
Check the version of jdbc driver first in the MANIFEST.MF.
It has following lines
```
....
Implementation-Version: 11.2.0.4.0
....
```
Otherwise, you should have another one for you.
good luck |
Question: What is the practical way to identify the factors that create variation in a data of a dataset? What category does this question fall into? Are there a set of algorithms that can be used for this purpose? Statistical modeling solutions? I googled a lot but no go! The question is so vague that hard to find an answer for! Thanks in advance ...
Answer: | For fitting continuous distributions (like exponential) try to use `fitdistr()` from package MASS (see `?fitdistr` or the [Ricci's paper](http://cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf) as DWin pointed out). It uses maximum likelihood parameter estimation.
You should probably ask at stats.stackexchange.com. | <http://cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf> |
Question: What is the practical way to identify the factors that create variation in a data of a dataset? What category does this question fall into? Are there a set of algorithms that can be used for this purpose? Statistical modeling solutions? I googled a lot but no go! The question is so vague that hard to find an answer for! Thanks in advance ...
Answer: | I would recommend using the `fitdistrplus` package, which has better support for maximum likelihood estimation. Read the [vignette](http://cran.r-project.org/web/packages/fitdistrplus/vignettes/intro2fitdistrplus.pdf) for more details on how to go about estimating any distribution. Here is an example using a weibull distribution.
```
# LOAD LIBRARIES
library(fitdistrplus);
library(ggplot2);
# GENERATE DUMMY DATA
x1 = rweibull(100, shape = 0.5, scale = 1);
# ESTIMATE WEIBULL DISTRIBUTION
f1 = fitdist(x1, 'weibull', method = 'mle');
# PLOT HISTOGRAM AND DENSITIES
p0 = qplot(x1[x1 > 0.1], geom = 'blank') +
geom_line(aes(y = ..density.., colour = 'Empirical'), stat = 'density') +
geom_histogram(aes(y = ..density..), fill = 'gray90', colour = 'gray40') +
geom_line(stat = 'function', fun = dweibull,
args = as.list(f1$estimate), aes(colour = 'Weibull')) +
scale_colour_manual(name = 'Density', values = c('red', 'blue')) +
opts(legend.position = c(0.85, 0.85))
```
![enter image description here](https://i.stack.imgur.com/CbMbZ.png) | <http://cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf> |
Question: What is the practical way to identify the factors that create variation in a data of a dataset? What category does this question fall into? Are there a set of algorithms that can be used for this purpose? Statistical modeling solutions? I googled a lot but no go! The question is so vague that hard to find an answer for! Thanks in advance ...
Answer: | <http://cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf> | It is true that most statistical software package come with function implementing the stuff for you however, I always find it useful to understand how the black box works.
So in the case of the MLE for the power law (easy to derive), the best $\alpha$ estimate is
$\hat \alpha = 1+ n\left(\sum\_{i=0}^n\ln{x\_i/x\_{min}}\right)^{-1}$ where $x\_{min}$ is the smallest observation you have and $n$ the number of observations.
You can then plot
$y=\frac{1-\hat\alpha}{x\_{min}}\left(\frac{x}{x\_{min}}\right)^{-\hat\alpha}$ |
Question: What is the practical way to identify the factors that create variation in a data of a dataset? What category does this question fall into? Are there a set of algorithms that can be used for this purpose? Statistical modeling solutions? I googled a lot but no go! The question is so vague that hard to find an answer for! Thanks in advance ...
Answer: | For fitting continuous distributions (like exponential) try to use `fitdistr()` from package MASS (see `?fitdistr` or the [Ricci's paper](http://cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf) as DWin pointed out). It uses maximum likelihood parameter estimation.
You should probably ask at stats.stackexchange.com. | It is true that most statistical software package come with function implementing the stuff for you however, I always find it useful to understand how the black box works.
So in the case of the MLE for the power law (easy to derive), the best $\alpha$ estimate is
$\hat \alpha = 1+ n\left(\sum\_{i=0}^n\ln{x\_i/x\_{min}}\right)^{-1}$ where $x\_{min}$ is the smallest observation you have and $n$ the number of observations.
You can then plot
$y=\frac{1-\hat\alpha}{x\_{min}}\left(\frac{x}{x\_{min}}\right)^{-\hat\alpha}$ |
Question: What is the practical way to identify the factors that create variation in a data of a dataset? What category does this question fall into? Are there a set of algorithms that can be used for this purpose? Statistical modeling solutions? I googled a lot but no go! The question is so vague that hard to find an answer for! Thanks in advance ...
Answer: | I would recommend using the `fitdistrplus` package, which has better support for maximum likelihood estimation. Read the [vignette](http://cran.r-project.org/web/packages/fitdistrplus/vignettes/intro2fitdistrplus.pdf) for more details on how to go about estimating any distribution. Here is an example using a weibull distribution.
```
# LOAD LIBRARIES
library(fitdistrplus);
library(ggplot2);
# GENERATE DUMMY DATA
x1 = rweibull(100, shape = 0.5, scale = 1);
# ESTIMATE WEIBULL DISTRIBUTION
f1 = fitdist(x1, 'weibull', method = 'mle');
# PLOT HISTOGRAM AND DENSITIES
p0 = qplot(x1[x1 > 0.1], geom = 'blank') +
geom_line(aes(y = ..density.., colour = 'Empirical'), stat = 'density') +
geom_histogram(aes(y = ..density..), fill = 'gray90', colour = 'gray40') +
geom_line(stat = 'function', fun = dweibull,
args = as.list(f1$estimate), aes(colour = 'Weibull')) +
scale_colour_manual(name = 'Density', values = c('red', 'blue')) +
opts(legend.position = c(0.85, 0.85))
```
![enter image description here](https://i.stack.imgur.com/CbMbZ.png) | It is true that most statistical software package come with function implementing the stuff for you however, I always find it useful to understand how the black box works.
So in the case of the MLE for the power law (easy to derive), the best $\alpha$ estimate is
$\hat \alpha = 1+ n\left(\sum\_{i=0}^n\ln{x\_i/x\_{min}}\right)^{-1}$ where $x\_{min}$ is the smallest observation you have and $n$ the number of observations.
You can then plot
$y=\frac{1-\hat\alpha}{x\_{min}}\left(\frac{x}{x\_{min}}\right)^{-\hat\alpha}$ |
Question: It seems that no matter what I do, I cannot get my two computers to work together and join the same Homegroup.
The computers in question:
* Desktop with Win7 Ultimate x64 connected via Wireless Connection
* Netbook with Win7 Home Pro (32 bit) connected via Wireless Connection
Other items:
* Both show the same network connection, connected through the same wireless router (Linksys WRT310N)
* Both are set to Home Network in Windows
* I can see both machines browsing through the Network Viewer in Windows Explorer
* Disabling the firewall on both machines has no effect on the Homegroup Feature
* Both are using the fully patched RTM version of Windows 7
Does anyone have any ideas? Is there anything else I can test with? Everything I read seems to imply that I should be good to go. Is this a 64bit issue?
What really bothers me is that this would be such a handy feature to have working since the netbook doesn't store much, and the desktop has all of my music/pic/docs etc.
Answer: | The registry key is loated in `HKEY_CURRENT_USER\Control Panel\Mouse\MouseSensitivity` but modifying this through AutoHotkey alone usually doesn't work. The best way is to use a DLL call:
```
^+u::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,20, Int,2) ;high sensitivity
^+d::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,5, Int,2) ;low sensitivity
^+n::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,10, Int,2) ;normal sensisivity
```
`Ctrl` + `Shift` + `u` sets sensitivity to high, `Ctrl` + `Shift` + `d` sets it low, and `Ctrl` + `Shift` + `n` sets it back to default. Edit this script to your hearts content.
But, what you **could** use the registry for is querying the current value, so you can increment the speed by 1 like so:
```
^+u::
RegRead, MyVar, HKEY_CURRENT_USER, Control Panel\Mouse,MouseSensitivity
if (MyVar == 20)
{
MsgBox Value is already at max
Exit, 0
}
DllCall("SystemParametersInfo", Int,113, Int,0, UInt,%MyVar%+1, Int,2)
return
``` | See if this [AutoHotKey forum](http://www.autohotkey.com/forum/) thread helps you: [**Adjusting Mouse Sensitivity via hotkey**](http://www.autohotkey.com/forum/topic14795.html) |
Question: It seems that no matter what I do, I cannot get my two computers to work together and join the same Homegroup.
The computers in question:
* Desktop with Win7 Ultimate x64 connected via Wireless Connection
* Netbook with Win7 Home Pro (32 bit) connected via Wireless Connection
Other items:
* Both show the same network connection, connected through the same wireless router (Linksys WRT310N)
* Both are set to Home Network in Windows
* I can see both machines browsing through the Network Viewer in Windows Explorer
* Disabling the firewall on both machines has no effect on the Homegroup Feature
* Both are using the fully patched RTM version of Windows 7
Does anyone have any ideas? Is there anything else I can test with? Everything I read seems to imply that I should be good to go. Is this a 64bit issue?
What really bothers me is that this would be such a handy feature to have working since the netbook doesn't store much, and the desktop has all of my music/pic/docs etc.
Answer: | See if this [AutoHotKey forum](http://www.autohotkey.com/forum/) thread helps you: [**Adjusting Mouse Sensitivity via hotkey**](http://www.autohotkey.com/forum/topic14795.html) | For me Eithermouse works the best.
It automatically switches settings when using a specific device. This way the speed settings get automatically adjusted.
You also get a tray icon in the bottom of the screen where you can fine-tune the speed of the device currently in use.
<http://www.eithermouse.com/>
From their website
```
Multiple mice, individual settings!
Instantly changes settings when any mouse is used:
swap buttons
mirror cursor
adjust speeds
and more...
Leave multiple mice on a pc and automatically swap buttons on each mouse
Have a left-handed and a right-handed mouse always connected and ready to use
Great for multi-user/public workstations to accomodate both left and right handed users.
Possibly helps with RSI/injury issues by allowing switching between left and right hand.
Easily swap mouse buttons from system tray if only one mouse is used
Tray icon points to active mouse
Freeware! no ads, no nags, free software, suggestions appreciated!
```
Also see my answer here:
<https://superuser.com/a/738986/313841> |
Question: It seems that no matter what I do, I cannot get my two computers to work together and join the same Homegroup.
The computers in question:
* Desktop with Win7 Ultimate x64 connected via Wireless Connection
* Netbook with Win7 Home Pro (32 bit) connected via Wireless Connection
Other items:
* Both show the same network connection, connected through the same wireless router (Linksys WRT310N)
* Both are set to Home Network in Windows
* I can see both machines browsing through the Network Viewer in Windows Explorer
* Disabling the firewall on both machines has no effect on the Homegroup Feature
* Both are using the fully patched RTM version of Windows 7
Does anyone have any ideas? Is there anything else I can test with? Everything I read seems to imply that I should be good to go. Is this a 64bit issue?
What really bothers me is that this would be such a handy feature to have working since the netbook doesn't store much, and the desktop has all of my music/pic/docs etc.
Answer: | The registry key is loated in `HKEY_CURRENT_USER\Control Panel\Mouse\MouseSensitivity` but modifying this through AutoHotkey alone usually doesn't work. The best way is to use a DLL call:
```
^+u::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,20, Int,2) ;high sensitivity
^+d::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,5, Int,2) ;low sensitivity
^+n::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,10, Int,2) ;normal sensisivity
```
`Ctrl` + `Shift` + `u` sets sensitivity to high, `Ctrl` + `Shift` + `d` sets it low, and `Ctrl` + `Shift` + `n` sets it back to default. Edit this script to your hearts content.
But, what you **could** use the registry for is querying the current value, so you can increment the speed by 1 like so:
```
^+u::
RegRead, MyVar, HKEY_CURRENT_USER, Control Panel\Mouse,MouseSensitivity
if (MyVar == 20)
{
MsgBox Value is already at max
Exit, 0
}
DllCall("SystemParametersInfo", Int,113, Int,0, UInt,%MyVar%+1, Int,2)
return
``` | For me Eithermouse works the best.
It automatically switches settings when using a specific device. This way the speed settings get automatically adjusted.
You also get a tray icon in the bottom of the screen where you can fine-tune the speed of the device currently in use.
<http://www.eithermouse.com/>
From their website
```
Multiple mice, individual settings!
Instantly changes settings when any mouse is used:
swap buttons
mirror cursor
adjust speeds
and more...
Leave multiple mice on a pc and automatically swap buttons on each mouse
Have a left-handed and a right-handed mouse always connected and ready to use
Great for multi-user/public workstations to accomodate both left and right handed users.
Possibly helps with RSI/injury issues by allowing switching between left and right hand.
Easily swap mouse buttons from system tray if only one mouse is used
Tray icon points to active mouse
Freeware! no ads, no nags, free software, suggestions appreciated!
```
Also see my answer here:
<https://superuser.com/a/738986/313841> |
Question: I am running this code and
```
char[] str = { 'a', 'b', 'c', 0, 'c', 'c', 'f' };
System.out.print(str);
System.out.println(" adksjfhak");
```
This prints just "abc".
while,
```
char[] str = { 'a', 'b', 'c', 0, 'c', 'c', 'f' };
System.out.print(str);
System.out.println("\n adksjfhak");
```
prints
```
abc
adksjfhak
```
Why does print buffer stop at null (0) character? Does this mean Java just keeps appending character to buffer and prints that buffer? And of course, since that buffer has 0 in between, it discards rest of the string.
Probably I have answered part of my own question. But I would like to know more details about this. Hows JVM handles this? Where is this output buffer? And Any reason to stop at 0? ALso why adding \n stops this behaviour?
Edit 1: Using JDK 1.7, Eclipse 3.8.1 and Ubuntu 13.10
Edit 2: Strangely, this one does not have that problem. <https://ideone.com/VwFbRr>
Edit 3: I ran the same on command line
```
[bin]$ java com.sakura.C
abcccf adksjfhak
```
Answer: | The behaviour you are seeing *cannot* be explained by looking just at the Java code. Rather, I suspect that it is something to do with what you are using to look at the output.
First this:
```
char[] str = { 'a', 'b', 'c', 0, 'c', 'c', 'f' };
System.out.print(str);
```
According to the PrintWriter javadoc,
```
System.out.print(str);
```
would be equivalent to calling
```
System.out.print(str[i]);
```
for each character. (Yes each one, including the zero character!). And the behaviour of `write(char)` to to just encode the character according to the default platform encoding, and write it. For a Zero character (codepoint zero) and a typical 7 or 8 bit charset, that is going to write the `NUL` character.
There is no funky "zero means of end of string" stuff on the Java side with standard Java strings of standard Java I/O classes. Period.
I can think of 3 possible explanations:
1. You are mistaken. Your actual code is writing something different. (For example, you might have forgotten to recompile ... if you are doing your testing from the command line.)
2. The strange behaviour you are seeing is happening because your console and/or the utility you are using to display the output is doing something "special" with NUL characters. (However, I don't recall hearing of a console, etc program that handled NUL in this strange way ...)
3. Your application has created a custom subtype of `PrintWriter` that implements some special handling for codepoint zero, and it has used `System.setOut(...)` to redirect the output via that class.
---
Having said that, it is probably a bad idea to try to print strings or character arrays that contain zero / NUL characters. The NUL character is a "control code" and is generally classed as not printable. What you will see when you try to print it is ... unpredictable.
If you want to pursue this further, I suggest that you redirect the suspect output to a file, and then use some (OS specific) utility to view the bytes of the file; e.g. `od` on a Unix / Linux system. I would expect to see the zero bytes in the file ... | Most likely, all of it is getting "printed" to the operating system in both cases, but in the first case, your operating system or shell takes the '0' character as a signal not to display the rest of the line. In the first case, both strings appear on the same line so the second string gets suppressed too. In the second case, the second string is on a new line and so gets displayed. |
Question: In other words, I'm looking for the equivalent of Python's [datetime.utcnow()](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow).
I'm also fine with a n-tuple containing years, months and so on, up until milliseconds (or microseconds).
I had thought of using `show` and then parsing the `String` value, but I believe there's something more convenient.
Answer: | Re-parsing a string is very un-Haskellish, you certainly don't want that.
I'd use, from [`Data.Time.LocalTime`](http://hackage.haskell.org/packages/archive/time/1.4.0.1/doc/html/Data-Time-LocalTime.html#g:2),
```
todSec . localTimeOfDay . utcToLocalTime utc :: UTCTime -> Data.Fixed.Pico
```
that gives you seconds in picosecond-resolution. | Seconds and milliseconds since when? Presumably there is an epoch (time zero) hiding somewhere here. You subtract the epoch from the UTCTime to get a NominalDiffTime, and then extract the seconds and milliseconds from that.
```
secondsSince :: UTCTime -> UTCTime -> (Integer, Int)
secondsSince t0 t1 = (i, round $ d * 1000)
where (i, d) = properFraction $ diffUTCTime t1 t0
```
Of course you probably want t0 to be 1/1/1970 (the Unix epoch), in which case you import [Data.Time.Clock.POSIX](https://www.stackage.org/haddock/lts-8.5/time-1.6.0.1/Data-Time-Clock-POSIX.html) and use utcTimeToPOSIXSeconds, which returns a NominalDiffTime.
NominalDiffTime is an instance of (amongst other things) Fractional and Num, so you have access to all the usual numeric operators when manipulating them. From an arithmetical point of view (including conversions) it is treated as a number of seconds.
When using this, do bear in mind that Unix gets time fundamentally wrong because it doesn't have any room for leap seconds. Every few years there is a day with 86401 seconds instead of the usual 86400. Back in the 70s the idea of a computer needing to know about this would have seemed absurd (clocks were generally set by the sysadmin consulting his mechanical watch), so the Unix time\_t simply counts seconds since the epoch and assumes that every day has exactly 86400 seconds. NominalDiffTime is "nominal" because it makes the same assumption.
The Right Thing would have been to make time\_t a struct with a day number and seconds since midnight as separate fields, and have the time arithmetic functions consult a table of leap seconds. However that would have its own set of disadvantages because new leap seconds get designated every so often, so a program could give different results when run at different times. Or to put it in Haskell terms, "diffUTCTime" would have to return a result in the IO monad. |
Question: I work on a website where there are many tables on each pages. I want to add a scroll bar at the top. I search and found this: <http://jsfiddle.net/simo/67xSL/>
Now, I try to adapt it so that each table gets it's own scroll bar.
This is what I have done so far:
```
jQuery( document ).ready(function(index) {
var base ='thescroll wpt'
var thediv ='thedivfix thediv'
var counter=0;
var theclass= base+counter;
var theinnerdiv = thediv+counter;
jQuery('table.tablepress').each(function(){
jQuery( "table.tablepress" ).before('<div class="'+theclass+'"><div class="'+theinnerdiv+'"></div></div>');
jQuery(theclass).on('scroll', function (e) {
jQuery(theinnerdiv).scrollLeft(jQuery(theclass).scrollLeft());
});
jQuery(theinnerdiv).on('scroll', function (e) {
jQuery(theclass).scrollLeft(jQuery(theinnerdiv).scrollLeft());
});
jQuery(window).on('load', function (e) {
jQuery(theinnerdiv).width(jQuery('table.tablepress').width());
});
})
```
});
Actually, the counter stays at 0 and many scroll bar appear instead of only one for each table. How could I fix that?
Answer: | As suggested by @RanSch, you can crop the image using **clip** attribute.
```
.imgClass{
clip:rect(top,right,bottom,0px);
margin-top: //someValue or
vertical-align: middle; //or
top: //someValue or
}
``` | use
```
.crop img{top:50%; left:50%;}
```
OR USE-
```
.crop img{vertical-align:middle;}
``` |
Question: I work on a website where there are many tables on each pages. I want to add a scroll bar at the top. I search and found this: <http://jsfiddle.net/simo/67xSL/>
Now, I try to adapt it so that each table gets it's own scroll bar.
This is what I have done so far:
```
jQuery( document ).ready(function(index) {
var base ='thescroll wpt'
var thediv ='thedivfix thediv'
var counter=0;
var theclass= base+counter;
var theinnerdiv = thediv+counter;
jQuery('table.tablepress').each(function(){
jQuery( "table.tablepress" ).before('<div class="'+theclass+'"><div class="'+theinnerdiv+'"></div></div>');
jQuery(theclass).on('scroll', function (e) {
jQuery(theinnerdiv).scrollLeft(jQuery(theclass).scrollLeft());
});
jQuery(theinnerdiv).on('scroll', function (e) {
jQuery(theclass).scrollLeft(jQuery(theinnerdiv).scrollLeft());
});
jQuery(window).on('load', function (e) {
jQuery(theinnerdiv).width(jQuery('table.tablepress').width());
});
})
```
});
Actually, the counter stays at 0 and many scroll bar appear instead of only one for each table. How could I fix that?
Answer: | /\* Just gonna leave this here.. \*/
```
.crop {
position: relative;
overflow: hidden;
height: 180px;
margin: 8px;
}
.crop img {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
``` | use
```
.crop img{top:50%; left:50%;}
```
OR USE-
```
.crop img{vertical-align:middle;}
``` |
Question: I work on a website where there are many tables on each pages. I want to add a scroll bar at the top. I search and found this: <http://jsfiddle.net/simo/67xSL/>
Now, I try to adapt it so that each table gets it's own scroll bar.
This is what I have done so far:
```
jQuery( document ).ready(function(index) {
var base ='thescroll wpt'
var thediv ='thedivfix thediv'
var counter=0;
var theclass= base+counter;
var theinnerdiv = thediv+counter;
jQuery('table.tablepress').each(function(){
jQuery( "table.tablepress" ).before('<div class="'+theclass+'"><div class="'+theinnerdiv+'"></div></div>');
jQuery(theclass).on('scroll', function (e) {
jQuery(theinnerdiv).scrollLeft(jQuery(theclass).scrollLeft());
});
jQuery(theinnerdiv).on('scroll', function (e) {
jQuery(theclass).scrollLeft(jQuery(theinnerdiv).scrollLeft());
});
jQuery(window).on('load', function (e) {
jQuery(theinnerdiv).width(jQuery('table.tablepress').width());
});
})
```
});
Actually, the counter stays at 0 and many scroll bar appear instead of only one for each table. How could I fix that?
Answer: | Use these classes :
```css
.center-crop-img {
object-fit: none; /* Do not scale the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-cover {
object-fit: cover; /* cover image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-contain {
object-fit: contain; /* contain the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-scale-down {
object-fit: scale-down; /* scale-down the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
``` | use
```
.crop img{top:50%; left:50%;}
```
OR USE-
```
.crop img{vertical-align:middle;}
``` |
Question: I work on a website where there are many tables on each pages. I want to add a scroll bar at the top. I search and found this: <http://jsfiddle.net/simo/67xSL/>
Now, I try to adapt it so that each table gets it's own scroll bar.
This is what I have done so far:
```
jQuery( document ).ready(function(index) {
var base ='thescroll wpt'
var thediv ='thedivfix thediv'
var counter=0;
var theclass= base+counter;
var theinnerdiv = thediv+counter;
jQuery('table.tablepress').each(function(){
jQuery( "table.tablepress" ).before('<div class="'+theclass+'"><div class="'+theinnerdiv+'"></div></div>');
jQuery(theclass).on('scroll', function (e) {
jQuery(theinnerdiv).scrollLeft(jQuery(theclass).scrollLeft());
});
jQuery(theinnerdiv).on('scroll', function (e) {
jQuery(theclass).scrollLeft(jQuery(theinnerdiv).scrollLeft());
});
jQuery(window).on('load', function (e) {
jQuery(theinnerdiv).width(jQuery('table.tablepress').width());
});
})
```
});
Actually, the counter stays at 0 and many scroll bar appear instead of only one for each table. How could I fix that?
Answer: | /\* Just gonna leave this here.. \*/
```
.crop {
position: relative;
overflow: hidden;
height: 180px;
margin: 8px;
}
.crop img {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
``` | As suggested by @RanSch, you can crop the image using **clip** attribute.
```
.imgClass{
clip:rect(top,right,bottom,0px);
margin-top: //someValue or
vertical-align: middle; //or
top: //someValue or
}
``` |
Question: I work on a website where there are many tables on each pages. I want to add a scroll bar at the top. I search and found this: <http://jsfiddle.net/simo/67xSL/>
Now, I try to adapt it so that each table gets it's own scroll bar.
This is what I have done so far:
```
jQuery( document ).ready(function(index) {
var base ='thescroll wpt'
var thediv ='thedivfix thediv'
var counter=0;
var theclass= base+counter;
var theinnerdiv = thediv+counter;
jQuery('table.tablepress').each(function(){
jQuery( "table.tablepress" ).before('<div class="'+theclass+'"><div class="'+theinnerdiv+'"></div></div>');
jQuery(theclass).on('scroll', function (e) {
jQuery(theinnerdiv).scrollLeft(jQuery(theclass).scrollLeft());
});
jQuery(theinnerdiv).on('scroll', function (e) {
jQuery(theclass).scrollLeft(jQuery(theinnerdiv).scrollLeft());
});
jQuery(window).on('load', function (e) {
jQuery(theinnerdiv).width(jQuery('table.tablepress').width());
});
})
```
});
Actually, the counter stays at 0 and many scroll bar appear instead of only one for each table. How could I fix that?
Answer: | Use these classes :
```css
.center-crop-img {
object-fit: none; /* Do not scale the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-cover {
object-fit: cover; /* cover image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-contain {
object-fit: contain; /* contain the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-scale-down {
object-fit: scale-down; /* scale-down the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
``` | As suggested by @RanSch, you can crop the image using **clip** attribute.
```
.imgClass{
clip:rect(top,right,bottom,0px);
margin-top: //someValue or
vertical-align: middle; //or
top: //someValue or
}
``` |
Question: I work on a website where there are many tables on each pages. I want to add a scroll bar at the top. I search and found this: <http://jsfiddle.net/simo/67xSL/>
Now, I try to adapt it so that each table gets it's own scroll bar.
This is what I have done so far:
```
jQuery( document ).ready(function(index) {
var base ='thescroll wpt'
var thediv ='thedivfix thediv'
var counter=0;
var theclass= base+counter;
var theinnerdiv = thediv+counter;
jQuery('table.tablepress').each(function(){
jQuery( "table.tablepress" ).before('<div class="'+theclass+'"><div class="'+theinnerdiv+'"></div></div>');
jQuery(theclass).on('scroll', function (e) {
jQuery(theinnerdiv).scrollLeft(jQuery(theclass).scrollLeft());
});
jQuery(theinnerdiv).on('scroll', function (e) {
jQuery(theclass).scrollLeft(jQuery(theinnerdiv).scrollLeft());
});
jQuery(window).on('load', function (e) {
jQuery(theinnerdiv).width(jQuery('table.tablepress').width());
});
})
```
});
Actually, the counter stays at 0 and many scroll bar appear instead of only one for each table. How could I fix that?
Answer: | /\* Just gonna leave this here.. \*/
```
.crop {
position: relative;
overflow: hidden;
height: 180px;
margin: 8px;
}
.crop img {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
``` | Use these classes :
```css
.center-crop-img {
object-fit: none; /* Do not scale the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-cover {
object-fit: cover; /* cover image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-contain {
object-fit: contain; /* contain the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
.center-crop-img-scale-down {
object-fit: scale-down; /* scale-down the image */
object-position: center; /* Center the image within the element */
width: 100%;
}
``` |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | you were in the right direction by using trim(). However, you put it in the wrong place.
`",".trim()` will always yield `","`. you want to trim the result of the substring operation:
```
String state = location.substring(location.indexOf(",") + 1).trim();
``` | try using `java.lang.String` [trim()](https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim%28%29) function in the correct place.
trim on `",".trim()` will produce `","`.
Need to `trim()` the final result.
```
if (location.contains(",")) {
String city = location.substring(0, location.indexOf(",")).trim();
String state = location.substring(location.indexOf(",")).trim();
}
``` |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | >
> How can I fix this, so that even if a user puts in 2 or 4 spaces after
> the comma it still shows the same results as the first case?
>
>
>
you can use `location.replaceAll(" ", "")`
for extracting the location into `city,state`
you can use `split()` method as
`String location[]=location.split(",");`
Now
```
String city=location[0];
String state=location[1];
```
**EDIT:(for Whome)**
```
String location="New York, NY";
String loc[]=location.split(",");
String city=loc[0].trim();
String state=loc[1].trim();
System.out.println("City->"+city+"\nState->"+state);
``` | try using `java.lang.String` [trim()](https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim%28%29) function in the correct place.
trim on `",".trim()` will produce `","`.
Need to `trim()` the final result.
```
if (location.contains(",")) {
String city = location.substring(0, location.indexOf(",")).trim();
String state = location.substring(location.indexOf(",")).trim();
}
``` |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | try using `java.lang.String` [trim()](https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim%28%29) function in the correct place.
trim on `",".trim()` will produce `","`.
Need to `trim()` the final result.
```
if (location.contains(",")) {
String city = location.substring(0, location.indexOf(",")).trim();
String state = location.substring(location.indexOf(",")).trim();
}
``` | Use
```
String state = location.substring(location.indexOf(",") + 1).trim();
```
Instead of
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
That should work. |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | you were in the right direction by using trim(). However, you put it in the wrong place.
`",".trim()` will always yield `","`. you want to trim the result of the substring operation:
```
String state = location.substring(location.indexOf(",") + 1).trim();
``` | Trim the entire result. For example:
```
String city = (location.substring(0, location.indexOf(","))).trim();
String state = (location.substring(location.indexOf(",") + 1)).trim();
``` |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | >
> How can I fix this, so that even if a user puts in 2 or 4 spaces after
> the comma it still shows the same results as the first case?
>
>
>
you can use `location.replaceAll(" ", "")`
for extracting the location into `city,state`
you can use `split()` method as
`String location[]=location.split(",");`
Now
```
String city=location[0];
String state=location[1];
```
**EDIT:(for Whome)**
```
String location="New York, NY";
String loc[]=location.split(",");
String city=loc[0].trim();
String state=loc[1].trim();
System.out.println("City->"+city+"\nState->"+state);
``` | you were in the right direction by using trim(). However, you put it in the wrong place.
`",".trim()` will always yield `","`. you want to trim the result of the substring operation:
```
String state = location.substring(location.indexOf(",") + 1).trim();
``` |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | you were in the right direction by using trim(). However, you put it in the wrong place.
`",".trim()` will always yield `","`. you want to trim the result of the substring operation:
```
String state = location.substring(location.indexOf(",") + 1).trim();
``` | Use
```
String state = location.substring(location.indexOf(",") + 1).trim();
```
Instead of
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
That should work. |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | >
> How can I fix this, so that even if a user puts in 2 or 4 spaces after
> the comma it still shows the same results as the first case?
>
>
>
you can use `location.replaceAll(" ", "")`
for extracting the location into `city,state`
you can use `split()` method as
`String location[]=location.split(",");`
Now
```
String city=location[0];
String state=location[1];
```
**EDIT:(for Whome)**
```
String location="New York, NY";
String loc[]=location.split(",");
String city=loc[0].trim();
String state=loc[1].trim();
System.out.println("City->"+city+"\nState->"+state);
``` | Trim the entire result. For example:
```
String city = (location.substring(0, location.indexOf(","))).trim();
String state = (location.substring(location.indexOf(",") + 1)).trim();
``` |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | Trim the entire result. For example:
```
String city = (location.substring(0, location.indexOf(","))).trim();
String state = (location.substring(location.indexOf(",") + 1)).trim();
``` | Use
```
String state = location.substring(location.indexOf(",") + 1).trim();
```
Instead of
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
That should work. |
Question: I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in **Chicago,IL**, everything works, but if they type in **Chicago, IL**, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
```
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
```
I have also tried this:
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
Answer: | >
> How can I fix this, so that even if a user puts in 2 or 4 spaces after
> the comma it still shows the same results as the first case?
>
>
>
you can use `location.replaceAll(" ", "")`
for extracting the location into `city,state`
you can use `split()` method as
`String location[]=location.split(",");`
Now
```
String city=location[0];
String state=location[1];
```
**EDIT:(for Whome)**
```
String location="New York, NY";
String loc[]=location.split(",");
String city=loc[0].trim();
String state=loc[1].trim();
System.out.println("City->"+city+"\nState->"+state);
``` | Use
```
String state = location.substring(location.indexOf(",") + 1).trim();
```
Instead of
```
String state = location.substring(location.indexOf(",".trim()) + 1);
```
That should work. |
Question: In python pandas I have create a dataframe with one value for each year and two subclasses - i.e., one metric for a parameter triplet
```
import pandas, requests, numpy
import matplotlib.pyplot as plt
df
Metric Tag_1 Tag_2 year
0 5770832 FOOBAR1 name1 2008
1 7526436 FOOBAR1 xyz 2008
2 33972652 FOOBAR1 name1 2009
3 17491416 FOOBAR1 xyz 2009
...
16 6602920 baznar2 name1 2008
17 6608 baznar2 xyz 2008
...
30 142102944 baznar2 name1 2015
31 0 baznar2 xyz 2015
```
I would like to produce a bar plot with metrics as y-values over x=(year,Tag\_1,Tag\_2) and sorting primarily for years and secondly for tag\_1 and color the bars depending on tag\_1. Something like
```
(2008,FOOBAR,name1) --> 5770832 *RED*
(2008,baznar2,name1) --> 6602920 *BLUE*
(2008,FOOBAR,xyz) --> 7526436 *RED*
(2008,baznar2,xyz) --> ... *BLUE*
(2008,FOOBAR,name1) --> ... *RED*
```
I tried starting with a grouping of columns like
```
df.plot.bar(x=['year','tag_1','tag_2']
```
but have not found a way to separate selections into two bar sets next to each other.
Answer: | If you need this for Continuous deployment purposes, and you are using git repo, than it's very simple, just follow instructions here [Continuous deployment using GIT in Azure App Service](https://azure.microsoft.com/en-us/documentation/articles/web-sites-publish-source-control/).
But, in general, it's not directly related to angular2. Try also this [Using Windows PowerShell scripts to publish to dev and test environments](https://azure.microsoft.com/en-us/documentation/articles/vs-azure-tools-publishing-using-powershell-scripts/) capabilities.
angular-cli, which is (or will became) main tool for angular building, testing, deploying, at this time do not have such function, nor requirement (as i know so far). You can request feature on [their github](https://github.com/angular/angular-cli/issues). | To achieve deploying angular application on azure webapps using bitbucket, create **bitbucket-pipelines.yml** in root directory. Create environment variables for FTP access for your webapps slot (environment variables are referred using $ in script below).
Enable the pipelines from Bitbucket settings.
That's it. Whenever you check-in the code in specific branch ( master branch in script below), it will deploy the application to azure webapps slot using FTP.
```
# registry for your build environment.
image: node:8.9.0
pipelines:
branches:
master:
- step:
script: # Modify the commands below to build your repository.
- npm install -g @angular/cli
- npm install
- ng build --prod
- apt-get update # Now run the FTP bash script to deploy dist folder to UAT
- apt-get install ncftp
- ncftpput -v -u "$FTP_USERNAME" -p $FTP_PASSWORD -R $FTP_HOST $FTP_SITE_ROOT dist/ROOT
- echo Finished uploading files to $FTP_HOST$FTP_SITE_ROOT
``` |
Question: In python pandas I have create a dataframe with one value for each year and two subclasses - i.e., one metric for a parameter triplet
```
import pandas, requests, numpy
import matplotlib.pyplot as plt
df
Metric Tag_1 Tag_2 year
0 5770832 FOOBAR1 name1 2008
1 7526436 FOOBAR1 xyz 2008
2 33972652 FOOBAR1 name1 2009
3 17491416 FOOBAR1 xyz 2009
...
16 6602920 baznar2 name1 2008
17 6608 baznar2 xyz 2008
...
30 142102944 baznar2 name1 2015
31 0 baznar2 xyz 2015
```
I would like to produce a bar plot with metrics as y-values over x=(year,Tag\_1,Tag\_2) and sorting primarily for years and secondly for tag\_1 and color the bars depending on tag\_1. Something like
```
(2008,FOOBAR,name1) --> 5770832 *RED*
(2008,baznar2,name1) --> 6602920 *BLUE*
(2008,FOOBAR,xyz) --> 7526436 *RED*
(2008,baznar2,xyz) --> ... *BLUE*
(2008,FOOBAR,name1) --> ... *RED*
```
I tried starting with a grouping of columns like
```
df.plot.bar(x=['year','tag_1','tag_2']
```
but have not found a way to separate selections into two bar sets next to each other.
Answer: | I know this is a bit late but none of the other answers give
explicit instructions. Hopefully this can help someone.
I'm assuming you are using Angular-CLI.
Run:
npm install
ng build (depending on your setup you might be able to run npm build)
This creates a folder called ./dist that contains the necessary files for your working website. Then use a script-able FTP client to push all of the content inside of ./dist to the ./site/wwwroot folder of the Azure webapp.
You'll need to use the FTP credentials of the wabapp, as found in the Publish Profile, from your Azure Portal.
This Stackoverflow question will hep you with that.
[Where is "download publish profile" in the new Azure Portal?](https://stackoverflow.com/questions/34191234/where-is-download-publish-profile-in-the-new-azure-portal/34191267) | To achieve deploying angular application on azure webapps using bitbucket, create **bitbucket-pipelines.yml** in root directory. Create environment variables for FTP access for your webapps slot (environment variables are referred using $ in script below).
Enable the pipelines from Bitbucket settings.
That's it. Whenever you check-in the code in specific branch ( master branch in script below), it will deploy the application to azure webapps slot using FTP.
```
# registry for your build environment.
image: node:8.9.0
pipelines:
branches:
master:
- step:
script: # Modify the commands below to build your repository.
- npm install -g @angular/cli
- npm install
- ng build --prod
- apt-get update # Now run the FTP bash script to deploy dist folder to UAT
- apt-get install ncftp
- ncftpput -v -u "$FTP_USERNAME" -p $FTP_PASSWORD -R $FTP_HOST $FTP_SITE_ROOT dist/ROOT
- echo Finished uploading files to $FTP_HOST$FTP_SITE_ROOT
``` |
Question: In python pandas I have create a dataframe with one value for each year and two subclasses - i.e., one metric for a parameter triplet
```
import pandas, requests, numpy
import matplotlib.pyplot as plt
df
Metric Tag_1 Tag_2 year
0 5770832 FOOBAR1 name1 2008
1 7526436 FOOBAR1 xyz 2008
2 33972652 FOOBAR1 name1 2009
3 17491416 FOOBAR1 xyz 2009
...
16 6602920 baznar2 name1 2008
17 6608 baznar2 xyz 2008
...
30 142102944 baznar2 name1 2015
31 0 baznar2 xyz 2015
```
I would like to produce a bar plot with metrics as y-values over x=(year,Tag\_1,Tag\_2) and sorting primarily for years and secondly for tag\_1 and color the bars depending on tag\_1. Something like
```
(2008,FOOBAR,name1) --> 5770832 *RED*
(2008,baznar2,name1) --> 6602920 *BLUE*
(2008,FOOBAR,xyz) --> 7526436 *RED*
(2008,baznar2,xyz) --> ... *BLUE*
(2008,FOOBAR,name1) --> ... *RED*
```
I tried starting with a grouping of columns like
```
df.plot.bar(x=['year','tag_1','tag_2']
```
but have not found a way to separate selections into two bar sets next to each other.
Answer: | I managed to do it successfully without actually doing too much. Here are the steps :
1. I used GitHub as my source control. So, after taking a build of my Angular 4 project with the command `ng build` on the VS Code terminal, I pushed the entire `dist` folder (which is generated in the project directory/folder after you run `ng build`) also to GitHub. If somehow the IDE can't detect the `dist` folder as `changes`, you can also manually upload the folder into your GitHub repository. Use the Drag & Drop feature to upload the entire folder.
2. Now get a new **`App Service`** created in your Azure Subscription.
3. Go to **`Deployment Options`** and choose `GitHub`, provide credentials, and give the name of the `repository` you'd be using.
[![enter image description here](https://i.stack.imgur.com/KsqNu.png)](https://i.stack.imgur.com/KsqNu.png)
4. Go to **`Application Settings`** ,then to **`Virtual Applications and Directories`**, and change the root directory to `site\wwwroot\dist`
[![enter image description here](https://i.stack.imgur.com/FWUgr.png)](https://i.stack.imgur.com/FWUgr.png)
5. Now everything is set. Go back to **`Deployment Options`** again, and you shall see that a **`Build`** is in progress. After updating the code at GitHub repository through check-in, you could just Sync in order to take a fresh build. (P.S : In my case, the new build was automatically triggered after a new check-in to GitHub)
6. Bingo! Now you can access your website on azure. :D | To achieve deploying angular application on azure webapps using bitbucket, create **bitbucket-pipelines.yml** in root directory. Create environment variables for FTP access for your webapps slot (environment variables are referred using $ in script below).
Enable the pipelines from Bitbucket settings.
That's it. Whenever you check-in the code in specific branch ( master branch in script below), it will deploy the application to azure webapps slot using FTP.
```
# registry for your build environment.
image: node:8.9.0
pipelines:
branches:
master:
- step:
script: # Modify the commands below to build your repository.
- npm install -g @angular/cli
- npm install
- ng build --prod
- apt-get update # Now run the FTP bash script to deploy dist folder to UAT
- apt-get install ncftp
- ncftpput -v -u "$FTP_USERNAME" -p $FTP_PASSWORD -R $FTP_HOST $FTP_SITE_ROOT dist/ROOT
- echo Finished uploading files to $FTP_HOST$FTP_SITE_ROOT
``` |
Question: I have a C# code like this:
```
using System;
delegate int anto(int x);
class Anto
{
static void Main()
{
anto a = square;
int result = a(3);
Console.WriteLine(result);
}
static int square(int x)
{
return x*x;
}
}
```
which output's : `9`. Well I'm a novice in C#, so I started to play around with this code and so when I remove the `static` keyword from the `square` method, then I'm getting error like this:
```
An object reference is required to access non-static member `Anto.square(int)'
Compilation failed: 1 error(s), 0 warnings
```
what causes this error? So if I use `delegates` I need the method to be `static`?
I run this code [here](http://ideone.com/9Y81q)
Thanks in advance.
Answer: | Because `Main` is static, it can only reference other static members. If you remove `static` from `square`, it becomes an instance member, and in the `static` context of `Main`, there is no instance of any object, so instance members aren't 'valid'.
Thankfully there's nothing crazy going on with delegates, it's just the way `static` works - it indicates members are global to a type and not an instance of that type. | It doesn't *need* to be static. You can assign a non-static method to a delegate, but if it is non-static then you need to instatiate an object of type `Anto`:
```
Anto anto = new Anto();
anto a = anto.square;
```
It's rather pointless here though since the method doesn't access any of the instance members. It makes more sense that it is static. |
Question: I have a C# code like this:
```
using System;
delegate int anto(int x);
class Anto
{
static void Main()
{
anto a = square;
int result = a(3);
Console.WriteLine(result);
}
static int square(int x)
{
return x*x;
}
}
```
which output's : `9`. Well I'm a novice in C#, so I started to play around with this code and so when I remove the `static` keyword from the `square` method, then I'm getting error like this:
```
An object reference is required to access non-static member `Anto.square(int)'
Compilation failed: 1 error(s), 0 warnings
```
what causes this error? So if I use `delegates` I need the method to be `static`?
I run this code [here](http://ideone.com/9Y81q)
Thanks in advance.
Answer: | Because `Main` is static, it can only reference other static members. If you remove `static` from `square`, it becomes an instance member, and in the `static` context of `Main`, there is no instance of any object, so instance members aren't 'valid'.
Thankfully there's nothing crazy going on with delegates, it's just the way `static` works - it indicates members are global to a type and not an instance of that type. | It's required to be static because it's used in a static method. You'd need an instance of `Anto` to make your example work.
```
var myAnto = new Anto();
anto a = myAnto.square;
```
This is untested and may not compile based on the protection level of `Anto.square`. |
Question: I have a C# code like this:
```
using System;
delegate int anto(int x);
class Anto
{
static void Main()
{
anto a = square;
int result = a(3);
Console.WriteLine(result);
}
static int square(int x)
{
return x*x;
}
}
```
which output's : `9`. Well I'm a novice in C#, so I started to play around with this code and so when I remove the `static` keyword from the `square` method, then I'm getting error like this:
```
An object reference is required to access non-static member `Anto.square(int)'
Compilation failed: 1 error(s), 0 warnings
```
what causes this error? So if I use `delegates` I need the method to be `static`?
I run this code [here](http://ideone.com/9Y81q)
Thanks in advance.
Answer: | Because `Main` is static, it can only reference other static members. If you remove `static` from `square`, it becomes an instance member, and in the `static` context of `Main`, there is no instance of any object, so instance members aren't 'valid'.
Thankfully there's nothing crazy going on with delegates, it's just the way `static` works - it indicates members are global to a type and not an instance of that type. | Static methods may be called from before creating an instance, you must be a static method.
Can be written as follows, if necessary
```
anto a = (x)=>x*x ;
``` |
Question: I have a C# code like this:
```
using System;
delegate int anto(int x);
class Anto
{
static void Main()
{
anto a = square;
int result = a(3);
Console.WriteLine(result);
}
static int square(int x)
{
return x*x;
}
}
```
which output's : `9`. Well I'm a novice in C#, so I started to play around with this code and so when I remove the `static` keyword from the `square` method, then I'm getting error like this:
```
An object reference is required to access non-static member `Anto.square(int)'
Compilation failed: 1 error(s), 0 warnings
```
what causes this error? So if I use `delegates` I need the method to be `static`?
I run this code [here](http://ideone.com/9Y81q)
Thanks in advance.
Answer: | It doesn't *need* to be static. You can assign a non-static method to a delegate, but if it is non-static then you need to instatiate an object of type `Anto`:
```
Anto anto = new Anto();
anto a = anto.square;
```
It's rather pointless here though since the method doesn't access any of the instance members. It makes more sense that it is static. | Static methods may be called from before creating an instance, you must be a static method.
Can be written as follows, if necessary
```
anto a = (x)=>x*x ;
``` |
Question: I have a C# code like this:
```
using System;
delegate int anto(int x);
class Anto
{
static void Main()
{
anto a = square;
int result = a(3);
Console.WriteLine(result);
}
static int square(int x)
{
return x*x;
}
}
```
which output's : `9`. Well I'm a novice in C#, so I started to play around with this code and so when I remove the `static` keyword from the `square` method, then I'm getting error like this:
```
An object reference is required to access non-static member `Anto.square(int)'
Compilation failed: 1 error(s), 0 warnings
```
what causes this error? So if I use `delegates` I need the method to be `static`?
I run this code [here](http://ideone.com/9Y81q)
Thanks in advance.
Answer: | It's required to be static because it's used in a static method. You'd need an instance of `Anto` to make your example work.
```
var myAnto = new Anto();
anto a = myAnto.square;
```
This is untested and may not compile based on the protection level of `Anto.square`. | Static methods may be called from before creating an instance, you must be a static method.
Can be written as follows, if necessary
```
anto a = (x)=>x*x ;
``` |
Question: I am trying to get a background image to display in the bottom right corner of a div (or asp:panel) but I believe that the display:inline-block is causing it to not show. That is required because I have multiple boxes horizontally aligned on the screen (without it they display vertically).
css:
```
.showIcon{
background: url('Images/icon.png') no-repeat right bottom;
display: inline-block;
box-shadow: 2px 2px 2px #808080;
}
```
Is there something wrong with the css?
I do have a table displayed within each div, can that be the reason?
Answer: | There is no problem with your code. And also as you asked, no table won't make any difference.
See this fiddle with your code: <http://jsfiddle.net/3V8m9/2/>
The only thing I added is the dimensions: `height: 100px; width: 100px;` to illustrate.
There can be two scenarios. One, either your image path is not correct. Two, width/height may not be adequate enough. | If you believe display:inline-block is the issue. You can always use float left to align each against each other.
**CSS**
```
.showIcon{
background: url('Images/icon.png') no-repeat right bottom;
float: left;
box-shadow: 2px 2px 2px #808080;
} code here
``` |
Question: I have a php file **verify.php** in a folder called **emailtest** on localhost. I'm implementing an email verification script. But i'm having issues with the activation url that is emailed after registration. Take a look:
```
define("BASE_PATH", dirname('http://localhost:8888/'))
$url = BASE_PATH . '/emailtest'.'/verify.php?email=' . urlencode($email) . "&key=$encode";
```
In the email sent, i'm getting a link that looks like this(which is unopenable):
```
`"http:/emailtest/verify.php?email=lexon4ril%40yahoo.com&key=58a9a..."`
```
But what i really want is this
```
`http:localhost:8888/emailtest/verify.php?email=lexon4ril%40yahoo.com&key=58a9a...`
```
How can i properly set the url.?
**UPDATE**
Just for future reference i mistyped the link, should be:
```
`http://localhost:8888//emailtest/verify.php?email=lexon4ril%40yahoo.com&key=58a9a...`
```
Answer: | Try `define("BASE_PATH", "http://localhost:8888")` - I don't think you need to use `dirname()` function. | Well, this works for me and this is dynamic too.
```
$url = $_SERVER['HTTP_HOST']. '/emailtest'.'/verify.php?email=' . urlencode($email) . "&key=$encode";
```
Made use of the global `SERVER`.
Hope this works for you. |
Question: Often times I want to do something like
```js
const styles = StyleSheet.create({
square: (size: number) => ({
width: size,
height: size,
}),
})
```
Now this doesn't work, because I get `Type '(size: number) => { width: number; height: number; }' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'`. I've tried doing things like
```js
interface Style {
square: (width: number) => ViewStyle
}
const styles = StyleSheet.create<Style>({
square: (size: number) => ({
width: size,
height: size,
}),
})
```
But then I get `Type 'Style' does not satisfy the constraint 'NamedStyles<any> | NamedStyles<Style>'.`
Any ideas how to deal with this?
Answer: | the above issue was due to the repo url on which i was trying to push the `git tag`.
The issue was fixed by adding `.git` extension in the repo url, the example is given below:
```
git remote set-url origin https://$USER_NAME:$GITLAB_TOKEN@${CI_PROJECT_URL:8}.git
``` | In my related work, we used slightly different approach.
```
create-git-tag:
image: alpine/git
stage: tagging
script:
- git config user.email "${GITLAB_USER_EMAIL}"
- git config user.name "${GITLAB_USER_NAME}"
- git remote add tag-origin https://oauth2:${GITLAB_ACCESS_TOKEN}@gitlab.com/${CI_PROJECT_PATH}
- git tag -a "dev-1.0.1" -m "Dev Tag Created Automatically"
- git push tag-origin "dev-1.0.1"
- echo "Git Tag created successfully"
rules:
- if: '$CI_COMMIT_TAG == null'
```
Above job runs automatically as part of **tagging** stage. It won't run when a GIT Tag is raised, otherwise it will go in infinite loop as the job itself is creating the Git Tag.
This is just an example to show the git tagging using the oauth url of GitLab.
GITLAB\_ACCESS\_TOKEN is variable defined in Settings -> CI/CD -> Variables and value is the GitLab Toke (Created separately from Profile -> Access Token)
You can also use Project Access Token (better approach than using personal token.
<https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html#bot-users-for-projects> |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | Instead of loading a gigantic log file in an editor, I'm using Unix command line tools like `grep`, `tail`, `gawk`, etc. to filter the interesting parts into a much smaller file and then, I open that.
On Windows, try [Cygwin](http://www.cygwin.com/). | Have you tried [context editor](http://www.contexteditor.org/)? It is small and fast. |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | [Tweak](http://www.chiark.greenend.org.uk/~sgtatham/tweak/) is a hex editor which can handle edits to very large files, including inserts and deletes. | [Emacs](http://www.gnu.org/software/emacs/) can handle [huge file sizes](http://www.freelists.org/archives/glug_t/03-2005/msg00032.html) and you can use it on Windows or \*nix. |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | Sorry to post on such an old thread, but I tried several of the tips here, and none of them worked for me.
It's slightly different than a text editor, but I found that Beyond Compare could handle an extremely large (3.6 Gig) file on my Vista 32-bit machine.
This is a file that that Emacs, Large Text File Viewer, HexEdit, and Notepad++ all choked on.
-Eric | For windows, unix, or Mac? On the Mac or \*nix you can use command line or GUI versions of emacs or vim.
For the Mac: TextWrangler to handle big files well. I'm not versed enough on the Windows landscape to help out there. |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | My favourite after trying a few to read a 6GB mysqldump file:
**PilotEdit Lite** <http://www.pilotedit.com/>
Because:
* Memory usage has (somehow?!) never gone above 25MB, so basically no impact on the rest of my system - though it took several minutes to open.
* There was an accurate progress bar during that time so I knew how it was getting on.
* Once open, simple searching, and browsing through the file all worked as well as a small notepad file.
* It's free.
Others I tried...
**EmEditor Pro** trial was very impressive, the file opened almost instantly, but unfortunately too expensive for my requirements.
**EditPad Pro** loaded the whole 6GB file into memory and slowed everything to a crawl. | [Emacs](http://www.gnu.org/software/emacs/) can handle [huge file sizes](http://www.freelists.org/archives/glug_t/03-2005/msg00032.html) and you can use it on Windows or \*nix. |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | My favourite after trying a few to read a 6GB mysqldump file:
**PilotEdit Lite** <http://www.pilotedit.com/>
Because:
* Memory usage has (somehow?!) never gone above 25MB, so basically no impact on the rest of my system - though it took several minutes to open.
* There was an accurate progress bar during that time so I knew how it was getting on.
* Once open, simple searching, and browsing through the file all worked as well as a small notepad file.
* It's free.
Others I tried...
**EmEditor Pro** trial was very impressive, the file opened almost instantly, but unfortunately too expensive for my requirements.
**EditPad Pro** loaded the whole 6GB file into memory and slowed everything to a crawl. | I have had problems with TextPad on 4G files too. Notepad++ works nicely. |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | glogg could also be considered, for a different usage:
![glogg screenshot](https://i.stack.imgur.com/2GUaT.png)
Caveat (reported by [Simon Tewsi](https://stackoverflow.com/users/216440/simon-tewsi) in [the comments](https://stackoverflow.com/questions/102829/best-free-text-editor-supporting-more-than-4gb-files/163941#comment20978000_163941), Feb. 2013)
>
> One caveat - has two search functions, `Main Search` and `Quick Find`.
>
> The lower one, which I assume is `Quick Find`, is at least an order of magnitude slower than the upper one, which is fast.
>
>
> | The question would need more details.
Do you want just to look at a file (eg. a log file) or to edit it?
Do you have more memory than the size of the file you want to load or less?
For example, [TheGun](http://www.movsd.com/thegun.htm "TheGun"), a very small text editor written in assembly language, claims to "*not have an effective file size limit and the maximum size that can be loaded into it is determined by available memory and loading speed of the file. [...] It has been speed optimised for both file load and save.*"
To abstract the memory limit, I suppose one can use mapped memory. But then, if you need to edit the file, some clever method should be used, like storing in memory the local changes, and applying them chunk by chunk when saving. Might be ineffective in some cases (big search/replace for example). |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | I've had to look at monster(runaway) log files (20+ GB). I used [hexedit FREE version](http://www.hhdsoftware.com/free-hex-editor) which can work with any size files. It is also open source. It is a Windows executable. | I Stumbled on this post many times, as I often need to handle huge files (10 Gigas+).
After being tired of buggy and pretty limited freeware, and not willing to pay fo costly editors after trial expired (not worth the money after all), I just used [VIM for Windows](ftp://ftp.vim.org/pub/vim/pc/gvim73_46.exe) with great success and satisfaction.
It is simply PERFECT for this need, fully customizable, with ALL feature one can think of when dealing with text files (searching, replacing, reading, etc. you name it)
I am very surprised nobody answered that (Except a previous answer but for MacOS)...
For the record I stumbled on it on [this blog post](http://blog.shlomoid.com/2009/08/free-text-editor-for-very-large-huge.html), which wisely adviced it. |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | Have you tried [context editor](http://www.contexteditor.org/)? It is small and fast. | [EmEditor](http://www.emeditor.com/) should handle this. As their [site claims](http://www.emeditor.com/modules/feature1/rewrite/tc_7.html#large_file_controller):
>
> EmEditor is now able to open even larger than **248 GB (or 2.1 billion lines)** by opening a
> portion of the file with the new custom bar - Large File Controller.
> The Large File Controller allows you to specify the beginning point,
> end point, and range of the file to be opened. It also allows you to
> stop the opening of the file and monitor the real size of the file and
> the size of the temporary disk available.
>
>
>
Not free though.. |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | [EmEditor](http://www.emeditor.com/) should handle this. As their [site claims](http://www.emeditor.com/modules/feature1/rewrite/tc_7.html#large_file_controller):
>
> EmEditor is now able to open even larger than **248 GB (or 2.1 billion lines)** by opening a
> portion of the file with the new custom bar - Large File Controller.
> The Large File Controller allows you to specify the beginning point,
> end point, and range of the file to be opened. It also allows you to
> stop the opening of the file and monitor the real size of the file and
> the size of the temporary disk available.
>
>
>
Not free though.. | The question would need more details.
Do you want just to look at a file (eg. a log file) or to edit it?
Do you have more memory than the size of the file you want to load or less?
For example, [TheGun](http://www.movsd.com/thegun.htm "TheGun"), a very small text editor written in assembly language, claims to "*not have an effective file size limit and the maximum size that can be loaded into it is determined by available memory and loading speed of the file. [...] It has been speed optimised for both file load and save.*"
To abstract the memory limit, I suppose one can use mapped memory. But then, if you need to edit the file, some clever method should be used, like storing in memory the local changes, and applying them chunk by chunk when saving. Might be ineffective in some cases (big search/replace for example). |
Question: I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.
Answer: | It's really tough to handle a 4G file as such. I used to handle larger text files, but I never used to load them in to my editor. I mostly used UltraEdit in my previous company, now I use Notepad++, but I would get just those parts which i needed to edit. (Most of the cases, the files never needed an edit).
Why do u want to load such a big file in to an editor? When I handled files of these size, I used GNU Core Utils. The most common operations i performed on those files were head ( to get the top 250k lines etc ), tail, split, sort, shuf, uniq etc. It's really powerful.
There's a lot of things you can do with GNU Core Utils. I would definitely recommend those, instead of a new editor. | What OS and CPU are you using? If you are using a 32-bit OS, then a process on your system physically cannot address more than 4GB of memory. Since most text editors try to load the entire file into memory, I doubt you'll find one that will do what you want. It would have to be a very fancy text editor, that can do out-of-core processing, i. e. load a chunk of the file at a time.
You may be able to load such a huge file with if you use a 64-bit text editor on a computer with a 64-bit CPU and a 64-bit operating system. And you have to make sure that you have enough space in your swap partition or your swap file. |
Question: Is it possible to run some Python command to not see so much ballast output in the console? I am talking now about running Scrapy where I see tons of not needed texts that disallow to see some meaningful output only.
But I see some ballast in there also when running e.g. `pip install`. Not helpful at all.
[![a sample of a screenful of output](https://i.stack.imgur.com/S2oMC.jpg)](https://i.stack.imgur.com/S2oMC.jpg)
Answer: | Ok solved partly thanks to Steve Barnes and partly to my knowledge haha. I had set an environment variable `PYTHONVERBOSE=1` had to remove it and then it works as expected. Good. | From looking at the materials found on scrapy's log [documentation](https://doc.scrapy.org/en/latest/topics/logging.html), it looks like you can enable or disable certain levels of log output with command line args:
```
--loglevel/-L LEVEL
```
where `LEVEL` is one of the debug levels. Additionally, if you would like no output, it appears there is the command line option:
```
--nolog
``` |
Question: I have this function:
```
function sum(x, y) {
var z = 1;
for (var i = x; i > 0; i--) {
if (i % y == (x % y)) {
console.log(z *= i);
}
}
}
sum(12, 5);
```
and the output is:
```
12, 84, 168
```
What should I edit in my function in order to get only the last value (168)?
Answer: | Move the log outside:
```
function sum(x, y) {
var z = 1;
for (var i = x; i > 0; i--) {
if (i % y == (x % y)) {
z *= i;
}
}
console.log(z);
}
sum(12, 5);
``` | ```
function sum(x, y) {
var z = 1;
for (var i = x; i > 0; i--) {
if (i % y == (x % y)) {
z *= i;
}
}
console.log(z);
}
sum(12, 5);
``` |
Question: Let $V$ be the $ℝ$-space of the continuous functions of $[0,1]$ in $ℝ$, with the product $\langle f, g\rangle = ∫\_0^1 f (t) g (t)\, dt$. Let $W$ be the
set of constant functions.
Can you state the existence of the orthogonal projection on $W$? If so, describe it, if not, justify it.
**Attempt:** By contradiction suppose that there exists the projection $E$ of $V$ in $W$. Then as $\dim W< \infty$, it follows that $V = W \bigoplus W^ \perp$. But
$W^ \perp = \{ f \in V; \langle f, c\rangle =0 \,\,\ \forall c \in W \}$.
that is
$0=\langle f, c\rangle = ∫\_0^1 f (t) c \,dt \,\,\ \forall c \in W $
that is
$0=∫\_0^1 f (t) \,dt \,\,\ \forall c \in W $.
But if we take $f (x) = x$, then $f\in V$, $f\notin W$,
then it must belong to $W^ \perp$. But $1=∫\_0^1 t dt=∫\_0^1 f(t) dt$. contradicting $V = W \bigoplus W^ \perp$.
Is this right?? I find it strange because the later exercise says so:
Show a formula for $p\_{W^⊥}(f)$ where $p\_{W^⊥}$ is the orthogonal projection on $W^⊥$.
And to show this, do I need the above projection of this exercise to be correct?
Answer: | The Poisson summation formula gives
$$\sum\_n \exp(-\pi (n+z)^2 y) =\sum\_n y^{-1/2}\exp\left(2\pi i n z -\pi n^2/y \right)$$ so as $y \to 0^+$ with $f(z) = z+1/2-\lfloor \Re(z) +1/2\rfloor$ for $\Re(z) \not\in \mathbb{Z}+1/2$ $$\sum\_n \exp\left(2\pi i n z -\pi n^2 y \right) \sim y^{-1/2} \exp(-\pi f(z)^2/y)$$
For the asymptotic as $z=ix,x \to + \infty$
$$\sum\_n \exp\left(2i\pi n (ix) -\pi n^2 y \right)= \exp(2\pi x^2/y)\sum\_n \exp\left(-\pi ( n+x/y)^2y\right)$$
where the latter series is $y$-periodic in $x$. Together with the $1$-periodicity in $z=ix$ of the LHS it gives the asymptotic in $z$ in every direction.
The intermediate cases, the asymptotic in $y$ depending on $z$, are less obvious, they require splitting one of the the series in two parts depending on the magnitude and growth. Which one are you interested in exactly and for what application ? | Yes, it is $e^{c x^2}$. The constant is obtained from the expression in $k$ above. The problem is that the remaining function is oscillatory. |
Question: Let $V$ be the $ℝ$-space of the continuous functions of $[0,1]$ in $ℝ$, with the product $\langle f, g\rangle = ∫\_0^1 f (t) g (t)\, dt$. Let $W$ be the
set of constant functions.
Can you state the existence of the orthogonal projection on $W$? If so, describe it, if not, justify it.
**Attempt:** By contradiction suppose that there exists the projection $E$ of $V$ in $W$. Then as $\dim W< \infty$, it follows that $V = W \bigoplus W^ \perp$. But
$W^ \perp = \{ f \in V; \langle f, c\rangle =0 \,\,\ \forall c \in W \}$.
that is
$0=\langle f, c\rangle = ∫\_0^1 f (t) c \,dt \,\,\ \forall c \in W $
that is
$0=∫\_0^1 f (t) \,dt \,\,\ \forall c \in W $.
But if we take $f (x) = x$, then $f\in V$, $f\notin W$,
then it must belong to $W^ \perp$. But $1=∫\_0^1 t dt=∫\_0^1 f(t) dt$. contradicting $V = W \bigoplus W^ \perp$.
Is this right?? I find it strange because the later exercise says so:
Show a formula for $p\_{W^⊥}(f)$ where $p\_{W^⊥}$ is the orthogonal projection on $W^⊥$.
And to show this, do I need the above projection of this exercise to be correct?
Answer: | Yes, it is $e^{c x^2}$. The constant is obtained from the expression in $k$ above. The problem is that the remaining function is oscillatory. | Let $x \in \mathbb R, \,\tau' = i/\tau, \, \tau' > 0$. The Poisson summation formula gives
$$\theta\_3(i x; \tau) =
\sqrt{\tau'} \,e^{\pi \tau' x^2} \left(
1 + 2 \sum\_{n > 0} e^{-\pi \tau' n^2} \cos(2 \pi \tau' n x) \right).$$
Setting the cosine to $\pm 1$ gives upper and lower bounds between which $\theta\_3(i x; \tau)$ will oscillate as $x \to \pm \infty$ for fixed $\tau$.
It seems fairly obvious that setting the cosine to $1$ and to $(-1)^n$ gives exact upper and lower bounds. But I'm blanking on how to prove that the derivative has exactly two zeroes in a cell. |
Question: Let $V$ be the $ℝ$-space of the continuous functions of $[0,1]$ in $ℝ$, with the product $\langle f, g\rangle = ∫\_0^1 f (t) g (t)\, dt$. Let $W$ be the
set of constant functions.
Can you state the existence of the orthogonal projection on $W$? If so, describe it, if not, justify it.
**Attempt:** By contradiction suppose that there exists the projection $E$ of $V$ in $W$. Then as $\dim W< \infty$, it follows that $V = W \bigoplus W^ \perp$. But
$W^ \perp = \{ f \in V; \langle f, c\rangle =0 \,\,\ \forall c \in W \}$.
that is
$0=\langle f, c\rangle = ∫\_0^1 f (t) c \,dt \,\,\ \forall c \in W $
that is
$0=∫\_0^1 f (t) \,dt \,\,\ \forall c \in W $.
But if we take $f (x) = x$, then $f\in V$, $f\notin W$,
then it must belong to $W^ \perp$. But $1=∫\_0^1 t dt=∫\_0^1 f(t) dt$. contradicting $V = W \bigoplus W^ \perp$.
Is this right?? I find it strange because the later exercise says so:
Show a formula for $p\_{W^⊥}(f)$ where $p\_{W^⊥}$ is the orthogonal projection on $W^⊥$.
And to show this, do I need the above projection of this exercise to be correct?
Answer: | The Poisson summation formula gives
$$\sum\_n \exp(-\pi (n+z)^2 y) =\sum\_n y^{-1/2}\exp\left(2\pi i n z -\pi n^2/y \right)$$ so as $y \to 0^+$ with $f(z) = z+1/2-\lfloor \Re(z) +1/2\rfloor$ for $\Re(z) \not\in \mathbb{Z}+1/2$ $$\sum\_n \exp\left(2\pi i n z -\pi n^2 y \right) \sim y^{-1/2} \exp(-\pi f(z)^2/y)$$
For the asymptotic as $z=ix,x \to + \infty$
$$\sum\_n \exp\left(2i\pi n (ix) -\pi n^2 y \right)= \exp(2\pi x^2/y)\sum\_n \exp\left(-\pi ( n+x/y)^2y\right)$$
where the latter series is $y$-periodic in $x$. Together with the $1$-periodicity in $z=ix$ of the LHS it gives the asymptotic in $z$ in every direction.
The intermediate cases, the asymptotic in $y$ depending on $z$, are less obvious, they require splitting one of the the series in two parts depending on the magnitude and growth. Which one are you interested in exactly and for what application ? | Let $x \in \mathbb R, \,\tau' = i/\tau, \, \tau' > 0$. The Poisson summation formula gives
$$\theta\_3(i x; \tau) =
\sqrt{\tau'} \,e^{\pi \tau' x^2} \left(
1 + 2 \sum\_{n > 0} e^{-\pi \tau' n^2} \cos(2 \pi \tau' n x) \right).$$
Setting the cosine to $\pm 1$ gives upper and lower bounds between which $\theta\_3(i x; \tau)$ will oscillate as $x \to \pm \infty$ for fixed $\tau$.
It seems fairly obvious that setting the cosine to $1$ and to $(-1)^n$ gives exact upper and lower bounds. But I'm blanking on how to prove that the derivative has exactly two zeroes in a cell. |
Question: In other words, instead of fixed **15 seconds**, is there a way to, to tell it to stop showing when my async function is finished?
Answer: | If you are using a separate screen for **Splash screen**, you can simply `await` the `async` function you have and the use `Navigator.pushReplacement()` to open your **Main Screen**
Example:
--------
```
class SplashScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}
class SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
handleSplashscreen();
}
void handleSplashscreen() async {
// Wait for async to complete
await someAsyncFunction();
// Open Main page
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomePage(user: null)));
}
Future<void> someAsyncFunction() async {
// Do some Network or other stuff
}
@override
Widget build(BuildContext context) {
return Container(
child: Center(child: Text("Loading...")),
);
}
}
```
If you are simply showing a loader in the same screen while async operation is being done, you can use a `FutureBuilder` as others suggested.
Or you can conditionally show **loader** and **Main UI** using a boolean and `setState()`.
Example:
--------
```
class MainPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MainPageState();
}
}
class MainPageState extends State<MainPage> {
// Boolean to show/ hide loader
bool isLoading = true;
@override
void initState() {
super.initState();
handleAsync();
}
void handleAsync() async {
// Wait for async to complete
await someAsyncFunction();
// Open Main page
setState(() {
isLoading = false;
});
}
Future<void> someAsyncFunction() async {
// Do some Network or other stuff
}
@override
Widget build(BuildContext context) {
// Using isLoading to check whether async function is complete
return isLoading
? Container(
child: Center(child: Text("Loading...")),
)
: Container(
child: Text("The Actual screen"),
);
}
}
```
Hope it helps. | Use `FutureBuilder` [from here](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html) in the page and show splash screen image when the data is not loaded. |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | You can express this as a series of arithmetic and bitwise operations, e.g.:
```
int myabs(const int& in) {
const int tmp = in >> ((sizeof(int) * CHAR_BIT) - 1);
return tmp - (in ^ tmp(;
}
int mymax(int a, int b) {
return ((a+b) + myabs(b-a)) / 2;
}
``` | It depends which language you're using, but the [Ternary Operator](http://en.wikipedia.org/wiki/Ternary_operator) might be useful.
But then, if you can't perform conditional checks in your 'scripting application', you probably don't have the ternary operator. |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | Solution without conditionals. Cast to uint then back to int to get abs.
```
int abs (a) { return (int)((unsigned int)a); }
int max (a, b) { return (a + b + abs(a - b)) / 2; }
int max3 (a, b, c) { return (max(max(a,b),c); }
``` | It depends which language you're using, but the [Ternary Operator](http://en.wikipedia.org/wiki/Ternary_operator) might be useful.
But then, if you can't perform conditional checks in your 'scripting application', you probably don't have the ternary operator. |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | I guess this one would be the most simplest if we manage to find difference between two numbers (only the magnitude not sign)
```
max = ((a+b)+|a-b|)/2;
```
where `|a-b|` is a magnitude of difference between `a` and `b`. | You can express this as a series of arithmetic and bitwise operations, e.g.:
```
int myabs(const int& in) {
const int tmp = in >> ((sizeof(int) * CHAR_BIT) - 1);
return tmp - (in ^ tmp(;
}
int mymax(int a, int b) {
return ((a+b) + myabs(b-a)) / 2;
}
``` |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | I guess this one would be the most simplest if we manage to find difference between two numbers (only the magnitude not sign)
```
max = ((a+b)+|a-b|)/2;
```
where `|a-b|` is a magnitude of difference between `a` and `b`. | ```
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
float a = 101, b = 15;
float max = (a + b) / 2 + ((a > b) ? a - b : b - a) / 2;
}
}
}
``` |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | If you can't trust your environment to generate the appropriate branchless operations when they are available, see [this page](http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax) for how to proceed. Note the restriction on input range; use a larger integer type for the operation if you cannot guarantee your inputs will fit. | Using logical operations only, short circuit evaluation and assuming the C convention of rounding towards zero, it is possible to express this as:
```
int lt0(int x) {
return x && (!!((x-1)/x));
}
int mymax(int a, int b) {
return lt0(a-b)*b+lt0(b-a)*a;
}
```
The basic idea is to implement a comparison operator that will return 0 or 1. It's possible to do a similar trick if your scripting language follows the convention of rounding toward the floor value like python does. |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | If you can't trust your environment to generate the appropriate branchless operations when they are available, see [this page](http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax) for how to proceed. Note the restriction on input range; use a larger integer type for the operation if you cannot guarantee your inputs will fit. | ```
#region GetMaximumNumber
/// <summary>
/// Provides method to get maximum values.
/// </summary>
/// <param name="values">Integer array for getting maximum values.</param>
/// <returns>Maximum number from an array.</returns>
private int GetMaximumNumber(params int[] values)
{
// Declare to store the maximum number.
int maximumNumber = 0;
try
{
// Check that array is not null and array has an elements.
if (values != null &&
values.Length > 0)
{
// Sort the array in ascending order for getting maximum value.
Array.Sort(values);
// Get the last value from an array which is always maximum.
maximumNumber = values[values.Length - 1];
}
}
catch (Exception ex)
{
throw ex;
}
return maximumNumber;
}
#endregion
``` |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | If you can't trust your environment to generate the appropriate branchless operations when they are available, see [this page](http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax) for how to proceed. Note the restriction on input range; use a larger integer type for the operation if you cannot guarantee your inputs will fit. | This is my implementation using only `+, -, *, %, /` operators
```
using static System.Console;
int Max(int a, int b) => (a + b + Abs(a - b)) / 2;
int Abs(int x) => x * ((2 * x + 1) % 2);
WriteLine(Max(-100, -2) == -2); // true
WriteLine(Max(2, -100) == 2); // true
``` |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | [finding the maximum of 2 variables:](http://guru.multimedia.cx/category/optimization/)
`max = a-((a-b)&((a-b)>>31))`
where >> is bitwise right-shift (also called SHR or ASR depeding on signedness).
Instead of 31 you use the number of bits your numbers have minus one. | If you can't trust your environment to generate the appropriate branchless operations when they are available, see [this page](http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax) for how to proceed. Note the restriction on input range; use a larger integer type for the operation if you cannot guarantee your inputs will fit. |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | This is my implementation using only `+, -, *, %, /` operators
```
using static System.Console;
int Max(int a, int b) => (a + b + Abs(a - b)) / 2;
int Abs(int x) => x * ((2 * x + 1) % 2);
WriteLine(Max(-100, -2) == -2); // true
WriteLine(Max(2, -100) == 2); // true
``` | >
> If A is always greater than B .. [ we can use] .. `MAX = (A - B) + B;`
>
>
>
No need. Just use: `int maxA(int A, int B){ return A;}`
(1) If conditionals are allowed you do `max = a>b ? a : b`.
(2) Any other method either use a defined set of numbers or rely on the implicit conditional checks.
(2a) `max = a-((a-b)&((a-b)>>31))` this is neat, but it only works `if` you use 32 bit numbers. You can expand it arbitrary large number N, but the method will fail if you try to find max(N-1, N+1). This algorithm works for finite state automata, but not a Turing machine.
(2b) Magnitude `|a-b|` is a condition `|a-b| = a-b>0 a-b : b-a`
What about:
[![enter image description here](https://i.stack.imgur.com/HDIrV.gif)](https://i.stack.imgur.com/HDIrV.gif)
Square root is also a condition. Whenever `c>0` and `c^2 = d` we have second solution `-c`, because `(-c)^2 = (-1)^2*c^2 = 1*c^2 = d`. Square root returns the greatest in the pair. I comes with a build in `int max(int c1, int c2){return max(c1, c2);}`
Without comparison operator math is very symmetric as well as limited in power. Positive and negative numbers cannot be distinguished without `if` of some sort. |
Question: ----------Updated ------------
codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right shift I divided by 29. Because with 32bits signed 2^31 = overflows to 29. Which works!
Prototype in PHP
```
$r = $x - (($x - $y) & (($x - $y) / (29)));
```
Actual code for LEADS (you can only do one math function PER LINE!!! AHHHH!!!)
```
DERIVDE1 = IMAGE1 - IMAGE2;
DERIVED2 = DERIVED1 / 29;
DERIVED3 = DERIVED1 AND DERIVED2;
MAX = IMAGE1 - DERIVED3;
```
----------Original Question-----------
I don't think this is quite possible with my application's limitations but I figured it's worth a shot to ask.
I'll try to make this simple. I need to find the max values between two numbers without being able to use a IF or any conditional statement.
In order to find the the MAX values I can only perform the following functions
```
Divide, Multiply, Subtract, Add, NOT, AND ,OR
```
Let's say I have two numbers
```
A = 60;
B = 50;
```
Now if A is always greater than B it would be simple to find the max value
```
MAX = (A - B) + B;
ex.
10 = (60 - 50)
10 + 50 = 60 = MAX
```
Problem is A is not always greater than B. I cannot perform ABS, MAX, MIN or conditional checks with the scripting applicaiton I am using.
Is there any way possible using the limited operation above to find a value VERY close to the max?
Answer: | I guess this one would be the most simplest if we manage to find difference between two numbers (only the magnitude not sign)
```
max = ((a+b)+|a-b|)/2;
```
where `|a-b|` is a magnitude of difference between `a` and `b`. | It depends which language you're using, but the [Ternary Operator](http://en.wikipedia.org/wiki/Ternary_operator) might be useful.
But then, if you can't perform conditional checks in your 'scripting application', you probably don't have the ternary operator. |
Question: In bash you have this handy variable: $BASHPID wich always returns the currently running subshell's PID. How can I get a subshell's PID in ksh? For example see the code below:
```
#!/usr/bin/ksh93
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
run_something &
echo "PID of backgrounded run_something: $!"
}
function run_something {
echo "*** PID in run_something: $$"
sleep 10;
}
run_in_background
echo "PID of run in background $!"
```
This outputs the following:
```
PID at start: 5328
PID in run_in_background 5328
*** PID in run_something: 5328
PID of backgrounded run_something: 5329
PID of run in background 5329
```
What I want is the line starting with `****` to output the subshell's PID, in the example's case that would be 5329.
Answer: | I don't think that's available in ksh. There's a POSIX solution which involves running an external process:
```
sh -c 'echo $PPID'
```
On Linux, `readlink /proc/self` would also work, but I fail to see any advantage (it might be marginally faster; it could be useful on a BusyBox variant that has `readlink` but not `$PPID`, but I don't think there is one).
Note that in order to get the value in the shell, you need to be careful not to run that command in a short-lived sub-sub-shell. For example, `p=$(sh -c 'echo $PPID')` might show the output of the subshell that invokes `sh` within the command substitution (or it might not, some shells optimize that case). Instead, run
```
p=$(exec sh -c 'echo $PPID')
``` | You can achieve what you want, but you need to put run\_something into a separate script. I'm not exactly sure why, but $$ is not re-evaluated when it is used in a function in the same script that is calling it. I guess that the value of $$ is assigned once after the script is parsed and before it is executed.
run\_in\_background.sh
```
#
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
./run_something.sh &
echo "PID of backgrounded run_something: $!"
}
run_in_background
echo "PID of run in background $!"
```
run\_something.sh
```
#
echo "*** PID in run_something: $$"
sleep 10;
```
output
```
PID at start: 24395
PID in run_in_background 24395
PID of backgrounded run_something: 24396
PID of run in background 24396
*** PID in run_something: 24396
``` |
Question: In bash you have this handy variable: $BASHPID wich always returns the currently running subshell's PID. How can I get a subshell's PID in ksh? For example see the code below:
```
#!/usr/bin/ksh93
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
run_something &
echo "PID of backgrounded run_something: $!"
}
function run_something {
echo "*** PID in run_something: $$"
sleep 10;
}
run_in_background
echo "PID of run in background $!"
```
This outputs the following:
```
PID at start: 5328
PID in run_in_background 5328
*** PID in run_something: 5328
PID of backgrounded run_something: 5329
PID of run in background 5329
```
What I want is the line starting with `****` to output the subshell's PID, in the example's case that would be 5329.
Answer: | I don't think that's available in ksh. There's a POSIX solution which involves running an external process:
```
sh -c 'echo $PPID'
```
On Linux, `readlink /proc/self` would also work, but I fail to see any advantage (it might be marginally faster; it could be useful on a BusyBox variant that has `readlink` but not `$PPID`, but I don't think there is one).
Note that in order to get the value in the shell, you need to be careful not to run that command in a short-lived sub-sub-shell. For example, `p=$(sh -c 'echo $PPID')` might show the output of the subshell that invokes `sh` within the command substitution (or it might not, some shells optimize that case). Instead, run
```
p=$(exec sh -c 'echo $PPID')
``` | ```
# KSH_VERSION hasn't always been a nameref, nor has it always existed.
# Replace with a better test if needed. e.g.:
# https://www.mirbsd.org/cvs.cgi/contrib/code/Snippets/getshver?rev=HEAD
if [[ ${!KSH_VERSION} == .sh.version ]]; then
# if AT&T ksh
if builtin pids 2>/dev/null; then # >= ksh93 v- alpha
function BASHPID.get { .sh.value=$(pids -f '%(pid)d'); }
elif [[ -r /proc/self/stat ]]; then # Linux / some BSDs / maybe others
function BASHPID.get { read -r .sh.value _ </proc/self/stat; }
else # Crappy fallback
function BASHPID.get { .sh.value=$(exec sh -c 'echo $PPID'); }
fi
elif [[ ! ${BASHPID+_} ]]; then
echo 'BASHPID requires Bash, ksh93, or mksh >= R41' >&2
exit 1
fi
``` |
Question: In bash you have this handy variable: $BASHPID wich always returns the currently running subshell's PID. How can I get a subshell's PID in ksh? For example see the code below:
```
#!/usr/bin/ksh93
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
run_something &
echo "PID of backgrounded run_something: $!"
}
function run_something {
echo "*** PID in run_something: $$"
sleep 10;
}
run_in_background
echo "PID of run in background $!"
```
This outputs the following:
```
PID at start: 5328
PID in run_in_background 5328
*** PID in run_something: 5328
PID of backgrounded run_something: 5329
PID of run in background 5329
```
What I want is the line starting with `****` to output the subshell's PID, in the example's case that would be 5329.
Answer: | I don't think that's available in ksh. There's a POSIX solution which involves running an external process:
```
sh -c 'echo $PPID'
```
On Linux, `readlink /proc/self` would also work, but I fail to see any advantage (it might be marginally faster; it could be useful on a BusyBox variant that has `readlink` but not `$PPID`, but I don't think there is one).
Note that in order to get the value in the shell, you need to be careful not to run that command in a short-lived sub-sub-shell. For example, `p=$(sh -c 'echo $PPID')` might show the output of the subshell that invokes `sh` within the command substitution (or it might not, some shells optimize that case). Instead, run
```
p=$(exec sh -c 'echo $PPID')
``` | ```
#!/bin/ksh
function os_python_pid {
/usr/bin/python -c 'import os,sys ; sys.stdout.write(str(os.getppid()))'
}
function os_perl_pid {
/usr/bin/perl -e 'print getppid'
}
echo "I am $$"
echo "I am $(os_python_pid) :: $(os_perl_pid)"
function proce {
sleep 3
echo "$1 :: $(os_python_pid) :: $(os_perl_pid)"
}
for x in aa bb cc; do
proce $x &
echo "Started: $!"
done
``` |
Question: In bash you have this handy variable: $BASHPID wich always returns the currently running subshell's PID. How can I get a subshell's PID in ksh? For example see the code below:
```
#!/usr/bin/ksh93
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
run_something &
echo "PID of backgrounded run_something: $!"
}
function run_something {
echo "*** PID in run_something: $$"
sleep 10;
}
run_in_background
echo "PID of run in background $!"
```
This outputs the following:
```
PID at start: 5328
PID in run_in_background 5328
*** PID in run_something: 5328
PID of backgrounded run_something: 5329
PID of run in background 5329
```
What I want is the line starting with `****` to output the subshell's PID, in the example's case that would be 5329.
Answer: | You can achieve what you want, but you need to put run\_something into a separate script. I'm not exactly sure why, but $$ is not re-evaluated when it is used in a function in the same script that is calling it. I guess that the value of $$ is assigned once after the script is parsed and before it is executed.
run\_in\_background.sh
```
#
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
./run_something.sh &
echo "PID of backgrounded run_something: $!"
}
run_in_background
echo "PID of run in background $!"
```
run\_something.sh
```
#
echo "*** PID in run_something: $$"
sleep 10;
```
output
```
PID at start: 24395
PID in run_in_background 24395
PID of backgrounded run_something: 24396
PID of run in background 24396
*** PID in run_something: 24396
``` | ```
# KSH_VERSION hasn't always been a nameref, nor has it always existed.
# Replace with a better test if needed. e.g.:
# https://www.mirbsd.org/cvs.cgi/contrib/code/Snippets/getshver?rev=HEAD
if [[ ${!KSH_VERSION} == .sh.version ]]; then
# if AT&T ksh
if builtin pids 2>/dev/null; then # >= ksh93 v- alpha
function BASHPID.get { .sh.value=$(pids -f '%(pid)d'); }
elif [[ -r /proc/self/stat ]]; then # Linux / some BSDs / maybe others
function BASHPID.get { read -r .sh.value _ </proc/self/stat; }
else # Crappy fallback
function BASHPID.get { .sh.value=$(exec sh -c 'echo $PPID'); }
fi
elif [[ ! ${BASHPID+_} ]]; then
echo 'BASHPID requires Bash, ksh93, or mksh >= R41' >&2
exit 1
fi
``` |
Question: In bash you have this handy variable: $BASHPID wich always returns the currently running subshell's PID. How can I get a subshell's PID in ksh? For example see the code below:
```
#!/usr/bin/ksh93
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
run_something &
echo "PID of backgrounded run_something: $!"
}
function run_something {
echo "*** PID in run_something: $$"
sleep 10;
}
run_in_background
echo "PID of run in background $!"
```
This outputs the following:
```
PID at start: 5328
PID in run_in_background 5328
*** PID in run_something: 5328
PID of backgrounded run_something: 5329
PID of run in background 5329
```
What I want is the line starting with `****` to output the subshell's PID, in the example's case that would be 5329.
Answer: | You can achieve what you want, but you need to put run\_something into a separate script. I'm not exactly sure why, but $$ is not re-evaluated when it is used in a function in the same script that is calling it. I guess that the value of $$ is assigned once after the script is parsed and before it is executed.
run\_in\_background.sh
```
#
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
./run_something.sh &
echo "PID of backgrounded run_something: $!"
}
run_in_background
echo "PID of run in background $!"
```
run\_something.sh
```
#
echo "*** PID in run_something: $$"
sleep 10;
```
output
```
PID at start: 24395
PID in run_in_background 24395
PID of backgrounded run_something: 24396
PID of run in background 24396
*** PID in run_something: 24396
``` | ```
#!/bin/ksh
function os_python_pid {
/usr/bin/python -c 'import os,sys ; sys.stdout.write(str(os.getppid()))'
}
function os_perl_pid {
/usr/bin/perl -e 'print getppid'
}
echo "I am $$"
echo "I am $(os_python_pid) :: $(os_perl_pid)"
function proce {
sleep 3
echo "$1 :: $(os_python_pid) :: $(os_perl_pid)"
}
for x in aa bb cc; do
proce $x &
echo "Started: $!"
done
``` |
Question: In bash you have this handy variable: $BASHPID wich always returns the currently running subshell's PID. How can I get a subshell's PID in ksh? For example see the code below:
```
#!/usr/bin/ksh93
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
run_something &
echo "PID of backgrounded run_something: $!"
}
function run_something {
echo "*** PID in run_something: $$"
sleep 10;
}
run_in_background
echo "PID of run in background $!"
```
This outputs the following:
```
PID at start: 5328
PID in run_in_background 5328
*** PID in run_something: 5328
PID of backgrounded run_something: 5329
PID of run in background 5329
```
What I want is the line starting with `****` to output the subshell's PID, in the example's case that would be 5329.
Answer: | ```
# KSH_VERSION hasn't always been a nameref, nor has it always existed.
# Replace with a better test if needed. e.g.:
# https://www.mirbsd.org/cvs.cgi/contrib/code/Snippets/getshver?rev=HEAD
if [[ ${!KSH_VERSION} == .sh.version ]]; then
# if AT&T ksh
if builtin pids 2>/dev/null; then # >= ksh93 v- alpha
function BASHPID.get { .sh.value=$(pids -f '%(pid)d'); }
elif [[ -r /proc/self/stat ]]; then # Linux / some BSDs / maybe others
function BASHPID.get { read -r .sh.value _ </proc/self/stat; }
else # Crappy fallback
function BASHPID.get { .sh.value=$(exec sh -c 'echo $PPID'); }
fi
elif [[ ! ${BASHPID+_} ]]; then
echo 'BASHPID requires Bash, ksh93, or mksh >= R41' >&2
exit 1
fi
``` | ```
#!/bin/ksh
function os_python_pid {
/usr/bin/python -c 'import os,sys ; sys.stdout.write(str(os.getppid()))'
}
function os_perl_pid {
/usr/bin/perl -e 'print getppid'
}
echo "I am $$"
echo "I am $(os_python_pid) :: $(os_perl_pid)"
function proce {
sleep 3
echo "$1 :: $(os_python_pid) :: $(os_perl_pid)"
}
for x in aa bb cc; do
proce $x &
echo "Started: $!"
done
``` |
Question: I have a table that contains a hierarchy of categories. It can have any number of category levels.
I need to display these categories in a simple string format, ie:
```
>>parent>>child1>>subchild>>...
```
This is the data sample:
```
Id Parent Name
1 NULL Categories
4 NULL Instrument
55 NULL Genre
65 NULL Geographical Place
8 1 CLASSICAL
47 1 SOLO INSTRUMENTS
10694 1 STYLES
4521 4 Piano
1137 8 SOLO INSTRUMENTS
1140 8 WALTZES
841 47 PIANO
93328 55 CLASSICAL
93331 55 BLUES
93334 55 CLUB / ELECTRONICA
93339 55 CONTEMPORARY FOLK
93344 55 CHILDREN
94892 65 EUROPE
4180 10694 CLASSICAL - SOLO PIANO
94893 94892 Western & Southern Europe
94900 94893 France
```
Answer: | Maybe someone has a better way to do the last part (getting rid of the intermediate strings), but this get's you there without hard coding any joins:
```
declare @Categories table
(
categoryID int,
categoryParentID int,
categoryDesc nvarchar(100)
)
insert into @Categories values
(1,NULL,'Categories'),
(4,NULL,'Instrument'),
(55,NULL,'Genre'),
(65,NULL,'Geographical Place '),
(8,1,'CLASSICAL'),
(47,1,'SOLO INSTRUMENTS'),
(10694,1,'STYLES'),
(4521,4,'Piano'),
(1137,8,'SOLO INSTRUMENTS'),
(1140,8,'WALTZES'),
(841,47,'PIANO'),
(93328,55,'CLASSICAL'),
(93331,55,'BLUES'),
(93334,55,'CLUB / ELECTRONICA'),
(93339,55, 'CONTEMPORARY FOLK'),
(93344,55,'CHILDREN'),
(94892,65,'EUROPE'),
(4180,10694,'CLASSICAL - SOLO PIANO'),
(94893,94892,'Western & Southern Europe'),
(94900,94893,'France')
;with CategoryCTE (categoryID, categoryString) as
(
select categoryID, cast(categoryDesc as nvarchar(max)) as categoryString
from @Categories
where categoryParentID is null
union all
select rsCat.categoryID, cast(CategoryCTE.categoryString + N'>>' + rsCat.categoryDesc as nvarchar(max))
from @Categories rsCat
inner join CategoryCTE on rsCat.categoryParentID = CategoryCTE.categoryID
)
select categoryString
from CategoryCTE o
where not exists
(
--eliminate intermediate strings
select i.categoryString
from CategoryCTE i
where LEN(i.categoryString) != LEN(o.categoryString)
and CHARINDEX(o.categoryString, i.categoryString) > 0
)
```
[Working example.](https://data.stackexchange.com/stackoverflow/q/119593/) | Your data looks like it'll be 4 categories deep, so you could try something like this:
```
SELECT parent.Name, child.Name, subchild.Name, subchild2.Name
FROM categories parent
LEFT JOIN categories child ON parent.Id = child.Parent
LEFT JOIN categories subchild ON child.Id = subchild.Parent
LEFT JOIN categories subchild2 ON subchild.Id = subchild2.Parent
WHERE parent.Parent is NULL;
```
Of course, you'll need to adjust it if you end up having more than 4 levels of categories. This method will also end-up yielding NULL results for hierarchies that don't extend to all 4 levels. |
Question: I would like to remove a license from a user using the microsoft graph API. I am currently using graph explorer to experiment with this.
I have not found much information here regarding microsoftgraph. I find the microsoft documentation and examples unclear on this point.
Here is the data I have to work with. [graph explorer snip\_one](https://i.stack.imgur.com/opdJ1.png) I have tried option A)
When I post to the assignLicense endpoint, I get this error message, and I find little information via google/SO about this. [graph explorer snip\_two](https://i.stack.imgur.com/dD725.png) Specifically, I find little about
"Cannot convert a primitive value to the expected type 'Edm.Guid'"
```
{
"error": {
"code": "Request_BadRequest",
"message": "Cannot convert a primitive value to the expected type 'Edm.Guid'. See the inner exception for more details.",
"innerError": {
"request-id": "7e63fcf2-8fce-4a5c-9f40-3348fba1fb13",
"date": "2019-12-05T01:37:14"
}
} }
```
Answer: | Using 'fixed' removes the element from the flow. This can work but you have to size the msgs element to make sure it doesn't go behind it. The method I use below makes the two elements directly related to each other spacially. The parent display of flex makes the two children create a column. Some rules here and there, shown below, instruct them how to take up space.
Added an overflow: auto that allows that content to scroll when too long.
CSS
```
* { box-sizing: border-box; } // so padding and borders are included in sizes
body, html {
margin: 0;
padding: 0;
}
chat-box { // using custom tag
display: flex; // magic
flex-flow: column; // column
height: 100vh; // better than height: 100% when full window height
}
#msgs {
flex: 1; // makes this flex element grow to fill the space
overflow: auto; // adds a scrollbar if too long
padding: 1em; // for pretty
}
textarea {
resize: none;
width: 100%;
}
footer {
padding: 0.4em 0.35em 0.2em 0.35em; // for pretty
background: #ccc; // for pretty
}
form { // removing native spacing
padding: 0;
margin: 0;
}
```
HTML
```
<chat-box>
<div id="msgs"></div>
<footer>
<form method="post" action="/api/msg" id="form">
<textarea autofocus name="msg" id="msgfield" rows=3 cols=80></textarea>
</form>
</footer>
</chat-box>
``` | msgs is an "id", CSS selector for that would be "#msgs".
Same for your footer > #footer |
Question: In VS with Resharper, there's the command `ctrl``w` that will select the whole word at cursor and then, when pressed repeatedly, extend the selection to the brackets, then include them too, then to the next outer brackets etc.
What is the name of the command for that in Visual Studio Code?
Answer: | The [shrink/expand selection](https://code.visualstudio.com/docs/editor/codebasics#_shrinkexpand-selection) commands should be what you are looking for. The command names are `editor.action.smartSelect.grow` (default keybinding `shift`+`alt`+`right`) and `editor.action.smartSelect.shrink` (default keybinding `shift`+`alt`+`left`). | i use alt+s for editor.action.smartSelect.grow.
```
{
"key": "alt+s",
"command": "editor.action.smartSelect.grow",
"when": "editorTextFocus"
}
``` |
Question: I am using R. I want to convert `DataFrame-1` to `DataFrame-2`
```
DataFrame-1
Variable1 Variable2
aa1 X1
aa1 Y2
aa1 Z1
bb1 Y1
bb1 Y2
```
I want to create `DataFrame-2` which will look like this
```
Variable1 Variable2
aa1 X1, Y2, Z1
bb1 Y1, Y2
```
Answer: | First of all, you don't need to use `props` property in AppRoot.vue file, it will pass down the props when you'll do use `:title="title"` to the child. `props` property is used to get the parent component property in the child.
For your query, you can use event bus to communicating between them. Or, you can use vuex for better state management. Here's how we can implement using event bus:
In your `main.js` file, define a event hub or in any file you want but just make sure event hub is available in your components importing that file.
```
var eventHub = new Vue();
```
Now, this will be used in all of your component.
Next, you'll need to emit the event:
AppToolbar.vue
```
// ...
methods: {
openDrawer: function () {
eventHub.$emit('open-drawer', PASS_WHATEVER_YOU_WANT);
}
}
```
And then listen to the emitted event on the child:
AppDrawer.vue
```
// ...
created: function () {
eventHub.$on('open-drawer', this.openDrawer)
},
methods: {
openDrawer(value) {
// ... do whatever you want to do with value
// this.isDrawerOpen = !this.isDrawerOpen
this.isDrawerOpen = value;
}
}
``` | Components have two kinds of state: internal and external. Internal state is typically controlled by the component's `data`, while external state usually comes in via `props`.
When the external state isn't closely related to the parent of the component, you can think of it as application state, or global state. That is usually kept in a "store" that is available to every component. A lot of people use Vuex for that, but I think most of the time you don't really need Vuex, which is largely concerned with synchronizing data affected by lots of possibly-simultaneous input.
In a single-user app, you just need a "godparent": something that, like a parent, you get props from and emit events to, but the relationship isn't as direct.
As it happens, if your application is a collection of components, `$root` is available to serve as that godparent: you can emit events to it and you can access its data items and computeds.
In your example (which I've stripped down to a minimal snippet below), the state of the drawer is shared across the application. It is not internal to the drawer component. So the drawer component receives its state as a prop; the parent of the drawer — `app-root` — supplies the prop using `:is-open="$root.drawerIsOpen"` so the drawer never knows or cares that its state is global; it's just handed down like any prop.
The toolbar component knows that there is a drawer in the app somewhere, not in its own parent, so it emits the `open-drawer` event to `$root`:
```
this.$root.$emit('open-drawer');
```
And the top-level Vue (which is `$root`) sets up event handling in its `created` hook, since there's no way to globally mark up `@open-drawer` in a template.
This should all feel pretty similar to the "props down, events up" way communication is designed to work in Vue.
```js
Vue.component('app-root', {
template: '#root-template',
props: ['title']
});
Vue.component('app-toolbar', {
template: '#toolbar-template',
methods: {
openDrawer() {
this.$root.$emit('open-drawer');
}
}
});
Vue.component('app-drawer', {
template: '#drawer-template',
props: ['isOpen']
});
new Vue({
el: '#app',
// This is your store!
data: {
drawerIsOpen: false
},
created() {
this.$on('open-drawer', () => {
this.drawerIsOpen = true;
});
}
});
```
```html
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<app-root title="My App!"></app-root>
</div>
<template id="root-template">
<div>
<h1>{{title}}</h1>
<app-toolbar></app-toolbar>
<app-drawer :is-open="$root.drawerIsOpen"></app-drawer>
</div>
</template>
<template id="toolbar-template">
<div>
<button @click="openDrawer">Open Drawer</button>
</div>
</template>
<template id="drawer-template">
<div v-show="isOpen">
Drawer here
</div>
</template>
``` |
Question: My father found an old glass during a recent move and has no idea where it's from. It looks vaguely familiar to me (maybe all coats of arms look vaguely familiar), but I've looked up the places we're mostly associated with (universities in the United Kingdom, South Africa, and Zimbabwe, although there are wider possible connections).
[![glass with coat of arms](https://i.stack.imgur.com/MYtNZ.jpg)](https://i.stack.imgur.com/MYtNZ.jpg)
Anyone know where the coat of arms is from?
Answer: | >
> N=6
>
>
>
>
> Team X must win more, and draw more, thus all other teams must lose at least twice (2N-2 losses)
>
> Team X must draw, thus wins at most N-2 times. If no other team wins more than once, they as a group win at most N-1 times.
>
> -> One of the other teams must win at least twice (to get the 2N-2 wins needed for the required losses)
>
> -> Team X must win at least 3 times
>
>
>
>
> Team X must draw more, thus draw against another team, thus (some) other teams draw
>
> -> Team X must draw at least 2 times
>
>
>
>
> This is possible for N=6 (the minimum required for the 5 results), e.g.:
>
>
> X 2 2 2 1 1
>
> 0 X 2 2 0 0
>
> 0 0 X 0 2 2
>
> 0 0 2 x 2 0
>
> 1 2 0 0 x 2
>
> 1 2 0 2 0 x
>
>
> | With N teams there are
>
> a total of $N(N-1)/2$ total games to be played. Any particular team will play $N-1$ games. Assume a team is awarded 2 points for a win, 1 point for a draw, and 0 points for a loss. Thus each game awards a total of 2 points, and there are a total of $N(N-1)$ points to be awarded.
> If I draw twice and win the rest of my games, I will get $2(N-3) + 2$ points. The remainder of the points need to be distributed amongst the remaining $N-1$ teams.
> If there are fewer than 7 teams, there is no way to allocate the remaining points in such a way that all of the teams would have fewer than my number of wins and my number of draws.
> With 7 teams, if I draw twice and win the other four games, I'll have a total of 10 points. There are 32 points left to distribute among the remaining 6 teams, meaning an average of 5.33 points per team. This can be done with 2 teams with 3 wins and 0 draws each, and 4 teams with 2 wins and 1 draw each.
>
>
>
>
>
>
>
>
>
Edited to improve solution:
>
> It actually is possible to allocate the points when N = 6, I made an arithmetical error previously which led me to believe it wasn't. For N = 6, you can draw twice and win three times for a total of 8 points. The remaining 22 points can be distributed between the other 5 teams by having two teams with two wins and a draw each, and three teams with two wins.
> For N = 5, if you win 2 and draw 2 you have 6 points. There would be 14 points remaining to distribute among the other four teams, meaning they'd have 3.5 points on average. At least one of the teams would have 4+ points, which is only possible if they have at least two wins or at least two draws.
>
>
>
>
> |
Question: My father found an old glass during a recent move and has no idea where it's from. It looks vaguely familiar to me (maybe all coats of arms look vaguely familiar), but I've looked up the places we're mostly associated with (universities in the United Kingdom, South Africa, and Zimbabwe, although there are wider possible connections).
[![glass with coat of arms](https://i.stack.imgur.com/MYtNZ.jpg)](https://i.stack.imgur.com/MYtNZ.jpg)
Anyone know where the coat of arms is from?
Answer: | >
> N=6
>
>
>
>
> Team X must win more, and draw more, thus all other teams must lose at least twice (2N-2 losses)
>
> Team X must draw, thus wins at most N-2 times. If no other team wins more than once, they as a group win at most N-1 times.
>
> -> One of the other teams must win at least twice (to get the 2N-2 wins needed for the required losses)
>
> -> Team X must win at least 3 times
>
>
>
>
> Team X must draw more, thus draw against another team, thus (some) other teams draw
>
> -> Team X must draw at least 2 times
>
>
>
>
> This is possible for N=6 (the minimum required for the 5 results), e.g.:
>
>
> X 2 2 2 1 1
>
> 0 X 2 2 0 0
>
> 0 0 X 0 2 2
>
> 0 0 2 x 2 0
>
> 1 2 0 0 x 2
>
> 1 2 0 2 0 x
>
>
> | >
> N = 6.
>
> Clearly, the dominating team (call it A) must draw at least twice. Since A needs to get some wins, not all of its matches can be draws, which means all teams have undrawn matches. These will be won by players, not all of which can be A, so some other team will have at least one win, and A must have at least two. In order for A to play four matches, N is at least five.
>
> Proof of impossibility for five: Let A beat B and C and draw against D and E, and let B and C draw against each other to minimine the total number of wins. D and E cannot draw, w.l.o.g D wins. Now D must lose to both B and C, which in turn must both lose to E, giving them two wins, a contradiction.
>
> Example scenario for N = 6: A draws against B,C and beats D,E,F. B beats C,D and loses to E,F. C loses to D and beats E,F, and D,E,F beat each other in a cycle.
>
> A has three wins and two draws, B,C have two wins and a draw each, D,E,F have two wins each.
>
>
> |
Question: I would like to replace multiple characters
```
echo "R \e&p[%20])l(a/ce" | sed 's|%20|-|g;s|\[||g;s|]||g;s| ||g;s|#||g;s|/||g;s|)||g;s|(||g;s|&||g;s|\\||g'
Rep-lace
```
Is there another way of doing so or is this it?
Replace %20 with - and the rest with nothing
Answer: | I'd use
```
echo "R \e&p[%20])l(a/ce" | sed 's/%20/-/g; s/[][ #/()&\\]//g'
```
Because the character set is easier to extend that way. The thing to know is that `]` has to be the first character in the set to be recognized as part of the set rather than the closing bracket.
Depending on what exactly it is you want to do, it may be worth a thought to invert the character set instead and replace everything but a specified number of characters. For example:
```
echo "R \e&p[%20])l(a/ce" | sed 's/%20/-/g; s/[^-[:alnum:]]//g'
```
This will replace `%20` with `-` and then remove all characters except `-` and alphanumeric characters. | In `Bash` you can use in *Parameter Expansion* + `sed`:
```
bash$ STR="R \e&p[%20])l(a/ce"
bash$ echo "${STR/"%20"/-}" | sed -r 's/[^a-z-]//gi'
Rep-lace
``` |
Question: I am making a forum that accesses threads based off the category in the URL using the GET method. I want to redirect to an error page if no parameters exist in the url, but I want this to be a generic piece of code that can be used around my whole site.
For example:
The url would normally contain the category id:
```
localhost/myforum/threads.php?categoryid=1
```
I want it so that when the url is:
```
localhost/myforum/threads.php
```
it is to redirect to an error page, and that this piece of code is usable all around the website
Answer: | Try:
```
$gets = parse_url($url));
if($gets['query'] == "")
{
echo "No GET variables";
}
``` | Just:
```
if (empty(array_diff($_GET, ['']))) {
header("Location: /path/to/error.php");
}
```
EDIT: Updated to remove empty values |
Question: I am making a forum that accesses threads based off the category in the URL using the GET method. I want to redirect to an error page if no parameters exist in the url, but I want this to be a generic piece of code that can be used around my whole site.
For example:
The url would normally contain the category id:
```
localhost/myforum/threads.php?categoryid=1
```
I want it so that when the url is:
```
localhost/myforum/threads.php
```
it is to redirect to an error page, and that this piece of code is usable all around the website
Answer: | Just:
```
if (empty(array_diff($_GET, ['']))) {
header("Location: /path/to/error.php");
}
```
EDIT: Updated to remove empty values | You can use is\_set to check if the parameter exists like this,
```
isset($_GET)
``` |
Question: I am making a forum that accesses threads based off the category in the URL using the GET method. I want to redirect to an error page if no parameters exist in the url, but I want this to be a generic piece of code that can be used around my whole site.
For example:
The url would normally contain the category id:
```
localhost/myforum/threads.php?categoryid=1
```
I want it so that when the url is:
```
localhost/myforum/threads.php
```
it is to redirect to an error page, and that this piece of code is usable all around the website
Answer: | The most reliable way is to check if the URL contains a question mark:
```php
if (false !== strpos($_SERVER['REQUEST_URI'], '?')) {
// There is a query string (including cases when it's empty)
}
``` | Just:
```
if (empty(array_diff($_GET, ['']))) {
header("Location: /path/to/error.php");
}
```
EDIT: Updated to remove empty values |
Question: I am making a forum that accesses threads based off the category in the URL using the GET method. I want to redirect to an error page if no parameters exist in the url, but I want this to be a generic piece of code that can be used around my whole site.
For example:
The url would normally contain the category id:
```
localhost/myforum/threads.php?categoryid=1
```
I want it so that when the url is:
```
localhost/myforum/threads.php
```
it is to redirect to an error page, and that this piece of code is usable all around the website
Answer: | Try:
```
$gets = parse_url($url));
if($gets['query'] == "")
{
echo "No GET variables";
}
``` | You can use is\_set to check if the parameter exists like this,
```
isset($_GET)
``` |