qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
345,274 | The main drawback in Rutherford's model of the atom as pointed out by Niels Bohr was that according to Maxwell's equations, a revolving charge experiences a centripetal acceleration hence it must radiate energy continuously as a result of which its kinetic energy is reduced and it eventually should fall into the nucleus. Bohr then proposed his own model in which he explained this through quantum theory stating that the general laws of electrodynamics and classical mechanincs do not apply in the case of electrons. Does this imply that if a body is revolving around another, then it will tend to spiral in towards the centre? If so, then how is the stability of the solar system explained? This question has been already asked but no satisfactory answers were recieved. Hence , I am reasking the same question | 2017/07/12 | [
"https://physics.stackexchange.com/questions/345274",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/78611/"
] | In classical electromagnetism, accelerated charges radiate. But the solar system is not held together by electromagnetic forces: it's held together by gravitation. In Newtonian gravity, accelerated objects do not radiate: indeed there is no wavelike solution in Newtonian gravity at all. So to the extent that Newtonian gravitation provides a good solution for the solar system, there is no radiation and the system is stable, at least in that sense (it may still lose energy by occasionally evicting objects due to close interactions).
But this is not the complete story: Newtonian gravitation is only an approximation to a more correct theory of gravitation, General Relativity. And in GR orbiting bodies *do* radiate power, in the form of gravitational waves, and therefore they *do* spiral in. But for the solar system the effect is extremely small: the power radiated by two orbiting bodies is
$$P = \frac{32 G^4}{5 c^5}
\frac{\left(m\_1 m\_2\right)^2 \left(m\_1 + m\_2\right)}{r^5}$$
where $m\_i$ is the mass of the $i$th body, $r$ is their separation (the orbit is assumed to be circular).
Well, you can compute this for the Earth-Sun system and $P \approx 200\,\mathrm{W}$, which is tiny. In particular compare it with the total energy in the Earth-Sun system according to Newtonian gravitation, which is given by:
$$E = -\frac{Gm\_1m\_2}{2r}$$
with assumptions that $m\_2\ll m\_1$. Note that $E$ is negative because the system is bound.
So, for Earth-Sun, $m\_1 \approx 2\times 10^{30}\,\mathrm{kg}$ (mass of Sun), $m\_2 \approx 6\times 10^{24}\,\mathrm{kg}$ (mass of Earth), $r\approx 1.5\times 10^{11}\,\mathrm{m}$ (semimajor axis of Earth's orbit), giving
$$E\approx - 2.6\times 10^{33}\,\mathrm{J}$$
Now I will be lazy and not do the integral I should do, but simply ask how long, assuming a constant $200\,\mathrm{W}$ of lost power (this is the lazy bit!), it would take to reduce $r$ to $0.9\times r$. Well, the change in energy is $\Delta E \approx 2.9\times 10^{32}\,\mathrm{J}$ (the lower orbit has a more negative energy, so energy is being extracted from the system as we would expect) and
$$\frac{\Delta E}{200\,\mathrm{J/s}} \approx 1.5\times 10^{30}\,\mathrm{s}$$
Well, the age of the universe is $4.3\times 10^{17}\,\mathrm{s}$ so this is about $3.4\times 10^{12}$ *times* the age of the universe, to radiate enough energy to lower Earth's orbit by a tenth. The real answer would be different as I've assumed constant power and been generally lazy, but not enough different to matter: this process takes stupidly long periods of time and the Earth's orbit around the Sun is, to all intents and purposes, stable over relatively short periods like the age of the universe: Newtonian gravitation is indeed a rather good approximation for the Earth-Sun system.
---
Of course, Newtonian gravitation fails to be a good approximation for very massive bodies in very close orbits, such as orbiting black holes, if their orbits are close enough (which eventually they will become). Two 10-solar-mass black holes orbiting each other at the radius of Earth's orbit (which is not close) radiate about $2\times 10^{16}$ times as much power as the Earth-Sun system, for instance. And very famously these systems do radiate a lot of power in their last moments as they spiral in: on the [14th of September 2015](https://en.wikipedia.org/wiki/First_observation_of_gravitational_waves) the first such event was detected. | As you said, charged objects produce electromagnetic radiation as they accelerate, and electrons can't have classical-style orbits for this reason. In contrast, the bodies in the solar system don't have very much net charge, so they don't generate very much electromagnetic radiation as they orbit. |
14,385,292 | I have the following /etc/hosts file
```
[root@vhost41 tmp]# cat hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
119.13.248.1 ccvcds1.ihost.com vcds1
171.221.160.11 vhost.ihost.com vhost41
[root@vhost41 tmp]# echo $(ifconfig eth0 | grep "inet addr:" | cut -d ":" -f 2 | cut -d " " -f 1)
171.221.160.11
```
How can I use sed or awk a single line to add "AWSHOST" to the the matching ip line. So the change would be:
```
[root@vhost41 tmp]# cat hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
119.13.248.1 ccvcds1.ihost.com vcds1
171.221.160.11 vhost.ihost.com vhost41 AWSHOST
```
I tried to pipe the outputof the above command to sed and awk and it is not working. Any help greatly appreciated | 2013/01/17 | [
"https://Stackoverflow.com/questions/14385292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988058/"
] | ```
sed -i "/$(ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | cut -d' ' -f1)[ \t]/ s/$/ AWHOST/ " hosts
``` | you can use `sed` to to this as such :
```
$ cat /etc/hosts
127.0.0.1 localhost
171.1.1.1 myhost
$ sudo sed -i 's/\(171\.1\.1\.1\).*/&\ mynewhost/g' /etc/hosts
$ cat /etc/hosts
127.0.0.1 localhost
171.1.1.1 myhost mynewhost
```
The ampersand `&` will be replaced by the caught expression e.g. here `171.1.1.1 myhost` and then you will append to it an escaped space and new host alias, here `mynewhost`
**EDIT**
As [David Ravetti](https://stackoverflow.com/users/1971315/david-ravetti) stated you can add an extension to be added to backup files if you do not want the file to be edited in place.
`sed -i .bak ......`
Then the file will be edited in place (replaced with your edit) but the original file will be backed up with `.bak` extension. |
9,943,789 | I just want to make a button using a RelativeLayout, so I can have as many drawables or textfields inside, and I want all the children to change color or drawable accordlingly to the RelativeLayout state.
If I press the custom button, it must have the correct colors and drawables.
Here is some code (only one TextView and an ImageView for the example):
In main.xml, the parent layout is a LinearLayout, here is the custom button:
```
<RelativeLayout
android:id="@+id/relativelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="25dp"
android:background="@drawable/background_state"
android:clickable="true"
android:focusable="true" >
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="8dip"
android:clickable="true"
android:text="Awesome text"
android:textColor="@color/textview_state"
android:textSize="20sp" />
<ImageView
android:id="@+id/imageview"
android:layout_width="51dip"
android:layout_height="51dip"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dip"
android:clickable="true"
android:src="@drawable/imageview_state" />
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_alignParentTop="true"
android:background="#FFFFFF"
android:clickable="false"
android:focusable="false" />
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_alignParentTop="true"
android:layout_marginTop="50dip"
android:background="#D3E992"
android:clickable="false"
android:focusable="false" />
</RelativeLayout>
```
In the drawable folder, imageview\_state.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/imageview_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/imageview" />
</selector>
```
In the drawable-hdpi folder, there is imageview.png and imageview\_pressed.png.
In the color folder, background\_state.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="#E0EBCC"/>
<item android:drawable="#669900"/>
</selector>
```
In the color folder, textview\_state.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#000"/>
<item android:color="#FFF"/>
</selector>
```
So far, when I click on the RelativeLayout, the RelativeLayout's background changes correctly, but the ImageView and the TextView stay in default state.
I tried setting the property android:clickable="true" for the TextView and the ImageView, but only the pressed element changes its state, not the whole button.
Any help to achieve my goal is welcome :) | 2012/03/30 | [
"https://Stackoverflow.com/questions/9943789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116427/"
] | A little known feature of the `DataGridView` is the ability to programmatically select some or all of the DataGridCells, and send them to a `DataObject` using the method `DataGridView.GetClipboardContent()`. Whats the advantage of this then?
A `DataObject` doesn't just store an object, but rather the representation of that object in various different formats. This is how the Clipboard is able to work its magic; it has various formats stored and different controls/classes can specify which format they wish to accept. In this case, the DataGridView will store the selected cells in the DataObject as a tab-delimited text format, a CSV format, or as HTML (\*).
The contents of the DataObject can be retrieved by calling the `DataObject.GetData()` or `DataObject.GetText()` methods and specifying a predefined data format enum. In this case, we want the format to be TextDataFormat.CommaSeparatedValue for CSV, then we can just write that result to a file using `System.IO.File` class.
*(\*) Actually, what it returns is not, strictly speaking, HTML. This format will also contain a data header that you were not expecting. While the header does contain the starting position of the HTML, I just discard anything above the HTML tag like `myString.Substring(IndexOf("<HTML>"));`.*
Observe the following code:
```
void SaveDataGridViewToCSV(string filename)
{
// Choose whether to write header. Use EnableWithoutHeaderText instead to omit header.
dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
// Select all the cells
dataGridView1.SelectAll();
// Copy selected cells to DataObject
DataObject dataObject = dataGridView1.GetClipboardContent();
// Get the text of the DataObject, and serialize it to a file
File.WriteAllText(filename, dataObject.GetText(TextDataFormat.CommaSeparatedValue));
}
```
Now, isn't that better? Why re-invent the wheel?
Hope this helps... | I think this is the correct for your SaveToCSV function : ( otherwise Null ...)
```
for (int i = 0; i < columnCount; i++)
```
Not :
```
for (int i = 1; (i - 1) < DGV.RowCount; i++)
``` |
8,358,261 | I have a set of integration test written in C# and NUnit and I want to run them in parallel on a build-machine. How do I do that? In a similar [question](https://stackoverflow.com/questions/3313163/how-can-i-run-nunit-tests-in-parallel) the accepted solution was:
* Create your own test runner
* Move to MBUnit
There is also a project [NUnit.MultiCore](https://nunitmulticore.codeplex.com/) but it is in Alpha version, which will be scary to use in production... Or run several standard NUnit runners in parallel using the build machine's capabilities, which is a workaround really rather than a durable solution.
Has anything changed so far? I would like to stay with NUnit and I am not too sure how easy it is to build my own test runner. | 2011/12/02 | [
"https://Stackoverflow.com/questions/8358261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706456/"
] | Starting with version 3, the NUnit framework itself supports parallel test execution. You may choose whether you want parallelism to be at test case level or fixture level.
More details are on [NUnit3 wiki at GitHub](https://github.com/nunit/docs/wiki/Parallel-Test-Execution) | What had good expieriences with a tool called ALPACA (see [homepage](http://ppcp.codeplex.com)). This analyzes the code and gives hints for data races and deadlocks. It's not perfect, but was very helpful. |
56,559 | Testing my contract locally with truffle. I have a function with the signature:
```
function purchase(address buyer, address seller, bytes16 bookId, uint tokens) public onlyOwner returns(bool success)
```
In truffle console I call this function as:
```
BookStore.deployed().then(function(instance){return instance.purchase(
'0xab67c3985384f5f4dc2fa828662f1f0601f81e62', //buyer
'0xd74ea687cc995cbbc1af6cf81106b31e32b4aa4f', //seller
[108, 120, 118, 13, 168, 153, 70, 225, 139, 168, 108, 184, 185, 58, 173, 17], //id
5) //tokens
;}).then(function(result){return result;});
```
When I debug the transaction I see that `tokens` has the value `2.316897056402557e+76`! But I'm passing 5.. what is happening? | 2018/08/15 | [
"https://ethereum.stackexchange.com/questions/56559",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/37258/"
] | OK, so I figured it out. I was misled by Redux DevTools that made me think that the action was not dispatched because when I filtered on the action's name, I didn't see anything. But apparently, the action was dispatched, but not picked up by Saga because there was a mistake in my initialization there:
```
export default function* root() {
yield all(
drizzleSagas.map(saga => fork(saga)),
takeEvery(actionTypes.GET_ETH_RATE, getEthRateSaga)
);
}
```
The issue is that all() expects an array, and I pass it an array and an isolated object. Here is the right syntax to fix that and append my takeEvery to the result of drizzleSagas.map():
```
export default function* root() {
yield all([
...drizzleSagas.map(saga => fork(saga)),
takeEvery(actionTypes.GET_ETH_RATE, getEthRateSaga)
]);
}
```
With that, everything works fine. | Your connect implementation is fine. Drizzle accepts mapDispatchToProps as you've implemented it here. (See the [source here](https://github.com/trufflesuite/drizzle-react/blob/master/src/drizzleConnect.js), if interested.) It looks to me like you've got a simple import error. You're exporting the action creator directly (`export const getEthRate`), but referencing it as `actions.getEthRate`. That would match up with the behavior you are seeing where the action is never dispatched, since `actions.getEthRate` would be undefined. |
13,511,502 | This is different from other "can I check the type of a block" posts on SO, as far as I can tell anyway.
I want to know if, given a block object of unknown signature, I can learn what arguments it accepts prior to invoking?
I have a situation where I have a number of callbacks associated with objects in a dictionary. I want some of those callbacks to expect a different set of arguments. The example here is extremely simplified, but I think it gets the point across.
How can I find out if a block is of a type I previously typedef'd?
```
//MyClass.m
// I start by declare two block types
typedef void (^callbackWithOneParam)(NSString*);
typedef void (^callbackWithTwoParams)(NSString*, NSObject*);
........
// I create a dictionary mapping objects to callback blocks
self.dict = @{
@"name": "Foo",
@"callback": ^(NSString *aString) {
// do stuff with string
}
}, {
@"name": "Bar",
@"callback": ^(NSString *aString, NSObject *anObject) {
// do stuff with string AND object
}
}
.....
// Later, this method is called.
// It looks up the "name" parameter in our dictionary,
// and invokes the associated callback accordingly.
-(void) invokeCallbackForName:(NSString*)name {
// What is the type of the result of this expression?
[self.dict objectForKey: name]
// I want to say: (pseudocode)
thecallback = [self.dict objectForKey: name];
if (thecallback is of type "callbackWithOneParam") {
thecallback(@"some param")
}
else if (thecallback is of type "callbackWithTwoParams") {
thecallback(@"some param", [[NSObject alloc] init]);
}
}
``` | 2012/11/22 | [
"https://Stackoverflow.com/questions/13511502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244374/"
] | Frankly, if the callbacks have different types, they should be under different keys. Why not use the keys `@"callbackWithOneParam"` and `@"callbackWithTwoParams"`? To me, that's superior to having a generic "callback" key plus a separate "type" key to tell you how to interpret the callback.
But what this really calls for is to use objects of custom classes instead of dictionaries. You've crossed the boundary where generic objects stop being convenient and start to cause more problems than they solve. | Personally, I use the ingenious [CTBlockDescription](https://github.com/ebf/CTObjectiveCRuntimeAdditions/blob/master/CTObjectiveCRuntimeAdditions/CTObjectiveCRuntimeAdditions/CTBlockDescription.h)...
>
> CTBlockDescription lets you inspect blocks including arguments and compile time features at runtime.
>
>
>
```
BOOL(^bk)(BOOL,id) = ^BOOL(BOOL ani, id obj) { return YES; };
```
---
```
[CTBlockDescription.alloc initWithBlock:bk].blockSignature.description;
```
---
```
<NSMethodSignature: 0x253f080>
number of arguments = 3
frame size = 12
is special struct return? NO
return value: -------- -------- -------- --------
type encoding (c) 'c'
flags {isSigned}
modifiers {}
frame {offset = 0, offset adjust = 0, size = 4, size adjust = -3}
memory {offset = 0, size = 1}
argument 0: -------- -------- -------- --------
type encoding (@) '@?'
flags {isObject, isBlock}
modifiers {}
frame {offset = 0, offset adjust = 0, size = 4, size adjust = 0}
memory {offset = 0, size = 4}
argument 1: -------- -------- -------- --------
type encoding (c) 'c'
flags {isSigned}
modifiers {}
frame {offset = 4, offset adjust = 0, size = 4, size adjust = -3}
memory {offset = 0, size = 1}
argument 2: -------- -------- -------- --------
type encoding (@) '@'
flags {isObject}
modifiers {}
frame {offset = 8, offset adjust = 0, size = 4, size adjust = 0}
memory {offset = 0, size = 4}
```
***Gorgeous...*** |
21,826,503 | **TABLE A**
```
ITEM BASE_WT BASE_AMT
AAA 50 500
BBB 100 6000
```
**TABLE B**
```
ITEM OUTDAY WT AMT
AAA 20140105 10 100
BBB 20140106 10 600
AAA 20140107 10 100
```
**TABLE A RESULT**
```
AAA 30 300
BBB 90 5400
```
**MSSQL QUERY**
```
UPDATE A SET
BASE_WT = BASE_WT - X.WT
BASE_AMT = BASE_AMT - X.AMT
FROM A,
(
SELECT ITEM , SUM(B.WT) WT, SUM(B.AMT) AMT
FROM B
WHERE OUTDAY BETWEEN '20140105' AND '20140107'
GROUP BY ITEM
) X
WHERE A.ITEM = X.ITEM
``` | 2014/02/17 | [
"https://Stackoverflow.com/questions/21826503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3318607/"
] | You dont have to do much to make what you want. I made a little js fiddle for you to see.
HTML:
```
<div id="div1">1</div>
<div id="div2">2</div>
```
CSS#:
```
#div1{
height: 40px;
width: 100px;
float: left;
background: blue;
}
#div2{
height: 40px;
background: red;
width: 100%;
}
```
[Fiddle](http://jsfiddle.net/M82pu/1/) | Try this.
```
#div1{
width:200px;
height: 40px;
float: left;
border: 1px solid black;
}
#div2{
clear:left;
height: 40px;
border: 1px solid black;
}
```
[**Demo Fiddle**](http://jsfiddle.net/tZfQL/) |
30,461,654 | I am learning Spring MVC, and am trying to troubleshoot an issue with an `@Autowired` Service object. I have the following annotation:
```
@Autowired
private UserServiceBLInt userService;
```
This is within the context of a `Controller` class, and I get a `NullPointerException` when using the `userService` object. Nowhere in the class am I manually instantiating the `userService` object, since my understanding is that for `@Autowired` to work, I have to let spring be responsible for creating the object.
My suspicion is that in the spring configuration file, the `component-scan base-package` declared incorrectly, so Spring doesn't know where to find the classes.
```
<context:component-scan base-package="com.app.service.**" />
```
The `UserServiceBLInt` is in `com.app.service.int`
The concrete implementation is in `com.app.service.impl`
Is the `**` notation correct? | 2015/05/26 | [
"https://Stackoverflow.com/questions/30461654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154644/"
] | This [tool](https://github.com/khellang/LangVersionFixer) I wrote might help you if you have many projects that you need to set `LangVersion` for. | Right click on Project in Project Explorer and select Properties.
When the Properties tab opens select Build and the click the Advance button in bottom right.
There is drop-down box called Language Version. Change the select to "C# 5.0" |
822 | The following is a "digest" version of the [July 2012 Moderator Election Town Hall Chat](https://webmasters.meta.stackexchange.com/questions/820/july-2012-moderator-town-hall-chat). The format, [as described on Meta Stack Overflow](https://meta.stackexchange.com/questions/77831/how-can-we-improve-the-town-hall-digests), is one *answer* to this question *for every question* asked in the Town Hall, containing all the candidate's answers to that question.
**To view the digest chronologically, please sort the answers by "oldest"**.
If you have questions or comments about this, **please do not answer this question** as the answers are designed to be used for the questions from the Town hall itself. Instead, please ask on [the parent question](https://meta.stackexchange.com/questions/77831/how-can-we-improve-the-town-hall-digests) or in [the Town Hall Discussion Room](http://chat.meta.stackoverflow.com/rooms/352/town-hall-discussion).
If you see any corrections which need to be made to this digest, or if you were a candidate who was unable to attend the town hall and would like your answers included, please @GraceNote or @TimStone [in the chat room](http://chat.stackexchange.com/rooms/4250/webmasters-town-hall-chat) and let us know! | 2012/07/27 | [
"https://webmasters.meta.stackexchange.com/questions/822",
"https://webmasters.meta.stackexchange.com",
"https://webmasters.meta.stackexchange.com/users/3665/"
] | *[Christofian http://www.gravatar.com/avatar/c35db03c7ecd3c62b6c89be47b60f3fd?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/c35db03c7ecd3c62b6c89be47b60f3fd?s=16&d=identicon&r=PG) [Christofian](http://chat.stackexchange.com/users/13590/christofian) [asked](http://chat.stackexchange.com/transcript/message/5521578#5521578):* **How can we make this site more active?**
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---
**[Christofian http://www.gravatar.com/avatar/c35db03c7ecd3c62b6c89be47b60f3fd?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/c35db03c7ecd3c62b6c89be47b60f3fd?s=16&d=identicon&r=PG) [Christofian](http://chat.stackexchange.com/users/13590/christofian) [answered](http://chat.stackexchange.com/transcript/message/5521882#5521882):** There was a [discussion about this on the meta](https://webmasters.meta.stackexchange.com/questions/633/what-can-be-done-to-get-webmasters-more-popular-in-2012), but I feel that my answer could use some updating. One of the things noticed in that discussion was that there are a lot of good questions on stack overflow and other sites that might be a better fit over here. As a moderator I can use the extra influence that comes with that position to get some of those questions migrated over here.
I think we need to get more interesting questions asked here. It's [OK to answer your question](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/), so hopefully that will encoradge more people to do that. I [posted more about this on the meta](https://webmasters.meta.stackexchange.com/q/660/6901), and while I haven't been asking any questions lately, I'm going to start doing so when I get back from vacation. It would be great if I could get 10 people committed to doing this: I think it would help out with the activity level a lot, and we would all learn a lot of new things.
Also, it would be great if more people would visit the chat. Getting a better sense of a community would be a great first step, and would help us coordinate any further efforts to make this site more active.
In addition, we might want to make sure that we are welcoming to newcomers. See here: <http://blog.stackoverflow.com/2012/07/kicking-off-the-summer-of-love/>. We wont gain activity if we push away new members.
However, there is only so much that a moderator can do. There is no magic button that I (or any mod) can press to make activity happen. This will require everyone’s involvement. Again, if we can get more people on the chat, it would be a great first step to coordinating an effort to make this site more active.
**[Aurelio De Rosa http://www.gravatar.com/avatar/8b01a8b4d7a0a9079a4e97b1ddedbe56?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/8b01a8b4d7a0a9079a4e97b1ddedbe56?s=16&d=identicon&r=PG) [Aurelio De Rosa](http://chat.stackexchange.com/users/27614/aurelio-de-rosa) [answered](http://chat.stackexchange.com/transcript/message/5534280#5534280):** The first thing that came to mind is this: Until few months ago Stackoverflow, that we all know is the most used website of the stackexchange network, has Webmaster as one of the options you can choose when you flag a question as off-topic. Now Webmaster is no more available, so people have to use the generic off-topic. I think that restoring the option could be worth for this website since a lot of users post questions about SEO, SEM and similar topics on Stackoverflow and having a direct option could let the discussions migrate easier. Other things that surely will help, but this is somehow reinventing the wheel, is to have more ads, mainly on Stackoverflow but also on other website, to let people discover Webmaster.
* **[paulmorriss http://www.gravatar.com/avatar/8691b744cb9151e4a173a23eb44eab3b?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/8691b744cb9151e4a173a23eb44eab3b?s=16&d=identicon&r=PG) [paulmorriss](http://chat.stackexchange.com/users/9263/paulmorriss) [remarked](http://chat.stackexchange.com/transcript/message/5534387#5534387):** Interesting. I didn't realise that we were even an option on Stackoverflow, as I don't spend much time there. I did some research a while back on a meta and it seems that list of options is drawn from the sites that questions get sent to: [Can we get ux on the "off topic - belongs on" list?](https://webmasters.meta.stackexchange.com/questions/771/can-we-get-ux-on-the-off-topic-belongs-on-list) So to get webmasters back on the list we need SO mods to send more stuff our way.
**[John Conde http://www.gravatar.com/avatar/64839d31baaefafa58120e1a5a503d66?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/64839d31baaefafa58120e1a5a503d66?s=16&d=identicon&r=PG) [John Conde](http://chat.stackexchange.com/users/77/john-conde) [noted](http://chat.stackexchange.com/transcript/message/5534419#5534419):** This can be done by flagging questions better suited for Webmasters such as SEO, payments (non-coding issues), etc. Picking some tags and following them is the best way to accomplish this. And they value flags from mods and generally migrate whatever we flag as being better suited for our site.
**[paulmorriss http://www.gravatar.com/avatar/8691b744cb9151e4a173a23eb44eab3b?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/8691b744cb9151e4a173a23eb44eab3b?s=16&d=identicon&r=PG) [paulmorriss](http://chat.stackexchange.com/users/9263/paulmorriss) [responded](http://chat.stackexchange.com/transcript/message/5534463#5534463):** Yes, I've done this with [hosting] but I didn't realise that seo was even a tag there.
**[Aurelio De Rosa http://www.gravatar.com/avatar/8b01a8b4d7a0a9079a4e97b1ddedbe56?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/8b01a8b4d7a0a9079a4e97b1ddedbe56?s=16&d=identicon&r=PG) [Aurelio De Rosa](http://chat.stackexchange.com/users/27614/aurelio-de-rosa) [added](http://chat.stackexchange.com/transcript/message/5534464#5534464):** Since I'm a very active SO user, I can say that there're lot of questions that are not sent to Webmaster even if they should
**[paulmorriss http://www.gravatar.com/avatar/8691b744cb9151e4a173a23eb44eab3b?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/8691b744cb9151e4a173a23eb44eab3b?s=16&d=identicon&r=PG) [paulmorriss](http://chat.stackexchange.com/users/9263/paulmorriss) [answered](http://chat.stackexchange.com/transcript/message/5534281#5534281):** I think Christofian's idea of a blog (suggested a few months ago on meta) would help attract more people to the site. I'm disappointed in how many questions are left unanswered, so we could do with more people with a variety of expertise. However a blog needs a small group of people who can write regular posts. So it's a chicken and egg situation.
**[paulmorriss http://www.gravatar.com/avatar/8691b744cb9151e4a173a23eb44eab3b?s=16&d=identicon&r=PG](http://www.gravatar.com/avatar/8691b744cb9151e4a173a23eb44eab3b?s=16&d=identicon&r=PG) [paulmorriss](http://chat.stackexchange.com/users/9263/paulmorriss) [continued](http://chat.stackexchange.com/transcript/message/5534334#5534334):** I think the key thing is to turn those looking for answer into those who give answers. I don't think we need a lot of daily activity, but we need quality questions and answers so that people value the site. | *Grace Note [Grace Note](http://chat.stackexchange.com/users/757/grace-note) [asked](http://chat.stackexchange.com/transcript/message/5535286#5535286):* We're nearing the close of the thing, so, to that end - **closing thoughts from the candidates**?
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---
** [Aurelio De Rosa](http://chat.stackexchange.com/users/27614/aurelio-de-rosa) [answered](http://chat.stackexchange.com/transcript/message/5535316#5535316):** I'll do what I can to improve community and the site but I'd love to do this kind of things with the help of the other moderators. My final proposal is merge, merge, merge......other sites, topics of other sites in the network and so on.
** [Christofian](http://chat.stackexchange.com/users/13590/christofian) [answered](http://chat.stackexchange.com/transcript/message/5535343#5535343):** I just want to say that it's been fun participating on the site and getting to know people, and that I'm looking forward to doing more of that when I get back.
** [paulmorriss](http://chat.stackexchange.com/users/9263/paulmorriss) [answered](http://chat.stackexchange.com/transcript/message/5535353#5535353):** I like webmasters. It's not super-crowded like SO. Very few problems with difficult people. I'd like to keep it that way, but improving - less unanswered questions, more experienced answerers. |
528,872 | I am trying to setup USB communication with an STM32F446RE
It is a custom board where:
* The clock source is an external 8Mhz quartz
* There is a micro USB port with USB+ connected to PA12 and USB- connected to PA11
The external quartz is working (I can load a firmware that just blinks a led) but I fail to enumerate the USB device with below message in the computer syslog.
I am using mbed with the NUCLEO F446RE configuration, I just enabled USB in the target configuration (USE\_USB\_OTG\_FS type)
Also, I noted that if I plug the board even without a firmware that is supposed to use USB, my computer tries to enumerate the device, however it shows a different message (like it's trying to enumerate a low-speed device instead of high-speed)
Do you have any idea/clue what could be going wrong?
```
Oct 23 19:13:51 destiny kernel: [4213209.733361] usb 1-10: new full-speed USB device number 17 using xhci_hcd
Oct 23 19:13:51 destiny kernel: [4213209.861500] usb 1-10: device descriptor read/64, error -71
Oct 23 19:13:51 destiny kernel: [4213210.097415] usb 1-10: device descriptor read/64, error -71
Oct 23 19:13:51 destiny kernel: [4213210.333311] usb 1-10: new full-speed USB device number 18 using xhci_hcd
Oct 23 19:13:51 destiny kernel: [4213210.461545] usb 1-10: device descriptor read/64, error -71
Oct 23 19:13:52 destiny kernel: [4213210.697528] usb 1-10: device descriptor read/64, error -71
Oct 23 19:13:52 destiny kernel: [4213210.805438] usb usb1-port10: attempt power cycle
Oct 23 19:13:52 destiny kernel: [4213211.461355] usb 1-10: new full-speed USB device number 19 using xhci_hcd
Oct 23 19:13:52 destiny kernel: [4213211.461721] usb 1-10: Device not responding to setup address.
Oct 23 19:13:53 destiny kernel: [4213211.669583] usb 1-10: Device not responding to setup address.
Oct 23 19:13:53 destiny kernel: [4213211.877357] usb 1-10: device not accepting address 19, error -71
Oct 23 19:13:53 destiny kernel: [4213212.005324] usb 1-10: new full-speed USB device number 20 using xhci_hcd
Oct 23 19:13:53 destiny kernel: [4213212.005568] usb 1-10: Device not responding to setup address.
Oct 23 19:13:53 destiny kernel: [4213212.213745] usb 1-10: Device not responding to setup address.
Oct 23 19:13:53 destiny kernel: [4213212.421346] usb 1-10: device not accepting address 20, error -71
Oct 23 19:13:53 destiny kernel: [4213212.421442] usb usb1-port10: unable to enumerate USB device
```
``` | 2020/10/23 | [
"https://electronics.stackexchange.com/questions/528872",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/90164/"
] | Yeah, well, your firmware needs to respond to the USB packets coming from the host. You seem to have enabled the USB hardware peripheral, but not included or at least not started any USB handling code. | Attempted enumeration of a low-speed device comes from a pull-up on D- alone - irrespective of any firmware that might or might not support USB. A pull-up on D+ would indicate a full-speed device (or a high speed one that must initially present as full speed before being stepped up)
In your case, what this low speed enumeration attempt was really reflecting was the accidental short between D- and VBus (which is additionally outside the bounds of the electrical spec, but *probably* survivable) |
71,156,992 | I have two files.
The first file contains, in each line, line number and text. For example:
```
2 AAAA
4 BBBB
5 nnnn
```
this text should replace the lines in the second file - according to the first column which is the line number on the second file.
So if initially the second files was:
```
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
```
after the change, it would be
```
XXXXX
AAAA
XXXXX
BBBB
nnnn
XXXXX
```
I thought using sed :
```
sed "$Ns/XXXXX/$A/" file > file-after-change
```
while `$N` is the line number (taken from the first file) and `$A` will be the string from the first file.
How can i read the line number first as variable `N` and the string itself to a different variable (`A`)? | 2022/02/17 | [
"https://Stackoverflow.com/questions/71156992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18232853/"
] | You can use `sed` to transform the first file into a `sed` script, and then pass that to a second `sed` instance.
```
sed 's%^\([0-9]*\) *\([^ ]*\)$%\1s/XXXXX/\2/' firstfile |
sed -f - secondfile
```
Linux `sed` will happily accept `-f -`; on some other platforms, maybe experiment with `-f /dev/stdin` or just save the generated script to a temporary file, and delete it when you are done. | Here is a potential solution that edits the "second.txt" file 'in place' and is along the lines of what you've already tried:
```
cat first.txt
2 AAAA
4 BBBB
5 nnnn
cat second.txt
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
# GNU sed
while read N A
do
sed -i "${N}s/XXXXX/${A}/" second.txt
done < first.txt
cat second.txt
XXXXX
AAAA
XXXXX
BBBB
nnnn
XXXXX
```
(macOS sed: `while read N A; do sed -i '' "${N}s/XXXXX/${A}/" second.txt; done < first.txt`) |
38,531,126 | Using Google Firebase in my ios swift app, I found the infamous message in my console output:
>
> App Transport Security has blocked a cleartext HTTP (http://) resource
> load since it is insecure. Temporary exceptions can be configured via
> your app's Info.plist file.
>
>
>
Using the method [here](https://stackoverflow.com/questions/31193579/how-can-i-figure-out-which-url-is-being-blocked-by-app-transport-security), I was able to find that this is triggered by a request to load `http://www.google-analytics.com/ga.js`, which is presumably from Firebase Analytics.
Do I need to add an exception for this? | 2016/07/22 | [
"https://Stackoverflow.com/questions/38531126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6426003/"
] | I'm using the `firebase/analytics` module (`firebase 7.1.0`) inside a react app using firebase hosting and I was getting an error trying to load the googletagmanager (which I am NOT doing explicitly, it is coming from the module).
`Mixed Content: The page at 'https://example.com/' was loaded over HTTPS, but requested an insecure script 'http://www.googletagmanager.com/gtag/js?id=someGTM-id'. This request has been blocked; the content must be served over HTTPS.`
I am not importing google analytics from inside the index.html file, rather I am loading firebase/analytics from a javascript file with basically:
```
import firebase from 'firebase/app';
import 'firebase/analytics';
const firebaseConfig = {
apiKey: "api-key",
authDomain: "project-id.firebaseapp.com",
databaseUrl: "https://project-id.firebaseio.com",
projectId: "project-id",
storageBucket: "project-id.appspot.com",
messagingSenderId: "sender-id",
appId: "app-id",
measurementId: "G-measurement-id",
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
```
I found: <https://developers.google.com/web/fundamentals/security/prevent-mixed-content/fixing-mixed-content>
and <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests>
And fixed it by placing the following line inside my `index.html` file:
```
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
``` | You do if you wish to use Firebase Analytics. Alternatively, you can disable analytics in the Firebase plist file. |
37,794,734 | I noticed an interesting problem while trying to debug a VBA routine that sorts the list of worksheets in a range and then redraws the border around that range.
The range containing is defined in Name Manager with the formula as shown below
```
=Tables!$L$2:$L$22
```
The problem that is occurring is that while doing the sheet name work, sometimes cells are deleted and sometimes cells are inserted. This CHANGES the cell address values in the named range. So if I deleted two cells and inserted one cell, the formula changes to
```
=Tables!$L$2:$L$21
```
And if I happen to insert into the first cell (L2), then the formula changes to
```
=Tables!$L$3:$L$22
```
I'm certain that problem can be solved using the header range name and offsetting by one, but I'm not sure how to do that in the formula for a named range as I've tried numerous ways and can't get it right. But I also need the ending range address to be static.
Any help appreciated. | 2016/06/13 | [
"https://Stackoverflow.com/questions/37794734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959663/"
] | I had a similar problem and it turned out that I archived the containing folder directly in my Archive.zip file, thus giving me this structure in the Archive.zip file:
```
RootFolder
- Dockerrun.aws.json
- Other files...
```
It turned out that by archiving only the RootFolder's content (and not the folder itself), Amazon Beanstalk recognized the ECS Task Definition file.
Hope this helps. | I got here due to the error. What my issue was is that I was deploying with a label using:
```
eb deploy --label MY_LABEL
```
What you need to do is deploy with `'`:
```
eb deploy --label 'MY_LABEL'
``` |
31,437,083 | I need help with BeautifulSoup, I'm trying to get the data:
`<font face="arial" font-size="16px" color="navy">001970000521</font>`
They are many and I need to get the value inside "font"
```
<div id="accounts" class="elementoOculto">
<table align="center" border="0" cellspacing=0 width="90%"> <tr><th align="left" colspan=2> permisos </th></tr><tr>
<td colspan=2>
<table width=100% align=center border=0 cellspacing=1>
<tr>
<th align=center width="20%">cuen</th>
<th align=center>Mods</th>
</tr>
</table>
</td>
</tr>
</table>
<table align="center" border="0" cellspacing=1 width="90%">
<tr bgcolor="whitesmoke" height="08">
<td align="left" width="20%">
<font face="arial" font-size="16px" color="navy">001970000521</font>
</td>
<td>......
<table align="center" border="0" cellspacing=1 width="90%">
<tr bgcolor="whitesmoke" height="08">
<td align="left" width="20%">
<font face="arial" font-size="16px" color="navy">001970000521</font>
</td>
```
I hope you can help me, thanks. | 2015/07/15 | [
"https://Stackoverflow.com/questions/31437083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4410003/"
] | how about this?
```
from bs4 import BeautifulSoup
str = '''<div id="accounts" class="elementoOculto">
<table align="center" border="0" cellspacing=0 width="90%"> <tr><th align="left" colspan=2> permisos </th></tr><tr>
<td colspan=2>
<table width=100% align=center border=0 cellspacing=1>
<tr>
<th align=center width="20%">cuen</th>
<th align=center>Mods</th>
</tr>
</table>
</td>
</tr>
</table>
<table align="center" border="0" cellspacing=1 width="90%">
<tr bgcolor="whitesmoke" height="08">
<td align="left" width="20%">
<font face="arial" font-size="16px" color="navy">001970000521</font>
</td>
<td>......
<table align="center" border="0" cellspacing=1 width="90%">
<tr bgcolor="whitesmoke" height="08">
<td align="left" width="20%">
<font face="arial" font-size="16px" color="navy">001970000521</font>
</td>'''
bs = BeautifulSoup(str)
print bs.font.string
``` | How about using a [CSS selector](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors) starting from the `div` with `id="accounts"`:
```
soup.select("div#accounts table > tr > font")
``` |
24,861,695 | I want to create a bouncy animation like in the Skitch application - when i press a button, a subview (simple view with several buttons) will appear from the side and will bounce a bit until it stops.
I can't find any standard animation that does that, so how i can implement this animation? | 2014/07/21 | [
"https://Stackoverflow.com/questions/24861695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243967/"
] | You can try this :
```
// Hide your view by setting its position to outside of the bounds of the screen
// Whenever you want, call this :
[UIView animateWithDuration:0.5
delay:0
usingSpringWithDamping:0.5
initialSpringVelocity:0
options:UIViewAnimationOptionCurveLinear
animations:^{
// Set your final view position here
}
completion:^(BOOL finished) {
}];
```
This method is the same as the usual `animateWithDuration:` but it introduces a spring animation. | Use UIView method:
```
+ (void)animateWithDuration:(NSTimeInterval)duration
delay:(NSTimeInterval)delay
usingSpringWithDamping:(CGFloat)dampingRatio
initialSpringVelocity:(CGFloat)velocity
options:(UIViewAnimationOptions)options
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion
```
This will do what you want |
64,337,292 | This is my HTML and CSS code where I want the animation to take place
```css
.pig {
animaton-name: apple;
animation-duration: 3s;
}
@keyframe apple {
from {
top: 0px;
}
to {
right: 200px;
}
}
```
```html
<div class='pig'>
<h2> About me </h2>
</div>
```
I'm trying to make my header move to the right, however it is not working, I am new to CSS, and I am using resources online but I can't figure out where I went wrong. | 2020/10/13 | [
"https://Stackoverflow.com/questions/64337292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9721392/"
] | first add `position : absolute` to .pig class because We need the position to be able to apply top , left , right ,bottom and then edit your `animaton-name` to `animation-name` and the last one is edit your `keyframe` to `keyframes`
```css
.pig {
animation-name: example;
animation-duration: 3s;
position: absolute;
}
@keyframes example {
from {
right: 0px;
}
to {
right: 200px;
}
}
```
```html
<div class='pig'>
<h2> About me </h2>
</div>
``` | Try this
```css
.pig{
animation: 3s linear 0s apple;
}
@keyframes apple {
from {
transform: translateX(0px);
}
to {
transform: translateX(200px);
}
}
```
```html
<div class = 'pig'>
<h2> About me </h2>
</div>
``` |
61,189,996 | I would like to align button in order to make responsive my web application.
The button are correctly aligned when the screen is large :
[Button correctly aligned](https://i.stack.imgur.com/UM1KU.png)
Here is a capture when the button are not correctly aligned :
[Button not correctly aligned](https://i.stack.imgur.com/oXA7e.png)
This is the sample :
```css
body{
display: block !important;
margin: 0 !important;
padding: 0 !important;
}
#message_bienvenue{
margin: 10px;
text-align: center;
width: 100%;
}
#bouton_mission{
margin: 0 auto;
}
#livraison_chauffeur{
margin: 0 auto;
padding-top: 20px;
width: 90%;
}
.container-fluid{
margin-top: 70px !important;
}
/* BOUTON */
.btn-circle.btn-xl {
position: relative;
width: 70px;
border-radius: 45px;
font-size: 34px;
padding: 0px;
margin: 5px
}
.btn-circle.btn-xl img{
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.btn-circle {
width: 30px;
height: 30px;
padding: 6px 0px;
border-radius: 15px;
text-align: center;
font-size: 12px;
line-height: 1.42857;
background-color: rgba(255, 255, 255, 0);
}
.text-button{
margin-top: 40px;
}
.text-button label{
font-size: 11px;
}
.block-mission{
text-align: center;
}
.block-mission label{
margin-top: 20px;
}
.btn-1 {
background-image: url("https://pngimage.net/wp-content/uploads/2018/06/icon-ok-png-2.png");
background-size: contain;
background-repeat: no-repeat;
width: 40px;
height: 40px;
}
.btn-2 {
background-image: url("https://pngimage.net/wp-content/uploads/2018/06/icon-ok-png-2.png");
background-size: contain;
background-repeat: no-repeat;
width: 70px;
height: 70px;
}
.btn-3 {
background-image: url("https://pngimage.net/wp-content/uploads/2018/06/icon-ok-png-2.png");
background-size: contain;
background-repeat: no-repeat;
width: 40px;
height: 40px;
}
```
```html
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="">
<title>Title</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://getbootstrap.com/docs/4.0/examples/sign-in/signin.css" integrity="sha384-mKB41Eu6sQQvXR8fqvXcVe8SXodkH6cYtVvHkvLwE7Nq0R/+coO4yJispNYKy9iZ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</head>
<body>
<div class="container-fluid" style="margin-top: 0px !important">
<form method="post" action="requetes/page.php" role="form" id="formulaire">
<h3>Créer mission :</h3>
<hr/>
<input class="form-control" id="numero_bon" type="number" min="0" name="numero_bon" placeholder="Numéro de bon de livraison" required>
<hr/>
<input class="form-control" id="nom_client" name="nom_client" type="text" placeholder="Client" required>
<hr/>
<input class="form-control" id="adresse_client" name="adresse_client" type="text" placeholder="Adresse" required>
<hr/>
<input class="form-control" id="volume_livraison" type="number" name="volume_livraison" placeholder="M³" pattern="[0-9]+([\.,][0-9]+)?" step="0.01" formnovalidate required>
<hr/>
<input class="form-control" id="nom_centrale"type="text" name="nom_centrale" placeholder="Centrale" required>
<hr/>
<span class="label label-default">Zone</span>
<select class="form-control form-control-sm" id="zone" type="text" name="zone">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
</select>
<hr/>
<div class="container-fluid" style="margin-top: 0 !important">
<div class="row d-flex justify-content-around">
<div class="d-flex flex-column align-items-center block-mission">
<button class="btn btn-circle btn-small btn-1" id="creer_mission_replacee" name="type_voyage" value="Replacé" type="submit">
</button>
<label>Voyage validé replacé</label>
</div>
<div class="d-flex flex-column align-items-center block-mission">
<button class="btn btn-circle btn-small btn-2" id="creer_mission" name="type_voyage" value="Livré" type="submit">
</button>
<label>Livraison effectuée validée</label>
</div>
<div class="d-flex flex-column align-items-center block-mission">
<button class="btn btn-circle btn-small btn-3" id="creer_mission_annulee" name="type_voyage" value="Annulé" type="submit">
</button>
<label>Voyage annulé</label>
</div>
</div>
</div>
</form>
</div>
</body>
</html>
```
Someone could fix my code ? I don't know how to do it ? To the problem : Click on `Run code snippet` --> `Full page` --> Reduce your browser border to the minimum. | 2020/04/13 | [
"https://Stackoverflow.com/questions/61189996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Here's a slight improvement:
```
def _if_between(value, arr):
if any([borders[0] <= value <= borders[1] for borders in arr]):
return True
return False
``` | Pandas 1.0.3 has an [IntervalArray](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.arrays.IntervalArray.html) type which has a contains method to check if a number exists in any interval in the array:
```
import pandas as pd
borders = [
[ 7848, 10705],
[10861, 13559],
[13747, 16319],
[16792, 19427],
[19963, 22535]
]
intervals = pd.arrays.IntervalArray.from_tuples(borders)
result = intervals.contains(19426)
```
result variable will look as follows:
```
array([False, False, False, True, False])
``` |
34,670 | If I left food out of the refrigerator for some period of time, is it still safe? If I left it out too long, can I salvage it by cooking it more? | 2013/06/13 | [
"https://cooking.stackexchange.com/questions/34670",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/14401/"
] | The question was: "If I left food out of the refrigerator for some period of time, is it still safe? If I left it out too long, can I salvage it by cooking it more?"
Answer: It depends ...
* How long did you leave it outside the fridge?
* What kind of food are we talking about?
* What is the moisture content of the food and the humidity of the air in the room?
* Is the air reasonably clean. Did you put it on a clean or contaminated surface?
* Is it raw or cooked food?
These are just a couple of questions so you get the general idea that it really is impossible to give a generalized answer to the question.
Considering that only a surprisingly small percentage of the worlds population actually has access to refrigerators and people still eat I think it might be obvious that refrigeration is really not the only way to store food for later consumption.
For a more in depth study of the topic I recommend:
Food Safety: The Science of Keeping Food Safe By Ian C. Shaw
As a more general tip I would stick to common sense. e.g. any food containing raw eggs (Mayonnaise) or food that must by its nature be considered contaminated (store bought raw chicken / raw meat) needs to be handled in a reasonable matter (you should be able to find the correct advise about handling these kinds of foods in any good cookbook) to avoid colonisation to an unhealthy (when eaten - even after cooking) point. On the other end of the spectrum leafy vegetables or fruit bought fresh from a farmers market actually comes with its own protection in the form of beneficial bacteria on the skin and is therefore less likely to be easily (meaning in a short time) colonized by pathogenetic organisms. Learn about your food and learn how to cook and you probably will be safe. | (in reply to a closed question:
>
> I left two bags of groceries in the car overnight. A beef shoulder roast, a pork loin, pack of ground beef and some smoked sausage. They were cold to the touch. That was our food for the week. Not sure what I should do.
>
>
>
The rule of thumb (and of the USDA) is: after two hours in the "danger zone" - temperatures between 5-60c/40-140f - the food has to go. That's the official answer and the only responsible one.
But it's indeed a one-size-fits-all-play-it-safe rule. Bacteria's growth rate rises with temperature until they start dying around 60c/140f. Two hours in a humid 40c/105f will turn fresh meat into a small civilization. But under 10c/50f there'll hardly be a change.
So as Kate Gregory wrote, the question is where you are, and how cold is it over there. If your food was left covered in cold "storage" temperatures, and in the morning felt cold and firm to the touch and smelled fine, it has stayed unspoiled. Problem is: you can't know. I still might be unsafe. Not all food spoilage shows or smells.
Still, if you consider taking the risk, you should always throw away the ground beef. Bacteria grows on the surface of foods. According to common sense, you can make a wholesome piece of meat safe by cooking it and sterilize its surface (only that here you need to be guided not by common sense but by a health expert). But either way - in ground meat the outside and the inside are mixed, and any contamination on the meat was spread all across it *before* the fearful night. So give up the ground meat and |
11,747,761 | The problem is that after I added the new class, the error came up when I did build the solution. What can be wrong?
In Form1, I don’t have any code yet.
I just added a new class:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenHardwareMonitor.Hardware;
namespace OpenHardwareMonitorReport
{
class Program
{
static void Main(string[] args)
{
Computer computer = new Computer();
computer.Open();
var temps = new List<decimal>();
foreach (var hardware in computer.Hardware)
{
if (hardware.HardwareType != HardwareType.CPU)
continue;
hardware.Update();
foreach (var sensor in hardware.Sensors)
{
if (sensor.SensorType != SensorType.Temperature)
{
if (sensor.Value != null)
temps.Add((decimal)sensor.Value);
}
}
}
foreach (decimal temp in temps)
{
Console.WriteLine(temp);
}
Console.ReadLine();
}
}
}
```
Then I see file *Program.cs* and the error on Main():
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace NvidiaTemp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Error 2 Program 'D:\C-Sharp\NvidiaTemp\NvidiaTemp\NvidiaTemp\obj\x86\Debug\NvidiaTemp.exe' has more than one entry point defined: 'NvidiaTemp.Program.Main()'. Compile with /main to specify the type that contains the entry point. D:\C-Sharp\NvidiaTemp\NvidiaTemp\NvidiaTemp\Program.cs 14 21 NvidiaTemp
``` | 2012/07/31 | [
"https://Stackoverflow.com/questions/11747761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1544479/"
] | Having two *Main* methods is just fine. If you receive the error you mentioned then you need only to tell Visual Studio which one you'd like to use.
1. Right-click on your project to view the properties.
2. Go to the *Application* tab and choose the entry point you desire from the *Startup object* dropdown.
Here's an example where I have two entry points depending on how I want to dev-test the assembly.
[](https://i.stack.imgur.com/mlKYc.png)
[](https://i.stack.imgur.com/ymcix.png)
[](https://i.stack.imgur.com/cDy3e.png) | An entry point may be chosen by add `StartupObject` into your .cspoj
```
<StartupObject>MyApplication.Core.Program</StartupObject>
```
See [-main (C# Compiler Options)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/main-compiler-option) |
4,267,928 | Adding indexes is often suggested here as a remedy for performance problems.
(I'm talking about reading & querying ONLY, we all know indexes can make writing slower).
I have tried this remedy many times, over many years, both on DB2 and MSSQL, and the result were invariably disappointing.
My finding has been that no matter how 'obvious' it was that an index would make things better, it turned out that the query optimiser was smarter, and my cleverly-chosen index almost always made things worse.
I should point out that my experiences relate mostly to small tables (<100'000 rows).
Can anyone provide some down-to-earth guidelines on choices for indexing?
The correct answer would be a list of recommendations something like:
* Never/always index a table with less than/more than NNNN records
* Never/always consider indexes on multi-field keys
* Never/always use clustered indexes
* Never/always use more than NNN indexes on a single table
* Never/always add an index when [some magic condition I'm dying to learn about]
Ideally, the answer will give some instructive examples. | 2010/11/24 | [
"https://Stackoverflow.com/questions/4267928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338101/"
] | An index that's never used is a waste of disk space, as well as adding to the insert/update/delete time. It's probably best to define the clustering index first, then define
additional indexes as you find yourself writing `WHERE` clauses.
One common index mistake I see is people wondering why a select on col2 (or col3) takes so long when the index is defined as `col1 ASC, col2 ASC, col3 ASC`. When you have a multiple column index, your `WHERE` clause must use the first column in the index, or the first and second column in the index, and so forth.
If you need to access the data by col2, then you need an additional index that's defined as `col2 ASC`.
With small domain tables, it's sometimes faster to do a table scan than it is to read rows from the table using an index. This depends on the speed of your database machine and the speed of the network. | You need indexes. Only with indexes you can access data fast enough.
To make it as short as possible:
* add indexes for columns you are frequently filtering (or grouping) for. (eg. a state or name)
* `like` and sql functions could make the DBMS not use indexes.
* add indexes only on columns which have many different values (eg. no boolean fields)
* It is common to add indexes to foreign keys, but it is not always needed.
* don't add indexes in very short tables
* never add indexes when you don't know how they should enhance performance.
Finally: look into execution plans to decide how to optimize queries.
You'll add indexes just for a single, critical query. In this case, you'll add exactly the indexes that are needed in the query in question (multi-column indexes). |
4,444,710 | Is it possible to remove the YouTube logo from a chromeless player? | 2010/12/14 | [
"https://Stackoverflow.com/questions/4444710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267945/"
] | You can't and you shouldn't.
>
> If you use the Embeddable Player on
> your website, you may not modify,
> build upon, or block any portion or
> functionality of the Embeddable
> Player, including but not limited to
> links back to the YouTube website.
>
>
>
www.youtube.com/static?gl=US&template=terms | You can, just add the code `?modestbranding=1` : [check here](http://youtube-global.blogspot.com/2011/06/next-step-in-embedded-videos-hd-preview.html) |
243,800 | **The Situation**
I have an area of the screen that can be shown and hidden via JavaScript (something like "show/hide advanced search options"). Inside this area there are form elements (select, checkbox, etc). For users using assistive technology like a screen-reader (in this case JAWS), we need to link these form elements with a label or use the "title" attribute to describe the purpose of each element. I'm using the title attribute because there isn't enough space for a label, and the tooltip you get is nice for non-screen-reader users.
The code looks something like this:
```
<div id="placeholder" style="display:none;">
<select title="Month">
<option>January</option>
<option>February</option>
...
</select>
</div>
```
**The Problem**
Normally, JAWS will not read hidden elements... because well, they're hidden and it knows that. However, it seems as though if the element has a title set, JAWS reads it no matter what. If I remove the title, JAWS reads nothing, but obviously this is in-accessible markup.
**Possible Solutions**
My first thought was to use a hidden label instead of the title, like this:
```
<div id="placeholder" style="display:none;">
<label for="month" style="display:none">Month</label>
<select id="month">...</select>
</div>
```
This results in the exact same behavior, and now we lose the tool-tips for non-screen-reader users. Also we end up generating twice as much Html.
The second option is to still use a label, put position it off the screen. That way it will be read by the screen-reader, but won't be seen by the visual user:
```
<div id="placeholder" style="display:none;">
<label for="month" style="position:absolute;left:-5000px:width:1px;">Month</label>
<select id="month">...</select>
</div>
```
This actually works, but again we lose the tool-tip and still generate additional Html.
My third possible solution is to recursively travel through the DOM in JavaScript, removing the title when the area is hidden and adding it back when the area is shown. This also works... but is pretty ugly for obvious reasons and doesn't really scale well to a more general case.
Any other ideas anyone? Why is JAWS behaving this way? | 2008/10/28 | [
"https://Stackoverflow.com/questions/243800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9960/"
] | Give items the aria-hidden="true" attribute, and it should be hidden from the screenreader. | This definitely looks like a bug in JAWS as the spec definitively states that display:none should cause an element and its children not to be displayed in any media.
However, playing with the speak: aural property might be useful? I don't know as I don't have JAWS available.
[<http://www.w3.org/TR/CSS2/aural.html#speaking-props>](http://www.w3.org/TR/CSS2/aural.html#speaking-props) |
20,091,197 | I have a image with noise. i want to remove all background variation from an image and want a plain image .My image is a retinal image and i want only the blood vessel and the retinal ring to remain how do i do it? 1 image is my original image and 2 image is how i want it to be.
this is my convoluted image with noise

 | 2013/11/20 | [
"https://Stackoverflow.com/questions/20091197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959820/"
] | There are multiple approaches for blood vessel extraction in retina images.
You can find a thorough overview of different approaches in [Review of Blood Vessel Extraction Techniques and Algorithms](http://www.siue.edu/~sumbaug/RetinalProjectPapers/Review%20of%20Blood%20Vessel%20Extraction%20Techniques%20and%20Algorithms.pdf). It covers prominent works of many approache.
As Martin mentioned, we have the Hessian-based [Multiscale Vessel Enhancement Filtering](http://www.dtic.upf.edu/~afrangi/articles/miccai1998.pdf) by Frangi et al. which has been shown to work well for many vessel-like structures both in 2D and 3D. There is a Matlab implementation, [FrangiFilter2D](http://www.mathworks.com/matlabcentral/fileexchange/24409-hessian-based-frangi-vesselness-filter), that works on 2D vessel images. The overview fails to mention Frangi but cover other works that use Hessian-based methods. I would still recommend trying Frangi's *vesselness* approach since it is both powerful and simple.
Aside from the Hesisan-based methods, I would recommend looking into morphology-based methods since Matlab provides a good base for morphological operations. One such method is presented in [An Automatic Hybrid Method for Retinal Blood Vessel Extraction](http://www.zbc.uz.zgora.pl/Content/13666/AMCS_18_3_13.pdf). It uses a morphological approach with openings/closings together with the top-hat transform. It then complements the morphological approach with fuzzy clustering and some post processing. I haven't tried to reproduce their method, but the results look solid and the paper is freely available online. | This is **not** an easy task.
Detecting boundary of blood vessals - try `edge( I, 'canny' )` and play with the threshold parameters to see what you can get.
A more advanced option is to use [this method for detecting faint curves in noisy images](http://www.wisdom.weizmann.ac.il/~meirav/Curves_Alpert_Galun_Nadler_Basri.pdf "ECCV 2010").
Once you have reasonably good edges of the blood vessals you can do the segmentation using watershed / NCuts or boundary-sensitive version of meanshift.
Some pointers:
- the blood vessals seems to have relatively the same thickness, much like text strokes. Would you consider using [Stroke Width Transform (SWT)](http://www.math.tau.ac.il/~turkel/imagepapers/text_detection.pdf "Boris Epshtein Eyal Ofek and Yonatan Wexler, Detecting Text in Natural Scenes with Stroke Width Transform, CVPR 2010") to identify them? A mex implementation of SWT can be found [here](https://stackoverflow.com/a/19971599/1714410).
- If you have reasonably good boundaries, you can consider [this approach](https://stackoverflow.com/questions/18972932/image-segmentation-based-on-edge-pixel-map/19510366#19510366) for segmentation.
Good luck. |
60,313,610 | I'm trying to share a link which would redirect a user to YouTube link if clicked on a desktop browser and redirect to the app if clicked on Android.The links are working fine but I'm getting the deep link instead of short link
```
Uri uri = getIntent().getData();
String path = uri.getPath();
```
Is there a way to get the short link in android ? | 2020/02/20 | [
"https://Stackoverflow.com/questions/60313610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10121512/"
] | the base routing structure in react is like below:
### 1.Root Component:
basically you have a Root Component in your application, mainly the `<App />` component
### 2.Inner Components:
inside of your `<App />` component you render 2 type of components:
1. components that should render in your routes
2. components that are shared between your routes ( which means that they are visible in every route )
type 2 components would render on each route, because they are out of `Switch`, like code structure below:
```
function App(props) {
return (
<>
<Header />
<Switch>
...your routes
</Switch>
<SharedComponent_1 /> // may be a notif manager
<SharedComponent_2 /> // may be a footer
<SharedComponent_1 /> // other type of shared component
</>
)
}
```
if you want to navigate from a route to another route inside of your component logic, you should ask your self two questions about your component:
1. is my component directly rendered by a `<Route ... />`?
2. is my component is just a simple sub component that rendered by another component which rendered by a `<Router ... />`
if your component has criteria of condition 1, then you already have `history, match, location` in your props and you can use `history.push('/targetRoute')` to navigate your user to another route.
however, if your component has criteras described in condition 2, you should wrap your component by a `withRouter` to get `history`, `match` and `location` into your props and user `push` function of `history` to navigate user around. | This function should be work on your code:
```
changeToggleMenuValue() {
this.setState({
toggleValue:
this.state.toggleValue
? history.push('') // or history.push('/')
: history.push('/videos');
});
}
``` |
65,308,798 | I have a program that prints data into the console like so (separated by space):
```
variable1 value1
variable2 value2
variable3 value3
varialbe4 value4
```
**EDIT:** Actually the output can look like this:
```
data[variable1]: value1
pre[variable2] value2
variable3: value3
flag[variable4] value4
```
In the end I want to search for a part of the name e.g. for `variable2` or `variable3` but only get `value2` or `value3` as output.
**EDIT:** This single value should then be stored in a variable for further processing within the bash script.
I first tried to put all the console output into a file and process it from there with e.g.
```
# value3_var="$(grep "variable3" file.log | cut -d " " -f2)"
```
This works fine but is too slow. I need to process ~20 of these variables per run and this takes ~1-2 seconds on my system. Also I need to do this for ~500 runs. **EDIT:** I actually do not need to automatically process all of the ~20 'searches' automatically with one call of e.g. awk. If there is a way to do it automaticaly, it's fine, but ~20 calls in the bash script are fine here too.
Therefore I thought about putting the console output directly into a variable to remove the slow file access. But this will then eliminate the newline characters which then again makes it more complicated to process:
```
# console_output=$(./programm_call)
# echo $console_output
variable1 value1 variable2 value2 variable3 value3 varialbe4 value4
```
**EDIT:** IT actually looks like this:
```
# console_output=$(./programm_call)
# echo $console_output
data[variable1]: value1 pre[variable2] value2 variable3: value3 flag[variable4] value4
```
I found a solution for this kind of string arangement, but these seem only to work with a text file. At least I was not able to use the string stored in `$console_output` with these examples
[How to print the next word after a found pattern with grep,sed and awk?](https://stackoverflow.com/questions/48606867/how-to-print-the-next-word-after-a-found-pattern-with-grep-sed-and-awk)
So, how can I output the next word after a found pattern, when providing a (long) string as variable?
PS: grep on my system does not know the parameter -P... | 2020/12/15 | [
"https://Stackoverflow.com/questions/65308798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12663842/"
] | I'd suggest to use `awk`:
```
$ cat ip.txt
data[variable1]: value1
pre[variable2] value2
variable3: value3
flag[variable4] value4
$ cat var_list
variable1
variable3
$ awk 'NR==FNR{a[$1]; next}
{for(k in a) if(index($1, k)) print $2}' var_list ip.txt
value1
value3
```
To use output of another command as input file, use `./programm_call | awk '...' var_list -` where `-` will indicate `stdin` as input.
>
> This single value should then be stored in a variable for further processing within the bash script.
>
>
>
If you are doing further text processing, you could do it within `awk` and thus avoid a possible slower `bash` loop. See [Why is using a shell loop to process text considered bad practice?](https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice) for details.
Speed up suggestions:
* Use `LC_ALL=C awk '..'` if input is ASCII (Note that as pointed out in comments, this doesn't apply for all cases, so you'll have to test it for your use case)
* Use `mawk` if available, that is usually faster. `GNU awk` may still be faster for some cases, so again, you'll have to test it for your use case
* Use [ripgrep](https://github.com/BurntSushi/ripgrep), which is usually faster than other `grep` programs.
```sh
$ ./programm_call | rg -No -m1 'variable1\S*\s+(\S+)' -r '$1'
value1
$ ./programm_call | rg -No -m1 'variable3\S*\s+(\S+)' -r '$1'
value3
```
Here, `-o` option is used to get only the matched portion. `-r` is used to get only the required text by replacing the matched portion with the value from the capture group. `-m1` option is used to stop searching input once the first match is found. `-N` is used to disable line number prefix. | This is how to do the job efficiently AND robustly (your approach and all other current answers will result in false matches from some input and some values of the variables you want to search for):
```
$ cat tst.sh
#!/usr/bin/env bash
vars='variable2 variable3'
awk -v vars="$vars" '
BEGIN {
split(vars,tmp)
for (i in tmp) {
tags[tmp[i]":"]
tags["["tmp[i]"]"]
tags["["tmp[i]"]:"]
}
}
$1 in tags || ( (s=index($1,"[")) && (substr($1,s) in tags) ) {
print $2
}
' "${@:--}"
```
```
$ ./tst.sh file
value2
value3
```
```
$ cat file | ./tst.sh
value2
value3
```
Note that the only loop is in the BEGIN section where it populates a hash table (`tags[]`) with the strings from the input that could match your variable list so that while processing the input it doesn't have to loop, it just does a hash lookup of the current $1 which will be very efficient as well as robust (e.g. will not fail on partial matches or even regexp metachars).
As shown, it'll work whether the input is coming from a file or a pipe. If that's not all you need then edit your question to clarify your requirements and improve your example to show a case where this does not do what you want. |
1,359,643 | I am moving a folder recursively between two filesystems using mv -v.
It seems like deletions happen at the end (in order to make mv *transactional* ?). I don't have enough space to hold two copies of the same folder, is there a way to force mv to delete a file as soon as it is done? | 2018/09/19 | [
"https://superuser.com/questions/1359643",
"https://superuser.com",
"https://superuser.com/users/220911/"
] | As the other answers and comments note, there is no such functionality in `mv`. But `rsync` has a `--remove-source-files` switch which behaves as you want, removing files from the source continuously as the operation progresses.
I'd also recommend the `-a` switch ("archive mode") to preserve (most) file metadata if you're making backups (`mv` doesn't do this if the move is between filesystems, so `rsync` is actually better in that regard). | No, the [Man pages](https://linux.die.net/man/1/mv) for `mv` do not indicate any switches that change the behavior of the command in the way you describe. You will have to look into other commands or algorithms.
>
> **Name**
>
>
> mv - move (rename) files Synopsis
>
>
> *mv [OPTION]... [-T] SOURCE DEST*
>
>
> *mv [OPTION]... SOURCE... DIRECTORY*
>
>
> *mv [OPTION]... -t DIRECTORY*
> SOURCE...
>
>
> **Description**
>
>
> Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.
>
>
> Mandatory arguments to long options are mandatory for short options
> too.
>
>
> --backup[=CONTROL]
>
>
>
> ```
> make a backup of each existing destination file
>
> ```
>
> -b
>
>
>
> ```
> like --backup but does not accept an argument
>
> ```
>
> -f, --force
>
>
>
> ```
> do not prompt before overwriting
>
> ```
>
> -i, --interactive
>
>
>
> ```
> prompt before overwrite
>
> ```
>
> -n, --no-clobber
>
>
>
> ```
> do not overwrite an existing file
>
> ```
>
> If you specify more than one of -i, -f, -n, only the final one takes
> effect.
>
>
> --strip-trailing-slashes
>
>
>
> ```
> remove any trailing slashes from each SOURCE argument
>
> ```
>
> -S, --suffix=SUFFIX
>
>
>
> ```
> override the usual backup suffix
>
> ```
>
> -t, --target-directory=DIRECTORY
>
>
>
> ```
> move all SOURCE arguments into DIRECTORY
>
> ```
>
> -T, --no-target-directory
>
>
>
> ```
> treat DEST as a normal file
>
> ```
>
> -u, --update
>
>
>
> ```
> move only when the SOURCE file is newer than the destination file or when the destination file is missing
>
> ```
>
> -v, --verbose
>
>
>
> ```
> explain what is being done
>
> ```
>
> --help
>
>
>
> ```
> display this help and exit
>
> ```
>
> --version
>
>
>
> ```
> output version information and exit
>
> ```
>
> The backup suffix is '~', unless set with --suffix or
> SIMPLE\_BACKUP\_SUFFIX. The version control method may be selected via
> the --backup option or through the VERSION\_CONTROL environment
> variable. Here are the values:
>
>
> none, off
>
>
>
> ```
> never make backups (even if --backup is given)
>
> ```
>
> numbered,t
>
>
>
> ```
> make numbered backups
>
> ```
>
> existing, nil
>
>
>
> ```
> numbered if numbered backups exist, simple otherwise
>
> ```
>
> simple, never
>
>
>
> ```
> always make simple backups
>
> ```
>
>
Source: <https://linux.die.net/man/1/mv> |
52,558,770 | I have a table that is presenting a list of items that I got using the following code:
```
interface getResources {
title: string;
category: string;
uri: string;
icon: string;
}
@Component
export default class uservalues extends Vue {
resources: getResources[] = [];
created() {
fetch('api/Resources/GetResources')
.then(response => response.json() as Promise<getResources[]>)
.then(data => {
this.resources = data;
});
}
}
}
```
And this is my table:
```
<div class="panel panel-default">
<div class="panel-heading" style="font-weight:bold"><span class="glyphicon glyphicon-align-justify"></span> All Resources</div>
<div class="row">
<div class="search-wrapper panel-heading col-sm-12">
<input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
</div>
</div>
<div class="panel-body" style="max-height: 400px;overflow-y: scroll;">
<table v-if="resources.length" class="table">
<thead>
<tr>
<th>Resource</th>
</tr>
</thead>
<tbody>
<tr v-for="item in resources">
<td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
```
I'm trying to implement a Search bar that filters the results for the user but I'm lost!
Any suggestions? | 2018/09/28 | [
"https://Stackoverflow.com/questions/52558770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3376642/"
] | You can use the `includes()` function of the `array` to search any position in a sentence or phrase.
```js
new Vue({
el: '#app',
data() {
return {
searchQuery: null,
resources:[
{title:"ABE Attendance",uri:"aaaa.com",category:"a",icon:null},
{title:"Accounting Services",uri:"aaaa.com",category:"a",icon:null},
{title:"Administration",uri:"aaaa.com",category:"a",icon:null},
{title:"Advanced Student Lookup",uri:"bbbb.com",category:"b",icon:null},
{title:"Art & Sciences",uri:"bbbb.com",category:"b",icon:null},
{title:"Auxiliares Services",uri:"bbbb.com",category:"b",icon:null},
{title:"Basic Skills",uri:"cccc.com",category:"c",icon:null},
{title:"Board of Trustees",uri:"dddd.com",category:"d",icon:null}
]
};
},
computed: {
resultQuery(){
if(this.searchQuery){
return this.resources.filter((item)=>{
return this.searchQuery.toLowerCase().split(' ').every(v => item.title.toLowerCase().includes(v))
})
}else{
return this.resources;
}
}
}
})
```
```html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >
</head>
<body>
<div id="app">
<div class="panel panel-default">
<div class="panel-heading">
<strong> All Resources</strong></div>
<div class="row">
<div class="search-wrapper panel-heading col-sm-12">
<input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
</div>
</div>
<div class="table-responsive">
<table v-if="resources.length" class="table">
<thead>
<tr>
<th>Resource</th>
</tr>
</thead>
<tbody>
<tr v-for="item in resultQuery">
<td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
```
Based on this answer → [Vue.js search keyword in array](https://stackoverflow.com/questions/53276545/vue-js-search-keyword-in-array) | **THIS NAVBAR COMPONENTS**
```
<template>
<nav class="navbar navbar-expand-lg navbar-light bg-info display-6">
<div class="container">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<form class="d-flex">
<input v-model="search" class="form-control me-2" id="inputGroup-sizing-lg" placeholder="Search...">
</form>
</div>
</div>
</nav>
</template>
<script>
import {mapActions} from "vuex"
export default{
data(){
return{
search: ""
}
},
watch:{
search(newsearch) {
this.filteredProducts(newsearch)
}
},
methods:{
...mapActions([
"filteredProducts"
])
}
}
</script>
```
**THIS STORE.JS**
```
const store = createStore({
state: {
productsList: products,
cartList: [],
filtered: []
},
mutations:{
filteredProducts(state, item) {
if(item){
state.filtered = products.filter((product) => product.Title.toUpperCase().includes(item.toUpperCase()))
console.log(state.filtered);
}
if(state.filtered){
console.log("state.filtered.lenght", state.filtered.lenght);
state.productsList = [...state.filtered]
}
}
},
actions:{
filteredProducts (context, item){
context.commit('filteredProducts', item)
}
}
});
``` |
89,566 | My question refers to a capital ship. Ideally, the ship wants to stay as low as possible. Does the mass of the ship affect its possible orbits? If so, what is the lowest orbit possible for this ship? I don't have a number for its mass, but imagine something like the farragut:
>
> Dimensions: Length: 2040m, Width: 806m, Height: 300m
>
>
> | 2017/08/21 | [
"https://worldbuilding.stackexchange.com/questions/89566",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/23503/"
] | Actually, in practice, a very massive object will be able to orbit ad *lower* altitude than a very light one.
The orbit mechanics is exactly the same (assuming *big body* mass is still negligible compared with planet).
**BUT**
It can skim atmosphere fringes and still keep going due to its much larger inertia where a lightweight would be slowed down to a forced reentry.
Of course even very massive objects *will* be slowed down, but it will take much more time, very likely longer than a space battle will last.
In practice such a massive object can flirt with atmosphere as much as friction won't heat it up too much.
All this is because friction (slow dawn force) is roughly proportional to cross section (square of dimensions) while inertia is roughly proportional to volume (cube of dimensions). You need more time to drag away all energy you gave to spaceship to put it into orbit in the first place. | As I mentioned initially in the comments: **no.** To the best of my knowledge, the mass of an object only affects how much energy is needed to get that object into a specific orbit. It doesn't affect the actual distance at which that object can orbit. So realistically, the lowest your ship can orbit is just above the edge of the planet's atmosphere. If the planet doesn't have an atmosphere, then you can practically skim across the surface. |
35,421,671 | I've run into some issue graphically representing some of my data via J Query in my Hangman game- right now I'm working on the last part of my play(space) function to take into account if there is more than one correctly guessed letter in a word & to display all instances of that letter- I've made a function to loop through the array created out of the split word, I'm getting the correct indexes of those letters, I'm just kind of stuck as to how to display these letters at these indexes in my table via J Query correctly & I'm kind of stuck... I've been console.log - ing my data & I'm getting the correct data (the letter and the indexes of that letter in my array), I now just need to figure out how to display these letters in my html table at their correct indexes corresponding to the table (I'm feeling kind of stuck & wondering if this is possible to salvage- I'm sure there must be a way to do it, I just haven't figured it out- I'm not sure if I should be creating a dictionary object to pair the correct letter w/it's indexes in the array to use .each() to loop through to graphically represent in my table or if there's a way to graphically represent it w/the data as is). I'd really appreciate any help.
Here's my code:
JS/JQuery:
```
var wordBank = ["modernism", "situationalist", "sartre", "camus", "hegel", "lacan", "barthes", "baudrillard", "foucault", "debord", "baudrillard"];
var word = [];
var wrongGuesses = [];
var rightGuesses = [];
var images = [gallows, head, body, armL, handL, armR, handR, legL, footL, legR, footR];
var y = 0;
var i = 1;
$(document).ready(function() {
function randomWord() {
var random = Math.floor(Math.random() * wordBank.length);
var toString = wordBank[random];
console.log(toString);
word = toString.split("");
console.log(word);
}
randomWord();
function wordSpaces() {
for (var i = 0; i < word.length; i++) {
$(".word-spaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>')
}
}
wordSpaces();
function play(space) {
//indexOf()==inArray()
var lIndex = jQuery.inArray(space, word);
console.log(lIndex);
if (lIndex == -1) {
wrongGuesses.push(space);
var wrong = wrongGuesses.length;
console.log('wrong ' + wrong);
$('.wrongLetters tbody tr td:nth-of-type(' + wrong + ')').text(space);
// $(this).css("background-color", "#ff4500").fadeIn(300).delay(800).fadeOut(300);
$(images[i - 1]).hide();
$(images[i]).show();
i++;
$("html").css("background-color", "#ff4500").fadeIn(300).delay(300).fadeOut(300).fadeIn(100);
console.log(word);
} else {
console.log(word + "word");
console.log(space + "space");
function getInstances(word,space) {
var indexes = [], w;
for(w=0; w<word.length;w++ )
if (word[w] === space)
indexes.push(w);
return indexes;
}
console.log(word + "word");
console.log(space + "space");
var indexes = getInstances(word, space);
console.log(indexes);
rightGuesses.push(space);
console.log(rightGuesses);
$(".word-spaces tbody tr td:nth-of-type(" + indexes + ")").css('color', 'black');
// rightGuesses.push(space);
}
}
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var space = $(this).val();
play(space);
$(this).val('');
endGame();
return false;
}
});
function endGame() {
if (wrongGuesses.length >= 10 || rightGuesses.length == word.length) {
$("body").css("background-color", "#ff4500");
$(".form-control").prop('disabled', true);
}
}
});
html:
<header>
<h2 style="font-family:paganini;">
Hangman
</h2>
</header>
<main style="font-family:paganini;">
<figure class="hangman">
<img src="https://i.imgur.com/gSxmkUf.gif" id="gallows" align="middle top">
<img src="https://i.imgur.com/Mb4owx9.gif" id="head" align="middle top" style="display:none;">
<img src="https://i.imgur.com/xkXISte.gif" id="body" align="middle top" style="display:none;">
<img src="https://i.imgur.com/U44ReUi.gif" id="armL" align="middle top" style="display:none;">
<img src="https://i.imgur.com/49kkaQF.gif" id="handL" align="middle top" style="display:none;">
<img src="https://i.imgur.com/tqtNazW.gif" id="armR" align="middle top" style="display:none;">
<img src="https://i.imgur.com/ydnz7eX.gif" id="handR" align="middle top" style="display:none;">
<img src="https://i.imgur.com/dlL7Kek.gif" id="legL" align="middle top" style="display:none;">
<img src="https://i.imgur.com/3AQYFV9.gif" id="footL" align="middle top" style="display:none;">
<img src="https://i.imgur.com/j9noEN7.gif" id="legR" align="middle top" style="display:none;">
<img src="https://i.imgur.com/kJofX7M.gif" id="footR" align="middle top" style="display:none;">
</figure>
<table class="word-spaces">
<caption>Your Word is: </caption>
<tbody>
<tr>
</tr>
</tbody>
</table>
<br/>
<fieldset class="guessIn">
<legend>
Guess a Letter
</legend>
<label for="form">Type a Letter then Click <b>Enter</b></label>
<input type="text" id="form" class="form-control" placeholder="guess">
</fieldset>
<table class="wrongLetters">
<caption>Letters Guessed Wrong:</caption>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</main>
<footer>
</footer>
``` | 2016/02/16 | [
"https://Stackoverflow.com/questions/35421671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5761395/"
] | This could be a problem with the parameter viUserId (value is correct?), try to initialize like this:
```
var paramUserId = new SqlParameter { ParameterName = "viUserId", Value = userId };
```
in my applications i've call procedures a little bit diferent. Translating to your problems should be like that:
```
var paramUserId = new SqlParameter { ParameterName = "viUserId", Value = userId };
var result = this.DbContext.Database.SqlQuery<MostRecentOrderDetail>("usp#GetMostRecentOrder @viUserId", paramUserId).FirstOrDefault();
```
And one last thing. be sure they have the same types (mapping and database). this could lead to an exception
\*EDIT
The procedure need to return all properties from your model (the same name). procedure returns 'order\_type\_code' but model expects OrderTypeCode. | There is a typo in your parameter code. Your missing `@` in `"viUserId"`
```
UserID = new SqlParameter("@viUserId", userId);
``` |
15,447,483 | I'm on Mac OS X and use the following bash script to run doxygen on around 10 source code libraries.
Problem is, doxygen runs the most time-consuming task "dot" (creates class diagrams) on separate threads by itself. This causes the wait command to not wait for the dot threads to finish. It effectively returns me to the command prompt right away (creating just the docs with doxygen is fast) while dot is still generating class diagrams in the background for another minute or so.
```
#!/bin/bash
DOXY="/Applications/Doxygen.app/Contents/Resources/doxygen"
#run doxygen on all configs
for config in doxygen*.config
do
$DOXY $config &
done
wait
```
I have tried enforcing dot to run on a single thread (DOT\_NUM\_THREADS=1) but that didn't help. I tried putting the wait command in the loop, but that only has doxygen take as long as it does without parallelizing, and still not wait for dot to finish.
I need to wait for the dot command to generate all class diagrams, or else I will be packaging/uploading incomplete docs in the next step.
**How can I parallelize doxygen and have it wait for all threaded dot commands to finish?**
Alternatively, is there a way for me to determine in the bash script if all dot commands have ended (I do not know what processes/threads doxygen actually spawns nor how to wait for them)?
**UPDATE:**
I tried using xargs which properly waits for all dot threads to finish, but isn't any faster:
```
find . -name "doxygen*.config" | xargs -n 1 -P 8 doxygen
```
Problem here is I can't set 'n' (number) higher than 1 because then doxygen won't create all the docsets because it ignores the additional arguments. | 2013/03/16 | [
"https://Stackoverflow.com/questions/15447483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201863/"
] | Have a look here <https://stackoverflow.com/a/8247993/784672>, where I describe a way to run doxygen in parallel using tag files and the GNU parallel utility. | I think another solution (not tested, as I don't have `doxygen` installed), is to just run `doxygen` as a foreground task in a subshell that is backgrounded. This is pretty much the same as the solution you found, but without the need to create a second script:
```
for config in doxygen*.config; do
( $DOXY $config ) &
done
wait
``` |
18,219,984 | I have the following data:
`data LinkedList a = Node a (LinkedList a) | Empty deriving (Show)`
And I would like to know how to get a single value out of it, without pattern matching.
So in a **C**-based language: `list.value` | 2013/08/13 | [
"https://Stackoverflow.com/questions/18219984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2175870/"
] | Rather than present a Haskell solution to your question, I will present a more realistic comparison with C and suggest that you don't *really* want what you seem to be asking for:
```
struct list {
int value;
struct list *next;
};
int main(void) {
struct list *list = NULL;
int val;
/* Goodbye, cruel world! */
val = list->value;
/* If I had "pattern-matched"... */
if (list == NULL) {
val = 0;
} else {
val = list->value;
}
return 0;
}
```
When you don't check for the NULL case in C (which corresponds to pattern matching in Haskell) you crash with a SEGFAULT at some point in the execution of your program instead of getting a compile error.
In other words, you can't get a value out of a 'possibly empty' recursive data type without doing case analysis in C either! At least not if you value the stability of your program. Haskell not only insists that you do the right thing, but provides convenient syntax to help you to do so!
As mentioned in other answers, record definition syntax provides you with convenient projections (i.e. accessor functions) automatically, which have a bit of a trade-off in comparison to accessing struct members in C: The projections are first-class, and can thus be used as parameters and return values; but they are in the same namespace as all other functions, which can lead to unfortunate name clashes.
So, in the case of straightforward data types (i.e. non-recursive) the syntax for accessing members is roughly at the same level of convenience: `whole.part` for C-like languages vs. `part whole` for Haskell.
For recursive types (like the one in your example) where one or more members reference possibly-empty instances of the same type, case analysis is necessary in either language before a value can be extracted. Here, you will either need to wrap the field access in your C-like language with a case analysis or possibly an exception handler. In Haskell, you have various forms of syntactic sugar for pattern matching that tend to be much more concise.
Furthermore, see the answer regarding Monads for ways of providing even *more* convenience for working with 'possibly empty' types in Haskell, hiding most of the intermediate pattern matching for multi-step computations inside library functions.
To wrap this up: My point is that as you take the time to learn the patterns and idioms of Haskell, you will likely find yourself missing the ways of doing things in C-like languages less and less. | I'd just pattern match.
```
llHead :: LinkedList a -> a
llHead Empty = error "kaboom"
llHead (Node x _) = x
```
If you want the element at a specific index, try something like this (which also uses pattern matching):
```
llIdx :: LinkedList a -> Int -> a
llIdx l i = go l i
where go Empty _ = error "out of bounds"
go (Node x _) 0 = x
go (Node _ xs) j = go xs (j - 1)
```
Some assurance that this works:
```
import Test.QuickCheck
fromList [] = Empty
fromList (x:xs) = Node x (fromList xs)
allIsGood xs i = llIdx (fromList xs) i == xs !! i
llIdxWorksLikeItShould (NonEmpty xs) =
let reasonableIndices = choose (0, length xs - 1) :: Gen Int
in forAll reasonableIndices (allIsGood xs)
-- > quickCheck llIdxWorksLikeItShould
-- +++ OK, passed 100 tests.
``` |
65,855,961 | I have an HTML form with a button and some checkboxes. The values of the checkboxes are passed to the next page via GET parameters. The target of the form submission is a blank page.
```
<form id="myForm" method="get" action="launch.php" target="_blank">
<input type="submit">Launch</input>
<input type="checkbox" class="checkbox" name="reset" /> Reset
<input type="checkbox" class="checkbox" name="erase" /> Erase
</form>
```
The checkboxes allow the user to reset and/or erase files prior to launching the web app. Since they are "dangerous", I wish to *uncheck* them automatically after the use launches the app. This is to help prevent the user from accidentally erasing or resetting their files twice in a row.
I added an `onClick` action to the button that unchecks the boxes using jQuery. However, they get unchecked *before* the form is submitted, and therefore the values of the boxes aren't included in the GET.
```
<input type="submit" onClick="uncheckBoxes();" />
...
<script>
function uncheckBoxes() {
$(".checkbox").prop("checked", false);
}
</script>
```
I think I want to do one of two things. Either:
* Use the `$("#myForm").submit()` function to uncheck the boxes, then open a new window. However, I'd have to write code to construct the URL, which is not very scalable (what if I want to add a new checkbox?) and error-prone. Or,
* Somehow hook into the normal form-submission process and execute the `uncheckBoxes` function *after* the new page/tab has opened. Since the page/tab with the form on it remains open, I can still run additional JS code.
What are some solutions to this? | 2021/01/23 | [
"https://Stackoverflow.com/questions/65855961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17312/"
] | * Right Click on Terminal [Step1](https://i.stack.imgur.com/SErKK.png)
* Click on Move Panel To Bottom [Step 2](https://i.stack.imgur.com/DkZkK.png)
* Then you can see your terminal at bottom | To make terminal appear at bottom as default, do following:
1. Open settings [`CRTL` + `,`]
2. Type *terminal default location*
3. Find *Terminal>Integrated>Default Location* and change value to **view** |
4,562,231 | I need to do multiplication on matrices. I'm looking for a library that can do it fast. I'm using the Visual C++ 2008 compiler and I have a core i7 860 so if the library is optimized for my configuration it's perfect. | 2010/12/30 | [
"https://Stackoverflow.com/questions/4562231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/558209/"
] | Look into [Eigen](http://eigen.tuxfamily.org/index.php?title=Main_Page). It should have all you need. | I have had good experience with Boost's [uBLAS](http://www.boost.org/doc/libs/1_45_0/libs/numeric/ublas/doc/index.htm). It's a nice option if you're already using Boost. |
51,260,866 | I found this question on an online exam. This is the code:
```
#include <stdio.h>
int main(void) {
int demo();
demo();
(*demo)();
return 0;
}
int demo(){
printf("Morning");
}
```
I saw the answer after the test. This is the answer:
```
MorningMorning
```
I read the explanation, but can't understand why this is the answer.
I mean, shouldn't the line `int demo();` cause any ***"problem"***?
Any explanation is helpful. Thanks. | 2018/07/10 | [
"https://Stackoverflow.com/questions/51260866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7544643/"
] | It is not a problem because that `int demo();` is not a function definition, it is just an external declaration, saying (declaring) that a function of such name exists.
In C you cannot define a nested function:
```
int main(void) {
int demo() {} //Error: nested function!!!
}
```
But you can declare a function just fine. It is actually equivalent to:
```
#include <stdio.h>
int demo(); //function declaration, not definition
int main(void) {
demo();
(*demo)();
return 0;
}
int demo(){
printf("Morning");
}
```
except that in your code the external forward `demo()` declaration is only visible inside `main`. | Other answers didn't explain the
```
(*demo)();
```
part. Here's a partial explanation:
`demo` (without parentheses) is the function *pointer*. So you can first dereference it to get a function *then* call it with parentheses (wrapping the dereferenced object into parentheses else it means that you want to dereference the *return value* of the function)
So it's strictly equivalent to
```
demo();
```
(the notation is useful when the function pointer is stored in a variable, here it's just more cryptic than necessary) |
12,743,204 | Thanks for going through this. I successfully integrated Zebra Printer working in xcode and got the label printer successfully from simulator, but the problem raises the moment i tried to debug it on my device saying
"ld: warning: ignoring file /Users/MYSystem/Desktop/MYProject/libZSDK\_API.a, file was built for archive which is not the architecture being linked (armv7)
Undefined symbols for architecture armv7:
"\_OBJC\_CLASS\_$\_ZebraPrinterFactory", referenced from:
objc-class-ref in MyViewController.o
"\_OBJC\_CLASS\_$\_TcpPrinterConnection", referenced from:
objc-class-ref in MyViewController.o
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)".
What would went wrong, please help me out from this..Thanks in advance | 2012/10/05 | [
"https://Stackoverflow.com/questions/12743204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758532/"
] | Use the 64-bit version of Java which allows you to use more memory. This is the limit of the 32-bit Java virtual machine. | You are not able to have an allocation of 4096m because. It tries to get a single block of 4096m. Which is not possible at any given point of time. So you can use some smaller values between
3000-4000. or make sure your RAM is not used by any of the processes |
2,139,273 | I've seen and googled and found many pretty url links.
But they all seem to look like <http://example.com/users/username>
I want it to be like github style <http://example.com/username>
Any directions that I can follow?? | 2010/01/26 | [
"https://Stackoverflow.com/questions/2139273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60072/"
] | A very Basic example could be this:
* declare a route with lowest priority pointing to your users controller's show action
* modify the show action to find records based on username
In `config/routes.rb`:
```
map.username '/:username', :controller => :users, :action => :show
```
In `UsersController`:
```
def show
@name = Name.find_by_name(params[:username]) || Name.find(params[:id])
end
```
You can then use `username_path(:username => user.name)` to generate links. | Isn't that you just need to drop `users/` in routes?
`map.connect '/:username',...` instead of `map.connect '/users/:username',...` |
24,394,772 | I've seen lots of examples with getting file names from URL or path, but am unable to solve this problem.
I have a URL that looks like below:
```
http://www.bob.net/john/john/ken/mary.html
```
I need to get `Mary` if both `/john/john` exist in the URL. Otherwise I need to get `ken` if only `/john` exists in the path
I can get `mary` with `\/\w*\/\w*\/(\w*)\/(\w*)` but that's reliant on `Mary` being after the 4th slash.
How can I accomplish this?
EDIT - thanks for the responses so far.
**Any chance of making this dynamic and getting just mary, if /john exists within the url? regardless of anything else?** | 2014/06/24 | [
"https://Stackoverflow.com/questions/24394772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3772597/"
] | Inline elements are sensitive to white space. Remove the white space and the problem goes away.
Ex:
```
<ul>
<li><a href="#">list1</a></li><li><a href="#">list2</a></li><li><a href="#">list3</a></li>
</ul>
```
**[jsFiddle example](http://jsfiddle.net/j08691/eF83x/1/)**
You can remove the spaces between the list items literally, occupy the space with HTML comments (`<!-- -->`), or float them left. | What you could also do is make the lis float left and display them as block. This will fix it without messing with the html code.
```
.nav-items ul li {
float: left;
display: block;
border-left: 1px solid #c8c8c8;
height: 100%;
margin: 0;
}
```
[jsFiddle example](http://jsfiddle.net/eF83x/2/) |
13,269,600 | Is there any easy way to get the keys for which same value exist?
Or more importantly, how can i get the number of same-value-more-than-once occurrences?
Consider the hashmap:
```
1->A
2->A
3->A
4->B
5->C
6->D
7->D
```
here same-value-more-than-once occurred 3 times(A two times, D one time).That(3) is what i want in return.
I could iterate over the hashmap by the keyset/map.values() list, but it seems quite cumbersome to do that way. Any suggestions or solutions?
**EDIT :**
My context is, i'm working on a timetable generator. The data-structure for a time-slot is
```
{String day-hour, HashMap<String,Event> Rooms}
```
For a day-hour, some Event-s are assigned on Rooms map. While checking the fitness of the solution, i need to know if one staff is assigned multiple events on same hour. Hence i want to check how many violations are there in Rooms map by the values Event.getStaff() .
**EDIT :**
Values are objects here, I don't want to count the occurrences of the same objects, rather a field of the object. The EVENT object has a field **staff** and i need to count the multiple occurrences of staffs. | 2012/11/07 | [
"https://Stackoverflow.com/questions/13269600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1805994/"
] | >
> I could iterate over the hashmap by the keyset/map.values() list, but it seems quite cumbersome to do that way.
>
>
>
Well it's *inefficient*, but there's not a lot you can do about that, without having some sort of multi-map to store reverse mappings of values to keys.
It doesn't have to be cumbersome in terms of *code* though, if you use [Guava](http://guava-libraries.googlecode.com):
```
Multiset<String> counts = HashMultiSet.create(map.values());
for (Multiset.Entry<String> entry : counts.entrySet) {
if (entry.getCount() > 1) {
System.out.println(entry.getElement() + ": " + entry.getCount());
}
}
``` | How about (expanding on Jon's answer)
```
Multiset<V> counts = HashMultiSet.create(map.values());
Predicate<Map.Entry<K,V>> pred = new Predicate<Map.Entry<K,V>>(){
public boolean apply(Map.Entry<K,V> entry){
return counts.count(entry.getValue()) > 1;
}
}
Map<K,V> result = Maps.filterEntries(map, pred);
```
This will result in a map where each key is mapped to a value that is duplicated.
This answer is only needed to address the first part of the question (the "less important part"), to get the keys that have duplicate values. |
54,182,039 | For closing a modal with the class `submitmodal` i use this code and it works fine.
```
$('.submitmodal').click(function() {
window.location.hash='close';
});
```
For click on the body somewhere i use this:
```
$('body').click(function() {
window.location.hash='close';
});
```
How can i merge them together?
I tried this but it does not work
```
$('.submitmodal', 'body').click(function() {
window.location.hash='close';
});
``` | 2019/01/14 | [
"https://Stackoverflow.com/questions/54182039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6036819/"
] | Try
```
(".submitmodal, body").click(function() {
window.location.hash="close";
});
```
The selectors have to be in the same string, seperated by a comma. | You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
```
$("body, .submitmodal").click(function() {
window.location.hash="close";
});
```
For More help see this : [multiple-selector](https://api.jquery.com/multiple-selector/)
I hope it helps you :), Thanks. |
24,054,648 | I encountered some encoding problems in learning Spring Boot;
I want to add a CharacterEncodingFilter like Spring 3.x.
just like this:
```
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
``` | 2014/06/05 | [
"https://Stackoverflow.com/questions/24054648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1649366/"
] | I also prefer `application.properties` configuration. But `spring.http.encoding` is depracted in the new spring boot versions (>2.3). So new application.setting should look like this:
```
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
``` | I think there is no need to explicity write the following properties in application.properties file:
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
Instead if you go to pom.xml in your application and if you have the following, then spring will do the needful.
[](https://i.stack.imgur.com/TuMg6.png) |
4,401,042 | Task in Combinatorics course:
>
> $1 \leq k < n$. Prove that the number $k$ can be found $(n-k+3)2^{n-k-2}$ times in sums that add up to $n$.
>
>
>
Example: $n=4, k=2$.
$1+1+2$
$1+2+1$
$2+1+1$
$2+2$
These are the sums that add up to $4$ and the number $2$ can be found $5$ times.
Thus far, I have tried making sense of that formula. $n-k$ is the number or countables left if we have one $k$. $2^{n-1}$ is how many sums that add up to $n$ there are in total so in the second half of the formula it could be $2^{n-1}2^{k-1}$ that would add up to $2^{n-k-2}$. But none of that comes together. Why would there be a $+3$ in the first half. | 2022/03/11 | [
"https://math.stackexchange.com/questions/4401042",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/763750/"
] | A [composition](https://en.wikipedia.org/wiki/Composition_(combinatorics)) which sums to $n$ corresponds to the placement of either a comma or an addition sign in each of the $n - 1$ spaces between successive ones in a row of $n$ ones.
$$1 \square 1 \square 1 \square \cdots \square 1 \square 1 \square 1$$
Since there are $2$ ways to fill each of the $n - 1$ spaces, there are $2^{n - 1}$ compositions of the number $n$.
We are told that one of the summands is $k$. That means there is a block of $k$ consecutive ones. Such a block must begin in one of the first $n - k + 1$ positions. Of these, two are at the ends of the row and $n - k - 1$ include neither end of the row. We will consider cases, depending on the position of the block.
If the first summand is $k$, there is a block of exactly $k$ ones at the start of the row. That block must be immediately followed by an addition sign. That leaves $n - k$ ones and $n - k - 1$ spaces where either a comma or an addition sign can be placed. Hence, there are $2^{n - k - 1}$ such compositions.
If the last summand is $k$, there is a block of exactly $k$ ones is at the end of the row. That block must be immediately preceded by an addition sign. That leaves $n - k$ ones and $n - k - 1$ spaces where either a comma or an addition sign can be placed. Hence, there are $2^{n - k - 1}$ such compositions.
If the summand $k$ does not appear in the first or last position of the composition, there are $n - k - 1$ places where the block of exactly $k$ consecutive ones could begin. The block must be immediately preceded and immediately followed by addition signs. That leaves $n - k$ ones and $n - k - 2$ spaces where either a comma or an addition sign can be placed. Hence, there are $(n - k - 1)2^{n - k - 2}$ such compositions.
Since these cases are mutually exclusive and exhaustive, the number of times the summand $k$ appears in compositions of $n$ is
\begin{align\*}
2 \cdot 2^{n - k - 1} + (n - k - 1)2^{n - k - 2} & = 4 \cdot 2^{n - k - 2} + (n - k - 1)2^{n - k - 2}\\
& = (n - k + 3)2^{n - k - 2}
\end{align\*}
Note that we have implicitly used the hypothesis that $k < n$ in order to separate the cases where $k$ is the first summand, $k$ is the last summand, and $k$ is neither the first nor last summand. | Fix $k$ and let $a\_n$ be the number of $k$s that appear among all ($2^{n-1}$) ordered partitions of $n$. Then $a\_n=0$ for $n<k$, $a\_k=1$, and conditioning on the first part $i$ yields recurrence relation
$$a\_n = \sum\_{i=1}^n ([i=k]2^{n-i-1} + a\_{n-i}) = 2^{n-k-1} + \sum\_{i=1}^{n-k} a\_{n-i} \quad \text{for $n > k$}.$$
Let $A(z) = \sum\_{n=0}^\infty a\_n z^n$ be the ordinary generating function. Then
\begin{align}
A(z)
&= \sum\_{n=0}^{k-1} 0 z^n + 1z^k + \sum\_{n=k+1}^\infty \left(2^{n-k-1} + \sum\_{i=1}^{n-k} a\_{n-i}\right) z^n \\
&= z^k + \sum\_{n=k+1}^\infty 2^{n-k-1} z^n + \sum\_{i=1}^\infty z^i \sum\_{n=i+k}^\infty a\_{n-i} z^{n-i} \\
&= z^k + \frac{z^{k+1}}{1-2z} + \sum\_{i=1}^\infty z^i A(z) \\
&= z^k + \frac{z^{k+1}}{1-2z} + \frac{zA(z)}{1-z}.
\end{align}
So
\begin{align}
A(z)
&= \frac{z^k(1-z)^2}{(1-2z)^2} \\
&= z^k \left(\frac{1}{4}+\frac{1/2}{1-2z}+\frac{1/4}{(1-2z)^2}\right) \\
&= z^k \left(\frac{1}{4}+\frac{1}{2}\sum\_{n=0}^\infty(2z)^n+\frac{1}{4}\sum\_{n=0}^\infty\binom{n+1}{1}(2z)^n\right) \\
&= z^k \left(1+\frac{1}{2}\sum\_{n=1}^\infty(2z)^n+\frac{1}{4}\sum\_{n=1}^\infty(n+1)(2z)^n\right) \\
&= z^k +\sum\_{n=k+1}^\infty \left(2^{n-k-1}+(n-k+1)2^{n-k-2}\right)z^n \\
&= z^k +\sum\_{n=k+1}^\infty (n-k+3)2^{n-k-2}z^n,
\end{align}
which immediately implies that
$a\_n = (n-k+3)2^{n-k-2}$ for $n>k$. |
348,537 | I'm looking for all (or most) theoretical *semi-classical* derivations of the **maximal magnetic field intensity** that there may be in the Universe. As an example, this paper evaluate a maximal field of about $3 \times 10^{12} \, \mathrm{teslas}$ :
<https://arxiv.org/abs/1511.06679>
but its calculations are buggy, especially on the first page, since there's a relativistic $\gamma$ factor missing in the first few formulae. When we take into account the $\gamma$ factor, it destroys the derivation of a maximal value for $B$ ! So this paper isn't satisfaying at all.
Please, I need ***semi-classical*** calculations ***with some rigor***, using fully *special relativity* and some quantum bits only, without a full blown quantum electrodynamics calculation with Feynmann diagrams !
You may use the *Heisenberg uncertainty principle*, the *quantification of angular momentum*, *Einstein/deBroglie relations*, and even things about "vacuum polarization" or some other quantum tricks, but they all need to be properly justified to make the calculations convincing !
From the previous paper as a (buggy) example, is it possible to derive a theoretical maximal $B\_{\text{max}}$ using classical electrodynamics and special relativity only (without quantum mechanics) ? I don't think it's possible, without at least *general relativity* which suggest that the field energy density cannot be larger than a certain limit without creating a black hole.
---
**EDIT :** Curiously, even in general relativity, it appears that there's no theoretical limit to the magnetic field strenght. The *Melvin magnetic universe* is an analytical solution to the Einstein field equation that is as close as possible to an uniform magnetic field. See for example this interesting paper from Kip Thorne :
<http://authors.library.caltech.edu/5184/1/THOpr65a.pdf>
The spacetime metric of Melvin's magnetic universe doesn't have any singularity, wathever the value of the field parameter, and there can be no gravitational collapse of the field under perturbations ! So apparently there's no maximal value of $B$ in classical general relativity, without matter! | 2017/07/25 | [
"https://physics.stackexchange.com/questions/348537",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/98263/"
] | **Why do you want to know?**
I'm not kidding. That's actually an important question. The answer really depends on what you intend to do with the information you are given.
Newton's laws are an empirical model. Newton ran a bunch of studies on how things moved, and found a small set of rules which could be used to predict what would happen to, say, a baseball flying through the air. The laws "work" because they are effective at predicting the universe.
When science justifies a statement such as "the rocket will go up," it does so using things that we assume are true. Newton's laws have a tremendous track record working for other objects, so it is highly likely they will work for this rocket as well.
As it turns out, Newton's laws *aren't* actually fundamental laws of the universe. When you learn about Relativity and Quantum Mechanics (QM), you will find that when you push nature to the extremes, Newton's laws aren't *quite* right. However, they are an extraordinarily good approximation of what really happens. So good that we often don't even take the time to justify using them unless we enter really strange environments (like the sub-atomic world where QM dominates).
Science is always built on top of the assumptions that we make, and it is always busily challenging those assumptions. If you had the mathematical background, I could demonstrate how Newton's Third Law can be explained as an approximation of QM as the size of the object gets large. However, in the end, you'd end up with a pile of mathematics and a burning question: "why does QMs work." All you do there is replace one question with another.
So where does that leave you? It depends on what you really want to know in the first place. One approach would simply be to accept that scientists say that Newton's Third Law works, because it's been tested. Another approach would be to learn a whole lot of extra math to learn why it works from a QM perspective. That just kicks the can down the road a bit until you can really tackle questions about QM.
The third option would be to go test it yourself. Science is built on scientists who didn't take the establishment's word at face value, went out, and proved it to themselves, right or wrong. Design your own experiment which shows Newton's Third Law works. Then go out there and try to come up with reasons it might not work. Test them. Most of the time, you'll find that the law holds up perfectly. When it doesn't hold up, come back here with your experiment, and we can help you learn how to explain the results you saw.
That's science. Science isn't about a classroom full of equations and homework assignments. It's about scientists questioning everything about their world, and then systematically testing it using the scientific method! | Newton's Third Law is a direct consequence of conservation of momentum, which essentially says that in an isolated system with no net force on it, momentum doesn't change. This means that if you change the momentum of one object, then another object's momentum must change in the opposite direction to preserve the total momentum. Forces cause changes in momentum, so every force must have an opposite reaction force.
In your rocket example, the rocket and its escaping fuel form an isolated system.\* The escaping fuel was originally at rest, and now is moving very fast, so it's obvious its momentum has changed. So the rocket, being the only other object in the system, must also change its momentum to counter that of the fast-moving gas. Thus the rocket exerts force on the gas, which generates an equal and opposite force on the rocket.
But now you may ask:
**Why is momentum conserved?**
Conservation of momentum comes from an idea called Noether's Theorem, which states that conservation laws in general are a direct result of the symmetries of physical systems. In particular, conservation of momentum comes from *translation symmetry*. This means that the behavior of a system doesn't change if you select a new origin for your coordinates (put differently, the system's behavior depends only on the positions of its components relative to each other). This symmetry is found in all isolated systems with no net force on them because it is effectively a symmetry of space itself. Translation symmetry of a system is a consequence of *homogeneity of space*, which means that space is "the same everywhere" - the length of a rod doesn't change if you put it in a different place.
But now you may ask:
**Why is space homogeneous?**
In classical mechanics, this is one of the basic assumptions that allows us to do anything else. In reality, according to General Relativity, space actually *isn't* homogeneous - it curves in the presence of massive objects. But usually it's close enough to homogeneous that classical mechanics works well (gravity is pretty spectacularly weak, after all), and so the assumption of homogeneity holds.
\*This is in the absence of gravity. If gravity is included, the isolated system would include any other gravitating masses. |
71,211,699 | I cannot understand how are box working, why when box is covering some layer of our screen, for example
we are three boxes
```
@Composable
fun TestScope() {
1
Box(modifier = Modifier
.fillMaxSize()
.background(color = Color.Black)) {
2
Box(
Modifier
.fillMaxSize()
.clickable { }
.background(color = Color.Yellow)
) {
}
3
Box(modifier = Modifier
.fillMaxHeight(0.4f).fillMaxWidth()
.background(color = Color.Blue)) {
}
}
}
```
If I click on box 3 and only its space I still can click on box 2 which is under it ? | 2022/02/21 | [
"https://Stackoverflow.com/questions/71211699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17553375/"
] | Click events in Compose pass from the top composable to the bottom composable. A Surface composable however prevents this and prevents click events from propagating further down. So when you click on Box 3, the click event is sent down to Box 2. If you place Box 3 inside a Surface, the click event on Box 3 will not go to Box 2. | This is expected. Any composable that does not handle click events is effectively transparent to those click events and can be captured by composables underneath it. This is no different from the view system where you could have a clickable view behind another opaque view - as long as the opaque view does not handle clicks, those go through it to the view underneath. |
5,049 | Can the Airbus A380 or Boeing 787 land safely without flaps/slats/spoilers or thrust reversers? | 2014/05/23 | [
"https://aviation.stackexchange.com/questions/5049",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/2171/"
] | Even the largest commercial airliners are able to land without flaps, since flap failures do happen occasionally. See a report [here](http://avherald.com/h?article=46d6dd03) where an A380 landed with no flaps. This was at the Auckland, New Zealand airport, where the runway is 3,635 m (11,926 ft) long.
The pilots have checklists to follow in the event of issues with flaps, which include information about what speeds they should fly with what amounts of flaps. They simply land at a higher than normal speed. The brakes can end up getting hotter than normal, so they may have to stop and let them cool or have them inspected by emergency services. The tires are designed to deflate with [fusible plugs](http://en.wikipedia.org/wiki/Fusible_plug) before high temperatures would cause them to blow.
Aircraft are also tested to make sure they can reject a takeoff at high weights (higher than normal landing weights) using no thrust reversers. Here is a video of the 747-8 doing this test. | Any aircraft can land without those devices. I would say that the [Gimli Glider](http://aviation-safety.net/database/record.php?id=19830723-0) is a nice example, with no power it could not extend its flaps/slats.
They are used, as @ratchetfreak notes in the comments, to reduce the touchdown speed and, as a consequence, the runway length needed to reach a stop or taxiing velocity.
To be noted, also, that a safe landing is mostly defined by the vertical velocity at tochdown, usually in the order of 1-3 feet per second. See for example [this accident report](http://www.ntsb.gov/aviationquery/brief2.aspx?ev_id=20001208X07083&ntsbno=LAX97LA061&akey=1) where it states
>
> mild touchdown rates [...] less than 5 feet per second
>
>
>
Since the vertical component is the relevant parameter for a safe landing, and given that without flaps/slats the forward velocity will be larger than usual, the aircraft will have to approach with a shallower angle than the usual 3°.
The absence of thrust reversers, as you might imagine, will only affect the braking process. |
35,120,566 | I have two lists in SharePoint 2013 Online. I need to get matching values for a user-entered key (string), sort, and display both lists as one. Easy enough if I were able to use SQL to create a view. Best solution seems to be to just display both lists.
I've tried using SPD Linked Sources, but the "linked field" option never displays and the no-preview SPD is awful (what were MS thinking?). Workflow isn't feasible. List items may be edited in 'datasheet view' (client requirement). Lookups require a selection to display the related field.
I can get both lists and display them separately.
What I have:
```
List 1 List 2
fruit apple type rome fruit apple state washington
fruit pear type bartlett fruit pear state oregon
fruit grapes type red fruit orange state florida
```
What I want:
```
fruit apple type rome state washington
fruit grapes type red
fruit orange state florida
fruit pear type bartlett state oregon
```
I'm missing two things (maybe more) an array that I can use for sorting and a comparison to use for matching the fruit on both lists. The real lists may have 50-120 items (each) that need to be matched.
All items should be returned. If there's a match, the data should be in the same row. If not, blanks should display.
The code below displays via an html page where the ID for each of the table cells matches the cell references in the script below. It's not sorted and the rows don't match.
```
$(function() {
$.ajax({
url: "sharepointlist/_api/web/lists/GetByTitle('List1')/items",
type: "GET",
headers: { "accept": "application/json;odata=verbose"
},
}).success(function (data) {
var title = '';
var type = '';
$.each(data.d.results,
function (key, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
$("#tdtitle").html(title);
$("#tdtype").html(status);
$.ajax({
url: "sharepointlist/_api/web/lists/GetByTitle('List2')/items",
type: "GET",
headers: { "accept": "application/json;odata=verbose"
},
}).success(function (data) {
var title2 = '';
var state = '';
$.each(data.d.results,
function (key, value) {
title2 += "Title2: " + value.Title + "<br/>";
city += "State: " + value.State + "<br/>";
});
$("#tdsecond").html(title2);
$("#tdstate").html(city);
``` | 2016/01/31 | [
"https://Stackoverflow.com/questions/35120566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344208/"
] | Seems like you miss API 19.
I suggest you go to Tools - Android - SDK Manager or click on the SDK Manager icon and check if API 19 is installed. | I already had API 19 installed even though the error seems to indicate API19 is an issue. I switched to API 17 and that got rid of that error but caused some new ones.
These issues are probably related to the Sherlock library that is in my app conflicting with the GooglePlayer libraries. After switching to API 17 I resolved the other errors by removing the dependancy:
compile 'com.google.android.gms:play-services:7.0.0'
And adding the following:
compile 'com.google.android.gms:play-services-ads:8.3.0'
compile 'com.google.android.gms:play-services-identity:8.3.0'
compile 'com.google.android.gms:play-services-gcm:8.3.0'
compile 'com.google.android.gms:play-services-plus:8.3.0'
compile 'com.google.android.gms:play-services-auth:8.3.0'
compile 'com.google.android.gms:play-services-maps:8.3.0'
to the project's build.gradle. |
35 | These two terms seem to be related, especially in their application in computer science and software engineering.
* Is one a subset of another?
* Is one a tool used to build a system for the other?
* What are their differences and why are they significant? | 2016/08/02 | [
"https://ai.stackexchange.com/questions/35",
"https://ai.stackexchange.com",
"https://ai.stackexchange.com/users/69/"
] | The machine learning is a sub-set of artificial intelligence which is only a small part of its potential. It's a specific way to implement AI largely focused on statistical/probabilistic techniques and evolutionary techniques.[Q](https://www.quora.com/What-are-the-main-differences-between-artificial-intelligence-and-machine-learning/answer/Phillip-Rhodes)
### Artificial intelligence
Artificial intelligence is '**the theory and development of computer systems able to perform tasks normally requiring human intelligence**' (such as visual perception, speech recognition, decision-making, and translation between languages).
We can think of AI as the concept of non-human decision making[Q](https://www.quora.com/What-are-the-main-differences-between-artificial-intelligence-and-machine-learning/answer/Yuval-Ariav) which aims to simulate cognitive human-like functions such as problem-solving, decision making or language communication.
### Machine learning
Machine learning (ML) is basically **a learning through doing** by the implementation of build models which can predict and identify patterns from data.
According to Prof. [Stephanie R. Taylor](http://www.cs.colby.edu/srtaylor/) of Computer Science and her [lecture paper](http://cs.colby.edu/courses/S15/cs251/LectureNotes/Lecture_15_MLandDMintro_03_09_2015.pdf), and also [Wikipedia page](https://en.wikipedia.org/wiki/Learning#Machine_learning), 'machine learning is a branch of artificial intelligence and **it's about construction and study of systems that can learn from data**' (like based on the existing email messages to learn how to distinguish between spam and non-spam).
According to [Oxford Dictionaries](http://www.oxforddictionaries.com/definition/english/machine-learning), the machine learning is '**the capacity of a computer to learn from experience**' (e.g. modify its processing on the basis of newly acquired information).
We can think ML as computerized pattern detection in the existing data to predict patterns in future data.[Q](https://www.quora.com/What-are-the-main-differences-between-artificial-intelligence-and-machine-learning/answer/Yuval-Ariav)
---
In other words, **machine learning involves the development of self-learning algorithms** and **artificial intelligence involves developing systems or software** to mimic human to respond and behave in a circumstance.[Quora](https://www.quora.com/What-are-the-main-differences-between-artificial-intelligence-and-machine-learning/answer/Sakthi-Dasan-2) | Machine learning is a subfield of artificial intelligence, as the following diagram (taken from [this blog post](https://www.linkedin.com/pulse/how-artificial-intelligence-different-from-machine-learning-singh)) illustrates.
[](https://i.stack.imgur.com/5i2z7.png) |
37,618,333 | I've this code :
```css
div {
width: 200px;
height: 200px;
background-color: #ececec;
margin-bottom: 10px;
}
```
```html
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
```
I want to target the 2nd div, then the 5th div, the 8th div etc. to change their background. | 2016/06/03 | [
"https://Stackoverflow.com/questions/37618333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4875059/"
] | Just use the [`nth-child`](https://developer.mozilla.org/en/docs/Web/CSS/:nth-child) pseudo-class with an appropriate parameter:
```
div:nth-child(3n+2){
background-color: blue;
}
``` | Add this CSS code,
```
div:nth-child(3n+2){
background:#00CC66;
}
``` |
598,552 | I visited a university CS department open day today and in the labs tour we sat down to play with a couple of final-year projects from undergraduate students. One was particularly good - a sort of FPS asteroids game. I decided to take a peek in the `src` directory to find it was done in C++ (most of the other projects were Java 3D apps).
I haven't done any C before but I have looked through some C code before. From what I saw in the .cpp code in this game it didn't look very different.
I'm interested in learning either C or C++ but will probably learn the other later on. **Is there any advantage to me learning one before the other** and **if so, which one?** | 2009/02/28 | [
"https://Stackoverflow.com/questions/598552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] | I think you should learn C first, because I learned C first. C gave me a good grasp of the syntax and gotchas with things like pointers, all of which flow into C++.
I think C++ makes it easy to wrap up all those gotchas (need an array that won't overflow when you use the [] operator and a dodgy index? Sure, make an array class that does bounds checking) but you need to know what they are and get bitten by them before you understand why things are done in certain ways.
When all is said and done, the way C++ is usually taught is "C++ is C with objects, here's the C stuff and here's how all this OO stuff works", so you're likely to learn basic C before any real C++ if you follow most texts anyway. | I think learning C first is a good idea.
There's a reason comp sci courses still use C.
In my opinion its to avoid all the "crowding" of the subject matter the obligation to require OOP carries.
I think that procedural programming is the most natural way to first learn programming. I think that's true because at the end of the day its what you have: lines of code executing one after the other.
Many texts today are pushing an "objects first" approach and start talking about cars and gearshifts before they introduce arrays. |
4,029,281 | How to determine what is selected in the drop down? In Javascript. | 2010/10/27 | [
"https://Stackoverflow.com/questions/4029281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488272/"
] | ```
<select onchange = "selectChanged(this.value)">
<item value = "1">one</item>
<item value = "2">two</item>
</select>
```
and then the javascript...
```
function selectChanged(newvalue) {
alert("you chose: " + newvalue);
}
``` | ```
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
``` |
9,252,266 | So, I understand what pointers are, what it means to reference something, and have a vague understanding of this 'heap'. Where I begin to lose my grip on things is when we introduce functions and classes with the use of these concepts, e.g. sending pointers, returning pointers, etc.
If by reference and passing pointers essentially perform the same function, what is the advantage of using one over the other? Both essentially are passing by reference and manipulating the object outside of the called function.
So, by reference:
```
#include <iostream>
class student{
public:
int semesterHours;
float gpa;
};
void defRefS( student &refS );
void defPointerS( student *Ps );
void defValueS( student cS );
int main()
{
student s;
defRefS(s); //Here,
std::cout << "\nBack in main we have " << s.semesterHours << " hours";
std::cout << "\nBack in main the GPA is: " << s.gpa;
student *Ps = &s;
defPointerS(&s); //And here is where I get confused
std::cout << "\nBack in main we have " << s.semesterHours << " hours";
std::cout << "\nBack in main the GPA is: " << s.gpa;
defValueS(s);
std::cout << "\nBack in main object S has: " << s.semesterHours << " hours";
std::cout << "\nBack in main object S has: " << s.gpa << " GPA\n\n";
}
void defRefS( student &refS ) //Passing by reference to object
{
refS.gpa = 4.0;
refS.semesterHours = 12;
std::cout << "\n------------- Reference Function ------------";
std::cout << "\n\nObject S has: " << refS.semesterHours << " hours";
std::cout << "\nObject S has: " << refS.gpa << " GPA";
}
void defPointerS( student *Ps ) //Passing a pointer to the object
{
Ps->gpa = 5.0;
Ps->semesterHours = 14;
std::cout << "\n\n------------- Pointer Function ---------------";
std::cout << "\n\nNow object S has: " << Ps->semesterHours << " hours";
std::cout << "\nNow object S has: " << Ps->gpa << " GPA";
}
void defValueS( student cS ) //Passing the object by value
{
cS.gpa = 100;
cS.semesterHours = 50;
std::cout << "\n\n------------- Value Function ------------------";
std::cout << "\n\nObject S has: " << cS.semesterHours << " hours";
std::cout << "\nObject S has: " << cS.gpa << " GPA";
}
```
Passing by reference essentially allows the notation to be similar since, I suppose, in all ways `refS` *is* the `s` object. So, this leads to a simple way to manipulate an object using a function.
Passing a pointer is easy enough to understand. It's just a pointer to the object. Although how about this in the above code:
```
void defRefS( student &refS );
void defPointerS( student *Ps );
void defValueS( student cS );
```
Are all of these functions only defined to work with the student class? So, these functions are only able to pass reference, pointer, and values of objects to this specific class?
```
defRefS(s); //Here,
defPointerS(&s); //And here is where I get confused
defValueS(s);
```
If passing by reference, shouldn't you pass the address of an object? So, for me, it made more since to pass the argument of the pointer function in the reference function.
The function `defPointerS` is defined to accept pointers; I'm sending it addresses? | 2012/02/12 | [
"https://Stackoverflow.com/questions/9252266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1200053/"
] | You're getting confused between two uses of the ampersand (&). In one case it is an operator and in the other case it's part of the type of a declaration.
```
int x = 5;
int* y = &x; // (1) Here it's an operator
int& z = x; // (2) Here it's part of the type of y
```
In line (1) above, we are declaring and defining a variable called `y` which is of type `pointer to int`. This means the variable `y` should contain the address of a variable of type `int`. To get the address of a variable, you use `&` as an operator. Thus, `&x` is the address of `x` and we're storing it in a pointer. `y` is now a pointer to `x`.
In line (2), we are defining a variable called `z` which is of type `reference to int`. Since we bind x to this refernece, this means we can use `z` as another name for `x`. Modifying `z` will modify `x` (and also the value that `y` points to!).
So when you have a function that takes a pointer, like `void func(int* p)`, you need to pass it the address of an int. To do this, you will either pass a pointer directly or take the address of an `int`:
```
int x = 5;
func(&x);
```
If you have a function that takes a reference, like `void func(int& r)`, you only need to pass it an `int`. The reference will refer to the same `int`.
```
int x = 5;
func(x);
```
These can be used in similar ways: to pass an argument in to a function so that the function can modify it or to avoid copying. However, a pointer argument also allows you to pass a null pointer in to the function. This doesn't work with a reference because a reference must always be bound to something. In addition, a reference cannot be rebound to a different object once it has been bound.
References are generally much more convenient and don't rely on C-style pointer manipulation. In C++, you normally want to use a reference whenever you can, and a pointer if you have to. See [the C++ FAQ](https://isocpp.org/wiki/faq/references#pointers-and-references) for details. | When you have `student s;` variable and you want to pass it to function `f` that takes argument of type `student` (passing by value) or `student&` (passing by reference), you just call `f(s)`. If you pass `s` by value, then copy of `s` is created and you work with copy of `s` in the body of function. If you pass it by reference, you work directly with the object `s`. Reference can not be NULL which is great advantage in many situations.
When type of this argument is `student*` (also passing by reference), you call `f(&s)` since pointer needs to be initialized with address it will point to.
You should also check: [Pointer vs. Reference](https://stackoverflow.com/q/114180/1168156) |
389,047 | >
> **Possible Duplicate:**
>
> [Vista to Windows 7 - Upgrading or clean installation?](https://superuser.com/questions/69662/vista-to-windows-7-upgrading-or-clean-installation)
>
>
>
Should I upgrade my Windows Vista to Windows 7 or wipe/format/install Windows 7?
I have a Dell Precision T3400 workstation that came with Windows Vista and a few months later Dell shipped me a Windows 7 upgrade (for free). I have yet to upgrade it and as it's inconvenient to backup/format/install Windows 7. The question is, should I just upgrade directly without a format?
I don't know if this is a proper question, or if it even can be one, but I need details on experiences with upgrading. I have *never* done this before, but Win Vista --> Win 7 doesn't seem like an upgrade with lots of pitfalls. | 2012/02/12 | [
"https://superuser.com/questions/389047",
"https://superuser.com",
"https://superuser.com/users/96062/"
] | Well the upgrade would work but it is a better approach do do a reinstall since you get rid of all the unneeded clutter.
I would go with a reinstall if I where you but an upgrade would serve you well too.
So if it is just a matter of using the free upgrade or buying a new disk for a fresh install then upgrade otherwise format | Do an inplace upgrade. A lot more convenient if you have got data there. If you haven’t, you should do a clean install. |
136,278 | For example, I rarely need:
```
using System.Text;
```
but it's always there by default. I assume the application will use more memory if your code contains unnecessary [using directives](http://msdn.microsoft.com/en-us/library/aa664764(VS.71).aspx). But is there anything else I should be aware of?
Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?
---
*Edit: Note that this question is not about the unrelated concept called a [using statement](http://msdn.microsoft.com/en-us/library/yh598w02.aspx), designed to help one manage resources by ensuring that when an object goes out of scope, its [IDisposable.Dispose](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) method is called. See [Uses of "using" in C#](https://stackoverflow.com/questions/75401/uses-of-using-in-c).* | 2008/09/25 | [
"https://Stackoverflow.com/questions/136278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
] | It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded.
Mainly, it's just to clean up for personal preference. | They are just used as a shortcut. For example, you'd have to write:
System.Int32 each time if you did not have a using System; on top.
Removing unused ones just makes your code look cleaner. |
31,244,547 | In the following code:
```
def main
someArray.all? { |item| checkSomething(item) }
end
private
def checkSomething(arg)
...
end
```
How do I shorten the `all?` statement in order to ged rid of the redundant `item` variable?
I'm looking for something like `someArray.all?(checkSomething)` which gives a "wrong number of arguments" error. | 2015/07/06 | [
"https://Stackoverflow.com/questions/31244547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326370/"
] | You could have a slightly shorter code if `checkSomething` was a method on your object class. Don't know what it is, so, I'm guessing, you're working with primitives (numbers, strings, etc.). So something like this should work:
```
class Object
def check_something
# check self
end
end
some_array.all?(&:check_something)
```
But this is, of course, a horrible, horrible way of going about it. Saving a few keystrokes at the cost of such global pollution - absolutely not worth it. Moreover, even this trick will not be available as soon as you will need to pass additional parameters to the check method.
Besides, the original code is quite readable too. | For block that executes a method with arguments, Checkout this way...
```
def main
someArray.all? &checkSomething(arg1, arg2, ...)
end
private
def checkSomething(arg1, arg2, ...)
Proc.new { |item| ..... }
end
``` |
32,639,112 | So I'm running into some issues that I'm not aware of how to solve when I'm improving my code.
Currently in my controller#show I have this ugly piece of code:
```
def show
@room = Room.find(params[:id])
if user_signed_in?
gon.push(
session_id: @room.session_id,
api_key: 453,
token: current_user.tokens.last.token
)
elsif customer_signed_in?
gon.push(
session_id: @room.session_id,
api_key: 453,
token: current_customer.tokens.last.token,
customer_id: current_customer.id
)
elsif @room.price == 0.0
@token = OT.generate_token @room.session_id
gon.push(
session_id: @room.session_id,
api_key: 453,
token: @token
)
else
@customer = Customer.new
end
end
```
now I would like to move this into the rooms model. The issue that I'm having is that I'm having an if else based on if it's a user, customer or neither. How would I go about moving this into a model and still be able to validate this? | 2015/09/17 | [
"https://Stackoverflow.com/questions/32639112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074646/"
] | I don't see why you would like to move this method to the model. (Are you using it from different places in your code? or just from this specific place?).
I would refactor this to the following:
```
def show
@room = Room.find(params[:id])
gon_args = { session_id: @room.session_id, api_key: 453, token: nil }
if user_signed_in?
gon_args.merge!(token: current_user.tokens.last.token)
elsif customer_signed_in?
gon_args.merge!(token: current_customer.tokens.last.token, customer_id: current_customer.id)
elsif @room.price == 0.0
gon_args.merge!(token: OT.generate_token(@room.session_id))
else
@customer = Customer.new
end
gon.push(gon_args) unless gon_args[:token].nil?
end
``` | You could always use a [PORO (Plain Old Ruby Object)](http://www.bootyard.com/programming/poro-for-unique-business-logic.html). Not only does it keep stuff clean, it helps a *bunch* in testing your app and keeping single responsibilities across your code. I'm sure you can do much better than below but this is just a starting point.
```
class YourController
def show
@room = Room.find(params[:id])
# no clue where some stuff comes from
pusher = RoomPusher.new @room, @token, gon
pusher.push
end
end
class RoomPusher
include YourHelpers
def initialize(room, token, endpoint)
@endpoint = endpoint
@room = room
@token = token
end
def push
if user_signed_in?
@endpoint.push(
session_id: @room.session_id,
api_key: 453,
token: current_user.tokens.last.token
)
elsif customer_signed_in?
@endpoint.push(
session_id: @room.session_id,
api_key: 453,
token: current_customer.tokens.last.token,
customer_id: current_customer.id
)
elsif @room.price == 0.0
@token = OT.generate_token @room.session_id
@endpoint.push(
session_id: @room.session_id,
api_key: 453,
token: @token
)
else
@customer = Customer.new
end
end
end
``` |
18,014,471 | I'd like to bind/set some boolean attributes to a directive. But I really don't know how to do this and to achieve the following behaviour.
Imagine that I want to set a flag to a structure, let's say that a list is collapsable or not. I have the following HTML code:
```
<list items="list.items" name="My list" collapsable="true"></list>
```
`items` are two-way binded, `name` is just an attribute
I'd like that `collapsable` attribute to be available in the list's $scope either by passing a value (true, false or whatever), either a two-way binding
```
<list items="list.items" name="{{list.name}}" collapsable="list.collapsed"></list>
```
I'm developing some UI components and I'd like to provide multiple way of interacting with them. Maybe, in time, some guys would like to know the state of that component, either is collapsed or not, by passing an object's property to the attribute.
Is there a way to achieve this? Please correct me if I missunderstood something or I'm wrong.
Thanks | 2013/08/02 | [
"https://Stackoverflow.com/questions/18014471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1454404/"
] | You can configure your own 1-way databinding behavior for booleans like this:
```
link: function(scope, element, attrs) {
attrs.$observe('collapsable', function() {
scope.collapsable = scope.$eval(attrs.collabsable);
});
}
```
Using $observe here means that your "watch" is only affected by the attribute changing and won't be affected if you were to directly change the $scope.collapsable inside of your directive. | Since Angular 1.3 attrs.$observe seems to trigger also for undefined attributes, so if you want to account for an undefined attribute, you need to do something like:
```
link: function(scope, element, attrs) {
attrs.$observe('collapsable', function() {
scope.collapsable = scope.$eval(attrs.collapsable);
if (scope.collapsable === undefined) {
delete scope.collapsable;
}
});
},
``` |
20,903,439 | How can you set up a `UIScrollView` to be paged and show `UIImages` such as the way app screenshots are presented in the app store (example in the image below).
Having the preview either side for the next / previous image is required too (like the old style tabs in Safari (iPhone) for iOS 6 and below).
I have found some example projects, but nothing I have found seems to work properly.
Does anyone know how to replicate this kind of functionality? I preferably do not want to use third party controls, but I am open to suggestions.
 | 2014/01/03 | [
"https://Stackoverflow.com/questions/20903439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451678/"
] | I've solved it, chaps. The method is as follows:
```
private Drawable invertImage(Drawable inputDrawable){
Bitmap bitmap = ((BitmapDrawable) inputDrawable).getBitmap();
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
int[] finalArray = new int[width * height];
for(int i = 0; i < finalArray.length; i++) {
int red = Color.red(pixels[i]);
int green = Color.green(pixels[i]);
int blue = Color.blue(pixels[i]);
finalArray[i] = Color.rgb(blue, green, red);
}
bitmap = Bitmap.createBitmap(finalArray, width, height, Bitmap.Config.ARGB_8888);
return new BitmapDrawable(getResources(),bitmap);
}
``` | You need to make a selector xml file which is described here <http://developer.android.com/guide/topics/resources/drawable-resource.html>
Possible implementation would look like this:
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_focused_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/button_focused" android:state_focused="true"/>
<item android:drawable="@drawable/button_disabled" android:state_enabled="false"/>
<item android:drawable="@drawable/button_normal"/>
```
For each supported button state you will need to make a new .png . Save this file in drawable folder of your resources (for instance button.xml) and apply it to your button as you would apply a normal png. |
8,011,216 | I need to update status line editor-specific information. I already have my own implementation, but I would like to take a look how is eclipse contribution item, which shows line number/column position in status line is implemented. Can anyone point me, where could I find the source code?
Thanks in advance,
AlexG. | 2011/11/04 | [
"https://Stackoverflow.com/questions/8011216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580147/"
] | I've been looking into it, it's quite involved, and I'm not sure I got the complete picture, but in case this helps someone...
The declarative way of binding an Editor with the contributions to the StatusLine (and Menu and Toolbar) is through [IEditorActionBarContributor](http://help.eclipse.org/indigo/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/IEditorActionBarContributor.html) class. This class is declared for a editor type in plugin.xml - and typically a single instance is created for each editor type (several running instances of a same editor type will share a `IEditorActionBarContributor` instance, calling its `doSetActiveEditor()` method when activated), and it will be disposed when when the last running editor of that type is closed.
Lets take as an example how the default text editor in Eclipse updates the "Insert/Override" info in the status line (from Eclipse 3.7)
The default text editor is declared in `org.eclipse.ui.editors`'s `plugin.xml` (some lines trimmed) as:
```
<extension point="org.eclipse.ui.editors">
<editor name="%Editors.DefaultTextEditor"
class="org.eclipse.ui.editors.text.TextEditor"
contributorClass="org.eclipse.ui.editors.text.TextEditorActionContributor"
id="org.eclipse.ui.DefaultTextEditor">
</editor>
</extension>
```
`TextEditorActionContributor` is the key. What interest us is implemented in the parent class [BasicTextEditorActionContributor](http://help.eclipse.org/indigo/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/texteditor/BasicTextEditorActionContributor.html); it defines (statically) the 4 status fields (`STATUS_FIELD_DEFS`) and it stores internally a fixed map (`fStatusFields`) of each statusField (the spec, say) to a StatusLineContributionItem object). When called from the Eclipse UI, it registers the 4 fields in the status line (the titles, basically) in the method `contributeToStatusLine(IStatusLineManager statusLineManager)` And each time a editor is activated, it passes to it -in `doSetActiveEditor(IEditorPart part)`- the full set of `StatusLineContributionItem`s , prepared with the corresponding actionHandlers. The editor understands all this because it implements `ITextEditorExtension.setStatusField()`.
In the case of `AbstractTextEditor`, it has an private field of (inner class) type `ToggleOverwriteModeAction`, which calls
```
toggleOverwriteMode()->handleInsertModeChanged()->updateStatusField("InputMode")
```
The editor looks if it has a `statusField` stored with this category, if so it will call `IStatusField.setText("Insert" / "Overwrite")` and this will result in the update of the status line message.
This is an example, but I guess it gives the general idea: an instance of `EditorActionContributor`, binded to a editor type, mantains a list of the StatusLineContributionItem to be updated, and the editor must write into the objects of this list when the corresponding status changes. In this way, the editor is decoupled from the status line (it doesn't know if/how a status change will be displayed in the UI). | In order to find out how something is implemented in Eclipse, you can also use the so called **Plug-in spy**. The Plug-in spy is included in the **Plug-in Development Environmend (PDE)**. It is executed with **ALT+SHIFT+F1**. For further details look this [Plug-in development FAQ](http://wiki.eclipse.org/Eclipse_Plug-in_Development_FAQ#There.27s_a_view_.2F_editor_that_I_want_to_model._How_do_I_find_out_what_its_source_looks_like_and_how_it_was_designed.3F). |
41,852,686 | How do i unit test python dataframes?
I have functions that have an input and output as dataframes. Almost every function I have does this. Now if i want to unit test this what is the best method of doing it? It seems a bit of an effort to create a new dataframe (with values populated) for every function?
Are there any materials you can refer me to? Should you write unit tests for these functions? | 2017/01/25 | [
"https://Stackoverflow.com/questions/41852686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/955237/"
] | I don't think it's hard to create small DataFrames for unit testing?
```
import pandas as pd
from nose.tools import assert_dict_equal
input_df = pd.DataFrame.from_dict({
'field_1': [some, values],
'field_2': [other, values]
})
expected = {
'result': [...]
}
assert_dict_equal(expected, my_func(input_df).to_dict(), "oops, there's a bug...")
``` | I would suggest writing the values as CSV in docstrings (or separate files if they're large) and parsing them using `pd.read_csv()`. You can parse the expected output from CSV too, and compare, or else use `df.to_csv()` to write a CSV out and diff it. |
951,596 | Given the code (which looks like it should be valid):
```
<!--[if lt IE 7]> <style type="text/css" media="screen">
<!--
div.stuff { background-image: none; }
--></style><![endif]-->
```
The W3C validator throws a fit:
* S separator in comment declaration
* invalid comment declaration: found name start character outside comment but inside comment declaration
* character data is not allowed here
etc etc
I'm not totally sure whats going on. Is it the 'nested' comments? The tag is being generated by the Zend Framework Viewhelper headStyle
```
$this->headStyle()->prependStyle('div.stuff { background-image: none; }',
array('conditional' => 'lt IE 7')
);
``` | 2009/06/04 | [
"https://Stackoverflow.com/questions/951596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95022/"
] | "`-->`" closes any comment, there is no notion of nesting comments inside each other. So in your code, the first "`-->`" closes both of your comments. Then the `<![endif]-->` is completely outside of any comments, so doesn't make any sense. | It is the nested comments. They are not allowed. |
37,319,576 | Item Position always taken as 0 inside onBindViewHolder and hence i am only getting one list item in recycler view although I have passed huge list in adapter.
This issue is occurring in some devices including Nexus 5 while my recycler view is working fine for few other devices like s5.
Can any body tell me what may be going wrong?
Any help would be appreciated | 2016/05/19 | [
"https://Stackoverflow.com/questions/37319576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3492435/"
] | Use a class loader you will get the desired output
```
Class.forName("<package>.Test6");
``` | Test6 is not initialized at all.
the foo is static, which means it can be used before class is intitialized and after a class is load. |
19,585,672 | I am creating a topmenu for a webpage, and with scripting, the sub menus pops up on hover. I have also taken measures to not let the menu grow too far to the right, by if needed let it grow in the other direction. This picture clarifies:

I do this by adding the class "to-the-left" to the sub sub menu.
Now, why is some menu items of the parent on top of my sub sub menu? You can read "Item 3" below "Sub sub item 2" which should not be possible.
I have tried to add z-index to the sub sub menu without succeeding.
<http://jsfiddle.net/VK7Mt/>
```
<!doctype html>
<html>
<head>
<style type="text/css">
div.top-menu
{
width: 920px;
margin: 0 auto;
}
div.top-menu ul.topmenu
{
margin: 0;
height: 41px;
background: #ccc;
padding: 0;
position: relative;
}
ul.topmenu li
{
list-style: none;
float: left;
padding: 12px 19px;
min-height: 17px;
position: relative;
}
ul.topmenu ul
{
width: 190px;
position: absolute;
top: 41px;
left: 0;
margin: 0;
padding: 0;
background: #dddddd;
border: #c4c4c4 1px solid;
}
ul.topmenu ul li
{
float: none;
padding: 3px 6px 3px 13px;
}
ul.topmenu a
{
color: #333;
text-decoration: none;
}
ul.topmenu ul li a
{
display: inline-block;
font-weight: normal;
width: 90%;
}
ul.topmenu ul li:hover
{
background: #3399cc;
}
ul.topmenu ul ul
{
left: 100%;
top: 0;
}
ul.topmenu div
{
cursor: pointer;
}
.topmenu-sub-item > .item
{
padding-left: 6px;
}
.topmenu-sub-item > .item > a
{
margin-top: 3px;
margin-bottom: 3px;
}
ul.topmenu ul ul.to-the-left
{
left: -100.5%;
}
</style>
</head>
<body>
<div class="top-menu">
<ul class="topmenu">
<li class="topmenu-root-node">
<a href="foobar.html">root item</a>
<ul class="topmenu-submenu-container">
<li class="topmenu-sub-item">
<div class="item">
<a href="/item1">item 1</a>
</div>
</li>
<li class="topmenu-sub-item nonempty">
<div class="item has-submenu">
<a class="topmenu-hassubmenu" href="/item2">item 2</a>
</div>
<ul class="topmenu-submenu-container to-the-right">
<li class="topmenu-sub-item nonempty">
<div class="item has-submenu">
<a class="topmenu-hassubmenu" href="/subitem1">Sub item 1</a>
</div>
<ul class="topmenu-submenu-container to-the-right">
<li class="topmenu-sub-item nonempty">
<div class="item has-submenu">
<a class="topmenu-hassubmenu" href="/subsubitem1">Sub sub item 1</a>
</div>
</li>
<li class="topmenu-sub-item">
<div class="item">
<a href="/subsubitem2">Sub sub item 2</a>
</div>
</li>
<li class="topmenu-sub-item">
<div class="item">
<a href="/subsubitem3">Sub sub item 3</a>
</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="topmenu-sub-item">
<div class="item">
<a href="/item3">Item 3</a>
</div>
</li>
</ul>
</li>
</ul>
</div>
<div class="top-menu" style="margin-top: 170px">
<ul class="topmenu">
<li class="topmenu-root-node">
<a href="foobar.html">root item</a>
<ul class="topmenu-submenu-container">
<li class="topmenu-sub-item">
<div class="item">
<a href="/item1">item 1</a>
</div>
</li>
<li class="topmenu-sub-item nonempty">
<div class="item has-submenu">
<a class="topmenu-hassubmenu" href="/item2">item 2</a>
</div>
<ul class="topmenu-submenu-container to-the-right">
<li class="topmenu-sub-item nonempty">
<div class="item has-submenu">
<a class="topmenu-hassubmenu" href="/subitem1">Sub item 1</a>
</div>
<ul class="topmenu-submenu-container to-the-left">
<li class="topmenu-sub-item nonempty">
<div class="item has-submenu">
<a class="topmenu-hassubmenu" href="/subsubitem1">Sub sub item 1</a>
</div>
</li>
<li class="topmenu-sub-item">
<div class="item">
<a href="/subsubitem2">Sub sub item 2</a>
</div>
</li>
<li class="topmenu-sub-item">
<div class="item">
<a href="/subsubitem3">Sub sub item 3</a>
</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="topmenu-sub-item">
<div class="item">
<a href="/item3">Item 3</a>
</div>
</li>
</ul>
</li>
</ul>
</div>
</body>
</html>
``` | 2013/10/25 | [
"https://Stackoverflow.com/questions/19585672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427758/"
] | The interfaces in Java are born to be implemented. Any class can implement any interface as long as it wants. So, I think there is no way to prevent that case. You probably need reconsider your design. | Not sure if this helps, but if you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.
So essentially, you could put your interface in one package, and any classes that you don't want to be able to implement it in another.. |
2,333,103 | I'm using Views dropdown filter (with tags) and it works great. However I would like to customize it in this way:
1 - remove button "Apply" and automatically update Views (at the moment I'm updating it with Ajax)
2- allow my customer to change the order of the dropdown items (specifying top items)
3- select multiple items without having to press the SHIFT button on keyboard (do not unselect other items if new items are selected)
<http://dl.dropbox.com/u/72686/viewsFilter1.png>
Let's suppose the items in the image are tags... something like this:
<http://dl.dropbox.com/u/72686/viewsFilter2.png>
thanks | 2010/02/25 | [
"https://Stackoverflow.com/questions/2333103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257022/"
] | The other way around is fine, bit I dont think you can run a 64bit app on a 32bit OS, you may be able to using a virtual machine or some kind of virtualisation. | No.
[See Microsoft FAQ](http://windows.microsoft.com/en-US/windows-vista/32-bit-and-64-bit-Windows-frequently-asked-questions):
>
> The terms 32-bit and 64-bit refer to
> the way a computer's processor (also
> called a CPU), handles information.
> The 64-bit version of Windows handles
> large amounts of random access memory
> (RAM) more effectively than a 32-bit
> system. For more details, go to A
> description of the differences between
> 32-bit versions of Windows Vista and
> 64-bit versions of Windows Vista
> online.
>
>
>
Understand the difference between 32-bit and 64-bit and you will see why it's not possible. |
14,073,989 | My ruby script should handle multiple external processes, so I was wondering how to redirect the output from different process to different log file(s). Also, as the external process takes quite a bit of time to complete, what is the best way of handling them in parallel?
As I am new to ruby I can show you an shell equivalent code:
```
LOGDIR="/tmp/test"
for host in $( h1 h2 h3 h4 ); do
( ssh root@${host} 'sh /tmp/scripttorun' >> ${LOGDIR}/${host}.log 2>&1 ) &
sleep 5
done
wait #wait for all subprocesses to complete
``` | 2012/12/28 | [
"https://Stackoverflow.com/questions/14073989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801327/"
] | This happened to me while collaborating with someone over Skype, so closing Skype was not an option.
One possible solution is changing the port XAMPP is using for Apache.
1. Change *Apache (httpd.conf)*
-------------------------------
Go to the XAMPP Control Panel, click *Config* for the Apache module and then *Apache (httpd.conf)*.


This will now open the configuration file in the editor that is configured in the XAMPP settings (Windows default is notepad.exe). Open the search tool and search for `80`. There should be two lines containing 80 as in the port number 80:
```
Listen 80
```
```
ServerName localhost:80
```
Now replace `80` with an open port. I used `8080`.
```
Listen 8080
```
```
ServerName localhost:8080
```
2. Change *Apache (httpd-ssl.conf)*
-----------------------------------
The same procedure needs to be repeated with the SSL configuration. Repeat the steps above but go to *Apache (httpd-ssl.conf)*. Replace the port numbers in the following lines:
```
Listen 443
```
```
<VirtualHost _default_:443>
```
```
ServerName www.example.com:443
```
I choose `4433`.
---
**Done.** Click *Start* for Apache and Apache should start fine. On my end, the errors would still show up, though. | It says that skype is using port 80. I would disable skype and then start your web server. |
40,765,877 | I'm setting up a Flask/uswgi web server. I'm still wondering about the micro-service architecture:
Should I put both nginx and Flask with uwsgi in one container or shall I put them in two different containers and link them?
I intend to run these services in a Kubernetes cluster.
Thanks | 2016/11/23 | [
"https://Stackoverflow.com/questions/40765877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3743089/"
] | **Short answer:**
I would deploy the nginx and uwsgi/flask application as separate containers. This gives you a more flexible architecture that allows you to link more microservices containers to the nginx instance, as your requirements for more services grow.
**Explanation:**
With docker the usual strategy is to split the nginx service and the uwsgi/flask service into two separate containers. You can then link both of them using links. This is a common architecture philosophy in the docker world. Tools like docker-compose simplify the management of running multiple containers and forming links between them. The following docker-compose configuration file shows an example of this:
```
version: '2'
services:
app:
image: flask_app:latest
volumes:
- /etc/app.cfg:/etc/app.cfg:ro
expose:
- "8090"
http_proxy:
image: "nginx:stable"
expose:
- "80"
ports:
- "80:8090"
volumes:
- /etc/app_nginx/conf.d/:/etc/nginx/conf.d/:ro
```
This means that if you want to add more application containers, you can attach them to the same ngnix proxy easily by linking them. Furthermore, if you want to upgrade one part of your infrastructure, say upgrade nginx, or shift from apache to nginx, you are only re-building the relevant container, and leaving all the rest in the place.
If you were to add both services to a single container (e.g. by launching supervisord process from the Dockerfile ENTRYPOINT), that would allow you to opt more easily for communication between the nginx and uwsgi process using the socks file, rather than by IP, but I don't think this in it self is a strong enough reason to put both in the same container.
Also, consider if eventually you end up running twenty microservices and each is running each own nginx instance, that means you now have twenty sets of nginx (access.log/error.log) logs to track across twenty containers.
If you are employing a "microservices" architecture, that implies that with time you will be adding more and more containers. In such an ecosystem, running nginx as a separate docker process and linking the microservices to it makes it easier to grow in line with your expanding requirements.
Furthermore, certain tasks only need to be done once. For example, SSL termination can be done at the nginx container, with it configured with the appropriate SSL certificates once, irrespective of how many microservices are being attached to it, if the nginx service is running on its own container.
**A note about service discovery**
If the containers are running in the same host then linking all the containers is easy. If the containers are running over multiple hosts, using Kubernetes or Docker swarm, then things may become a bit more complicated, as you (or your cluster framework) needs to be able to link your DNS address to your nginx instance, and the docker containers need to be able to 'find' each other - this adds a bit of conceptual overhead. Kubernetes helps you achieve this by grouping containers into pods, defining services, etc. | If you're using Nginx in front of your Flask/uwsgi server, you're using Nginx as a proxy: it takes care of forwarding traffic to the server, eventually taking care of TLS encryption, maybe authentication etc...
The point of using a proxy like Nginx is to be able to load-balance the traffic to the server(s): the Nginx proxy receives the requests, and distributes the load among multiple servers.
This means you need one instance of Nginx, and one or multiple instances of the Flask/usqgi server as 'upstream' servers.
To achieve this the only way is to use separate containers.
Note that if you're on a cloud provider like AWS or GKE, which provides the load-balancer to bring your external traffic to your Kubernetes cluster, and if you are merely using Nginx to forward the traffic (i.e. not using it for TLS or auth) then you probably don't even need the Nginx proxy but can use a Service which does the proxying for you. Adding Nginx just gives you more control. |
13,276,574 | I'd like to get a string from my ArrayList, but it contains lines from my input fole. How do I split them correctly to have all the elements?
My program looks like this:
```
private static ArrayList<String> lista;
static void fileReading() {
inp = new LineNumberReader(new BufferedReader(new InputStreamReader(new FileInputStream(inFileNev), "ISO8859-1")));
String sor;
while ((sor = inp.readLine()) != null) {
lista.add(sor);
lista.add(System.getProperty("line.separator"));
}
```
In another method how do I get this lists only one string and not the line?
EDIT:
Vineet Verma your code is great, but it gets me a great string, and I need to know the indexes of the strings within this, replace them later, and I can't get it done with only one string.
It's still not working, if I use this:
>
>
> ```
> String[] temp=null;
> for(String s : lista) {
> temp = s.split("\\W+");
> }
>
> ```
>
> System.out.println(temp);
>
>
>
I get: [Ljava.lang.String;@6ef53890
Wihtin the for I get many : [Ljava.lang.String;@6ef53890
If I use this:
>
>
> ```
> String str ="" ;
> for(int i=0; i<lista.size(); i++){
> str+=lista.get(i)+" ";
>
> String[] temp = new String[str.length()];
> for(int i=0; i < str.length(); i++) {
> temp[i]=str.valueOf(i);
> System.out.println(temp[i]);
> }
>
> ```
>
>
I get only numbers, and can't figure out how to get the string from str. | 2012/11/07 | [
"https://Stackoverflow.com/questions/13276574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796823/"
] | The string `"//"` can be used directly as a separator, it doesn't need escaping:
```
String[] data = str.split("//");
```
A different situation occurs with `"\\"`, the `'\'` character is used as escape character in a regular expression and in turn it needs to be escaped by placing another `'\'` in front of it:
```
String[] data = str.split("\\\\");
``` | ```
theString.split( "//" );
```
<http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String>)
since the arg is a regex, it might require some escaping, but that should work. |
6,070 | I know it is also possible to get a re-entry permit in both int. airports.
Is it possible also on land-borders, specifically, Laos via Nong-Khai? | 2015/04/28 | [
"https://expatriates.stackexchange.com/questions/6070",
"https://expatriates.stackexchange.com",
"https://expatriates.stackexchange.com/users/6320/"
] | Yes, it is possible.
Evidence:
1. It is, as of 1 July 2016, explicty stated on the [Nong Khai Immigration](http://nongkhai.immigration.go.th/index.php) web site that this is possible (see screenshot below)
2. I telephoned Nong Khai immigration to check, to make absolutely sure, and they said that it is. They also said that the re-entry desk is open until 10pm, I think on weekdays. But you would want to check this.
3. I got a re-entry permit from Thai border control at the friendship bridge myself in June 2016. I got the permit during regular working hours, i.e. before 16:30.
[](https://i.stack.imgur.com/aA2DX.jpg) | No, you cannot do this on land.
In the international airport, they have a special re-entry desk. However, for land border, you should have a origin country. In the case of Laos, you should come from Laos. This means, when you leave Thailand, you should enter Laos and leave Laos to be eligible to enter Thailand again. |
68,027,117 | I tried this in TypeScript:
```js
import events from 'events'
import EventEmitter from 'events'
class MyEmitter extends EventEmitter {
condition: boolean
emit() {
if (this.condition) {
return events.EventEmitter.prototype.emit.apply(this, arguments)
}
}
}
const myEmitter = new MyEmitter()
myEmitter.emit('something')
```
This results in `Expected 0 arguments, but got 1.ts(2554)` in the last line (when calling `emit('something')`.
How do I deal with this? | 2021/06/17 | [
"https://Stackoverflow.com/questions/68027117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90800/"
] | >
> I want my program to look inside of this tag and output the text exactly like how they appear on the webpage.
>
>
>
The browser does a lot of processing to display a web page. This includes removing extra spaces. Additionally, the browser developer tools show a parsed version of the HTML as well as potential additions from dynamic JavaScript code.
On the other hand, you are opening a raw text file and get the text as it is, including any formatting such as indentation and line breaks. You will need to process this yourself to format it the way you want when you output it.
There are at least two things to look for:
1. Is the indentation tab or space characters? By default `print()` represents a tab as 8 spaces. You can either replace the tabs with spaces to reduce the indentation or you can use another output method that allows you to configure specify how to show tabs.
2. The strings themselves will include a newline character. But then `print()` also adds a line break. So either remove the newline character from each string or do `print(para.get_text(), end='')` to disable print adding another newline. | Would something like this work:
1. Strip left and right of the p
2. Indent the paragraph with 1em (so 1 times the font size)
3. Newline each paragraph
```
font_size = 16 # get the font size
for para in desiredText.find_all('p'):
print(font_size * " " + para.get_text().strip(' \t\n\r') + "\n")
``` |
43,546,788 | our program connects to a db and when you sign into the program, it's throwing this error: "Syntax error or access violation" along with "Cannot insert the value NULL into column 'ID', table 'CADDB.dbo.AuditTrail'; column does not allow nulls. INSERT fails"
I've tried Microsoft's Fix to Use ANSI Nulls, Padding and Warnings in the ODBC connections, but it still occurs.
Can someone point me where to look? I believe it's corrupt data in the db... but not 100% sure. I will attach the error that gets logged with that message if you need me to. | 2017/04/21 | [
"https://Stackoverflow.com/questions/43546788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7902332/"
] | The exception showed you the root cause that your app is trying to insert NULL value into column ID, a column not allowing NULL. If this is caused by your application's bug and you also want to insert a NULL value into ID column. Then you may change the table to allow NULL for column ID or use a special value representing NULL (not recommended) for the insertion.
Otherwise, it is more likely to be your application's issue. | Thank you everybody! The issue was the db was corrupt. I got a working backup of the same db and it works fine without any errors. |
18,018,577 | ```
.newboxes {
display: none;
}
<script language="javascript">
function showonlyone(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200);
}
else {
$(this).hide(600);
}
});
}
</script>
<a href="javascript:showonlyone('newboxes1');" id="myHeader1">
<a href="javascript:showonlyone('newboxes2');" id="myHeader2">
<a href="javascript:showonlyone('newboxes3');" id="myHeader3">
<a href="javascript:showonlyone('newboxes4');" id="myHeader4">
<div class="newboxes" id="newboxes1" style="display: none;padding: 0px; width: 750px; font-size:14px;">
<div class="newboxes" id="newboxes2" style="display: none;padding: 0px; width: 750px; font-size:14px;">
<div class="newboxes" id="newboxes3" style="display: none;padding: 0px; width: 750px; font-size:14px;">
<div class="newboxes" id="newboxes4" style="display: none;padding: 0px; width: 750px; font-size:14px;">
```
I want to show first when page load first time. How should I do it with this piece of code? If I add display: block; to first div it dosn't work like that. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18018577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2448030/"
] | ```
var s = document.getElementById('thing').style;
s.opacity = 1;
(function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();
```
taken from <http://vanilla-js.com/> | CSS
```
.fade{
opacity: 0;
}
```
JavaScript
```
var myEle=document.getElementById("myID");
myEle.className += " fade"; //to fadeIn
myEle.className.replace( /(?:^|\s)fade(?!\S)/ , '' ) //to fadeOut
``` |
194,156 | *With the popularity of the Apple iPhone, the potential of the Microsoft [Surface](http://www.microsoft.com/surface/index.html), and the sheer fluidity and innovation of the interfaces pioneered by Jeff Han of [Perceptive Pixel](http://link.brightcove.com/services/link/bcpid713271701/bclid713073346/bctid709364416) ...*
### What are good examples of Graphical User Interfaces which have evolved beyond the
### Windows, Icons, ( Mouse / Menu ), and Pointer paradigm ? | 2008/10/11 | [
"https://Stackoverflow.com/questions/194156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] | Are you only interested in GUIs? A lot of research has been done and continues to be done on [tangible interfaces](http://en.wikipedia.org/wiki/Tangible_User_Interface) for example, which fall outside of that category (although they can include computer graphics). The [User Interface Wikipedia](http://en.wikipedia.org/wiki/User_interface) page might be a good place to start. You might also want to explore the [ACM CHI Conference](http://www.chi2008.org/). I used to know some of the people who worked on zooming interfaces; the [Human Computer Interaction Lab an the University of Maryland](http://www.cs.umd.edu/hcil/research/) also has a bunch of links which you may find interesting.
Lastly I will point out that a lot of innovative user interface ideas work better in demos than they do in real use. I bring that up because your example, as a couple of commenters have pointed out, might, if applied inappropriately, be tiring to use for any extended period of time. Note that light pens were, for the most part, replaced by mice. Good design sometimes goes against naive intuition (mine anyway). There is a nice [rant](http://www.useit.com/alertbox/981115.html) on this topic with regard to 3d graphics on [useit.com](http://useit.com). | Technically, the interface you are looking for may be called **Post-WIMP user interfaces**, according to [a paper of the same name](http://portal.acm.org/citation.cfm?id=253708) by Andries van Dam. The reasons why we need other paradigms is that WIMP is not good enough, especially for some specific applications such as 3D model manipulation.
To those who think that UI research builds only cool-looking but non-practical demos, [the first mouse](http://en.wikipedia.org/wiki/File:Firstmouseunderside.jpg) was bulky and it took decades to be prevalent. Also Douglas Engelbart, the inventor, thought people would use both mouse and (a short form of) keyboard at the same time. This shows that even a pioneer of the field had a wrong vision about the future.
Since we are still in WIMP era, there are diverse comments on how the future will be (and most of them must be wrong.) Please search for these keywords in Google for more details.
* **Programming by example/demonstration**
In short, in this paradigm, users show what they want to do and computer will learn new behaviors.
* **3D User Interfaces**
I guess everybody knows and has seen many examples of this interface before. Despite a lot of hot debates on its usefulness, a part of 3D interface ongoing research has been implemented into many leading operating systems. The state of the art could be **BumpTop**. See also: **Zooming User Interfaces**
* **Pen-based/Sketch-based/Gesture-based Computing**
Though this interface may use the same hardware setup like WIMP but, instead of point-and-click, users command through strokes which are information-richer.
* **Direct-touch User Interface**
This is ike Microsoft's Surface or Apple's iPhone, but it doesn't have to be on tabletop. The interactive surface can be vertical, say wall, or not flat.
* **Tangible User Interface**
This has already been mentioned in another answer. This can work well with touch surface, a set of computer vision system, or augmented reality.
* **Voice User Interface**, **Mobile computing**, **Wearable Computers**, **Ubiquitous/Pervasive Computing**, **Human-Robot Interaction**, etc.
Further information:
[Noncommand User Interface](http://www.useit.com/papers/noncommand.html) by Jakob Nielsen (1993) is another seminal paper on the topic. |
6,800,631 | I want to send the xml file to .net web service but it did not work. In my project i have created xml file by using DOM Object. I want to send that Dom object to the server but It doent work.
I also used Ksoap2 jar file in my project. Please help me how to send the xml file to .net server. Here is my code:
```
package com.Android.Xml;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class BuildAndSend extends Activity {
private static final String METHOD_NAME = "SaveXmlData";
private static final String NAMESPACE = "http://tempuri.org/";
//private static final String URL = "http://61.12.109.69/AndroidWebservice/Service.asmx";
private static final String URL = "http://192.168.0.51/WebServiceExample/Service.asmx";
final String SOAP_ACTION = "http://tempuri.org/SaveXmlData";
TextView tv;
Button send;
StringBuilder sb;
Document doc;
DOMSource source;
StringWriter writer ;
InputStream inputStream;
/** Called when the activity is first created. */
String[] input = {"", ""};
String[] line = new String[2];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sb = new StringBuilder();
tv=(TextView)findViewById(R.id.text);
send=(Button)findViewById(R.id.button1);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
call();
}
});
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
doc = builder.newDocument();
Element root = doc.createElement("root");
doc.appendChild(root);
//Element memberList = doc.createElement("members");
// root.appendChild(memberList);
for (int i = 0; i < input.length; i++) {
line = input[i].split(",");
Element member = doc.createElement("member");
root.appendChild(member);
Element name = doc.createElement("name");
name.appendChild(doc.createTextNode(line[0]));
member.appendChild(name);
Element phone = doc.createElement("phone");
phone.appendChild(doc.createTextNode(line[1]));
member.appendChild(phone);
}
TransformerFactory tFact = TransformerFactory.newInstance();
Transformer trans;
try {
trans = tFact.newTransformer();
writer = new StringWriter();
StreamResult result = new StreamResult(writer);
source = new DOMSource(doc);
trans.transform(source, result);
System.out.println(writer.toString());
// call();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
public void call() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo p=new PropertyInfo();
p.setName("XmlFile");
p.setValue(doc);
p.setType(Document.class);
request.addProperty(p);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String resultData = result.toString();
sb.append(resultData + "\n");
} catch (Exception e) {
sb.append("Error:\n" + e.getMessage() + "\n");
System.out.println("error::::::::"+e.getMessage());
}
}
}
``` | 2011/07/23 | [
"https://Stackoverflow.com/questions/6800631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/859255/"
] | Yes. You are using parameterized queries, which are in general considered safe from SQL injection.
You may still want to consider filtering your inputs anyway. | Yes, all the non-static data is being fed in via bound parameters. |
8,911,684 | I want to submit a s:form when page loads.
here is my code :
```
<s:form id="login_form" action="" method="post">
<s:textfield label="User name" id="login_form_username"
name="username" value="abc.xyz" cssClass="txtbox"
required="true" />
<s:password label="Password" id="login_form_password" name="password"
value="pass" cssClass="txtbox" required="true" />
<s:submit value="Login" />
</s:form>
```
Actually as shown in above code, I will set uname and pwd dynamically and then want to submit this form directly using javascript.
I tried this :
```
<script type="text/javascript">
document.forms.login_form.submit();
</script>
```
but had no success.
Please help...
Thanks.. | 2012/01/18 | [
"https://Stackoverflow.com/questions/8911684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130032/"
] | you can use Jquery code:
```
document.ready(function(){
$("#login_form").submit();
});
```
dont forget to specify action attribute of form.
Note: to use jquery you need to add jquery library. | If you want to submit through java script means you have to give code like this eg:
If your from name is **\*login\_form\*** in java script then you can give like this
```
function submitform()
{
document.forms["login_form"].submit();
}
<s:form id="login_form" name="login_form" action="your action name" method="post">
<s:textfield label="User name" id="login_form_username"
name="username" value="abc.xyz" cssClass="txtbox"
required="true" />
<s:password label="Password" id="login_form_password" name="password"
value="pass" cssClass="txtbox" required="true" />
<s:submit value="Login" onClick="submitform()"/>
</s:form>
```
Here you should remember 2 important points:
>
> 1)without action name it will not work because, for going to the
> struts.xml you need action name right in your code i didn't see the action name.
>
>
> 2)Secondly, in your code you written some java script code but, you not
> called that function name either through submit button nor through
> body onload function. I will assume like for posting purpose you did
> this coding k that is not the problem.
>
>
>
what i was showed above code that is one way. Another way is without submit button your code should run means, you can type like this in a jsp page
```
<META HTTP-EQUIV="Refresh" CONTENT="1;URL=youractionname.action">
```
you have to write this code before body only then your jsp page works like what you want.
Here i used for both the codes ***action name(youractionname)*** means without action name in struts2 page won't go to the action class
>
> Bottom Line:Action name is important in struts2
>
>
> |
2,275,876 | I need to extract the contents of the title tag from an HTML page displayed in a UIWebView. What is the most robust means of doing so?
I know I can do:
```
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
```
However, that only works if javascript is enabled.
Alternatively, I could just scan the text of the HTML code for the title but that feels a bit cumbersome and might prove fragile if the page's authors got freaky with their code. If it comes to that, what's the best method to use for processing the html text within the iPhone API?
I feel that I've forgotten something obvious. Is there a better method than these two choices?
Update:
-------
Following from the answer to this question: [UIWebView: Can You Disable Javascript?](https://stackoverflow.com/questions/2302975/uiwebview-can-you-disable-javascript) there appears to be no way to turn off Javascript in UIWebView. Therefore the Javascript method above will always work. | 2010/02/16 | [
"https://Stackoverflow.com/questions/2275876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190807/"
] | `WKWebView` has 'title' property, just do it like this,
```
func webView(_ wv: WKWebView, didFinish navigation: WKNavigation!) {
title = wv.title
}
```
I don't think `UIWebView` is suitable right now. | I dońt have experience with webviews so far but, i believe it sets it´s title to the page title, so, a trick I suggest is to use a category on webview and overwrite the setter for self.title so you add a message to one of you object or modify some property to get the title.
Could you try and tell me if it works? |
43,991,608 | I'm a rookie so forgive me if this is obvious. I'm trying to access class attributes from a separate class file, as you can probably tell from the title. I run into a problem when calling the class.
```
class Example:
def __init__(self, test):
self.test = test
```
Say test is the attribute I wish to access.
```
from test import Example
class Example2:
def __init__(self):
self.test = Example()
```
When I call example it says parameter test is unfilled. Let's pretend test already has an important value and I don't want to change it. What do I do in a situation like this and why? | 2017/05/16 | [
"https://Stackoverflow.com/questions/43991608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7826175/"
] | You need to restore NuGet packages before attempting the build to resolve references to the reference assemblies that provide you the core types.
You can do this using `msbuild /t:Restore` (TFS/VSTS: use msbuild task) or `nuget.exe restore` (use a nuget.exe >= 4.0.0). | There must be some issue within the latest Visual Studio 2017. They, the Microsoft, change the project file structure of .Net Core / standard a lot from 2017 RC to current one. |
6,659,445 | I want to avoid my child form from appearing many times when a user tries to open the child form which is already open in MDIParent. One way to avoid this is by disabling the Controller (in my case BUTTON) but I have given a shortcut key (`Ctrl`+`L`) for this function as well. So if the user types `Ctrl`+`L`, the same child Form opens and I can see two child forms are in MDI.
```
private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
frmWebLeads formWeblead = new frmWebLeads();
formWeblead.MdiParent = this;
formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
formWeblead.Show();
}
```
I want to avoid this. How can I do this?

In the image you can see that a child form Name **Online Leads** is opened twice as the user opened first time using Menu (LEADS) and second time by Shortcut key. I don't want this to happen. If the form is already opened it should avoid opening another same form ... How to do this? | 2011/07/12 | [
"https://Stackoverflow.com/questions/6659445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818355/"
] | ```
frmWebLeads formWeblead;
bool isformWebleadOpen =false;
private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
if(isformWebleadOpen == false)
{
formWeblead = new frmWebLeads();
isformWebleadOpen =true;
formWeblead.Closed += formWeblead_Closed;
formWeblead.Show();
}
}
void formWeblead_Closed(object sender, EventArgs e)
{
isformWebleadOpen = false;
}
``` | The easiest way is to keep a reference to the child form, and only spawn a new one if it doesn't already exist. Something like this:
```
class ParentForm : Form {
frmWebLeads formWeblead = null;
//...
private void leadsToolStripMenuItem_Click(object sender, EventArgs e)
{
if(formWeblead != null) return;
formWeblead = new frmWebLeads();
formWeblead.MdiParent = this;
formWeblead.WindowState = System.Windows.Forms.FormWindowState.Maximized;
formWeblead.Show();
}
}
```
You also need code to set formWeblead to null when you close it, but I'm sure you can figure that part out :) |
3,404,642 | I want to have access to the same message that Powershell prints when you send an error record to the output stream
Example:
>
> This is the exception message At
> C:\Documents and
> Settings\BillBillington\Desktop\psTest\exThrower.ps1:1
> char:6
> + throw <<<< (New-Object ArgumentException("This is the
> exception"));
> + CategoryInfo : OperationStopped: (:) [],
> ArgumentException
> + FullyQualifiedErrorId : This is the exception
>
>
>
I when a get the last ErrorRecord by doing $Error[0] I can't seem to figure out how to get this information in a simple way
I found this 'Resolve-Error' function from the community extensions [here](http://blogs.msdn.com/b/powershell/archive/2006/12/07/resolve-error.aspx "here") which does roughly what I want but it prints a huge semi-formatted list of stuff I don't need that I have to then strip
Is there way of accessing the message that Powershell uses or failing that a simpler way of getting hash of the values I care about so I can put them into a string in a format of my choosing? | 2010/08/04 | [
"https://Stackoverflow.com/questions/3404642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24773/"
] | I took it a bit further because I didn't like the multilines from $error[0].InvocationInfo.PositionMessage.
```
Function FriendlyErrorString ($thisError) {
[string] $Return = $thisError.Exception
$Return += "`r`n"
$Return += "At line:" + $thisError.InvocationInfo.ScriptLineNumber
$Return += " char:" + $thisError.InvocationInfo.OffsetInLine
$Return += " For: " + $thisError.InvocationInfo.Line
Return $Return
}
[string] $ErrorString = FriendlyErrorString $Error[0]
$ErrorString
```
You can look at what else is availible to construct your own String via:
```
$Error | Get-Member
$Error[0].InvocationInfo | Get-Member
``` | ```
Foreach ($Errors in $Error){
#Log Eintrag wird zusammengesetzt und in errorlog.txt geschrieben
"[$Date] $($Errors.CategoryInfo.Category) $($Errors.CategoryInfo.Activity) $($Errors.CategoryInfo.Reason) $($Errors.CategoryInfo.TargetName) $($Errors.CategoryInfo.TargetType) $($Errors.Exception.Message)" |Add-Content $Path\errorlog.txt -Encoding UTF8
}
```
You can also do this and you will get all Informations about the Error |
25,454,559 | Currently I'm using
```
data-parsley-`constraint`-message="English sentence goes here"
```
but now that I'm working to add localization these messages will never be translated using the i18n library because they are custom.
Is there a way to add something like
```
data-parsley-`constraint`-message-fr="Francais francais francais"
```
or someway to do it through JS?
Specifically I'm using data-parsley-required-message="" | 2014/08/22 | [
"https://Stackoverflow.com/questions/25454559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/923934/"
] | Why don't you use the localization of Parsley instead of defining the messages on the inputs?
I suggest you download the localizations that you need [from the source](https://github.com/guillaumepotier/Parsley.js/tree/master/src/i18n). After that, [according to the docs](http://parsleyjs.org/doc/index.html#psly-installation-localization) you can load the i18n before the plugin, like this:
```
<script src="i18n/fr.js"></script>
<script src="i18n/it.js"></script>
<script src="parsley.min.js"></script>
<script type="text/javascript">
window.ParsleyValidator.setLocale('fr');
</script>
```
Or you can load the i18n after the plugin (in that case, it will assume the last loaded localization - in the following example it will be Italian), like this:
```
<script src="parsley.min.js"></script>
<script src="i18n/fr.js"></script>
<script src="i18n/it.js"></script>
```
On my projects I typically load the needed localization based a Cookie or Session variable:
```
<script src="parsley.min.js"></script>
<script src="i18n/"<?= echo $lang ?>".js"></script>
```
With either of the options, you don't need to add **data-parsley-`constraint`-message** to each input. And when you need to change a message you can do that in the localization file.
To conclude, if you need custom validators, you can check [the docs](http://parsleyjs.org/doc/index.html#psly-validators-craft) to see how you can define the different localizations.
---
UPDATE
======
**This solves the OP's need by changing the source code of the plugin**
You can edit in your *parsley.js* a method called `_getErrorMessage` (line 1264 with 2.0.4), which looks like this:
```
_getErrorMessage: function (fieldInstance, constraint) {
var customConstraintErrorMessage = constraint.name + 'Message';
if ('undefined' !== typeof fieldInstance.options[customConstraintErrorMessage])
return window.ParsleyValidator.formatMessage(fieldInstance.options[customConstraintErrorMessage], constraint.requirements);
return window.ParsleyValidator.getErrorMessage(constraint);
},
```
To something like this:
```
_getErrorMessage: function (fieldInstance, constraint) {
//added
var locale = window.ParsleyValidator.locale;
var namespace = fieldInstance.options.namespace;
var customConstraintErrorMessage = namespace + constraint.name + '-' + locale;
if (fieldInstance.$element.attr(customConstraintErrorMessage)) {
// treat parameters
if (fieldInstance.$element.attr(customConstraintErrorMessage).indexOf("%s") !== -1)
return window.ParsleyValidator.formatMessage(fieldInstance.$element.attr(customConstraintErrorMessage), constraint.requirements);
return fieldInstance.$element.attr(customConstraintErrorMessage);
}
// original
var customConstraintErrorMessage = constraint.name + 'Message';
if ('undefined' !== typeof fieldInstance.options[customConstraintErrorMessage])
return window.ParsleyValidator.formatMessage(fieldInstance.options[customConstraintErrorMessage], constraint.requirements);
return window.ParsleyValidator.getErrorMessage(constraint);
},
```
With this, you can specify the messages directly in the input, using the sintax **data-parsley-`constraint`-`locale`**. Here is a sample:
```
<input type="text" name="name" value="" data-parsley-required="true"
data-parsley-required-en="Name is required"
data-parsley-required-pt="O nome é obrigatório" />
<input type="number" name="phone" value=""
data-parsley-minlength="9"
data-parsley-minlength-en="Phone length must be equal to %s"
data-parsley-minlength-pt="O telefone deverá ter %s digitos" />
```
When you need to use some kind of constrains (in the above example, there is `data-parsley-minlength` which is variable) you can use the `%s` inside the message. This will be replaced for the correct value.
Just before you bind parsley to your form, you need to set the locale you want to use (beware: you need to include the javascript file relative to the locale that you are using, otherwise you will get an error like `Error: pt is not available in the catalog`):
```
window.ParsleyValidator.setLocale('pt');
$("#myForm").parsley();
```
Here is a [jsfiddle](http://jsfiddle.net/062kf8te/) for demonstration. If you want to test, just `setLocale('en')` and see the messages in English. | You only put -message after your attribute of parsley which is you used for validation.
for example,
```
<input type="password" name="cpassword" id="cpassword" class="form-control"
placeholder="Enter confirm password" data-parsley-equalto="#password"
data-parsley-equalto-message="This value should be the same as password"
required>
```
>
> data-parsley-equalto is my parsley validator then after for custome message show for that equalto i simple put -message after that.
> `data-parsley-equalto` >> `data-parsley-equalto-message`
>
>
> |
118,833 | First time player playing as a tempest cleric.
As I understand the rules, a cleric of any domain has access to all the general cleric spells (i.e. not the ones that are only accessible to certain domains). However, my DM informed me that my god (custom storm god that he made up) would not allow me to cast Animate Dead because that's outside his domain. He also said that while I could cast first aid type resurrection spells like Revivify, the more powerful, return-the-soul-from-the-afterlife type spells would be a no-go. However, he'd let a life domain cleric use those spells more freely.
Are there any official sources that these rules are based off? As far as I can tell this is just a homebrew push to make the domain more thematic. | 2018/03/20 | [
"https://rpg.stackexchange.com/questions/118833",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/42418/"
] | >
> Are there any official sources that these rules are based off?
>
>
>
Not that I know of. This does indeed seem to be a homebrew approach.
You might want to ask your DM to write down the full Cleric spell list that you are allowed to use; it'll cut down on arguments later if you feel they're just removing spells at will. They are essentially making a new Cleric Spell List for each deity or domain (or however it's organized)
That seems perfectly fine to me, as long as it's clear what you're getting in to. | No, all clerics can cast cleric spells regardless of domain.
============================================================
The [Divine Domain](https://www.dndbeyond.com/classes/cleric#DivineDomain-109) feature description reads:
>
> Choose one domain related to your deity: Knowledge, Life, Light, Nature, Tempest, Trickery, or War. The Life domain is detailed at the end of the class description and provides examples of gods associated with it. See the *Player’s Handbook* for details on all the domains. Your choice grants you domain spells and other features when you choose it at 1st level. It also grants you additional ways to use Channel Divinity when you gain that feature at 2nd level, and additional benefits at 6th, 8th, and 17th levels.
>
>
>
Besides additional benefits granted by each domain, cleric domains simply add a list of spells that are treated as cleric spells for clerics of those domains; these spells are always auto-prepared for those clerics. They do not restrict you from using existing cleric spells. |
21,366 | The Chinese idiom " 不翼而飞" contains the character 翼 meaning wings, but how could one fly without wings?
Here 不翼 = 无翼 ? I'm confused.
I am aware of the fact that the saying means "vanish into the air or disappear without trace".
Thanks. | 2016/10/06 | [
"https://chinese.stackexchange.com/questions/21366",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/11212/"
] | I don't study language, here is what I think:
Idioms, or rather, Classical Chinese is grammatically much different than Modern Chinese. Back then, you can have a greater freedom on how you write and words with similar meanings can be used alternatively but in Modern Chinese, we tend to centralize meanings of characters more and use less of the other meanings.
This is the definition of 不: <http://xh.5156edu.com/html3/1680.html>
不
bù
副词。
用在动词、形容词和其它词前面表示否定或加在名词或名词性语素前面,构成形容词:不去。不多。不法。不料。不材(才能平庸,常用作自谦)。不刊(无须修改,不可磨灭)。不学无术。不速之客。
单用,做否定性的回答:不,我不知道。
用在句末表疑问:他现在身体好不?
**没有**
So, one meaning of `不` is `没有`, but it is not the most commonly used meaning of `不`. | 翼 = Wing
Yes, here, 不翼 = 无翼
It basically means something is gone in a weird way. For example, you could swear you left something at a certain place and you couldn't find it. You would use this phrase. |
14,683,963 | Each and every time I start Microsoft Office 2010 I get a Security Alert saying that there is a problem with the security certificate for `autodiscover.xxx.xxx`. I have followed the Certificate installation wizard to install the certificate on my machine, but even after a restart of the application I am still being prompted.
Do I have to restart the machine itself? I am using Windows 7.
 | 2013/02/04 | [
"https://Stackoverflow.com/questions/14683963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691505/"
] | Yes, the server certificate needs to be renewed. However, it also looks like that certificate does not have a *Subject Alternative Name* entry for autodiscover.yourdomain.com, which is the second problem shown in the screenshot.
The CAS server(s) should have at a minimum the OWA FQDN (e.g. webmail.yourdomain.com) and autodiscover (e.g. autodiscover.yourdomain.com). There are other considerations when setting up the cert request (such as load balancers, multiple datacenters, etc.)
You can use these as a references, or send to your Exchange administrator if you do not manage the infrastructure:
* <http://exchangeserverpro.com/configure-an-ssl-certificate-for-exchange-server-2010>
* <http://technet.microsoft.com/en-us/library/dd351044(v=exchg.141).aspx> | I encountered this problem and tried to resolve it by importing the valid unexpired self signed certificate into "Trusted Root Certification Authorities" from the Certificate Warning dialogue, but the certificate did not import even though it said "Import Successful". I successfully imported the certificate through "Internet Options/Content/Certificate/Trusted Root Certification Authorities", after which I no longer got the Certificate warning (Problem Solved). Perhaps this may solve your problem. |
5,283,770 | well I have 3 LinkButton
```
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit Record" OnClientClick='ControlVisible();'/>
<asp:LinkButton ID="lnkSave" runat="server" Text="Save" Visible="false" />
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" Visible="false" />
```
when I'll click to lnkEdit button lnkSave and lnkCancel buttons must unvisible
```
<script language="javascript" type="text/javascript">
function ControlVisible() {
var Edit = document.getElementById("lnkEdit");
var Save = document.getElementById("lnkSave");
var Cancel = document.getElementById("lnkCancel");
Edit.visible = false;
Save.visible = true;
Cancel.visible = true;
}
</script>
```
But when I'll cLick Edit **LinkButton** : var Edit = document.getElementById("lnkEdit"); here comes Null, can not retrive Control's ID
what the proble? | 2011/03/12 | [
"https://Stackoverflow.com/questions/5283770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/626157/"
] | ASP .NET automatically includes the IDs of the parent elements when generating an ID for an element. The generated HTML will have IDs following this kind of format: `ctl00$MainContent$txtSymbol`. So, the default DOM function `getElementById` won't find an element if you only use the last ID.
Source Element:
```
<asp:TextBox runat="server" ID="txtSymbol">
```
HTML generated:
```
<input type="text" id="ctl00_MainContent_txtSymbol" name="ctl00$MainContent$txtSymbol">
```
You can create a helper jQuery function which takes care of this. The next function created by [Rick Strahl](http://www.west-wind.com/weblog/posts/42319.aspx) does the job:
```
function $$(id, context) {
var el = $("#" + id, context);
if (el.length < 1) {
el = $("[id$=_" + id + "]", context);
}
return el;
}
```
You can use it like this to find your element:
```
$$("txtSymbol")
``` | If the controls are inside a container, the id of the container will be prepended to the if of the conbtrol to create a client id that is unique.
You can use the `ClientID` property to find out the generated id:
```
var Edit = document.getElementById("<%=lnkEdit.ClientId%>");
var Save = document.getElementById("<%=lnkSave.ClientId%>");
var Cancel = document.getElementById("<%=lnkCancel.ClientId%>");
``` |
22,881,934 | I'm trying to extract the file extension part in a string value.
For example, assuming the string value is "file.cpp", I need to extract the "cpp" or ".cpp" part.
I've tried using strtok() but it doesn't return what I am looking for. | 2014/04/05 | [
"https://Stackoverflow.com/questions/22881934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2357327/"
] | This will work, but you'll have to be sure to give it a valid string with a dot in it.
```
#include <iostream> // std::cout
#include <string> // std::string
std::string GetExtension (const std::string& str)
{
unsigned found = str.find_last_of(".");
return str.substr( found + 1 );
}
int main ()
{
std::string str1( "filename.cpp" );
std::string str2( "file.name.something.cpp" );
std::cout << GetExtension( str1 ) << "\n";
std::cout << GetExtension( str2 ) << "\n";
return 0;
}
``` | Here is a simple C implementation:
```
void GetFileExt(char* ext, char* filename)
{
int size = strlen(filename);
char* p = filename + size;
for(int i=size; i >= 0; i--)
{
if( *(--p) == '.' )
{
strcpy(ext, p+1);
break;
}
}
}
int main()
{
char ext[10];
char filename[] = "nome_del_file.txt";
GetFileExt(ext, filename);
}
```
You can use this as starting point. |
24,353,736 | I have this jquery
```
$(".waitingTime .button").click(function () {
alert("Ema");
});
```
I have a `a` tag like this:
```
<a href="{{ URL::to('restaurants/20') }}"></a>
```
Can I do the same `href` action in the jquery function?
Many Thanks | 2014/06/22 | [
"https://Stackoverflow.com/questions/24353736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3722029/"
] | yes this is possible and has nothing to do with Laravel.
There are different possibilities. If your query is embedded within the same laravel view, you put the URL directly in your jQuery code, for example like this:
```
$(".waitingTime .button").click(function () {
window.location.href = "{{URL::to('restaurants/20')}}"
});
```
But I think the best option is to add the URL on your button tag as a data attribute and then let jquery go to that URL. That way you can make your buttons more dynamic and have more capsulated code.
One example might be:
```
<div class="waitingTime">
<button class="button link-button" data-href="{{URL::to('restaurants/20')}}">
Click me
</button>
</div>
$(".link-button").click(function () {
window.location.href = $(this).data('href');
});
```
That way you can always give a button with the class `link-button` a `data-href` attribute with the URL you want to open when the button is clicked and don't have to add additional jquery. | Just output php in your javascript
```
$(".waitingTime .button").click(function () {
window.location.href = "<?php echo URL::to('restaurants/20'); ?>";
});
``` |
17,463,037 | I have an [MSI](http://en.wikipedia.org/wiki/Windows_Installer) file created with [WiX](http://en.wikipedia.org/wiki/WiX), that intalls my executables and copies a configuration file, that placed near the MSI file. I can change configuration file before installation and the changed version will be copied to installation folder.
```
<Component Id="ProductComponent"
Guid="714DCBE1-F792-401E-9DDC-67BC1853BE14">
....
<File Source="Chiffa.exe.config"
Compressed='no'/>
</Component>
```
That is what I want and I'm happy, but not satisfied, because I need to install some other packages along with this MSI file. So I created a bundle project with WiX and placed all my lovely MSI packages to its chain:
```
<Chain>
.....
<MsiPackage Compressed="yes"
SourceFile="$(var.ChiffaSetup.TargetPath)"
Vital="yes"
Visible="no">
<Payload SourceFile="Chiffa.exe.config"
Compressed="no"/>
</MsiPackage>
</Chain>
```
Everything is works fine except one little thing. I can't change the configuration file since bundle checks the consistency of an MSI package and fails with "the hash code" thing. | 2013/07/04 | [
"https://Stackoverflow.com/questions/17463037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356605/"
] | Ok. With the comments, we might go for something like that (assuming you have a navigation property in `EntityProperties` table, which is a collection of `PropertyValues`, and named `PropertyValueList` (if you don't have, just do a join instead of using `Include`).
Here is some sample code, really rustic, **working only with Int32 properties**, but this might be the start of a solution.
You may also look at [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx)...
Anyway
I use an "intermediate class" Filter.
```
public class Filter
{
public string PropertyName { get; set; }
public List<string> Values { get; set; }
}
```
Then an helper class, which will return an `IQueryable<T>`, but... filtered
```
public static class FilterHelper {
public static IQueryable<T> Filter(this IQueryable<T> queryable, Context context, int userId) {
var entityName = typeof(T).Name;
//get all filters for the current entity by userId, Select the needed values as a `List<Filter>()`
//this could be done out of this method and used as a parameter
var filters = context.EntityProperties
.Where(m => m.entityName == entityName && m.userId = userId)
.Include(m => m.PropertyValueList)
.Select(m => new Filter {
PropertyName = m.property,
Values = m.PropertyValueList.Select(x => x.value).ToList()
})
.ToList();
//build the expression
var parameter = Expression.Parameter(typeof(T), "m");
var member = GetContains( filters.First(), parameter);
member = filters.Skip(1).Aggregate(member, (current, filter) => Expression.And(current, GetContains(filter, parameter)));
//the final predicate
var lambda = Expression.Lambda<Func<T, bool>>(member, new[] { parameter });
//use Where with the final predicate on your Queryable
return queryable.Where(lambda);
}
//this will build the "Contains" part
private static Expression GetContains(Filter filter, Expression expression)
{
Expression member = expression;
member = Expression.Property(member, filter.PropertyName);
var values = filter.Values.Select(m => Convert.ToInt32(m));
var containsMethod = typeof(Enumerable).GetMethods().Single(
method => method.Name == "Contains"
&& method.IsGenericMethodDefinition
&& method.GetParameters().Length == 2)
.MakeGenericMethod(new[] { typeof(int) });
member = Expression.Call(containsMethod, Expression.Constant(values), member);
return member;
}
}
```
usage
```
var orders = from order in Context.Orders
select order;
var filteredOrders = orders.Filter(Context, 1);//where 1 is a userId
``` | My answer depends on whether you are happy to alter your access model slightly. I've got a similar situation in an application that I have written and personally I don't like the idea of having to rely on my calling code to correctly filter out the records based on the users authentication.
My approach was to use an OData service pattern to call into my Entity Framework, each of the repositories are exposed via OData independently.
An OData (WCFDataService) has QueryInterceptors which perform on the fly filtering of your data when a query is made. Thus if you asked the OData repository for context.Orders(o => o.Id) you'd only see the orders that that user was permitted to see with no additional clauses.
A good link to the basics is found [here](http://msdn.microsoft.com/en-us/library/dd744842.aspx) but it requires some work to manage the calling user and provide the filtering that you may require. You can provide the query interceptor at every record level. |
18,145,360 | This is a C program that i am trying to make print a list of ASCII characters. I could make the program print a range of numbers,
bit i cannot get it to print the ASCII value of each number in the list.
```
#include <stdio.h>
#define N 127
int main(void)
{
int n;
int c;
for (n=32; n<=N; n++) {
char c = atoi( n);
printf("%d", c);
}
return 0;
}
``` | 2013/08/09 | [
"https://Stackoverflow.com/questions/18145360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300216/"
] | Have a look at [`printf` formats](http://www.cplusplus.com/reference/cstdio/printf/).
Indeed, `%d` is used to print signed decimal integers. You want to print the corresponding character, so the format you are looking for is `%c`.
So it gives :
```
printf("%d", c);
``` | Final solution
==============
---
I tried to make it so compact (although not obfuscated) as possible.
--------------------------------------------------------------------
---
```
#include <stdio.h>
int main() {
// for loop // outputs |data type|
// for(int i='a';i<='z';putchar(i),i++); // a,b,c...x,y,z | char |
// for(int i='a';i<='z';printf("%c\n",i),i++); // a,b,c...x,y,z | char |
// for(int i='A';i<='Z';putchar(i),i++); // A,B,C...X,Y,Z | char |
for(int i='a';i<='z';printf("%d\n",i),i++); // 97,98,99..120,121,122 | ascii |
//for(int i='a';i<='z';printf("%x\n",i),i++); // 61,62,63 ,78,79,7a | hex |
//// for(int i='a';i<'z';printf("%d\n",i),F(i < 5),i++);
// for(int i='a';i<='z'; printf("%c\n",i),i++);
return 0;
}
``` |
240,571 | ### Task
A *reverse checkers* position is a chess position where every piece for one player is on one colour and every piece for the other player is on the other colour. Your task is to find if the given (valid) position meets these criteria.
For example, this position does (click for larger images). Every white piece is on a light square, while every black piece is on a dark square:
[](https://i.stack.imgur.com/F989p.jpg)
This position is also a reverse checkers position. Every white piece is on a dark square, while every black piece is on a light square:
[](https://i.stack.imgur.com/716Nb.jpg)
### Input
Your input will be a ***valid*** chess position. You choose whether it'll be a [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) (for the purpose of this challenge, we'll only consider the first field, [piece placement](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation#Definition)), or an 8x8 grid (with spaces or not between). If the latter, mention in your answer what characters you used to denote empty squares and the pieces.
---
The examples below will use upper-case letters for white pieces and lower-case for black. Empty squares are represented by dots (`.`).
1. The first position above:
```
5r1k/2p3b1/1p1p1r2/p2PpBp1/P1P3Pp/qP1Q1P1P/4R1K1/7R
. . . . . r . k
. . p . . . b .
. p . p . r . .
p . . P p B p .
P . P . . . P p
q P . Q . P . P
. . . . R . K .
. . . . . . . R
```
*is* a reverse checkers position.
2. The second position above:
```
r3r3/5pBk/p3nPp1/1p1pP2p/2pPb1p1/P1P1N1P1/1P3R1P/R5K1
r...r...
.....pBk
p...nPp.
.p.pP..p
..pPb.p.
P.P.N.P.
.P...R.P
R.....K.
```
is a reverse checkers position as well.
3. The starting position:
```
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
bbbbbbbb
bbbbbbbb
........
........
........
........
wwwwwwww
wwwwwwww
```
*is **not*** a reverse checkers position.
### Rules
* The chess position will *always* be valid.
* You may use two characters for the pieces, one for white pieces and one for black pieces (i.e. you don't have to use a different character for every piece).
* You can receive input through any of the standard IO methods.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! | 2022/01/04 | [
"https://codegolf.stackexchange.com/questions/240571",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/85914/"
] | [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
=========================================================
```
ŒJ§ḂṬƙFṀḊ
```
[Try it online!](https://tio.run/##y0rNyan8///oJK9Dyx/uaHq4c82xmW4PdzY83NH1/3D70UkPd87QjPz/P5orOtpIR8EAhhDsWB0uhWgDJCmIrCGQBEsZYYoj6TJCEoeqQTIQoR5JF0QlOgnTZYhkHVQWSZcBmmwsUA7oM0znYzoERRbD@Qg1qJ42xPA0ssMRamC6sHgOI4AxPY2JDKE@MwLbjI5gtuGSwmqkAW2kDMFeQUf4pGgaZ4bYEip944xynxnhTo0GA5wa0WyjXbqilxRyPjNE89yQ91ksAA "Jelly – Try It Online")
Takes input as an \$8 \times 8\$ matrix, with `0` being empty space, `1` being white and `2` being black. Outputs an empty list `[]` for truthy, and a non-empty list `[1]` for falsey.
Additionally, if we *really* want to stretch the output format, we can have this 8 byter
```
ŒJ§ḂṬƙFṀ
```
[Try it online!](https://tio.run/##y0rNyan8///oJK9Dyx/uaHq4c82xmW4Pdzb8P9x@dNLDnTM0I///j@aKjjbSUTCAIQQ7VodLIdoASQoiawgkwVJGmOJIuoyQxKFqkAxEqEfSBVGJTsJ0GSJZB5VF0mWAJhsLlAP6DNP5mA5BkcVwPkINqqcNMTyN7HCEGpguLJ7DCGBMT2MiQ6jPjMA2oyOYbbiksBppQBspQ7BX0BE@KZrGmSG2hErfOKPcZ0a4U6PBAKdGNNtol67oJYWczwzRPDfkfRYLAA "Jelly – Try It Online")
which outputs `[1]` for truthy, and `[1, 1]` for falsey.
How it works
------------
```
ŒJ§ḂṬƙFṀḊ - Main link. Takes a matrix M on the left
ŒJ - 8x8 grid of coordinates [x, y] between 1 and 8
§ - Sum of each coordinate
Ḃ - Bit
F - Flatten M
ƙ - Over the lists formed by grouping the flattened M by the bit of the coordinate:
Ṭ - Yield a boolean list, with 1s at the indices in the list
Ṁ - Maximum
Ḋ - Dequeue, remove the first element
``` | [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes
====================================================
```
a->sum(n=0,1,!matrix(8,,i,j,(i+j+n+t=a[i,j])%2*t))
```
[Try it online!](https://tio.run/##lY7BCsMgEER/xQYK2mzAeCosyY8ED15SDE2Q1EL79dZobDW3siw6M@I8o1bd3IwbSedU0z@eM106Di2cZmVX/aJXAA0TUF1P9VLbTg1eSnYWF8uYU8bc31SRpidm1Yv112oTFRmpYgzIMHBI026L6bafuPvJxZgJr0TIRVA8udhCcsIi/2Zh8dcXXOkZsrpQkSPFLzOVIcXahCwSJBYA4b3IIGKeYUWEYvCoS2r@txZQzFFLydwH "Pari/GP – Try It Online")
Takes input as an 8x8 matrix of `0`s (empty), `1`s (black), `2`s (white). |
35,784,936 | I'm trying to write a function that takes an input list and two integers as parameters, the function should then return a two-dimensional list with the rows and columns of the list being specified by the two input integers. e.g. if the input list is `[8, 2, 9, 4, 1, 6, 7, 8, 7, 10]` and the two integers are 2 and 3 then the function should return `[[8, 2, 9],[4, 1, 6]]`
```
def one_to_2D(some_list, r, c):
output = []
for a in range(0, r):
my_list = some_list[0:c]
some_list.reverse()
for k in range(0,r):
some_list.pop()
some_list.reverse()
output.append(my_list)
return output
some_list = [8, 2, 9, 4, 1, 6, 7, 8, 7, 10]
print(one_to_2D(some_list, 2, 3))
``` | 2016/03/03 | [
"https://Stackoverflow.com/questions/35784936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6009386/"
] | Here's a solution for you:
```
def one_to_2D(some_list, r, c):
return [[some_list[j] for j in range(c*i, c*(i+1))] for i in range(r)]
```
Examples:
```
In [3]: one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3)
Out[3]: [[8, 2, 9], [4, 1, 6]]
In [4]: one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 3, 3)
Out[4]: [[8, 2, 9], [4, 1, 6], [7, 8, 7]]
In [5]: one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 2)
Out[5]: [[8, 2], [9, 4]]
``` | ```
In [10]: reshaped = [some_list[i:i+c] for i in range(0,r*c, c)]
[[8, 2, 9], [4, 1, 6]]
``` |
54,520,304 | here what i am doing is i am creating a "Drag n Drop feature" using ng2 file upload and here my issue is when ever im trying to drop more than one file the select all function will be enabled and it will select all check boxes by default but that is not happening in my scenario after file drop
<https://stackblitz.com/edit/angular-r6cbrj>
```
<div class="container">
<div class="well well-lg metadata-well text-center add-file ">
<h4 style="float:left ">
<span *ngIf="uploader?.queue?.length> 1">
<input type="checkbox" id="selectAll" [(ngModel)]="selectAll" (change)="selectAllFiles($event)" class="form-check-input deltha">
</span>Add Files</h4>
<br />
<br />
</div>
<span *ngIf="uploader?.queue?.length== 0">
<p class="text-wrap">Your upload queue is empty.
<br />Drag and drop files to add them to the queue</p>
</span>
<span *ngIf="uploader?.queue?.length > 0">
<div class="upload-section">
<table class="table">
<tbody>
<tr *ngFor="let item of uploader.queue;let i = index">
<td style="padding-top: 0rem">
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" value="{{item?.file?.name}}" [checked]="fileSelectState[item?.file?.name]"
(change)="fileChecked($event)">
</label>
</div>
</td>
<td id="{{ item?.file?.name }}">
<a (click)="selectFile($event);">
<strong>{{ item?.file?.name }}</strong>
</a>
</td>
<td>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</td>
<td >{{ item?.file?.type}}</td>
<td>
<button type="button" class="icon-button" (click)="item.remove();fileRemoved(item)">
<i class="fas fa-times"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</span>
<div ng2FileDrop [ngClass]="{'nv-file-over': hasBaseDropZoneOver}" (fileOver)="fileOverBase($event)" (onFileDrop)="fileDropped($event)" [uploader]="uploader" class="well well-sm metadata-well-sm text-center my-drop-zone">
<img src={{imga}} />
<p>Drag and drop your files here</p>
</div>
</div>
``` | 2019/02/04 | [
"https://Stackoverflow.com/questions/54520304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10385262/"
] | This works in your StackBlitz:
See: <https://stackblitz.com/edit/angular-rtzkhd>
```
constructor(){
this.uploader.onAfterAddingAll = () => {
this.selectedFilesArray = [];
this.uploader.queue.forEach(fileItem => {
this.fileSelectState[fileItem.file.name] = true;
});
}
}
``` | ```
constructor(){
this.uploader.onAfterAddingAll = () => {
this.selectedFilesArray = [];
this.uploader.queue.forEach(fileItem => {
this.fileSelectState[fileItem.file.name] = true;
});
}
}
``` |
21,997,587 | This is my first work with web scraping. So far I am able to navigate and find the part of the HTML I want. I can print it as well. The problem is printing only the text, which will not work. I get following error, when trying it: `AttributeError: 'ResultSet' object has no attribute 'get_text'`
Here my code:
```
from bs4 import BeautifulSoup
import urllib
page = urllib.urlopen('some url')
soup = BeautifulSoup(page)
zeug = soup.find_all('div', attrs={'class': 'fm_linkeSpalte'}).get_text()
print zeug
``` | 2014/02/24 | [
"https://Stackoverflow.com/questions/21997587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2212634/"
] | `find_all()` returns an array of elements. You should go through all of them and select that one you are need. And than call `get_text()`
**UPD**
For example:
```
for el in soup.find_all('div', attrs={'class': 'fm_linkeSpalte'}):
print el.get_text()
```
But note that you may have more than one element. | Try `for` inside the list for getting the data, like this:
```
zeug = [x.get_text() for x in soup.find_all('div', attrs={'class': 'fm_linkeSpalte'})]
``` |
60,970,479 | I think I have my head wrapped around the Javascript callback functions when it comes to one on one, i.e.
```
funcA // generates some params needed for funcB
funcB
```
Can be implemented as
```
function funcA (Aparams callback) {
//some processing using Aparams to generate params
callback(params)
}
function funcB (Bparams) {
//waiting for Bparams
//some processing
}
//main program
funcA(something,funcB)
```
But what is the best way to implement...
```
funcA // generates some params needed for funcB AND funcC?
funcB
funcC
```
Assume same params can be used for both B and C.
I thought about chaining them, but I kinda got lost in the syntax. I don't want to run funcA twice, once with B and once with C, which would be the brute force method. | 2020/04/01 | [
"https://Stackoverflow.com/questions/60970479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9543847/"
] | You seem to be looking for
```
funcA(something, function(aResults) {
funcB(aResults);
funcC(aResults);
});
``` | Do you really need a callback to achieve it. you can use.
```
let A_res = funcA(param);
funcB(A_res);
funcC(A_res);
// This is suitable in All when there is no async Process in funcA...
```
Now definitely in case of async process in funcA you need a call back...
```
function funcA(param){
// processing...
let Temp_A_res = processed_result;
return function (callBack){
callBack(Temp_A_res);
}
}
let A_res = funcA();// A_res will be a function which take further call back...
A_res(funcB);
A_res(funcC);
```
This all that I have shown is easily done by promises Please Read them too.. |
42,854 | Will the voice dictation technology built into iOS 5.1 running on the new iPad be made available on the iPad 2? | 2012/03/07 | [
"https://apple.stackexchange.com/questions/42854",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/7961/"
] | It's too bad Apple decided not to include this technology in the iPad 2. I'm dictating this response on Dragon and works just fine. The iPad 2 has ample horsepower to support dictation.
It's unfortunate that many perceive the dictation function was excluded for obvious marketing reasons, but the iPhone 4S features advanced noise cancelling and voice clarification hardware not present in the iPad 2. | Maybe it needs to be enabled in settings? See here:
<http://9to5mac.com/2012/01/09/looks-like-apple-is-working-on-siri-dictation-for-the-ipad-ios-5-1-beta-reveals/> |
40,762,688 | could anyone help me with following problem:
I have a tab delimited file that doesn’t have the same number of columns in every row. I need to divide the value in first column subsequently by the values in all other columns. As a result I would like to get the final number to a new file.
example\_file.txt
>
>
> ```
> 0.0002 0.2 0.2 0.6
> 0.03 0.3 0.7
> 0.004 0.1 0.2 0.005 0.3 0.005
>
> ```
>
>
I filled all empty rows with 1, to avoid problem with division by 0:
```
awk '{for(i=NF+1;i<=6;i++)$i="1"}1' < example_file.txt > example_file_filled.txt
```
example\_file\_filled.txt
>
>
> ```
> 0.002 0.2 0.2 0.6 1 1
> 0.03 0.3 0.7 1 1 1
> 0.004 0.1 0.2 0.005 0.3 0.005
>
> ```
>
>
Expected output:
output.txt
>
>
> ```
> 0.083
> 0.14
> 26666.66
>
> ```
>
>
I know that I can:
- either divide the first column by second column, then take this value and divide by third column etc.
- or multiply all columns from second column till the last one and use this value to divide the first column
For the first possibility I was trying to use:
```
awk '{$1=$1/$2; $2=""; print $0 }' example_file_filled.txt
```
This divides the first row by the second one and prints as output the result followed by the numbers that were not yet used for division. I tried to loop over it to get it done until there is no second row, but I didn’t manage.
Could anyone suggest a solution? My real file has >100 of columns. I am mostly using bash / unix, but I will be happy to learn also from other approaches.
Thanks in advance! | 2016/11/23 | [
"https://Stackoverflow.com/questions/40762688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7199260/"
] | Use a loop to go through the other columns, then divide:
```
awk '{ val = 1; for (i = 2; i <= NF; ++i) val *= $i; print $1 / val }' file
```
Or just do successive divisions, again with a loop:
```
awk '{ for (i = 2; i <= NF; ++i) $1 /= $i; print $1 }' file
```
It's up to you how you want to treat the presence of a `0` in any column - you can add an `if` before performing the division if you like. | With `perl`
```
$ cat ip.txt
0.002 0.2 0.2 0.6
0.03 0.3 0.7
0.004 0.1 0.2 0.005 0.3 0.005
$ perl -lane '$a=$F[0]; $a /= $_ foreach (@F[1..$#F]); print $a' ip.txt
0.0833333333333333
0.142857142857143
26666.6666666667
```
Limiting decimal points:
```
$ perl -lane '$a=$F[0]; $a /= $_ foreach (@F[1..$#F]); printf "%.3f\n", $a' ip.txt
0.083
0.143
26666.667
```
See [Perl flags -pe, -pi, -p, -w, -d, -i, -t?](https://stackoverflow.com/questions/6302025/perl-flags-pe-pi-p-w-d-i-t) for explanation on `perl` command line options |
17,737,840 | I'm trying to edit my gridview header title however, unfortunately it doesn't work
```
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source = localhost; Initial Catalog = project; Integrated Security= SSPI";
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("SELECT policeid, password, email, nric, fullname, contact, address, location From LoginRegisterPolice where pending='pending'", conn);
da.Fill(ds);
GVVerify.DataSource = ds;
GVVerify.DataBind();
GVVerify.Columns[1].HeaderText = "Police ID ";
GVVerify.Columns[2].HeaderText = "Password";
GVVerify.Columns[3].HeaderText = "Email ";
GVVerify.Columns[4].HeaderText = "NRIC ";
GVVerify.Columns[5].HeaderText = "Full Name ";
GVVerify.Columns[6].HeaderText = "Contact ";
GVVerify.Columns[7].HeaderText = "Address ";
GVVerify.Columns[8].HeaderText = "Location ";
conn.Close();
```
This is the error i received
>
> Index was out of range. Must be non-negative and less than the size of
> the collection.
>
>
>
I have checked that my column index is not negative and it's the correct column number as well. I have added `allowgenerateselectbutton` in my gridview. Therefore, i started it with 1-8 instead of 0. | 2013/07/19 | [
"https://Stackoverflow.com/questions/17737840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2316009/"
] | You can do it by simply using column alias in your select SQL, no need to do it from code.
```
SELECT policeid as [Police ID] , password as [Password] ...............
``` | The columns property is a zero based array. Unless there is a hidden first column you are starting at 1. Re-number the indices to 0-7 instead of 1-8.
<http://msdn.microsoft.com/en-US/library/system.windows.forms.datagridview.columns(v=vs.80).aspx>
```
GVVerify.Columns[0].HeaderText = "Police ID ";
GVVerify.Columns[1].HeaderText = "Password";
GVVerify.Columns[2].HeaderText = "Email ";
GVVerify.Columns[3].HeaderText = "NRIC ";
GVVerify.Columns[4].HeaderText = "Full Name ";
GVVerify.Columns[5].HeaderText = "Contact ";
GVVerify.Columns[6].HeaderText = "Address ";
GVVerify.Columns[7].HeaderText = "Location ";
``` |
39,246,308 | I'm trying to automate the process of installing some Android SDK tools through a Gradle script.
The idea is to run this build.gradle script within a Docker machine which will prepare the environment before issuing the main build itself.
The problem I'm having is with automatically accepting the licenses for the relevant packages i'm installing.
Following [this SO question](https://stackoverflow.com/questions/4681697/is-there-a-way-to-automate-the-android-sdk-installation/4682241#4682241), I'm trying to use this method:
```
echo "y" | android update sdk -u -a -t 2,4,56,57,58
```
If I run it in terminal it works for up to 6 packages in one command but if I want to install more packages than that, for example:
```
echo "y" | android update sdk -u -a -t 2,6,7,4,30,153,160,161,167,54,53,63,56,57,58,59
```
Then the command fails:
```
Do you accept the license 'intel-android-extra-license-3626590a' [y/n]:
Unknown response ''.
Do you accept the license 'intel-android-extra-license-3626590a' [y/n]:
Unknown response ''.
Max number of retries exceeded. Rejecting 'intel-android-extra-license-3626590a'
Package Android TV Intel x86 Atom System Image, Android API 24, revision 6 not installed due to rejected license 'android-sdk-preview-license-d099d938'.
Package Android Wear ARM EABI v7a System Image, Android API 24, revision 1 not installed due to rejected license 'android-sdk-preview-license-d099d938'.
Package ARM 64 v8a System Image, Android API 24, revision 6 not installed due to rejected license 'android-sdk-preview-license-d099d938'.
```
More than that, I need Gradle to run it for me and when I do so, it seems like the output of the first echo (echo "y") is not redirected to the pipe for some reason.
So when I run the relevant Gradle task:
```
12:46:01.178 [DEBUG] [org.gradle.process.internal.DefaultExecHandle] Changing state to: STARTING
12:46:01.179 [DEBUG] [org.gradle.process.internal.DefaultExecHandle] Waiting until process started: command '/bin/echo'.
12:46:01.183 [DEBUG] [org.gradle.process.internal.DefaultExecHandle] Changing state to: STARTED
12:46:01.183 [DEBUG] [org.gradle.process.internal.ExecHandleRunner] waiting until streams are handled...
12:46:01.183 [INFO] [org.gradle.process.internal.DefaultExecHandle] Successfully started process 'command '/bin/echo''
12:46:01.184 [QUIET] [system.out] y | /usr/local/bin/android update sdk -u -a -t 2,6,7,4,30,153,160,161,167,54,53,63,56,57,58,59
12:46:01.184 [DEBUG] [org.gradle.process.internal.DefaultExecHandle] Changing state to: SUCCEEDED
12:46:01.185 [DEBUG] [org.gradle.process.internal.DefaultExecHandle] Process 'command '/bin/echo'' finished with exit value 0 (state: SUCCEEDED)
12:46:01.185 [DEBUG] [org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter] Finished executing task ':installSdkBuildTools'
12:46:01.185 [INFO] [org.gradle.execution.taskgraph.AbstractTaskPlanExecutor] :installSdkBuildTools (Thread[main,5,main]) completed. Took 0.023 secs.
12:46:01.185 [DEBUG] [org.gradle.execution.taskgraph.AbstractTaskPlanExecutor] Task worker [Thread[main,5,main]] finished, busy: 0.023 secs, idle: 0.001 secs
12:46:01.185 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskGraphExecuter] Timing: Executing the DAG took 0.044 secs
12:46:01.185 [LIFECYCLE] [org.gradle.BuildResultLogger]
12:46:01.186 [LIFECYCLE] [org.gradle.BuildResultLogger] BUILD SUCCESSFUL
```
The echo command ends successfully with exit status 0 but the packages are not being installed.
I've tried breaking the command to 3 mini commands which will install 6 packages each time but then the `echo "y" | android...` command is not interpreted correctly as mentioned above.
The relevant Gradle task looks like so:
```
task installSdkBuildToolsPart2(type: Exec) {
commandLine '/bin/echo', "y", '|', '/usr/local/bin/android ', 'update ', 'sdk ', '-u -a -t 160,161,167,54,53'
}
```
And I've also tried like that but to no avail:
```
task installSdkBuildToolsPart1(type: Exec) {
commandLine 'bash', '-c'," '/bin/echo', "y", '|', '/usr/local/bin/android ', 'update ', 'sdk ', '-u -a -t 2,6,7,4,30,153'"
}
```
**This is a Gradle question... how should I write the `commandLine` directive in the build.gradle file correctly so that the command is interpreted correctly and the packages are installed and licenses are accepted?**
Anyone knows how to overcome this issue?
Thanks in advance, | 2016/08/31 | [
"https://Stackoverflow.com/questions/39246308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1702942/"
] | Your problem is that the exec task in Gradle does not know about pipes, so what you have written is simply passing a number of strings to echo; the "y", the pipe "|", the android path, the update command, etc.
One way to do this is to put the command you want to execute that contains pipes or other shell redirections characters into a shell script file, and then have the Gradle task exec that shell script. | We have this command, which works perfectly for us:
```
( sleep 5 && while [ 1 ]; do sleep 1; echo y; done ) \
| android update sdk --all -u -t
``` |
14,504,423 | I am reading the Modern C++ Design by Andrei, where it is mentioned that
```
"Pointers to allocated objects does not have a value semantics"
```
For Value semantic example, it is mentioned that 'int' is perfect.
so
```
int x = 200, y;
y = x;
```
**My Question?**
1) What is the parameter to be considered so that i can claim that is a 'value semantic'.?
2) Why Pointers to Objects does not claimed to be 'value Semantic'.
**what I understood?**
If you can not copy the variable to another variable which is totally detacted from the original, then that is the 'value semantics'.
Kindly correct me if my understanding is wrong?, and also provide few simple examples. | 2013/01/24 | [
"https://Stackoverflow.com/questions/14504423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/916439/"
] | The phrase "value semantics" is widely used, but generally rather loosely defined. I think Scott Meyers had about as good of a definition as any: "do as the ints do."
In other words, an object with value semantics is one that you can treat pretty much like an int, and if you do so, it generally won't do anything surprising. Copying, assignment, applicable operators, etc., all "just work". Each "thing" you create is independent of any others, so (for example) `x + y` won't change `x` as if you'd used `x += y` (which a (completely un-)fair number of string classes have done, for one example). | SEE [Value-semantics here](http://www.parashift.com/c++-faq/val-vs-ref-semantics.html).
In other words, a pointer (or reference) to an object is not a new unique object, but the pointer refers to the original object you made it point to. So as such, you will have to be careful with pointers, so you make sure you know what you are pointing at and what that will change if you modify something the pointer is pointing at.
Conversely, we couldn't live completely with "value semantics" all the time (in C at least), because you couldn't write a function that modifies the content of a passed in value - which can be handy at times... |
112,387 | Having screwwed up my permissions by trying to have two users accessing one home folder I'm now going through the process of reseting my main user home permissions via the OSX install disk utilities, which seems to be taking a while.
Does this process take a while to do, though I assume it depends on how many files I have in the folder, which in my case is a good few 100 GBs.
At what point should I be concerned that it may have got stuck and thus reset my computer and try again?
I assume, though not sure that if the little circle indicator is still moving then it's not completely frozen, but as there's no progress bar or details I'm not sure how true that is. | 2010/02/23 | [
"https://superuser.com/questions/112387",
"https://superuser.com",
"https://superuser.com/users/18636/"
] | Depends on how many files you have. If you have a ton of smaller files in your profile folder (bits of source code, multi-part archives) it'll take quite awhile. If you're a normal user, it shouldn't take too long at all. Maybe 15 minutes, at the most. | Am I missing something here, or would `sudo chown [your username] ~/` from your home folder do the job? |
37,719,823 | We are attempting to modify the default Woocommerce Checkout Shipping City Field using the documented methods on [docs.woothemes](https://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/) but have run into an issue.
We have replaced the `shipping_city` text field with a `select` dropdown menu.
On page load the `select` dropdown menu is replaced with the default text field and if available is autofilled with the users previous delivery destination.
However, if the page is reloaded/refreshed the text field is then replaced with the new and much desired `select` dropdown menu.
We have filtered the field using several WordPress `add_filter` functions and changed `priority` both up and down (-999 to 999).
We have run the `filter` both inside and outside of our Shipping Method `Class`
We have even disabled the browser auto form complete because we… well ran out of other ideas…
When the `select` field is working… it works well. The Shipping costs get updated, data gets returned, stored and emailed.
The `filters` used are:
`add_filter( 'woocommerce_checkout_fields', array( $this, 'fn_name' ) );`
`add_filter( 'woocommerce_default_address_fields', array( $this, 'fn_name' ) );`
and the `$field` array looks like:
```
$fields[ 'shipping' ][ 'shipping_city' ] = array(
'label' => __( 'Suburb/City', 'woocommerce' ),
'required' => FALSE,
'clear' => TRUE,
'type' => 'select',
'options' => $options_array,
'class' => array( 'update_totals_on_change' )
);
return $fields;
```
Oddly, when we ran two filters on the same field; the label of the sendond was overwritten by the first… go figure… Gee I wish I knew Ajax… i think its Ajax but then if I knew AJAX I'd know if it was Ajax…
WordPress Version 4.5.2 && WooCommerce Version 2.5.5
***Addendum regarding final accepted solution:***
The code suggested and supplied by @LoicTheAztec worked very well and has been included in our implementation.
However, the issue was caused by our original inclusion of the $field filter inside of our Shipping Method Class which is hooked into the shipping\_class\_init
To correct the issue we have moved the new woocommerce\_form\_field\_args filter into a seperate file and retrieved our options array after the new Shipping Method Class has worked its magic. | 2016/06/09 | [
"https://Stackoverflow.com/questions/37719823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1747169/"
] | This should work with `woocommerce_form_field_args` hook, this way:
```
add_filter( 'woocommerce_form_field_args', 'custom_form_field_args', 10, 3 );
function custom_form_field_args( $args, $key, $value ) {
if ( $args['id'] == 'billing_city' ) {
$args = array(
'label' => __( 'Suburb/City', 'woocommerce' ),
'required' => FALSE,
'clear' => TRUE,
'type' => 'select',
'options' => $options_array,
'class' => array( 'update_totals_on_change' )
);
} // elseif … and go on
return $args;
};
```
This are he default `$args` parameter values:
```
$defaults = array(
'type' => 'text',
'label' => '',
'description' => '',
'placeholder' => '',
'maxlength' => false,
'required' => false,
'autocomplete' => false,
'id' => $key,
'class' => array(),
'label_class' => array(),
'input_class' => array(),
'return' => false,
'options' => array(),
'custom_attributes' => array(),
'validate' => array(),
'default' => '',
);
```
References:
* [Customizing placehorlder in billing/shipping forms](https://stackoverflow.com/questions/37601551/customizing-placehorlder-in-billing-shipping-forms/37603801#37603801)
* [Add custom css class to WooCommerce checkout fields](https://stackoverflow.com/questions/23943791/add-custom-css-class-to-woocommerce-checkout-fields/36724593#36724593) | Put this code into your child theme function.php and should do the job
```
$city_args = wp_parse_args( array(
'type' => 'select',
'options' => array(
'city1' => 'Amsterdam',
'city2' => 'Rotterdam',
'city3' => 'Den Haag',
),
), $fields['shipping']['shipping_city'] );
$fields['shipping']['shipping_city'] = $city_args;
$fields['billing']['billing_city'] = $city_args; // Also change for billing field
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'jeroen_sormani_change_city_to_dropdown' );
``` |
538,711 | I have a point class like:
```
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
```
and a list of points:
```
std::list <Point> pointList;
std::list <Point>::iterator iter;
```
I'm pushing points on to my pointList (although the list might contain no Points yet if none have been pushed yet).
I have two questions:
**How can I delete the closest point to some arbitrary (x, y) from the list?**
Lets say I have the x,y (5,12) and I want to find the Point in the list closest to that point and remove it from the STD::List.
I know I'll have to use the distance formula and I'll have to iterate through the list using an iterator but I'm having some trouble conceptualizing how I'll keep track of which point is the closest as I iterate through the list.
**How can I return an array or list of points within x radius of a given (x,y)?**
Similar to the last question except I need a list of pointers to the "Point" objects within say 5 radius of a given (x,y). Also, should I return an array or a List?
If anyone can help me out, I'm still struggling my way through C++ and I appreciate it. | 2009/02/11 | [
"https://Stackoverflow.com/questions/538711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64878/"
] | Use a std::list::iterator variable to keep track of the closest point as you loop through the list. When you get to the end of the list it will contain the closest point and can be used to erase the item.
```
void erase_closest_point(const list<Point>& pointList, const Point& point)
{
if (!pointList.empty())
{
list<Point>::iterator closestPoint = pointList.begin();
float closestDistance = sqrt(pow(point.x - closestPoint->x, 2) +
pow(point.y - closestPoint->y, 2));
// for each point in the list
for (list<Point>::iterator it = closestPoint + 1;
it != pointList.end(); ++it)
{
const float distance = sqrt(pow(point.x - it->x, 2) +
pow(point.y - it->y, 2));
// is the point closer than the previous best?
if (distance < closestDistance)
{
// replace it as the new best
closestPoint = it;
closestDistance = distance
}
}
pointList.erase(closestPoint);
}
}
```
Building a list of points within a radius of a given point is similar. Note that an empty radius list is passed into the function by reference. Adding the points to the list by reference will eliminate the need for copying all of the points when returning the vector by value.
```
void find_points_within_radius(vector<Point>& radiusListOutput,
const list<Point>& pointList,
const Point& center, float radius)
{
// for each point in the list
for (list<Point>::iterator it = pointList.begin();
it != pointList.end(); ++it)
{
const float distance = sqrt(pow(center.x - it->x, 2) +
pow(center.y - it->y, 2));
// if the distance from the point is within the radius
if (distance > radius)
{
// add the point to the new list
radiusListOutput.push_back(*it);
}
}
}
```
Again using copy if:
```
struct RadiusChecker {
RadiusChecker(const Point& center, float radius)
: center_(center), radius_(radius) {}
bool operator()(const Point& p)
{
const float distance = sqrt(pow(center_.x - p.x, 2) +
pow(center_.y - p.y, 2));
return distance < radius_;
}
private:
const Point& center_;
float radius_;
};
void find_points_within_radius(vector<Point>& radiusListOutput,
const list<Point>& pointList,
const Point& center, float radius)
{
radiusListOutput.reserve(pointList.size());
remove_copy_if(pointList.begin(), pointList.end(),
radiusListOutput.begin(),
RadiusChecker(center, radius));
}
```
*Note that the **sqrt** can be removed if you need extra performance since the square of the magnitude works just as well for these comparisons. Also, if you really want to increase performance than consider a data structure that allows for scene partitioning like a [quadtree](http://en.wikipedia.org/wiki/Quadtree). The first problem is closely related to [collision detection](http://en.wikipedia.org/wiki/Collision_detection) and there is a ton of valuable information about that topic available.* | You can do this using a combination of the STL and [Boost.Iterators](http://www.boost.org/doc/libs/1_38_0/libs/iterator/doc/index.html) and [Boost.Bind](http://www.boost.org/doc/libs/1_38_0/libs/bind/bind.html) -- I'm pasting the whole source of the solution to your problem here for your convenience:
```
#include <list>
#include <cmath>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/bind.hpp>
#include <cassert>
using namespace std;
using namespace boost;
struct Point {
int x, y;
Point() : x(0), y(0) {}
Point(int x1, int y1) : x(x1), y(y1) {}
Point(Point const & other) : x(other.x), y(other.y) {}
Point & operator=(Point rhs) { rhs.swap(*this); return *this; }
void swap(Point & other) { std::swap(other.x, x); std::swap(other.y, y); }
};
double point_distance(Point const & first, Point const & second) {
double x1 = first.x;
double x2 = second.x;
double y1 = first.y;
double y2 = second.y;
return sqrt( ((x2 - x1) * (x2 -x1)) + ((y2 - y1) * (y2 - y1)) );
}
int main(int argc, char * argv[]) {
list<Point> points;
points.push_back(Point(1, 1));
points.push_back(Point(2, 2));
points.push_back(Point(3, 3));
Point source(0, 0);
list<Point>::const_iterator closest =
min_element(
make_transform_iterator(
points.begin(),
bind(point_distance, source, _1)
),
make_transform_iterator(
points.end(),
bind(point_distance, source, _1)
)
).base();
assert(closest == points.begin());
return 0;
}
```
The meat of the solution is to transform each element in the list using the transform iterator using the `point_distance` function and then get the minimum distance from all the distances. You can do this while traversing the list, and in the end reach into the `transform_iterator` to get the base iterator (using the `base()` member function).
Now that you have that iterator, you can replace the `assert(closest == points.begin())` with `points.erase(closest)`. |
65,415 | This is something I don't understand. Are they trying to hide their identities? How many turtles are there that can stand on their feet? Is it because they are ninjas? Again the shell is a big give away. | 2014/08/11 | [
"https://scifi.stackexchange.com/questions/65415",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/31522/"
] | The only answer I can give is an out of universe one (I'd love someone to answer in-universe!).
The turtles are colour coded:
* Leonardo - Blue
* Donatello - Purple
* Michelangelo - Orange
* Raphael - Red
In the original comics the characters had no voices (clearly) so their weapons were the only other way to distinguish between the characters, which is no use if they're not fighting or are disarmed. So the original comic book authors needed some clothing.
What's the distinctive clothing of a ninja? | Ninjas wear masks!
Like in the movie *3 ninjas*, they wore masks. Its also so we can identify them. |
1,371,261 | How could I retrieve the current working directory/folder name in a bash script, or even better, just a terminal command.
`pwd` gives the full path of the current working directory, e.g. `/opt/local/bin` but I only want `bin`. | 2009/09/03 | [
"https://Stackoverflow.com/questions/1371261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86024/"
] | Surprisingly, no one mentioned this alternative that uses only built-in bash commands:
```
i="$IFS";IFS='/';set -f;p=($PWD);set +f;IFS="$i";echo "${p[-1]}"
```
As an **added bonus** you can easily obtain the name of the parent directory with:
```
[ "${#p[@]}" -gt 1 ] && echo "${p[-2]}"
```
These will work on Bash 4.3-alpha or newer. | Just remove any character until a `/` (or `\`, if you're on Windows). As the match is gonna be made greedy it will remove everything until the last `/`:
```
pwd | sed 's/.*\///g'
```
In your case the result is as expected:
```
λ a='/opt/local/bin'
λ echo $a | sed 's/.*\///g'
bin
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.