qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
6,181,706 | I'm looking for some OLAP data preferably in star schema (or snowflake) for testing a new tool. I've already got the Foodmart database that Mondrian provides. Type of data is not important as long as it has dimensions and associated facts. The larger the size the better for load testing. Anybody knows where I can download such a dataset, ideally in SQL or CSV? (other formats are fine too) | 2011/05/30 | [
"https://Stackoverflow.com/questions/6181706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Apologies for being MS SQL focussed, but the [Adventure Works DWH](http://technet.microsoft.com/en-us/library/ms124623.aspx) is not bad as far as an snowflake schema design. Not not huge as far as data volumes. With some clever SQL you would be able to generate extra rows in the database.
Alternatively try [Project Real](http://technet.microsoft.com/en-us/library/cc966416.aspx) - a larger DWH project that put together by MS on 2005 | This article give a pretty clear description of a Star Schema:-
[IBM (nee Informix) red brick warehouse](http://publib.boulder.ibm.com/infocenter/rbhelp/v6r3/index.jsp?topic=/com.ibm.redbrick.doc6.3/wag/wag35.htm) |
25,148,782 | If I fetch the following object from the server via Ajax:
```
$.get('/product/10', function (response) {
product = response;
// product:
// {
// name: "Product X",
// stock: 20
// }
});
```
And then output it to HTML using an Underscore.js template like this:
```
<input type="number" value="<%- product.name %>">
<input type="number" value="<%= product.stock %>">
```
Is there any reason to also escape the `stock` attribute if I know it will always come as an integer from the server?
I can't think of a way to exploit it so I was wondering if an "escape all the things" is a good policy or if an "escape only what you need" is a better one. | 2014/08/05 | [
"https://Stackoverflow.com/questions/25148782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2792897/"
] | You don't need to escape integers obviously. It may be in a good habit to escape everything in general and to print the raw versions of what you intend to. However you can also say you should trust what comes from the server- not what comes from the client. In the end it only matters what you want to get in the habit of. Personally I wouldn't think to escape it (because it doesn't need to be escaped) so I wouldn't escape it. | If the input is of type `number` then you're guaranteed to get a number or nothing in that input.
As a test, try adding the string `drop database` to an input of type number. **Spoiler Alert**: The input will stay empty.
Inputs of type `text` can be more dangerous. |
25,148,782 | If I fetch the following object from the server via Ajax:
```
$.get('/product/10', function (response) {
product = response;
// product:
// {
// name: "Product X",
// stock: 20
// }
});
```
And then output it to HTML using an Underscore.js template like this:
```
<input type="number" value="<%- product.name %>">
<input type="number" value="<%= product.stock %>">
```
Is there any reason to also escape the `stock` attribute if I know it will always come as an integer from the server?
I can't think of a way to exploit it so I was wondering if an "escape all the things" is a good policy or if an "escape only what you need" is a better one. | 2014/08/05 | [
"https://Stackoverflow.com/questions/25148782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2792897/"
] | If you want to be completely on the safe side, escape everything. Code may change and you may decide to use a string where you previously used a number. If you escape everything, you won't have a problem.
However, that is just being cautious. If you can guarantee that it will always be a number, even when the AJAX request fails, and in all edge cases, then it's OK not to escape it. Note that everywhere I've worked, the consensus was play it safe. | You don't need to escape integers obviously. It may be in a good habit to escape everything in general and to print the raw versions of what you intend to. However you can also say you should trust what comes from the server- not what comes from the client. In the end it only matters what you want to get in the habit of. Personally I wouldn't think to escape it (because it doesn't need to be escaped) so I wouldn't escape it. |
25,148,782 | If I fetch the following object from the server via Ajax:
```
$.get('/product/10', function (response) {
product = response;
// product:
// {
// name: "Product X",
// stock: 20
// }
});
```
And then output it to HTML using an Underscore.js template like this:
```
<input type="number" value="<%- product.name %>">
<input type="number" value="<%= product.stock %>">
```
Is there any reason to also escape the `stock` attribute if I know it will always come as an integer from the server?
I can't think of a way to exploit it so I was wondering if an "escape all the things" is a good policy or if an "escape only what you need" is a better one. | 2014/08/05 | [
"https://Stackoverflow.com/questions/25148782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2792897/"
] | If you want to be completely on the safe side, escape everything. Code may change and you may decide to use a string where you previously used a number. If you escape everything, you won't have a problem.
However, that is just being cautious. If you can guarantee that it will always be a number, even when the AJAX request fails, and in all edge cases, then it's OK not to escape it. Note that everywhere I've worked, the consensus was play it safe. | If the input is of type `number` then you're guaranteed to get a number or nothing in that input.
As a test, try adding the string `drop database` to an input of type number. **Spoiler Alert**: The input will stay empty.
Inputs of type `text` can be more dangerous. |
25,148,782 | If I fetch the following object from the server via Ajax:
```
$.get('/product/10', function (response) {
product = response;
// product:
// {
// name: "Product X",
// stock: 20
// }
});
```
And then output it to HTML using an Underscore.js template like this:
```
<input type="number" value="<%- product.name %>">
<input type="number" value="<%= product.stock %>">
```
Is there any reason to also escape the `stock` attribute if I know it will always come as an integer from the server?
I can't think of a way to exploit it so I was wondering if an "escape all the things" is a good policy or if an "escape only what you need" is a better one. | 2014/08/05 | [
"https://Stackoverflow.com/questions/25148782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2792897/"
] | JavaScript is dynamically typed, so there is no way to ensure that `product.stock` is really a number by the time it gets to the template. Any code written in the future using the template (possibly written by someone else) could pass any value for `product`, so `stock` could be of any type.
Best to always escape, except in the rare case when you expect the value to actually be HTML, in which case you cannot escape, so that future changes to the code are less likely to break the template. | If the input is of type `number` then you're guaranteed to get a number or nothing in that input.
As a test, try adding the string `drop database` to an input of type number. **Spoiler Alert**: The input will stay empty.
Inputs of type `text` can be more dangerous. |
25,148,782 | If I fetch the following object from the server via Ajax:
```
$.get('/product/10', function (response) {
product = response;
// product:
// {
// name: "Product X",
// stock: 20
// }
});
```
And then output it to HTML using an Underscore.js template like this:
```
<input type="number" value="<%- product.name %>">
<input type="number" value="<%= product.stock %>">
```
Is there any reason to also escape the `stock` attribute if I know it will always come as an integer from the server?
I can't think of a way to exploit it so I was wondering if an "escape all the things" is a good policy or if an "escape only what you need" is a better one. | 2014/08/05 | [
"https://Stackoverflow.com/questions/25148782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2792897/"
] | If you want to be completely on the safe side, escape everything. Code may change and you may decide to use a string where you previously used a number. If you escape everything, you won't have a problem.
However, that is just being cautious. If you can guarantee that it will always be a number, even when the AJAX request fails, and in all edge cases, then it's OK not to escape it. Note that everywhere I've worked, the consensus was play it safe. | JavaScript is dynamically typed, so there is no way to ensure that `product.stock` is really a number by the time it gets to the template. Any code written in the future using the template (possibly written by someone else) could pass any value for `product`, so `stock` could be of any type.
Best to always escape, except in the rare case when you expect the value to actually be HTML, in which case you cannot escape, so that future changes to the code are less likely to break the template. |
26,623,807 | minimal number of privileged instructions?
Say we want to write a OS with minimal number of privileged instruction.
I think it should be 1, only MMU register. But what about other things? i.e mode bit, trap | 2014/10/29 | [
"https://Stackoverflow.com/questions/26623807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4163332/"
] | It's a typo it should be:
```
var currentLight = document.getElementById('light'); //Not ID
``` | It should be `Id` not `ID`:
```
document.getElementById('light');
```
Also note that you don't have element with id `light` on your page. It probably should be
```
document.getElementById('pumpkin');
``` |
26,623,807 | minimal number of privileged instructions?
Say we want to write a OS with minimal number of privileged instruction.
I think it should be 1, only MMU register. But what about other things? i.e mode bit, trap | 2014/10/29 | [
"https://Stackoverflow.com/questions/26623807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4163332/"
] | Incorrect capitalisation on
```
var currentLight = document.getElementByID('light')
```
Should be:
```
var currentLight = document.getElementById('pumpkin')
```
I have attached a working fiddle:
<http://jsfiddle.net/11csf4k2/> | It should be `Id` not `ID`:
```
document.getElementById('light');
```
Also note that you don't have element with id `light` on your page. It probably should be
```
document.getElementById('pumpkin');
``` |
159,252 | I have set up a network as such:
Set up host-only networking on VirtualBox. The first adapter is configured with NAT, the second with host-only networking
HOST: Windows
GUEST: CentOS VM1, CentOS VM2 (clone of VM1)
When executing ifconfig -a on both VMs, I noticed that the MAC addresses are exactly the same. My question is how am I able to ping from VM1 to VM2 considering that the MAC addresses are the same?
```
VM1:
eth0 Link encap:Ethernet HWaddr 08:00:27:AF:A3:28
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:feaf:a328/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:27 errors:0 dropped:0 overruns:0 frame:0
TX packets:47 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:10671 (10.4 KiB) TX bytes:5682 (5.5 KiB)
eth1 Link encap:Ethernet HWaddr 08:00:27:C4:A8:B6
inet addr:192.168.56.102 Bcast:192.168.56.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fec4:a8b6/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:859 errors:0 dropped:0 overruns:0 frame:0
TX packets:41 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:114853 (112.1 KiB) TX bytes:4823 (4.7 KiB)
ip -6 addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
inet6 fe80::a00:27ff:feaf:a328/64 scope link
valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
inet6 fe80::a00:27ff:fec4:a8b6/64 scope link
valid_lft forever preferred_lft forever
VM2:
eth0 Link encap:Ethernet HWaddr 08:00:27:AF:A3:28
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:feaf:a328/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:114 errors:0 dropped:0 overruns:0 frame:0
TX packets:151 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:41594 (40.6 KiB) TX bytes:13479 (13.1 KiB)
eth1 Link encap:Ethernet HWaddr 08:00:27:C4:A8:B6
inet addr:192.168.56.101 Bcast:192.168.56.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fec4:a8b6/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1900 errors:0 dropped:0 overruns:0 frame:0
TX packets:78 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:259710 (253.6 KiB) TX bytes:9736 (9.5 KiB)
ip -6 addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
inet6 fe80::a00:27ff:feaf:a328/64 scope link
valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
inet6 fe80::a00:27ff:fec4:a8b6/64 scope link tentative dadfailed
valid_lft forever preferred_lft forever
``` | 2014/10/04 | [
"https://unix.stackexchange.com/questions/159252",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/44594/"
] | This is one of those things that surprises people because it goes against what they've been taught.
2 machines with the same hardware mac address on the same broadcast domain can talk to each other just fine as long as they have different IP addresses (and the switching gear plays nice).
Lets start with a test setup:
```
VM1 $ ip addr show dev enp0s8
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 08:00:27:3c:f9:ad brd ff:ff:ff:ff:ff:ff
inet 169.254.0.2/24 scope global enp0s8
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe3c:f9ad/64 scope link
valid_lft forever preferred_lft forever
```
```
VM2 $ ip addr show dev enp0s8
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 08:00:27:3c:f9:ad brd ff:ff:ff:ff:ff:ff
inet 169.254.0.3/24 scope global enp0s8
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe3c:f9ad/64 scope link tentative dadfailed
valid_lft forever preferred_lft forever
```
So notice how both machines have the same MAC addr, but different IPs.
Lets try pinging:
```
VM1 $ ping -c 3 169.254.0.3
PING 169.254.0.3 (169.254.0.3) 56(84) bytes of data.
64 bytes from 169.254.0.3: icmp_seq=1 ttl=64 time=0.505 ms
64 bytes from 169.254.0.3: icmp_seq=2 ttl=64 time=0.646 ms
64 bytes from 169.254.0.3: icmp_seq=3 ttl=64 time=0.636 ms
--- 169.254.0.3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2001ms
rtt min/avg/max/mdev = 0.505/0.595/0.646/0.070 ms
```
So, the remote host responded. Well, that's weird. Lets look at the neighbor table:
```
VM1 $ ip neigh
169.254.0.3 dev enp0s8 lladdr 08:00:27:3c:f9:ad REACHABLE
10.0.2.2 dev enp0s3 lladdr 52:54:00:12:35:02 STALE
```
That's our MAC!
Lets do a `tcpdump` on the other host to see that it's actually getting the traffic:
```
VM2 $ tcpdump -nn -e -i enp0s8 'host 169.254.0.2'
16:46:21.407188 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.2 > 169.254.0.3: ICMP echo request, id 2681, seq 1, length 64
16:46:21.407243 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.3 > 169.254.0.2: ICMP echo reply, id 2681, seq 1, length 64
16:46:22.406469 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.2 > 169.254.0.3: ICMP echo request, id 2681, seq 2, length 64
16:46:22.406520 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.3 > 169.254.0.2: ICMP echo reply, id 2681, seq 2, length 64
16:46:23.407467 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.2 > 169.254.0.3: ICMP echo request, id 2681, seq 3, length 64
16:46:23.407517 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.3 > 169.254.0.2: ICMP echo reply, id 2681, seq 3, length 64
```
So, as you can see, even though the traffic has the same source and destination hardware mac address, everything still works perfectly fine.
The reason for this is that the MAC address lookup comes very late in the communication process. The box has already used the destination IP address, and the routing tables to determine which interface it is going to send the traffic out on. The mac address that it adds onto the packet comes after that decision.
I should also note that this is dependent upon the layer 2 infrastructure. How these machines are connected, and what sits between them. If you've got a more intelligent switch, this may not work. It may see this packet coming through and reject it.
Now, going on to the traditional belief, of that this doesn't work. Well it is true, from a certain point of view :-)
The problem arises when another host on the network needs to talk to either of these machines. When the traffic goes out, the switch is going to route the traffic by the destination mac address, and it's only going to send it to a single host.
There are a few possible reasons why this test setup works:
1. The traffic is broadcast to all ports, or to all ports which the MAC matches.
2. The switch discards the source port as an option when determining the destination port.
3. The switch is actually a layer 3 switch and is routing based on the IP address, and not the mac address. | The effects of a duplicate MAC address can be subtle in some cases.
Switches distribute traffic to hosts based on "seen MAC" addresses. When you turn on your computer and it sends its first packet out on the network, your switch will log in its MAC table that "MAC address X came from port Y". Conversely then, in the future when it sees a unicast packet addressed to MAC address X, it knows to send it to port Y.
Since your VM is only on a single physical switch port, it's up to your hypervisor (VirtualBox) to sort out where to send the packets directed to that virtual MAC. In the case of a duplicate, it probably just sends it to both VMs and lets the network stack on each VM sort it out. (the networking stack would likely see that traffic was sent to its MAC address that did not belong to one of its own IP addresses, and silently drop the packet.) So you can imagine that this would cause a fair amount of extra work, for the OS to wake up and process each packet, whereas if you had unique MAC addresses the [virtual] hardware or driver could drop the packet intended for the other host, before sending it up the stack.
On a switched network (unlike your VM example), a duplicate MAC address would cause a switch to be confused about where to send traffic. Each packet a host with a duplicate MAC sends out would typically cause the switch to surmise that the host "moved" from one port on the switch to another. If both hosts were sending and receiving traffic at the same rate, you would expect each host to lose 50% of its return traffic.
ARP and IPv4 may not be too concerned about duplicate MAC addresses, so IPv4 networking may work properly. (though a robust stack, or a host with additional security/networking tools, may consider a duplicate MAC address as a red flag.) Also, if you are using DHCP, a DHCP server (absent a sufficiently unique client ID) could assign a duplicate IPv4 address, which could be problematic.
On the other hand, [IPv6 bases automatically configured addresses on the MAC address](https://www.rfc-editor.org/rfc/rfc4291#page-20). IPv6 also includes the concept of [duplicate address detection](https://www.rfc-editor.org/rfc/rfc4862#section-5.4), which means that a duplicate MAC address could cause the following effects (according to RFC 4862 section 5.4.5):
```
- not send any IP packets from the interface,
- silently drop any IP packets received on the interface, and
- not forward any IP packets to the interface (when acting as a
router or processing a packet with a Routing header).
``` |
40,399,435 | I have created a procedure to input value and filter information from `Inventory_view_03` table and insert those data in to `Trn_note_header` but procedure is running properly.
When I insert one one value to the input if I enter two or more i doesn't work, but doesn't showing erros.
Can you tell me what was the problem?
```
CREATE PROCEDURE insertrecord
@KITITEM Varchar(20)
AS
BEGIN
DECLARE @LASTNO int
IF (@LASTNO IS NULL) OR (LEN(@LASTNO) > 0)
BEGIN
SET @LASTNO= 0
END
SELECT @LASTNO=ISNUMERIC([Trn_number])from [dbo].[Trn_note_header]
SET @LASTNO=@LASTNO+1
insert into[dbo].[Trn_note_header]([Trn_number],[kit_number],[Supplier],[Season],[Pcs])
select @LASTNO,[trb_kit_desc],[shortname],[se_name],[Expr1] From[dbo].[Inventory_view_03]
WHERE trb_kit_desc IN(@KITITEM)
End
``` | 2016/11/03 | [
"https://Stackoverflow.com/questions/40399435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6108217/"
] | Plug these two functions below into a pascal class. I tested it and it works. That link that Prateek Darmwal posted is pretty much the same thing.
```java
public void nonRecursivePrint() {
nonRecursivePrint(n, true);
}
public void nonRecursivePrint(int n, boolean upsideDown) {
if (!upsideDown) {
for (int j = 0; j < (n + 1); j++) {
for (int i = 0; i < (j); i++) {
System.out.print(binom(j - 1, i) + (j == i + 1 ? "\n" : " "));
}
}
} else {
for (int j = n; j > 0; j--) {
for (int i = 0; i < (j); i++) {
System.out.print(binom(j - 1, i) + (j == i + 1 ? "\n" : " "));
}
}
}
}
``` | Go through this link you will find your answer explained in detail
<http://www.geeksforgeeks.org/pascal-triangle/> |
27,742,763 | Usually when I'm getting some data async way I would do it like
```
var promise = $http.get('/api/v1/movies/avengers');
promise.then(
function(payload) {
$scope.movieContent = payload;
});
```
In fact the scenario is very common - I send some request and when it's ready, I assing EVERYTHING it returns to some variable/prop. But everytime it require to make callback even if the callback is always the same.
Is there any way to do it like
```
$scope.movieContent = $http.get('/api/v1/movies/avengers'); //updates to real value when request is done
```
or kind of
```
updateWhenReady($scope.movieContent , '/api/v1/movies/avengers');
```
It's not big deal but when used a lot makes difference in my opinion. | 2015/01/02 | [
"https://Stackoverflow.com/questions/27742763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2446799/"
] | You can design your service so that it returns an empty reference and populates itself when the service call returns successfully. Use `angular.copy` to preserve the reference:
**Service**
```
app.factory('avengersService', function($http) {
return {
getAvengers: function() {
var avengers = [];
avengers.$promise = $http.get('/api/v1/movies/avengers').then(function(result) {
angular.copy(result.data, avengers);
return result;
});
return avengers;
}
}
});
```
**Controller**
```
app.controller('ctrl', function($scope, avengersService) {
$scope.movieContent = avengersService.getAvengers();
// or call the promise version
avengersService.getAvengers().$promise.then(function(result) {
$scope.movieContent = result.data;
});
});
``` | You could wrap the async call in a function:
```
function load(cb, model){
cb.then(function(payload){
model = payload;
});
}
```
\*But I would not recommend you doing this. Often, you want to perform specific tasks in the callback function (like handling loading indicators, ...). |
27,742,763 | Usually when I'm getting some data async way I would do it like
```
var promise = $http.get('/api/v1/movies/avengers');
promise.then(
function(payload) {
$scope.movieContent = payload;
});
```
In fact the scenario is very common - I send some request and when it's ready, I assing EVERYTHING it returns to some variable/prop. But everytime it require to make callback even if the callback is always the same.
Is there any way to do it like
```
$scope.movieContent = $http.get('/api/v1/movies/avengers'); //updates to real value when request is done
```
or kind of
```
updateWhenReady($scope.movieContent , '/api/v1/movies/avengers');
```
It's not big deal but when used a lot makes difference in my opinion. | 2015/01/02 | [
"https://Stackoverflow.com/questions/27742763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2446799/"
] | You can design your service so that it returns an empty reference and populates itself when the service call returns successfully. Use `angular.copy` to preserve the reference:
**Service**
```
app.factory('avengersService', function($http) {
return {
getAvengers: function() {
var avengers = [];
avengers.$promise = $http.get('/api/v1/movies/avengers').then(function(result) {
angular.copy(result.data, avengers);
return result;
});
return avengers;
}
}
});
```
**Controller**
```
app.controller('ctrl', function($scope, avengersService) {
$scope.movieContent = avengersService.getAvengers();
// or call the promise version
avengersService.getAvengers().$promise.then(function(result) {
$scope.movieContent = result.data;
});
});
``` | Not exactly what you asked for, but you can generate these callbacks "on-the-fly":
```
function assignToScope(propName) {
return function (data) { $scope[propName] = data; };
}
$http.get('/api/v1/movies/avengers').then(assignToScope('movieContent'));
```
or (if you like this syntax more):
```
function assignToScope(propName, promise) {
promise.then(function (data) { $scope[propName] = data; });
}
assignToScope('movieContent', $http.get('/api/v1/movies/avengers'));
```
Please note that error handling is important. If the promise rejects, you probably want to notify the user. |
1,395,707 | I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?
Here is my current code:
```
JFileChooser chooser = new JFileChooser()
{
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile != null && selectedFile.exists( ) )
{
int response = JOptionPane.showConfirmDialog(
this,
"The file " + selectedFile.getName() + " already exists."
+ " Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION )
{
return;
}
}
super.approveSelection();
}
};
``` | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] | Use this constructor:
```
JOptionPane(Object message, int messageType, int optionType,
Icon icon, Object[] options, Object initialValue)
```
where `options` specifies the buttons, and have `initialValue` (one of the `options` values) specify what the default is.
**Update:** You can call `showOptionDialog` rather than `showConfirmDialog`. The former takes `options` and `initialValue` parameters. | If you don't want to hardcode "Yes" and "No" (for instance when your app is localized for other languages), you can use UIManager resources:
```
UIManager.getString("OptionPane.yesButtonText", l)
UIManager.getString("OptionPane.noButtonText", l)
``` |
1,395,707 | I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?
Here is my current code:
```
JFileChooser chooser = new JFileChooser()
{
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile != null && selectedFile.exists( ) )
{
int response = JOptionPane.showConfirmDialog(
this,
"The file " + selectedFile.getName() + " already exists."
+ " Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION )
{
return;
}
}
super.approveSelection();
}
};
``` | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] | Use this constructor:
```
JOptionPane(Object message, int messageType, int optionType,
Icon icon, Object[] options, Object initialValue)
```
where `options` specifies the buttons, and have `initialValue` (one of the `options` values) specify what the default is.
**Update:** You can call `showOptionDialog` rather than `showConfirmDialog`. The former takes `options` and `initialValue` parameters. | For the above example, it is `JOptionPane.showOptionDialog`
Those arguments can no be passed to `showConfirmDialog` because it does not have them.
More people might be looking for this so why not offer a "working" solution. |
1,395,707 | I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?
Here is my current code:
```
JFileChooser chooser = new JFileChooser()
{
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile != null && selectedFile.exists( ) )
{
int response = JOptionPane.showConfirmDialog(
this,
"The file " + selectedFile.getName() + " already exists."
+ " Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION )
{
return;
}
}
super.approveSelection();
}
};
``` | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] | Use this constructor:
```
JOptionPane(Object message, int messageType, int optionType,
Icon icon, Object[] options, Object initialValue)
```
where `options` specifies the buttons, and have `initialValue` (one of the `options` values) specify what the default is.
**Update:** You can call `showOptionDialog` rather than `showConfirmDialog`. The former takes `options` and `initialValue` parameters. | This is my solution:
```
import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class NegativeDefaultButtonJOptionPane {
public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) {
List<Object> options = new ArrayList<Object>();
Object defaultOption;
switch(optionType){
case JOptionPane.OK_CANCEL_OPTION:
options.add(UIManager.getString("OptionPane.okButtonText"));
options.add(UIManager.getString("OptionPane.cancelButtonText"));
defaultOption = UIManager.getString("OptionPane.cancelButtonText");
break;
case JOptionPane.YES_NO_OPTION:
options.add(UIManager.getString("OptionPane.yesButtonText"));
options.add(UIManager.getString("OptionPane.noButtonText"));
defaultOption = UIManager.getString("OptionPane.noButtonText");
break;
case JOptionPane.YES_NO_CANCEL_OPTION:
options.add(UIManager.getString("OptionPane.yesButtonText"));
options.add(UIManager.getString("OptionPane.noButtonText"));
options.add(UIManager.getString("OptionPane.cancelButtonText"));
defaultOption = UIManager.getString("OptionPane.cancelButtonText");
break;
default:
throw new IllegalArgumentException("Unknown optionType "+optionType);
}
return JOptionPane.showOptionDialog(parentComponent, message, title, optionType, JOptionPane.QUESTION_MESSAGE, null, options.toArray(), defaultOption);
}
}
``` |
1,395,707 | I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?
Here is my current code:
```
JFileChooser chooser = new JFileChooser()
{
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile != null && selectedFile.exists( ) )
{
int response = JOptionPane.showConfirmDialog(
this,
"The file " + selectedFile.getName() + " already exists."
+ " Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION )
{
return;
}
}
super.approveSelection();
}
};
``` | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] | That's the first thing that comes to my mind.
```
//Custom button text
Object[] options = {"Yes",
"No"};
JOptionPane.showOptionDialog(this, "The file " + selectedFile.getName() +
" already exists. Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
```
But probably there's a better approach. | If you don't want to hardcode "Yes" and "No" (for instance when your app is localized for other languages), you can use UIManager resources:
```
UIManager.getString("OptionPane.yesButtonText", l)
UIManager.getString("OptionPane.noButtonText", l)
``` |
1,395,707 | I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?
Here is my current code:
```
JFileChooser chooser = new JFileChooser()
{
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile != null && selectedFile.exists( ) )
{
int response = JOptionPane.showConfirmDialog(
this,
"The file " + selectedFile.getName() + " already exists."
+ " Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION )
{
return;
}
}
super.approveSelection();
}
};
``` | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] | That's the first thing that comes to my mind.
```
//Custom button text
Object[] options = {"Yes",
"No"};
JOptionPane.showOptionDialog(this, "The file " + selectedFile.getName() +
" already exists. Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
```
But probably there's a better approach. | For the above example, it is `JOptionPane.showOptionDialog`
Those arguments can no be passed to `showConfirmDialog` because it does not have them.
More people might be looking for this so why not offer a "working" solution. |
1,395,707 | I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?
Here is my current code:
```
JFileChooser chooser = new JFileChooser()
{
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile != null && selectedFile.exists( ) )
{
int response = JOptionPane.showConfirmDialog(
this,
"The file " + selectedFile.getName() + " already exists."
+ " Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION )
{
return;
}
}
super.approveSelection();
}
};
``` | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] | That's the first thing that comes to my mind.
```
//Custom button text
Object[] options = {"Yes",
"No"};
JOptionPane.showOptionDialog(this, "The file " + selectedFile.getName() +
" already exists. Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
```
But probably there's a better approach. | This is my solution:
```
import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class NegativeDefaultButtonJOptionPane {
public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) {
List<Object> options = new ArrayList<Object>();
Object defaultOption;
switch(optionType){
case JOptionPane.OK_CANCEL_OPTION:
options.add(UIManager.getString("OptionPane.okButtonText"));
options.add(UIManager.getString("OptionPane.cancelButtonText"));
defaultOption = UIManager.getString("OptionPane.cancelButtonText");
break;
case JOptionPane.YES_NO_OPTION:
options.add(UIManager.getString("OptionPane.yesButtonText"));
options.add(UIManager.getString("OptionPane.noButtonText"));
defaultOption = UIManager.getString("OptionPane.noButtonText");
break;
case JOptionPane.YES_NO_CANCEL_OPTION:
options.add(UIManager.getString("OptionPane.yesButtonText"));
options.add(UIManager.getString("OptionPane.noButtonText"));
options.add(UIManager.getString("OptionPane.cancelButtonText"));
defaultOption = UIManager.getString("OptionPane.cancelButtonText");
break;
default:
throw new IllegalArgumentException("Unknown optionType "+optionType);
}
return JOptionPane.showOptionDialog(parentComponent, message, title, optionType, JOptionPane.QUESTION_MESSAGE, null, options.toArray(), defaultOption);
}
}
``` |
1,395,707 | I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?
Here is my current code:
```
JFileChooser chooser = new JFileChooser()
{
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile != null && selectedFile.exists( ) )
{
int response = JOptionPane.showConfirmDialog(
this,
"The file " + selectedFile.getName() + " already exists."
+ " Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION )
{
return;
}
}
super.approveSelection();
}
};
``` | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] | If you don't want to hardcode "Yes" and "No" (for instance when your app is localized for other languages), you can use UIManager resources:
```
UIManager.getString("OptionPane.yesButtonText", l)
UIManager.getString("OptionPane.noButtonText", l)
``` | For the above example, it is `JOptionPane.showOptionDialog`
Those arguments can no be passed to `showConfirmDialog` because it does not have them.
More people might be looking for this so why not offer a "working" solution. |
1,395,707 | I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?
Here is my current code:
```
JFileChooser chooser = new JFileChooser()
{
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile != null && selectedFile.exists( ) )
{
int response = JOptionPane.showConfirmDialog(
this,
"The file " + selectedFile.getName() + " already exists."
+ " Do you want to replace the existing file?",
getDialogTitle(),
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION )
{
return;
}
}
super.approveSelection();
}
};
``` | 2009/09/08 | [
"https://Stackoverflow.com/questions/1395707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46635/"
] | This is my solution:
```
import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class NegativeDefaultButtonJOptionPane {
public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) {
List<Object> options = new ArrayList<Object>();
Object defaultOption;
switch(optionType){
case JOptionPane.OK_CANCEL_OPTION:
options.add(UIManager.getString("OptionPane.okButtonText"));
options.add(UIManager.getString("OptionPane.cancelButtonText"));
defaultOption = UIManager.getString("OptionPane.cancelButtonText");
break;
case JOptionPane.YES_NO_OPTION:
options.add(UIManager.getString("OptionPane.yesButtonText"));
options.add(UIManager.getString("OptionPane.noButtonText"));
defaultOption = UIManager.getString("OptionPane.noButtonText");
break;
case JOptionPane.YES_NO_CANCEL_OPTION:
options.add(UIManager.getString("OptionPane.yesButtonText"));
options.add(UIManager.getString("OptionPane.noButtonText"));
options.add(UIManager.getString("OptionPane.cancelButtonText"));
defaultOption = UIManager.getString("OptionPane.cancelButtonText");
break;
default:
throw new IllegalArgumentException("Unknown optionType "+optionType);
}
return JOptionPane.showOptionDialog(parentComponent, message, title, optionType, JOptionPane.QUESTION_MESSAGE, null, options.toArray(), defaultOption);
}
}
``` | For the above example, it is `JOptionPane.showOptionDialog`
Those arguments can no be passed to `showConfirmDialog` because it does not have them.
More people might be looking for this so why not offer a "working" solution. |
50,850,079 | I need to make a predicate called *fAtomPairs* so that given an atom (first argument), and a list of pairs (each pair is in turn a list of two atoms), unify a third parameter with the *filtered* list of pairs by selecting only those pairs that have as their first component the atom which is the first argument.
For example :
```
fAtomPairs(sA,[[basA,absAb],[ab,bbsA],[sA,abbsB],[bsA,sAsB],[sA,bb]],X)
```
must result in
```
X = [[sA,abbsB],[sA,bb]]
```
How can I do this?, I'm currently working in [SWISH](https://swish.swi-prolog.org/) | 2018/06/14 | [
"https://Stackoverflow.com/questions/50850079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9062852/"
] | ```
:- use_module(library(reif)). % [SICStus](http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/sicstus/reif.pl)|[SWI](http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/swi/reif.pl)
:- use_module(library(lambda)). % [SICStus](http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/sicstus/lambda.pl)|[SWI](http://www.swi-prolog.org/pack/file_details/lambda/prolog/lambda.pl)
fAtomPairs(Sel, DEs, Es) :-
tfilter(\[A,_]^ ( Sel = A ), DEs, Es).
``` | You can use a version of [tfilter/3](https://stackoverflow.com/questions/297996/prolog-filtering-a-list) and [if\_/3](https://stackoverflow.com/questions/27358456/prolog-union-for-a-u-b-u-c/27358600#27358600).
I also changed the representation from lists of two elements to pairs.
```
fAtomPairs(sA,[basA-absAb,ab-bbsA,sA-abbsB,bsA-sAsB,sA-bb]).
tfilter(_CT_2, [], []).
tfilter(CT_2, [E-Thing|Es], Fs0) :-
if_(call(CT_2,E), Fs0 = [E-Thing|Fs], Fs0 = Fs ),
tfilter(CT_2, Es, Fs).
=(X,X,true).
=(X,Y,false) :- dif(X,Y).
if_(If_1, Then_0, Else_0) :-
call(If_1, T),
( T == true -> call(Then_0)
; T == false -> call(Else_0)
; nonvar(T) -> throw(error(type_error(boolean,T),_))
; /* var(T) */ throw(error(instantiation_error,_))
).
```
Then query:
```
?-fAtomPairs(SA,Pairs),tfilter(=(SA),Pairs,Filtered).
Filtered = [sA-abbsB, sA-bb],
Pairs = [basA-absAb, ab-bbsA, sA-abbsB, bsA-sAsB, sA-bb],
SA = sA
false
``` |
24,711,074 | I have this is my config file:
```
CKEDITOR.stylesSet.add( 'custom_styles', [
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } },
{ name: 'Custom Image', element: 'img', attributes: { 'class': 'myClass' } }
]);
```
but in the dropdown only the first 5 are showing, even when I click on an image. I've tried it in recent Chrome and Firefox and the config is not being cached (I added the yellow style to check that and it works fine). When I click on the image the bottom bar shows "body p image" but the default in the dropdown says "paragraph". I've also tried switching the order of styles around.
Documentation seems straight-forward so I'm not sure what I'm doing wrong. Is there some trick to getting object styles to show up?
EDIT:
There also seems to be something strange going on with other selected parts. I have Image2 plugin and when I add a link to an image then click that image the bottom bar just shows "body p image" and doesn't mention the "a" even though it's there in the HTML. | 2014/07/12 | [
"https://Stackoverflow.com/questions/24711074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3819158/"
] | Images in ckeditor now use a widget system. I'm not sure why this is not really documented yet but the solution is to specify:
* type: widget
* widget: image
So the following should work:
```
{ name: 'Custom Image', type: 'widget', widget: 'image', attributes: { 'class': 'myClass' } }
``` | Not 100% sure where you are fuzzy but if you are asking why the option isn't always in the ***styles*** drop-down menu: It's because the behaviour is context-sensitive depending on where the caret is and/or what is currently selected. Selecting an image allows you to retrospectively apply styles to it via this menu, but not insert new images - for that you'd need to add your own control.
As far as adding classes to objects goes, what you have should work as long as *CKEDITOR* knows about the stylesheet. Because the content pane of the editor uses an `<iframe>` element, a stylesheet would need to be added to it's respective document. This can be done via the global config ([docs](http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-contentsCss)):
```js
CKEDITOR.config.contentsCss = '/path/custom.css';
```
...or on an individual editor instance since version 4.4 ([docs](http://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-addContentsCss)):
```js
CKEDITOR.instances['myEditorId'].addContentsCss( '/path/custom.css' );
``` |
26,007,902 | I am trying to use the [Countries Gem](https://github.com/hexorx/countries), but had some basic questions on how to incorporate this gem after I've bundle-installed it.
1. Do I need to create a new controller/model to access the countries?
2. How do I create a simple select drop-down to show a list of countries for a user to select?
3. Where are all the countries stored? (I saw the data file in the Gem, but need some clarity how to bring that into my own app) | 2014/09/24 | [
"https://Stackoverflow.com/questions/26007902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4072856/"
] | 1) You don't need a new controller/model to access the countries
2) There is an [example app on the README page](https://github.com/scudco/country_select_test/blob/master/app/views/welcome/_simple_form_form.html.erb) which shows you how to use forms and dropdowns.
3) The countries are stores within the app. I believe [country\_select](https://github.com/stefanpenner/country_select) includes the [ISO 3166](https://github.com/hexorx/countries/) gem to get the list of countries. You can view the data in the [countries.yaml](https://github.com/hexorx/countries/blob/master/lib/data/countries.yaml) file
If want to know anything else, I recommend looking at the [example app](https://github.com/scudco/country_select_test). It provides a good example of how to use the gem. | You do not need to create a new controller/model to work with the gem.
In order for you to create dropdown, just install the `country_select` gem (as stated in the doc)
Then to use it, just do that in your views:
```
country_select(:your_model_name, :your_attribute_name)
```
To integrate it in a `form_for` with some extra params like Bootstrap classes or default country selected:
```
<%= form_for @message, url: contact_path, html: { :class => "form-horizontal " } do |f| %>
<div class="form-group">
<%= f.label :country, :class => "col-md-3 control-label" %>
<div class="col-md-9">
<%= f.country_select :country, ["United States"], {}, { :class => "form-control" } %>
</div>
</div>
<%= f.submit "Submit", :class => "btn btn-default" %>
<% end %>
```
For the exact options you have w/ this method, see here:
```
country_select(method, priority_or_options = {}, options = {}, html_options = {})
```
Hope it helps ! |
2,377,412 | $$\lim\limits\_{x\to\infty} \ \frac{\ln \ x}{x} = 0$$
How can I know this without looking at the graph? What's the easiest way to equate that expression to 0?
I understand that an integer over x approaches 0 as x approaches 0, but since ln x is an increasing function as x approaches infinity, how do we know which effect outweighs the other? | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377412",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/140396/"
] | By L'Hospital rule
$$\lim\_{x \rightarrow \infty}\frac{\ln x}{x}=\lim\_{x \rightarrow \infty}\frac{\frac{1}{x}}{1}$$
$$\lim\_{x \rightarrow \infty}\frac{\frac{1}{x}}{1}=\lim\_{x \rightarrow \infty}\frac{1}{x}$$
$$\lim\_{x \rightarrow \infty}\frac{1}{x}=0$$ | With $x=e^t$ we have to investigate $\lim\_{t\to \infty} \frac{t}{e^t} $. For $t>0$ we have
$0<\frac{t}{e^t}=\frac{t}{1+t+\frac{t^2}{2}+...} \le \frac{t}{\frac {t^2}{2}}=\frac{2}{t}$.
Your turn ! |
2,377,412 | $$\lim\limits\_{x\to\infty} \ \frac{\ln \ x}{x} = 0$$
How can I know this without looking at the graph? What's the easiest way to equate that expression to 0?
I understand that an integer over x approaches 0 as x approaches 0, but since ln x is an increasing function as x approaches infinity, how do we know which effect outweighs the other? | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377412",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/140396/"
] | $$\lim\_{x\to \infty} {\ln x \over x} =\lim\_{x\to \infty} \ln x^{1/x} = \ln\left( \lim\_{x\to \infty} x^{1/x}\right) = \ln 1 = 0$$
Limit used : [How to show that $\lim\_{n \to +\infty} n^{\frac{1}{n}} = 1$?](https://math.stackexchange.com/questions/115822/how-to-show-that-lim-n-to-infty-n-frac1n-1) | By L'Hospital rule
$$\lim\_{x \rightarrow \infty}\frac{\ln x}{x}=\lim\_{x \rightarrow \infty}\frac{\frac{1}{x}}{1}$$
$$\lim\_{x \rightarrow \infty}\frac{\frac{1}{x}}{1}=\lim\_{x \rightarrow \infty}\frac{1}{x}$$
$$\lim\_{x \rightarrow \infty}\frac{1}{x}=0$$ |
2,377,412 | $$\lim\limits\_{x\to\infty} \ \frac{\ln \ x}{x} = 0$$
How can I know this without looking at the graph? What's the easiest way to equate that expression to 0?
I understand that an integer over x approaches 0 as x approaches 0, but since ln x is an increasing function as x approaches infinity, how do we know which effect outweighs the other? | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377412",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/140396/"
] | By L'Hospital rule
$$\lim\_{x \rightarrow \infty}\frac{\ln x}{x}=\lim\_{x \rightarrow \infty}\frac{\frac{1}{x}}{1}$$
$$\lim\_{x \rightarrow \infty}\frac{\frac{1}{x}}{1}=\lim\_{x \rightarrow \infty}\frac{1}{x}$$
$$\lim\_{x \rightarrow \infty}\frac{1}{x}=0$$ | A high school proof, using only basic properties of the integral:
For $t\ge 1$, we have $\sqrt t\le t$, so $\dfrac1t\le\dfrac 1{\sqrt t}$ and hence, if $x\ge 1$,
$$ \ln x=\int\_1^x\frac{\mathrm d\mkern1mut}{t}\le\int\_1^x\frac{\mathrm d\mkern1mut}{\sqrt t}=2(\sqrt x-1)<2\sqrt x$$
from which we deduce at once
$$0\le\frac{\ln x}{x}<\frac{2\sqrt x}{x},\quad\text{which tends to }0.$$ |
2,377,412 | $$\lim\limits\_{x\to\infty} \ \frac{\ln \ x}{x} = 0$$
How can I know this without looking at the graph? What's the easiest way to equate that expression to 0?
I understand that an integer over x approaches 0 as x approaches 0, but since ln x is an increasing function as x approaches infinity, how do we know which effect outweighs the other? | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377412",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/140396/"
] | Since $\ln t \le t$, for $t = \sqrt{x}$ we would have
$$\ln \sqrt{x}=\dfrac{1}{2}\ln x \leq \sqrt{x} \iff \ln x \leq 2\sqrt{x}$$
and, for $x>1$,
$$0\le\ln x\leq 2\sqrt{x}\iff 0\le\dfrac{\ln x}{x}\leq \dfrac{2}{\sqrt{x}}$$
With the squeeze theorem we have $\dfrac{\ln x}{x} \underset{x\to +\infty}{\longrightarrow}0$ | With $x=e^t$ we have to investigate $\lim\_{t\to \infty} \frac{t}{e^t} $. For $t>0$ we have
$0<\frac{t}{e^t}=\frac{t}{1+t+\frac{t^2}{2}+...} \le \frac{t}{\frac {t^2}{2}}=\frac{2}{t}$.
Your turn ! |
2,377,412 | $$\lim\limits\_{x\to\infty} \ \frac{\ln \ x}{x} = 0$$
How can I know this without looking at the graph? What's the easiest way to equate that expression to 0?
I understand that an integer over x approaches 0 as x approaches 0, but since ln x is an increasing function as x approaches infinity, how do we know which effect outweighs the other? | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377412",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/140396/"
] | $$\lim\_{x\to \infty} {\ln x \over x} =\lim\_{x\to \infty} \ln x^{1/x} = \ln\left( \lim\_{x\to \infty} x^{1/x}\right) = \ln 1 = 0$$
Limit used : [How to show that $\lim\_{n \to +\infty} n^{\frac{1}{n}} = 1$?](https://math.stackexchange.com/questions/115822/how-to-show-that-lim-n-to-infty-n-frac1n-1) | With $x=e^t$ we have to investigate $\lim\_{t\to \infty} \frac{t}{e^t} $. For $t>0$ we have
$0<\frac{t}{e^t}=\frac{t}{1+t+\frac{t^2}{2}+...} \le \frac{t}{\frac {t^2}{2}}=\frac{2}{t}$.
Your turn ! |
2,377,412 | $$\lim\limits\_{x\to\infty} \ \frac{\ln \ x}{x} = 0$$
How can I know this without looking at the graph? What's the easiest way to equate that expression to 0?
I understand that an integer over x approaches 0 as x approaches 0, but since ln x is an increasing function as x approaches infinity, how do we know which effect outweighs the other? | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377412",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/140396/"
] | $$\lim\_{x\to \infty} {\ln x \over x} =\lim\_{x\to \infty} \ln x^{1/x} = \ln\left( \lim\_{x\to \infty} x^{1/x}\right) = \ln 1 = 0$$
Limit used : [How to show that $\lim\_{n \to +\infty} n^{\frac{1}{n}} = 1$?](https://math.stackexchange.com/questions/115822/how-to-show-that-lim-n-to-infty-n-frac1n-1) | Since $\ln t \le t$, for $t = \sqrt{x}$ we would have
$$\ln \sqrt{x}=\dfrac{1}{2}\ln x \leq \sqrt{x} \iff \ln x \leq 2\sqrt{x}$$
and, for $x>1$,
$$0\le\ln x\leq 2\sqrt{x}\iff 0\le\dfrac{\ln x}{x}\leq \dfrac{2}{\sqrt{x}}$$
With the squeeze theorem we have $\dfrac{\ln x}{x} \underset{x\to +\infty}{\longrightarrow}0$ |
2,377,412 | $$\lim\limits\_{x\to\infty} \ \frac{\ln \ x}{x} = 0$$
How can I know this without looking at the graph? What's the easiest way to equate that expression to 0?
I understand that an integer over x approaches 0 as x approaches 0, but since ln x is an increasing function as x approaches infinity, how do we know which effect outweighs the other? | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377412",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/140396/"
] | Since $\ln t \le t$, for $t = \sqrt{x}$ we would have
$$\ln \sqrt{x}=\dfrac{1}{2}\ln x \leq \sqrt{x} \iff \ln x \leq 2\sqrt{x}$$
and, for $x>1$,
$$0\le\ln x\leq 2\sqrt{x}\iff 0\le\dfrac{\ln x}{x}\leq \dfrac{2}{\sqrt{x}}$$
With the squeeze theorem we have $\dfrac{\ln x}{x} \underset{x\to +\infty}{\longrightarrow}0$ | A high school proof, using only basic properties of the integral:
For $t\ge 1$, we have $\sqrt t\le t$, so $\dfrac1t\le\dfrac 1{\sqrt t}$ and hence, if $x\ge 1$,
$$ \ln x=\int\_1^x\frac{\mathrm d\mkern1mut}{t}\le\int\_1^x\frac{\mathrm d\mkern1mut}{\sqrt t}=2(\sqrt x-1)<2\sqrt x$$
from which we deduce at once
$$0\le\frac{\ln x}{x}<\frac{2\sqrt x}{x},\quad\text{which tends to }0.$$ |
2,377,412 | $$\lim\limits\_{x\to\infty} \ \frac{\ln \ x}{x} = 0$$
How can I know this without looking at the graph? What's the easiest way to equate that expression to 0?
I understand that an integer over x approaches 0 as x approaches 0, but since ln x is an increasing function as x approaches infinity, how do we know which effect outweighs the other? | 2017/07/31 | [
"https://math.stackexchange.com/questions/2377412",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/140396/"
] | $$\lim\_{x\to \infty} {\ln x \over x} =\lim\_{x\to \infty} \ln x^{1/x} = \ln\left( \lim\_{x\to \infty} x^{1/x}\right) = \ln 1 = 0$$
Limit used : [How to show that $\lim\_{n \to +\infty} n^{\frac{1}{n}} = 1$?](https://math.stackexchange.com/questions/115822/how-to-show-that-lim-n-to-infty-n-frac1n-1) | A high school proof, using only basic properties of the integral:
For $t\ge 1$, we have $\sqrt t\le t$, so $\dfrac1t\le\dfrac 1{\sqrt t}$ and hence, if $x\ge 1$,
$$ \ln x=\int\_1^x\frac{\mathrm d\mkern1mut}{t}\le\int\_1^x\frac{\mathrm d\mkern1mut}{\sqrt t}=2(\sqrt x-1)<2\sqrt x$$
from which we deduce at once
$$0\le\frac{\ln x}{x}<\frac{2\sqrt x}{x},\quad\text{which tends to }0.$$ |
20,523,485 | I have a single activity controlling many fragments. When i perform certain fragment transactions I add the transaction to the back stack and enable the app icon in the action bar to navigate up, i.e., `setDisplayHomeAsUpEnabled(true)`. However, I'd like to change the text alongside the app icon (currently defaulting to the app name) at run time to provide the user with a better indication of where they are located in the app. Any ideas of how this can be done? | 2013/12/11 | [
"https://Stackoverflow.com/questions/20523485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1501327/"
] | Use
```
setTitle("title text")
```
...within an Activity to change the text shown in the title bar next to the icon. | Two ways, dynamically:
```
ActionBar bar = getActionBar();
bar.setTitle("Title");
bar.setSubtitle("subtitle");
```
In manifest.xml:
```
<application
android:label="@string/app_name" >
```
In Fragment:
```
(FragmentActivity) getActivity()).getActionBar().setTitle(R.string.title);
```
There is a lot of answers on that, try to do some researches to take these tricks, see: [Handling ActionBar title with the fragment back stack?](https://stackoverflow.com/a/13473186/2668136) |
41,359,459 | I am using C#
I got a string which looks something like this :
```
myString = "User1:John&User2:Bob'More text"
```
I used
```
var parsed = HttpUtility.ParseQueryString(myString);
```
and then i use `parsed["User1"]` and `parsed["User2"]` to get the data.
My problem is that `parsed["User2"]` returns me not only the name but also everything that comes after it.
I thought maybe to then seperate by the char `'`
But i not sure how to do it since it has a specific behaviour in Visual studio.
I thought about something like this?
```
private static string seperateStringByChar(string text)
{
int indexOfChar = text.IndexOf(');
if (indexOfChar > 0)
{
return text.Substring(0, indexOfChar);
}
else
{
return "";
}
}
``` | 2016/12/28 | [
"https://Stackoverflow.com/questions/41359459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3603579/"
] | The form begin has two purposes.
```
1. To sequence the evaluation of expressions
2. To "splice" sequences together (used by macros)
```
The first one is what is used most often:
```
(begin e0 e1 ...)
```
will evaluate the expressions e0 e1 ... in order.
The second is used when a macro expands to multiple definitions and/or expressions.
As an example, the following
```
(begin
(begin d1 e1 d2 d3)
(begin)
e2
...)
```
will be flattened by the macro expander into:
```
(begin d1 e1 d2 d3 e2 ...)
```
Now to the question "Why is (begin) allowed at all?". If `begin` was used for purpose 1 (sequencing) then an empty `begin` could be disallowed. For purpose 2 (splicing) it is very convenient to use `(begin)` as the result of a macro that does nothing. Consider a macro `(debug expression)` that either expands into `expression` (when debugging is enabled) or into `(begin)` when debugging is disabled. | The answer I posted [here](https://stackoverflow.com/a/44835725/5544472) about `(begin ())` is another acceptable reason to use begin in `(if () )` statements. |
38,380,121 | I wrote a typeclass to avoid having to write a duplicate function for a different type as below:
```
import Statistics.Distribution.Normal
import Data.Random
d1 :: Double -> Double -> Double -> Double -> Double -> Double
d1 s k r v t = ( log ( s / k ) + ( ( v * v ) / 2 ) * t ) / ( v * sqrt t )
d2 :: Double -> Double -> Double -> Double -> Double -> Double
d2 s k r v t = d1 s k r v t - v * sqrt t
call :: Double -> Double -> Double -> Double -> Double -> Double
call s k r t v = exp ( -r * t ) * ( s * cdf normal ( d1 s k r v t )
- k * cdf normal ( d2 s k r v t ) )
where normal = Normal (0 :: Double) 1
put :: Double -> Double -> Double -> Double -> Double -> Double
put s k r t v = exp ( -r * t ) * ( k * cdf normal ( - d2 s k r v t )
- s * cdf normal ( - d1 s k r v t ) )
where normal = Normal (0 :: Double) 1
class Black a where
price :: a -> Double -> Double -> Double
instance Black ( Option Future ) where
price ( Option ( Future s ) Call European k t ) r v = call s k r t v
price ( Option ( Future s ) Put European k t ) r v = put s k r t v
instance Black ( Option Forward ) where
price ( Option ( Forward s ) Call European k t ) r v = call s k r t v
price ( Option ( Forward s ) Put European k t ) r v = put s k r t v
```
Is this a valid use of typeclasses? The reason I am asking is that I am not overloading the definition of the price function for any given type. All I am doing is avoiding having to write:
```
priceFuture :: (Option Future) -> Double -> Double -> Double
// impl
priceFoward :: (Option Forward) -> Double -> Double -> Double
impl
data Option a = Option a Type Style Strike Expiration deriving (Show)
data Future = Future Price deriving (Show)
data Forward = Forward Price deriving (Show)
type Barrier = Double
type Expiration = Double
type Price = Double
type Strike = Double
type Value = Double
type Dividend = Double
type Rate = Double
data Type = Call | Put deriving (Eq, Show)
data Style = European | American deriving (Eq, Show)
``` | 2016/07/14 | [
"https://Stackoverflow.com/questions/38380121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3248346/"
] | I think I would just make the the argument to `Option` be a phantom type:
```
data Option a = Option Price Type Style Strike
data Future
data Forward
price :: Option a -> Double -> Double -> Double
price (Option s Call European k t) r v = call s k r t v
price (Option s Put European k t) r v = put s k r t v
```
Much less repetition, and no need for a type-class, but you still get a type-level distinction between forward options (`Option Forward`) and future options (`Option Future`) should you need that elsewhere. If you're really excited, you could turn on `DataKinds` to make sure that `Future` and `Forward` are the only two possible type-level arguments to `Option`. | How about this?
```
data Option = Option ForFut Type Style Strike Expiration deriving (Show)
data ForFut = Forward Price | Future Price deriving (Show)
type Barrier = Double
type Expiration = Double
type Price = Double
type Strike = Double
type Value = Double
type Dividend = Double
type Rate = Double
data Type = Call | Put deriving (Eq, Show)
data Style = European | American deriving (Eq, Show)
call :: Double -> Double -> Double -> Double -> Double -> Double
call = undefined
put :: Double -> Double -> Double -> Double -> Double -> Double
put = undefined
price :: Option -> Double -> Double -> Double
price ( Option ( Future s ) Call European k t ) r v = call s k r t v
price ( Option ( Future s ) Put European k t ) r v = put s k r t v
price ( Option ( Forward s ) Call European k t ) r v = call s k r t v
price ( Option ( Forward s ) Put European k t ) r v = put s k r t v
```
So I've combined the `Forward` and `Future` types into a single type. This then avoids the need to make `Option` a higher kinded type. The type class can then be removed, and `price` can be defined with simple pattern matching. |
70,827,267 | After installing `TensorFlow` in `Anaconda`, I tried to test it :
```
import tensorflow as tf
```
In `Jupyter`, I get this error :
```
ModuleNotFoundError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13080/3793406994.py in <module>
----> 1 import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
```
[](https://i.stack.imgur.com/MsSkX.png)
How I can fix this issue? | 2022/01/23 | [
"https://Stackoverflow.com/questions/70827267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7954210/"
] | Open your terminal, then switch to your env directory and run:
```
conda activate virtual_env_name
```
now try again | You can reinstall tensorflow.
```
pip install tensorflow
```
or
```
conda install tensorflow
``` |
15,895,610 | I cannot get the following chart to display. The following is the jQuery. I've tried other examples by replacing the jQuery and it works. I have all my files in the same folder, including data.csv.
```
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'column'
},
< ...more options here... >
};
$.get('./data.csv', function (data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
// header line containes categories
if (lineNo == 0) {
$.each(items, function (itemNo, item) {
if (itemNo > 0) options.xAxis.categories.push(item);
});
}
// the rest of the lines contain data with their name in the first position
else {
var series = {
data: []
};
$.each(items, function (itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
}
});
var chart = new Highcharts.Chart(options);
});
});
```
The CSV file looks like:
```
Categories,Apples,Pears,Oranges,Bananas
John,8,4,6,5
Jane,3,4,2,3
Joe,86,76,79,77
Janet,3,16,13,15
```
Here is the example I am trying to get working:
<http://www.highcharts.com/studies/data-from-csv.htm>
**EDIT: I just realized that the chart displays on Firefox. I have been using Chrome. Very weird. However, the example link above works on both.** | 2013/04/09 | [
"https://Stackoverflow.com/questions/15895610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119779/"
] | In Chrome you are not allowed to use AJAX to get local files. If you want do such thing use XAMPP or WAMP to create local server. Firefox doens't have such limits. | I was able to use this Chrome switch as a temporary fix to allow local file usage: --allow-file-access-from-files |
178,406 | Am planing to run a business and i have two option to choose between Magento or Php custom build (both of them will have the same functionality) so am considering about **STABILITY** and about **SECURITY**.
impatiently waiting for your advice. | 2017/06/10 | [
"https://magento.stackexchange.com/questions/178406",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/55193/"
] | Here is 2 ways to add you custom styles in your theme.
**1.** Backend
==============
Navigate to Content > Design > Configuration > Select Theme > HTML Head section > Scripts and Style Sheets field
**2.** Less processor.
======================
here is your theme directory
>
> app / design / frontend / [vendor] / [yourtheme]
>
>
>
create new file
>
> Magento\_Theme / web / css / source / \_extend.less
>
>
>
add new styles here
---
deploy changes
--------------
you need to deploy static content to see any changes. For development purpose Magento 2 provides grunt tool.
1. cp package.json.sample package.json
2. cp Gruntfile.js.sample Gruntfile.js
3. npm install (yes you need node and npm installed)
4. add your theme to this file
>
> dev / tools / grunt / configs / themes.js
>
>
>
you will find luma example here
5. cd Magento\_root && grunt watch
More information here <http://devdocs.magento.com/guides/v2.1/frontend-dev-guide/css-topics/css_debug.html> | after deploy please Confirm your custom css is created in your theme
>
> pub/static/frontend/Magento/[theme]/en\_us
>
>
>
if it is not created confirm you are follow the step
Can you please confirm did you created the below step.
>
>
> ```
> app / design / frontend / [vendor] / [theme] / Magento_Theme / layout
> app / design / frontend / [vendor] / [theme] / web / css
>
> ```
>
>
Create the following files:
>
>
> ```
> app / design / frontend / [vendor] / [theme] / Magento_Theme / layout / default_head_blocks.xml
> app / design / frontend / [vendor] / [theme] / web / css / custom-m.css
> app / design / frontend / [vendor] / [theme] / web / css / custom-l.css
>
> ```
>
>
place this code within default\_head\_blocks.xml
>
>
> ```
> <?xml version="1.0"?>
> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/framework/Module/etc/module.xsd">
> <head>
> <css src="css/custom-m.css" />
> <css src="css/custom-l.css" media="screen and (min-width: 768px)"/>
> </head>
> </page>
>
> ```
>
> |
236,226 | I have 2 user accounts in the same organization.
I have created an installed package with the "Marketing Cloud Component" that gives access to login, redirect, logout urls.
In the app exchange menu, there is a link to the following page:
<https://mc.s10.exacttarget.com/cloud/#app/>
But it is only accessible to the account that added the "Marketing Cloud" component, no other user account can see the menu option, nor visit that link.
I know this is an unpublished app, but I want to know if the other user accounts can be able to view. | 2018/10/16 | [
"https://salesforce.stackexchange.com/questions/236226",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/61173/"
] | To allow other users to view the app you need to:
Administration (top right) > Installed Packages > Click your app > LICENSES > License to everyone in org | You need to configure the app per business unit. Once the app is installed for that business unit, users in that business unit will see the link under the AppExchange menu, provided that they have the permissions. |
17,491,042 | I'm working with PCL and a Mesh editor (MeshLab). I'm interested in importing my meshes to PCL to do some 3D processing.
I've a mesh model in ply format. When I load the model with the code:
```
PointCloud<PointXYZRGBA>::Ptr cloud (new PointCloud<PointXYZRGBA> ());
pcl::io::loadPLYFile<pcl::PointXYZRGBA>(argv[1], *cloud);
```
and I visualize it as a point cloud:
```
visualization::PCLVisualizer viewer ("Model");
viewer.addPointCloud (cloud,"model");
```
the geometry is different from loading and visualizing the mesh directly:
```
viewer.addModelFromPLYFile(argv[1], "model");
```
In the second case, I visualize the model exactly as I do with a Mesh editor, but in the first case I visualize a deformed version of it, i.e and sphere is like and ellipsoid. What is happening here? Maybe I should manually sample the mesh?
If I add the two models in the viewer, the difference is very evident, the point cloud is smaller than the mesh, and it has suffered some strange deformation (please, see attached image)
Thank you very much
[](https://i.stack.imgur.com/m8iz1.png)
(source: [pcl-users.org](http://www.pcl-users.org/file/n4028582/meshply.png)) | 2013/07/05 | [
"https://Stackoverflow.com/questions/17491042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1719607/"
] | If someone is interested, here's the answer:
```
PointCloud<PointXYZRGBA>::Ptr cloud (new PointCloud<PointXYZRGBA> ());
pcl::PolygonMesh triangles;
pcl::io::loadPolygonFilePLY(argv[1], triangles);
pcl::fromROSMsg(triangles.cloud, *cloud);
```
This code opens a PLY file and converts it to a point cloud with the correct shape. | I'm quite sure that it's a bug of PCL before 1.7.2, as disclaimed in the release notes and proved by my own experience:
>
> Fixed a bug in PLYReader which lead to deformation of point clouds when displayed in CloudViewer or PCLVisualizer [#879](https://github.com/PointCloudLibrary/pcl/pull/879)
>
>
>
If you don't upgrade, please add one line to fix the bug as follows:
```
if (pcl::io::loadPLYFile <pcl::PointXYZRGBNormal> (file, *cloud) == -1)
{
std::cout << "Cloud reading failed." << std::endl;
return (-1);
}
cloud->sensor_orientation_.setIdentity();
``` |
73,303,683 | I would like to get the record where one column has the same value and the other column has different value. See table below:
| Name | Type |
| --- | --- |
| XX01 | Table |
| XX01 | Chair |
| XX02 | Box |
| XX02 | Box |
My end results will show XX01 since the column Name is the same but the column Type is different. I tried the following sql query which returns nothing:
```
select Name,Type from table where Name != Name
``` | 2022/08/10 | [
"https://Stackoverflow.com/questions/73303683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16966969/"
] | I do this with an expression that truncates any date expression to the preceding Sunday.
This gets Sunday of the current week.
```sql
CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) AS DATE);
```
This gets Sunday of the previous week.
```sql
CAST(DATEADD(DAY, (1-DATEPART(WEEKDAY, GETDATE()))-7, GETDATE()) AS DATE);
```
So if I want the previous week's data (Sunday to Sunday) it looks like this.
```sql
SELECT *
FROM mytable
WHERE dateval >= CAST(DATEADD(DAY, (1-DATEPART(WEEKDAY, GETDATE()))-7, GETDATE()) AS DATE)
AND dateval < CAST(DATEADD(DAY, (1-DATEPART(WEEKDAY, GETDATE())), GETDATE()) AS DATE);
```
Notice the `<` at the end of the date range. We want everything up to, but not including, the beginning of the current week.
I've used this in production for many years. It works correctly during the first and last weeks of a year, and at other times. And, it is [sargable](https://dba.stackexchange.com/questions/162263/what-does-the-word-sargable-really-mean): it can exploit an index on the `dateval` column. | You can use `DATEADD(WEEK, -1, DateTimePrinted)` to get the date -1 week.
Then just use that in your DATEPART to get the week number.
```
DATEPART(WEEK, DATEADD(WEEK, -1, DateTimePrinted))
``` |
73,303,683 | I would like to get the record where one column has the same value and the other column has different value. See table below:
| Name | Type |
| --- | --- |
| XX01 | Table |
| XX01 | Chair |
| XX02 | Box |
| XX02 | Box |
My end results will show XX01 since the column Name is the same but the column Type is different. I tried the following sql query which returns nothing:
```
select Name,Type from table where Name != Name
``` | 2022/08/10 | [
"https://Stackoverflow.com/questions/73303683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16966969/"
] | I do this with an expression that truncates any date expression to the preceding Sunday.
This gets Sunday of the current week.
```sql
CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) AS DATE);
```
This gets Sunday of the previous week.
```sql
CAST(DATEADD(DAY, (1-DATEPART(WEEKDAY, GETDATE()))-7, GETDATE()) AS DATE);
```
So if I want the previous week's data (Sunday to Sunday) it looks like this.
```sql
SELECT *
FROM mytable
WHERE dateval >= CAST(DATEADD(DAY, (1-DATEPART(WEEKDAY, GETDATE()))-7, GETDATE()) AS DATE)
AND dateval < CAST(DATEADD(DAY, (1-DATEPART(WEEKDAY, GETDATE())), GETDATE()) AS DATE);
```
Notice the `<` at the end of the date range. We want everything up to, but not including, the beginning of the current week.
I've used this in production for many years. It works correctly during the first and last weeks of a year, and at other times. And, it is [sargable](https://dba.stackexchange.com/questions/162263/what-does-the-word-sargable-really-mean): it can exploit an index on the `dateval` column. | I found the answer.
```
Where
DATEPART(WEEK, DateTimePrinted) = cast(dateadd(w,-1,cast(DATEname(WW,getdate()) as int)) as int)
```
I had to cast the data due to some errors on our date records. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | Another option is Ringo ([Play Store](http://play.google.com/store/apps/details?id=com.electricpocket.ringopro), [developer's site](http://epckt.com/ringo/)), which I've been using for over a year and it works great for just this purpose (I have a server that yells at me too). The free version has everything I need, though there is a paid version with more options as well.
**Update if you use Hangouts as your messaging app:** As of Hangouts version 2.1.2 (June 2014), you can customize the sound for each conversation. To do so:
1. Open (or start) a conversation with the contact you'd like to edit
2. Tap the three dots in the upper right corner
3. Tap "People & options"
4. Tap "Chat message sound" and select the sound you'd like
**Update if you use Messenger as your messaging app:** As of sometime in 2015 or earlier, you can follow the same instructions as for Hangouts above, except in #4 you select "Sound". | You cannot change the notification tone for a single user, only the Ringtone. You may be able to find a 3rd party SMS that will allow you to set up different notification sounds for specific users, but I am not aware of any. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | Another option is Ringo ([Play Store](http://play.google.com/store/apps/details?id=com.electricpocket.ringopro), [developer's site](http://epckt.com/ringo/)), which I've been using for over a year and it works great for just this purpose (I have a server that yells at me too). The free version has everything I need, though there is a paid version with more options as well.
**Update if you use Hangouts as your messaging app:** As of Hangouts version 2.1.2 (June 2014), you can customize the sound for each conversation. To do so:
1. Open (or start) a conversation with the contact you'd like to edit
2. Tap the three dots in the upper right corner
3. Tap "People & options"
4. Tap "Chat message sound" and select the sound you'd like
**Update if you use Messenger as your messaging app:** As of sometime in 2015 or earlier, you can follow the same instructions as for Hangouts above, except in #4 you select "Sound". | If you don't want to download a new messenger app, you can try using [Contact Alert](https://play.google.com/store/apps/details?id=com.rsminsmith.omnialert.app). It allows you to set custom notification sounds per contact and runs parallel to whatever messaging app you currently use. You will have to turn off sounds in your current messenger app to prevent your phone from playing 2 notifications at once. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | Another option is Ringo ([Play Store](http://play.google.com/store/apps/details?id=com.electricpocket.ringopro), [developer's site](http://epckt.com/ringo/)), which I've been using for over a year and it works great for just this purpose (I have a server that yells at me too). The free version has everything I need, though there is a paid version with more options as well.
**Update if you use Hangouts as your messaging app:** As of Hangouts version 2.1.2 (June 2014), you can customize the sound for each conversation. To do so:
1. Open (or start) a conversation with the contact you'd like to edit
2. Tap the three dots in the upper right corner
3. Tap "People & options"
4. Tap "Chat message sound" and select the sound you'd like
**Update if you use Messenger as your messaging app:** As of sometime in 2015 or earlier, you can follow the same instructions as for Hangouts above, except in #4 you select "Sound". | Use [Go SMS Pro](https://play.google.com/store/apps/details?id=com.jb.gosms&hl=en) to change individual customization for notification. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | Ryan is correct and I would recommend [SMS Popup](https://play.google.com/store/apps/details?id=net.everythingandroid.smspopup). Been using it since my G1 days. Lots of options like quick replies, custom vibration, and alert repetition to complement the custom message tones. You will need to turn off the native message notifications though, but it's definitely worth it. | this is what I did without any 3rd party apps.. for a long time I used go sms.. but.. if you go into and make your own file folders by coopying and pasting.. voile'!
1. Open My Files application (The default file manager on Samsung devices)
2. Under Local Storage, open the Device Storage option
3. Browse the audio file, long press on it, tap the 3dot icon, and select the Copy option
4. under Device Storage, find the "Notifications" folder, open it, and Paste the copied audio file
5. Now, open the Messages application
6. Tap the 3dot icon and Settings after that
7. Tap the Notifications option, and then the Notification Sound.
8. On the opened list, you should now see the name of your audio file, and you just need to select it. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | Use [Go SMS Pro](https://play.google.com/store/apps/details?id=com.jb.gosms&hl=en) to change individual customization for notification. | If you don't want to download a new messenger app, you can try using [Contact Alert](https://play.google.com/store/apps/details?id=com.rsminsmith.omnialert.app). It allows you to set custom notification sounds per contact and runs parallel to whatever messaging app you currently use. You will have to turn off sounds in your current messenger app to prevent your phone from playing 2 notifications at once. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | If you don't want to download a new messenger app, you can try using [Contact Alert](https://play.google.com/store/apps/details?id=com.rsminsmith.omnialert.app). It allows you to set custom notification sounds per contact and runs parallel to whatever messaging app you currently use. You will have to turn off sounds in your current messenger app to prevent your phone from playing 2 notifications at once. | this is what I did without any 3rd party apps.. for a long time I used go sms.. but.. if you go into and make your own file folders by coopying and pasting.. voile'!
1. Open My Files application (The default file manager on Samsung devices)
2. Under Local Storage, open the Device Storage option
3. Browse the audio file, long press on it, tap the 3dot icon, and select the Copy option
4. under Device Storage, find the "Notifications" folder, open it, and Paste the copied audio file
5. Now, open the Messages application
6. Tap the 3dot icon and Settings after that
7. Tap the Notifications option, and then the Notification Sound.
8. On the opened list, you should now see the name of your audio file, and you just need to select it. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | Use [Go SMS Pro](https://play.google.com/store/apps/details?id=com.jb.gosms&hl=en) to change individual customization for notification. | this is what I did without any 3rd party apps.. for a long time I used go sms.. but.. if you go into and make your own file folders by coopying and pasting.. voile'!
1. Open My Files application (The default file manager on Samsung devices)
2. Under Local Storage, open the Device Storage option
3. Browse the audio file, long press on it, tap the 3dot icon, and select the Copy option
4. under Device Storage, find the "Notifications" folder, open it, and Paste the copied audio file
5. Now, open the Messages application
6. Tap the 3dot icon and Settings after that
7. Tap the Notifications option, and then the Notification Sound.
8. On the opened list, you should now see the name of your audio file, and you just need to select it. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | Go into your contacts. Open the contact you want to personalize the message tone. Click "edit". Then scroll down to the bottom and click on "ADD ANOTHER FIELD". Tap to put a check mark beside "Message tone" then tap "OK". Then tap on "Message tone" and your options should come up e.g. Media storage, Zedge, etc. Tap which option you want to choose the message tone for that person. then choose the ringtone for them and tap "set ringtone". Make sure you then "save" that contact.
That worked for me with my Samsung Galaxy S5. Hope this works for you. | this is what I did without any 3rd party apps.. for a long time I used go sms.. but.. if you go into and make your own file folders by coopying and pasting.. voile'!
1. Open My Files application (The default file manager on Samsung devices)
2. Under Local Storage, open the Device Storage option
3. Browse the audio file, long press on it, tap the 3dot icon, and select the Copy option
4. under Device Storage, find the "Notifications" folder, open it, and Paste the copied audio file
5. Now, open the Messages application
6. Tap the 3dot icon and Settings after that
7. Tap the Notifications option, and then the Notification Sound.
8. On the opened list, you should now see the name of your audio file, and you just need to select it. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | Another option is Ringo ([Play Store](http://play.google.com/store/apps/details?id=com.electricpocket.ringopro), [developer's site](http://epckt.com/ringo/)), which I've been using for over a year and it works great for just this purpose (I have a server that yells at me too). The free version has everything I need, though there is a paid version with more options as well.
**Update if you use Hangouts as your messaging app:** As of Hangouts version 2.1.2 (June 2014), you can customize the sound for each conversation. To do so:
1. Open (or start) a conversation with the contact you'd like to edit
2. Tap the three dots in the upper right corner
3. Tap "People & options"
4. Tap "Chat message sound" and select the sound you'd like
**Update if you use Messenger as your messaging app:** As of sometime in 2015 or earlier, you can follow the same instructions as for Hangouts above, except in #4 you select "Sound". | this is what I did without any 3rd party apps.. for a long time I used go sms.. but.. if you go into and make your own file folders by coopying and pasting.. voile'!
1. Open My Files application (The default file manager on Samsung devices)
2. Under Local Storage, open the Device Storage option
3. Browse the audio file, long press on it, tap the 3dot icon, and select the Copy option
4. under Device Storage, find the "Notifications" folder, open it, and Paste the copied audio file
5. Now, open the Messages application
6. Tap the 3dot icon and Settings after that
7. Tap the Notifications option, and then the Notification Sound.
8. On the opened list, you should now see the name of your audio file, and you just need to select it. |
10,519 | If it matters any I have an HTC Desire Z with the original Sense install.
We have this monitoring service at work that keeps an eye on the various servers and starts frantically SMS'ing me whenever things aren't working right.
I'd like to set a separate notification tone for SMS's from that one contact. How do you do that? Under the contact I have an option for the Ringtone, but there doesn't seem to be an option for the SMS notification tone. | 2011/06/17 | [
"https://android.stackexchange.com/questions/10519",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1070/"
] | You cannot change the notification tone for a single user, only the Ringtone. You may be able to find a 3rd party SMS that will allow you to set up different notification sounds for specific users, but I am not aware of any. | Use [Go SMS Pro](https://play.google.com/store/apps/details?id=com.jb.gosms&hl=en) to change individual customization for notification. |
31,162,128 | I have a menu here:
```
<header></header>
<a class="back">Back</a>
<ul>
<li>
<a href="#">Something</a>
</li>
<li>
<a href="#">Something1</a>
</li>
<li>
<a href="#">Something2</a>
</li>
<li>
<a href="#">Something3</a>
</li>
</ul>
```
When a user clicks on a link within the menu, how do I get whatever link they clicked to show up within the header tag? So if a user picks the second link, Something2, I want whatever the text is between the a tag, in this case Something2, to show up between the header tag. | 2015/07/01 | [
"https://Stackoverflow.com/questions/31162128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547971/"
] | There are number of working examples for your context in SO. Its very simple in jquery and you asking very hard. Please look through [API Jquery](http://api.jquery.com/)
```
$("ul li a").click(function(e) {
e.preventDefault();
$('header').text($(this).text());
});
```
[**Fiddle**](http://jsfiddle.net/0xrxeufh/)
**for your second question** "I have a back button, how do I revert the previous link back to what it was? "
```
var temp = '';
$("ul li a").click(function(e) {
e.preventDefault();
temp = $('header').text();
$('header').data('value', temp);
$('header').text($(this).text());
});
$(".back").click(function(e) {
e.preventDefault();
var val = $('header').data('value');
$('header').text(val);
});
```
[**Fiddle2**](http://jsfiddle.net/0xrxeufh/1/) | ```
$("ul > li > a").click(function(e) {
var element = document.getElementById("header");
element.innerHTML = $(this).text();
});
```
You can try something like this to modify the header text whenever a link is clicked. |
31,162,128 | I have a menu here:
```
<header></header>
<a class="back">Back</a>
<ul>
<li>
<a href="#">Something</a>
</li>
<li>
<a href="#">Something1</a>
</li>
<li>
<a href="#">Something2</a>
</li>
<li>
<a href="#">Something3</a>
</li>
</ul>
```
When a user clicks on a link within the menu, how do I get whatever link they clicked to show up within the header tag? So if a user picks the second link, Something2, I want whatever the text is between the a tag, in this case Something2, to show up between the header tag. | 2015/07/01 | [
"https://Stackoverflow.com/questions/31162128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547971/"
] | There are number of working examples for your context in SO. Its very simple in jquery and you asking very hard. Please look through [API Jquery](http://api.jquery.com/)
```
$("ul li a").click(function(e) {
e.preventDefault();
$('header').text($(this).text());
});
```
[**Fiddle**](http://jsfiddle.net/0xrxeufh/)
**for your second question** "I have a back button, how do I revert the previous link back to what it was? "
```
var temp = '';
$("ul li a").click(function(e) {
e.preventDefault();
temp = $('header').text();
$('header').data('value', temp);
$('header').text($(this).text());
});
$(".back").click(function(e) {
e.preventDefault();
var val = $('header').data('value');
$('header').text(val);
});
```
[**Fiddle2**](http://jsfiddle.net/0xrxeufh/1/) | try this:-
```
$('ul li a').click(function(){
$('header').html($(this).text());
});
```
[Demo](http://jsfiddle.net/tm6SH/59/) |
31,162,128 | I have a menu here:
```
<header></header>
<a class="back">Back</a>
<ul>
<li>
<a href="#">Something</a>
</li>
<li>
<a href="#">Something1</a>
</li>
<li>
<a href="#">Something2</a>
</li>
<li>
<a href="#">Something3</a>
</li>
</ul>
```
When a user clicks on a link within the menu, how do I get whatever link they clicked to show up within the header tag? So if a user picks the second link, Something2, I want whatever the text is between the a tag, in this case Something2, to show up between the header tag. | 2015/07/01 | [
"https://Stackoverflow.com/questions/31162128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547971/"
] | There are number of working examples for your context in SO. Its very simple in jquery and you asking very hard. Please look through [API Jquery](http://api.jquery.com/)
```
$("ul li a").click(function(e) {
e.preventDefault();
$('header').text($(this).text());
});
```
[**Fiddle**](http://jsfiddle.net/0xrxeufh/)
**for your second question** "I have a back button, how do I revert the previous link back to what it was? "
```
var temp = '';
$("ul li a").click(function(e) {
e.preventDefault();
temp = $('header').text();
$('header').data('value', temp);
$('header').text($(this).text());
});
$(".back").click(function(e) {
e.preventDefault();
var val = $('header').data('value');
$('header').text(val);
});
```
[**Fiddle2**](http://jsfiddle.net/0xrxeufh/1/) | I have set up a fiddle with the following (also takes care of the back button): <https://jsfiddle.net/0dLy3xwq/2/>
HTML:
```
<header id="linkLabel"></header>
<a href="#" id="backButton">Back</a>
<ul id="navigationList">
<li>
<a href="#">Something</a>
</li>
<li>
<a href="#">Something1</a>
</li>
<li>
<a href="#">Something2</a>
</li>
<li>
<a href="#">Something3</a>
</li>
</ul>
```
And the JavaScript:
```
(function ($) {
var navStack = [];
$('#navigationList a').click(function (event) {
var el = $(event.target),
label = el.text();
if (navStack[navStack.length - 1] !== label) {
navStack.push(label);
updateView();
}
});
$('#backButton').click(function () {
navStack.pop();
updateView();
});
function updateView() {
$('#linkLabel').text(navStack[navStack.length - 1] || '');
}
}(jQuery));
```
For the back button just use a simple stack to keep track of where the user has been. If you have a forward button then create another stack that pushes the popped label when back is clicked. |
11,871,805 | Here is the scenario: I am getting data from database through web server. Based on that data page sends another request to the same server to perform some action. Simplified structure is the following:
```
var datacon;
$.post('method',function(data){
datacon = data;
// populating some tags;
}) // end of post
//some other staff happening;
$.post('other',{datacon}, function(env){
...// taking data from populated tags
$("div").load(env);
...
}) // end of post
```
This happens every time user enters the page. This code doesn't work in a sense that datacon is empty when the page is opened. But if I will refresh it once or twice, it starts working. Second $.post works perfectly, checked hundreds of times. I changed first $.post with $.get, but it doesn't help.
Probably it concerns asynchronous / synchronous calls. I don't understand much why it happens. Please help.
p.s. server is CherryPy. | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254285/"
] | Use the CSS [`max-width`](http://quirksmode.org/css/width.html) property on the div.
Something like this should work:
```
$('#Div').css({display:'block',
position: 'absolute',
top: offset.top,
left:offset.left,
max-width: '200px'
}).append("<img src='" + largePic+ "'/>");
``` | Constrain it with a max-height, or a max-width. |
11,871,805 | Here is the scenario: I am getting data from database through web server. Based on that data page sends another request to the same server to perform some action. Simplified structure is the following:
```
var datacon;
$.post('method',function(data){
datacon = data;
// populating some tags;
}) // end of post
//some other staff happening;
$.post('other',{datacon}, function(env){
...// taking data from populated tags
$("div").load(env);
...
}) // end of post
```
This happens every time user enters the page. This code doesn't work in a sense that datacon is empty when the page is opened. But if I will refresh it once or twice, it starts working. Second $.post works perfectly, checked hundreds of times. I changed first $.post with $.get, but it doesn't help.
Probably it concerns asynchronous / synchronous calls. I don't understand much why it happens. Please help.
p.s. server is CherryPy. | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254285/"
] | You can constrain the image by way of the div, or the image. Here's a jsfiddle of constraining the image by setting a width on the div, and having the image fill the div as best possible: <http://jsfiddle.net/LELns/> | Use the CSS [`max-width`](http://quirksmode.org/css/width.html) property on the div.
Something like this should work:
```
$('#Div').css({display:'block',
position: 'absolute',
top: offset.top,
left:offset.left,
max-width: '200px'
}).append("<img src='" + largePic+ "'/>");
``` |
11,871,805 | Here is the scenario: I am getting data from database through web server. Based on that data page sends another request to the same server to perform some action. Simplified structure is the following:
```
var datacon;
$.post('method',function(data){
datacon = data;
// populating some tags;
}) // end of post
//some other staff happening;
$.post('other',{datacon}, function(env){
...// taking data from populated tags
$("div").load(env);
...
}) // end of post
```
This happens every time user enters the page. This code doesn't work in a sense that datacon is empty when the page is opened. But if I will refresh it once or twice, it starts working. Second $.post works perfectly, checked hundreds of times. I changed first $.post with $.get, but it doesn't help.
Probably it concerns asynchronous / synchronous calls. I don't understand much why it happens. Please help.
p.s. server is CherryPy. | 2012/08/08 | [
"https://Stackoverflow.com/questions/11871805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254285/"
] | You can constrain the image by way of the div, or the image. Here's a jsfiddle of constraining the image by setting a width on the div, and having the image fill the div as best possible: <http://jsfiddle.net/LELns/> | Constrain it with a max-height, or a max-width. |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | You can use script like this for mac:
```
for f in $(curl -s -l -u user:pass ftp://your_ftp_server_ip/folder/)
do curl -O -u user:pass ftp://your_ftp_server_ip/folder/$f
done
``` | Oh, I have just the thing you need!
```
$host = "ftp://example.com/dir/";
$savePath = "downloadedFiles";
if($check = isFtpUp($host)){
echo $ip." -is alive<br />";
$check = trim($check);
$files = explode("\n",$check);
foreach($files as $n=>$file){
$file = trim($file);
if($file !== "." || $file !== ".."){
if(!saveFtpFile($file, $host.$file, $savePath)){
// downloading failed. possible reason: $file is a folder name.
// echo "Error downloading file.<br />";
}else{
echo "File: ".$file." - saved!<br />";
}
}else{
// do nothing
}
}
}else{
echo $ip." - is down.<br />";
}
```
and functions `isFtpUp` and `saveFtpFile` are as follows:
```
function isFtpUp($host){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_USERPWD, "anonymous:your@email.com");
curl_setopt($ch, CURLOPT_FTPLISTONLY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$result = curl_exec($ch);
return $result;
}
function saveFtpFile( $targetFile = null, $sourceFile = null, $savePath){
// function settings
set_time_limit(60);
$timeout = 60;
$ftpuser = "anonymous";
$ftppassword = "your@email.com";
$savePath = "downloadedFiles"; // should exist!
$curl = curl_init();
$file = @fopen ($savePath.'/'.$targetFile, 'w');
if(!$file){
return false;
}
curl_setopt($curl, CURLOPT_URL, $sourceFile);
curl_setopt($curl, CURLOPT_USERPWD, $ftpuser.':'.$ftppassword);
// curl settings
// curl_setopt($curl, CURLOPT_FAILONERROR, 1);
// curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_FILE, $file);
$result = curl_exec($curl);
if(!$result){
return false;
}
curl_close($curl);
fclose($file);
return $result;
}
```
EDIT:
it's a php script.
save it as a .php file, put it on your webserver, change $ip to address(need not be ip) of ftp server you want to download files from, create a directory named downloadedFiles on the same directory as this file. |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | OK, considering that you are using Windows, the most simple way to do that is to use the standard `ftp` tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.
First of all, you need to create a batch (script) file for the `ftp` program, containing instructions for it. Name it as you want, and put into it:
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
open ftp.myftpsite.com
login
pass
mget *
quit
```
The first line opens a connection to the ftp server at `ftp.myftpsite.com`. The two following lines specify the login, and the password which ftp will ask for (replace `login` and `pass` with just the login and password, without any keywords). Then, you use `mget *` to get all files. Instead of the `*`, you can use any wildcard. Finally, you use `quit` to close the `ftp` program without interactive prompt.
If you needed to enter some directory first, add a `cd` command before `mget`. It should be pretty straightforward.
Finally, write that file and run `ftp` like this:
```
ftp -i -s:yourscript
```
where `-i` disables interactivity (asking before downloading files), and `-s` specifies path to the script you created.
---
Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use [PuTTy](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) tools anyway. The one of particular interest for this case would be `pscp` which is practically the PuTTy counter-part of the openssh `scp` command.
The syntax is similar to `copy` command, and it supports wildcards:
```
pscp -batch login@mysshsite.com:iiumlabs* .
```
If you authenticate using a key file, you should pass it using `-i path-to-key-file`. If you use password, `-pw pass`. It can also reuse sessions saved using PuTTy, using the load `-load your-session-name` argument. | You can use script like this for mac:
```
for f in $(curl -s -l -u user:pass ftp://your_ftp_server_ip/folder/)
do curl -O -u user:pass ftp://your_ftp_server_ip/folder/$f
done
``` |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | If you're not bound to curl, you might want to use [wget](https://www.gnu.org/software/wget/manual/wget.html) in recursive mode but restricting it to one level of recursion, try the following;
```
wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
```
* `--no-parent` : Do not ever ascend to the parent directory when retrieving recursively.
* `--level=depth` : Specify recursion maximum depth level depth. The default maximum depth is five layers.
* `--no-directories` : Do not create a hierarchy of directories when retrieving recursively. | Here is how I did to download quickly with cURL (I'm not sure how many files it can download though) :
```
setlocal EnableDelayedExpansion
cd where\to\download
set STR=
for /f "skip=2 delims=" %%F in ('P:\curl -l -u user:password ftp://ftp.example.com/directory/anotherone/') do set STR=-O "ftp://ftp.example.com/directory/anotherone/%%F" !STR!
path\to\curl.exe -v -u user:password !STR!
```
Why **skip=2** ?
To get ride of `.` and `..`
Why **delims=** ?
To support names with spaces |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | What about something like this:
```
for /f %%f in ('curl -s -l -u user:pass ftp://ftp.myftpsite.com/') do curl -O -u user:pass ftp://ftp.myftpsite.com/%%f
``` | Oh, I have just the thing you need!
```
$host = "ftp://example.com/dir/";
$savePath = "downloadedFiles";
if($check = isFtpUp($host)){
echo $ip." -is alive<br />";
$check = trim($check);
$files = explode("\n",$check);
foreach($files as $n=>$file){
$file = trim($file);
if($file !== "." || $file !== ".."){
if(!saveFtpFile($file, $host.$file, $savePath)){
// downloading failed. possible reason: $file is a folder name.
// echo "Error downloading file.<br />";
}else{
echo "File: ".$file." - saved!<br />";
}
}else{
// do nothing
}
}
}else{
echo $ip." - is down.<br />";
}
```
and functions `isFtpUp` and `saveFtpFile` are as follows:
```
function isFtpUp($host){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_USERPWD, "anonymous:your@email.com");
curl_setopt($ch, CURLOPT_FTPLISTONLY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$result = curl_exec($ch);
return $result;
}
function saveFtpFile( $targetFile = null, $sourceFile = null, $savePath){
// function settings
set_time_limit(60);
$timeout = 60;
$ftpuser = "anonymous";
$ftppassword = "your@email.com";
$savePath = "downloadedFiles"; // should exist!
$curl = curl_init();
$file = @fopen ($savePath.'/'.$targetFile, 'w');
if(!$file){
return false;
}
curl_setopt($curl, CURLOPT_URL, $sourceFile);
curl_setopt($curl, CURLOPT_USERPWD, $ftpuser.':'.$ftppassword);
// curl settings
// curl_setopt($curl, CURLOPT_FAILONERROR, 1);
// curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_FILE, $file);
$result = curl_exec($curl);
if(!$result){
return false;
}
curl_close($curl);
fclose($file);
return $result;
}
```
EDIT:
it's a php script.
save it as a .php file, put it on your webserver, change $ip to address(need not be ip) of ftp server you want to download files from, create a directory named downloadedFiles on the same directory as this file. |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | What about something like this:
```
for /f %%f in ('curl -s -l -u user:pass ftp://ftp.myftpsite.com/') do curl -O -u user:pass ftp://ftp.myftpsite.com/%%f
``` | Here is how I did to download quickly with cURL (I'm not sure how many files it can download though) :
```
setlocal EnableDelayedExpansion
cd where\to\download
set STR=
for /f "skip=2 delims=" %%F in ('P:\curl -l -u user:password ftp://ftp.example.com/directory/anotherone/') do set STR=-O "ftp://ftp.example.com/directory/anotherone/%%F" !STR!
path\to\curl.exe -v -u user:password !STR!
```
Why **skip=2** ?
To get ride of `.` and `..`
Why **delims=** ?
To support names with spaces |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | If you're not bound to curl, you might want to use [wget](https://www.gnu.org/software/wget/manual/wget.html) in recursive mode but restricting it to one level of recursion, try the following;
```
wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
```
* `--no-parent` : Do not ever ascend to the parent directory when retrieving recursively.
* `--level=depth` : Specify recursion maximum depth level depth. The default maximum depth is five layers.
* `--no-directories` : Do not create a hierarchy of directories when retrieving recursively. | You can use script like this for mac:
```
for f in $(curl -s -l -u user:pass ftp://your_ftp_server_ip/folder/)
do curl -O -u user:pass ftp://your_ftp_server_ip/folder/$f
done
``` |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | If you're not bound to curl, you might want to use [wget](https://www.gnu.org/software/wget/manual/wget.html) in recursive mode but restricting it to one level of recursion, try the following;
```
wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
```
* `--no-parent` : Do not ever ascend to the parent directory when retrieving recursively.
* `--level=depth` : Specify recursion maximum depth level depth. The default maximum depth is five layers.
* `--no-directories` : Do not create a hierarchy of directories when retrieving recursively. | OK, considering that you are using Windows, the most simple way to do that is to use the standard `ftp` tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.
First of all, you need to create a batch (script) file for the `ftp` program, containing instructions for it. Name it as you want, and put into it:
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
open ftp.myftpsite.com
login
pass
mget *
quit
```
The first line opens a connection to the ftp server at `ftp.myftpsite.com`. The two following lines specify the login, and the password which ftp will ask for (replace `login` and `pass` with just the login and password, without any keywords). Then, you use `mget *` to get all files. Instead of the `*`, you can use any wildcard. Finally, you use `quit` to close the `ftp` program without interactive prompt.
If you needed to enter some directory first, add a `cd` command before `mget`. It should be pretty straightforward.
Finally, write that file and run `ftp` like this:
```
ftp -i -s:yourscript
```
where `-i` disables interactivity (asking before downloading files), and `-s` specifies path to the script you created.
---
Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use [PuTTy](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) tools anyway. The one of particular interest for this case would be `pscp` which is practically the PuTTy counter-part of the openssh `scp` command.
The syntax is similar to `copy` command, and it supports wildcards:
```
pscp -batch login@mysshsite.com:iiumlabs* .
```
If you authenticate using a key file, you should pass it using `-i path-to-key-file`. If you use password, `-pw pass`. It can also reuse sessions saved using PuTTy, using the load `-load your-session-name` argument. |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | OK, considering that you are using Windows, the most simple way to do that is to use the standard `ftp` tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.
First of all, you need to create a batch (script) file for the `ftp` program, containing instructions for it. Name it as you want, and put into it:
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
open ftp.myftpsite.com
login
pass
mget *
quit
```
The first line opens a connection to the ftp server at `ftp.myftpsite.com`. The two following lines specify the login, and the password which ftp will ask for (replace `login` and `pass` with just the login and password, without any keywords). Then, you use `mget *` to get all files. Instead of the `*`, you can use any wildcard. Finally, you use `quit` to close the `ftp` program without interactive prompt.
If you needed to enter some directory first, add a `cd` command before `mget`. It should be pretty straightforward.
Finally, write that file and run `ftp` like this:
```
ftp -i -s:yourscript
```
where `-i` disables interactivity (asking before downloading files), and `-s` specifies path to the script you created.
---
Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use [PuTTy](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) tools anyway. The one of particular interest for this case would be `pscp` which is practically the PuTTy counter-part of the openssh `scp` command.
The syntax is similar to `copy` command, and it supports wildcards:
```
pscp -batch login@mysshsite.com:iiumlabs* .
```
If you authenticate using a key file, you should pass it using `-i path-to-key-file`. If you use password, `-pw pass`. It can also reuse sessions saved using PuTTy, using the load `-load your-session-name` argument. | What about something like this:
```
for /f %%f in ('curl -s -l -u user:pass ftp://ftp.myftpsite.com/') do curl -O -u user:pass ftp://ftp.myftpsite.com/%%f
``` |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | You can use script like this for mac:
```
for f in $(curl -s -l -u user:pass ftp://your_ftp_server_ip/folder/)
do curl -O -u user:pass ftp://your_ftp_server_ip/folder/$f
done
``` | Here is how I did to download quickly with cURL (I'm not sure how many files it can download though) :
```
setlocal EnableDelayedExpansion
cd where\to\download
set STR=
for /f "skip=2 delims=" %%F in ('P:\curl -l -u user:password ftp://ftp.example.com/directory/anotherone/') do set STR=-O "ftp://ftp.example.com/directory/anotherone/%%F" !STR!
path\to\curl.exe -v -u user:password !STR!
```
Why **skip=2** ?
To get ride of `.` and `..`
Why **delims=** ?
To support names with spaces |
11,783,280 | I am using cURL to try to download all files in a certain directory.
here's what my list of files looks like:

I have tried to do in bash script: `iiumlabs.[].csv.pgp` and `iiumlabs*` and I guess curl is not big on wildcards.
```
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
```
**question:** how do i download this directory of files using cURL? | 2012/08/02 | [
"https://Stackoverflow.com/questions/11783280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117700/"
] | If you're not bound to curl, you might want to use [wget](https://www.gnu.org/software/wget/manual/wget.html) in recursive mode but restricting it to one level of recursion, try the following;
```
wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
```
* `--no-parent` : Do not ever ascend to the parent directory when retrieving recursively.
* `--level=depth` : Specify recursion maximum depth level depth. The default maximum depth is five layers.
* `--no-directories` : Do not create a hierarchy of directories when retrieving recursively. | What about something like this:
```
for /f %%f in ('curl -s -l -u user:pass ftp://ftp.myftpsite.com/') do curl -O -u user:pass ftp://ftp.myftpsite.com/%%f
``` |
70,782,592 | I'm new to React and just started working with state so please bare with me. I also found a lot of similar questions but nothing that really addresses the following:
I have a reactstrap form that has disabled FormControls. When the user clicks the 'edit' button the FormControls need to be enabled. According to my knowledge, this should be simple with JSX but nothing I've tried has worked. It might just be a stupid implementation error on my side.
```
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = {
editToggle: false,
userName: "Star Lord",
accTier: "Premium",
credit: "95 855 651",
vehicle: "The Milano",
contact: "Echoe Golf Oscar 12.465Ghz"
}
// This binding is necessary to make `this` work in the callback
this.editInputToggle = this.editInputToggle.bind(this);
}
editInputToggle() {
this.setState(prevState => ({
editToggle: !prevState.editToggle
}));
}
onValueChange = (e) => {
this.setState({ fullName: e.target.value });
};
render() {
const { editToggle } = this.state;
// We need give the components function a return statement.
return (
/* The Component can only return one parent element,
while parent elements can have many children */
<div className='profileDetails'>
{/* Bootstrap Form is used for the form
Bootstrap Button is used for the edit button */}
<Form id='formProfile'>
<Form.Group className="mb-3" controlId="formProfileDetails">
<Form.Label>US3RNAME:</Form.Label>
<Form.Control type="text" value={this.state.userName}
onChange={this.onValueChange} className='user-info' />
<Form.Label>ACC0uNT TI3R:</Form.Label>
<Form.Control disabled type="text" value={this.state.accTier} onChange={this.onValueChange} className='user-info' />
<Form.Label>CR3DiT:</Form.Label>
<Form.Control disabled type="text" value={this.state.credit} onChange={this.onValueChange} className='user-info' />
<Form.Label>R3GiSTERED VEHiCL3:</Form.Label>
<Form.Control disabled type="text" value={this.state.vehicle} onChange={this.onValueChange} className='user-info' />
<Form.Label>C0NTACT D3TAiLS:</Form.Label>
<Form.Control disabled type="text" value={this.state.contact} onChange={this.onValueChange} className='user-info' />
</Form.Group>
<Button variant="light" size="sm" className='p-2 m-4 headerBtn' onClick={ () => this.editInputToggle(editToggle) }>
Edit
</Button>
</Form>
</div>
);
}
}
```
What do I need to do to change "disabled" to ""? | 2022/01/20 | [
"https://Stackoverflow.com/questions/70782592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13848021/"
] | For enabling the FormControl,
```
<Form.Control disabled={!this.state.editToggle} type="text" value={this.state.accTier} onChange={this.onValueChange} className='user-info' />
``` | Try replacing "disabled" with this line: disabled={this.state.editToggle ? "true" : "false"} |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | **Update**, if you are running SQL Server 2012 see: <https://stackoverflow.com/a/10309947>
The problem is that the SQL Server implementation of the Over clause is [somewhat limited](http://wayback.archive.org/web/20090625062153/http://www.mydatabasesupport.com/forums/sqlserver-programming/189015-tsql-accmulations.html).
Oracle (and ANSI-SQL) allow you to do things like:
```
SELECT somedate, somevalue,
SUM(somevalue) OVER(ORDER BY somedate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS RunningTotal
FROM Table
```
SQL Server gives you no clean solution to this problem. My gut is telling me that this is one of those rare cases where a cursor is the fastest, though I will have to do some benchmarking on big results.
The update trick is handy but I feel its fairly fragile. It seems that if you are updating a full table then it will proceed in the order of the primary key. So if you set your date as a primary key ascending you will `probably` be safe. But you are relying on an undocumented SQL Server implementation detail (also if the query ends up being performed by two procs I wonder what will happen, see: MAXDOP):
Full working sample:
```
drop table #t
create table #t ( ord int primary key, total int, running_total int)
insert #t(ord,total) values (2,20)
-- notice the malicious re-ordering
insert #t(ord,total) values (1,10)
insert #t(ord,total) values (3,10)
insert #t(ord,total) values (4,1)
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
order by ord
ord total running_total
----------- ----------- -------------
1 10 10
2 20 30
3 10 40
4 1 41
```
You asked for a benchmark this is the lowdown.
The fastest SAFE way of doing this would be the Cursor, it is an order of magnitude faster than the correlated sub-query of cross-join.
The absolute fastest way is the UPDATE trick. My only concern with it is that I am not certain that under all circumstances the update will proceed in a linear way. There is nothing in the query that explicitly says so.
Bottom line, for production code I would go with the cursor.
Test data:
```
create table #t ( ord int primary key, total int, running_total int)
set nocount on
declare @i int
set @i = 0
begin tran
while @i < 10000
begin
insert #t (ord, total) values (@i, rand() * 100)
set @i = @i +1
end
commit
```
Test 1:
```
SELECT ord,total,
(SELECT SUM(total)
FROM #t b
WHERE b.ord <= a.ord) AS b
FROM #t a
-- CPU 11731, Reads 154934, Duration 11135
```
Test 2:
```
SELECT a.ord, a.total, SUM(b.total) AS RunningTotal
FROM #t a CROSS JOIN #t b
WHERE (b.ord <= a.ord)
GROUP BY a.ord,a.total
ORDER BY a.ord
-- CPU 16053, Reads 154935, Duration 4647
```
Test 3:
```
DECLARE @TotalTable table(ord int primary key, total int, running_total int)
DECLARE forward_cursor CURSOR FAST_FORWARD
FOR
SELECT ord, total
FROM #t
ORDER BY ord
OPEN forward_cursor
DECLARE @running_total int,
@ord int,
@total int
SET @running_total = 0
FETCH NEXT FROM forward_cursor INTO @ord, @total
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @running_total = @running_total + @total
INSERT @TotalTable VALUES(@ord, @total, @running_total)
FETCH NEXT FROM forward_cursor INTO @ord, @total
END
CLOSE forward_cursor
DEALLOCATE forward_cursor
SELECT * FROM @TotalTable
-- CPU 359, Reads 30392, Duration 496
```
Test 4:
```
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
-- CPU 0, Reads 58, Duration 139
``` | If you are using Sql server 2008 R2 above. Then, It would be shortest way to do;
```
Select id
,somedate
,somevalue,
LAG(runningtotal) OVER (ORDER BY somedate) + somevalue AS runningtotal
From TestTable
```
[LAG](https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql) is use to get previous row value. You can do google for more info.
[1]: |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | Using join
Another variation is to use join. Now the query could look like:
```
SELECT a.id, a.value, SUM(b.Value)FROM RunTotalTestData a,
RunTotalTestData b
WHERE b.id <= a.id
GROUP BY a.id, a.value
ORDER BY a.id;
```
for more you can visite this link
<http://askme.indianyouth.info/details/calculating-simple-running-totals-in-sql-server-12> | ```
BEGIN TRAN
CREATE TABLE #Table (_Id INT IDENTITY(1,1) ,id INT , somedate VARCHAR(100) , somevalue INT)
INSERT INTO #Table ( id , somedate , somevalue )
SELECT 45 , '01/Jan/09', 3 UNION ALL
SELECT 23 , '08/Jan/09', 5 UNION ALL
SELECT 12 , '02/Feb/09', 0 UNION ALL
SELECT 77 , '14/Feb/09', 7 UNION ALL
SELECT 39 , '20/Feb/09', 34 UNION ALL
SELECT 33 , '02/Mar/09', 6
;WITH CTE ( _Id, id , _somedate , _somevalue ,_totvalue ) AS
(
SELECT _Id , id , somedate , somevalue ,somevalue
FROM #Table WHERE _id = 1
UNION ALL
SELECT #Table._Id , #Table.id , somedate , somevalue , somevalue + _totvalue
FROM #Table,CTE
WHERE #Table._id > 1 AND CTE._Id = ( #Table._id-1 )
)
SELECT * FROM CTE
ROLLBACK TRAN
``` |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | **Update**, if you are running SQL Server 2012 see: <https://stackoverflow.com/a/10309947>
The problem is that the SQL Server implementation of the Over clause is [somewhat limited](http://wayback.archive.org/web/20090625062153/http://www.mydatabasesupport.com/forums/sqlserver-programming/189015-tsql-accmulations.html).
Oracle (and ANSI-SQL) allow you to do things like:
```
SELECT somedate, somevalue,
SUM(somevalue) OVER(ORDER BY somedate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS RunningTotal
FROM Table
```
SQL Server gives you no clean solution to this problem. My gut is telling me that this is one of those rare cases where a cursor is the fastest, though I will have to do some benchmarking on big results.
The update trick is handy but I feel its fairly fragile. It seems that if you are updating a full table then it will proceed in the order of the primary key. So if you set your date as a primary key ascending you will `probably` be safe. But you are relying on an undocumented SQL Server implementation detail (also if the query ends up being performed by two procs I wonder what will happen, see: MAXDOP):
Full working sample:
```
drop table #t
create table #t ( ord int primary key, total int, running_total int)
insert #t(ord,total) values (2,20)
-- notice the malicious re-ordering
insert #t(ord,total) values (1,10)
insert #t(ord,total) values (3,10)
insert #t(ord,total) values (4,1)
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
order by ord
ord total running_total
----------- ----------- -------------
1 10 10
2 20 30
3 10 40
4 1 41
```
You asked for a benchmark this is the lowdown.
The fastest SAFE way of doing this would be the Cursor, it is an order of magnitude faster than the correlated sub-query of cross-join.
The absolute fastest way is the UPDATE trick. My only concern with it is that I am not certain that under all circumstances the update will proceed in a linear way. There is nothing in the query that explicitly says so.
Bottom line, for production code I would go with the cursor.
Test data:
```
create table #t ( ord int primary key, total int, running_total int)
set nocount on
declare @i int
set @i = 0
begin tran
while @i < 10000
begin
insert #t (ord, total) values (@i, rand() * 100)
set @i = @i +1
end
commit
```
Test 1:
```
SELECT ord,total,
(SELECT SUM(total)
FROM #t b
WHERE b.ord <= a.ord) AS b
FROM #t a
-- CPU 11731, Reads 154934, Duration 11135
```
Test 2:
```
SELECT a.ord, a.total, SUM(b.total) AS RunningTotal
FROM #t a CROSS JOIN #t b
WHERE (b.ord <= a.ord)
GROUP BY a.ord,a.total
ORDER BY a.ord
-- CPU 16053, Reads 154935, Duration 4647
```
Test 3:
```
DECLARE @TotalTable table(ord int primary key, total int, running_total int)
DECLARE forward_cursor CURSOR FAST_FORWARD
FOR
SELECT ord, total
FROM #t
ORDER BY ord
OPEN forward_cursor
DECLARE @running_total int,
@ord int,
@total int
SET @running_total = 0
FETCH NEXT FROM forward_cursor INTO @ord, @total
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @running_total = @running_total + @total
INSERT @TotalTable VALUES(@ord, @total, @running_total)
FETCH NEXT FROM forward_cursor INTO @ord, @total
END
CLOSE forward_cursor
DEALLOCATE forward_cursor
SELECT * FROM @TotalTable
-- CPU 359, Reads 30392, Duration 496
```
Test 4:
```
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
-- CPU 0, Reads 58, Duration 139
``` | Using join
Another variation is to use join. Now the query could look like:
```
SELECT a.id, a.value, SUM(b.Value)FROM RunTotalTestData a,
RunTotalTestData b
WHERE b.id <= a.id
GROUP BY a.id, a.value
ORDER BY a.id;
```
for more you can visite this link
<http://askme.indianyouth.info/details/calculating-simple-running-totals-in-sql-server-12> |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | If you are using Sql server 2008 R2 above. Then, It would be shortest way to do;
```
Select id
,somedate
,somevalue,
LAG(runningtotal) OVER (ORDER BY somedate) + somevalue AS runningtotal
From TestTable
```
[LAG](https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql) is use to get previous row value. You can do google for more info.
[1]: | Though best way is to get it done will be using a window function, it can also be done using a simple **correlated sub-query**.
```
Select id, someday, somevalue, (select sum(somevalue)
from testtable as t2
where t2.id = t1.id
and t2.someday <= t1.someday) as runningtotal
from testtable as t1
order by id,someday;
``` |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | While Sam Saffron did great work on it, he still didn't provide **recursive common table expression** code for this problem. And for us who working with SQL Server 2008 R2 and not Denali, it's still fastest way to get running total, it's about 10 times faster than cursor on my work computer for 100000 rows, and it's also inline query.
So, here it is (I'm supposing that there's an `ord` column in the table and it's sequential number without gaps, for fast processing there also should be unique constraint on this number):
```
;with
CTE_RunningTotal
as
(
select T.ord, T.total, T.total as running_total
from #t as T
where T.ord = 0
union all
select T.ord, T.total, T.total + C.running_total as running_total
from CTE_RunningTotal as C
inner join #t as T on T.ord = C.ord + 1
)
select C.ord, C.total, C.running_total
from CTE_RunningTotal as C
option (maxrecursion 0)
-- CPU 140, Reads 110014, Duration 132
```
**`[sql fiddle demo](http://sqlfiddle.com/#!3/d41d8/6967)`**
**update**
I also was curious about this **update with variable** or **quirky update**. So usually it works ok, but how we can be sure that it works every time? well, here's a little trick (found it here - <http://www.sqlservercentral.com/Forums/Topic802558-203-21.aspx#bm981258>) - you just check current and previous `ord` and use `1/0` assignment in case they are different from what you expecting:
```
declare @total int, @ord int
select @total = 0, @ord = -1
update #t set
@total = @total + total,
@ord = case when ord <> @ord + 1 then 1/0 else ord end,
------------------------
running_total = @total
select * from #t
-- CPU 0, Reads 58, Duration 139
```
From what I've seen if you have proper clustered index/primary key on your table (in our case it would be index by `ord_id`) update will proceed in a linear way all the time (never encountered divide by zero). That said, it's up to you to decide if you want to use it in production code :)
**update 2** I'm linking this answer, cause it includes some useful info about unreliability of the quirky update - [nvarchar concatenation / index / nvarchar(max) inexplicable behavior](https://stackoverflow.com/a/15163136/1744834). | ```
SELECT TOP 25 amount,
(SELECT SUM(amount)
FROM time_detail b
WHERE b.time_detail_id <= a.time_detail_id) AS Total FROM time_detail a
```
You can also use the ROW\_NUMBER() function and a temp table to create an arbitrary column to use in the comparison on the inner SELECT statement. |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | **Update**, if you are running SQL Server 2012 see: <https://stackoverflow.com/a/10309947>
The problem is that the SQL Server implementation of the Over clause is [somewhat limited](http://wayback.archive.org/web/20090625062153/http://www.mydatabasesupport.com/forums/sqlserver-programming/189015-tsql-accmulations.html).
Oracle (and ANSI-SQL) allow you to do things like:
```
SELECT somedate, somevalue,
SUM(somevalue) OVER(ORDER BY somedate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS RunningTotal
FROM Table
```
SQL Server gives you no clean solution to this problem. My gut is telling me that this is one of those rare cases where a cursor is the fastest, though I will have to do some benchmarking on big results.
The update trick is handy but I feel its fairly fragile. It seems that if you are updating a full table then it will proceed in the order of the primary key. So if you set your date as a primary key ascending you will `probably` be safe. But you are relying on an undocumented SQL Server implementation detail (also if the query ends up being performed by two procs I wonder what will happen, see: MAXDOP):
Full working sample:
```
drop table #t
create table #t ( ord int primary key, total int, running_total int)
insert #t(ord,total) values (2,20)
-- notice the malicious re-ordering
insert #t(ord,total) values (1,10)
insert #t(ord,total) values (3,10)
insert #t(ord,total) values (4,1)
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
order by ord
ord total running_total
----------- ----------- -------------
1 10 10
2 20 30
3 10 40
4 1 41
```
You asked for a benchmark this is the lowdown.
The fastest SAFE way of doing this would be the Cursor, it is an order of magnitude faster than the correlated sub-query of cross-join.
The absolute fastest way is the UPDATE trick. My only concern with it is that I am not certain that under all circumstances the update will proceed in a linear way. There is nothing in the query that explicitly says so.
Bottom line, for production code I would go with the cursor.
Test data:
```
create table #t ( ord int primary key, total int, running_total int)
set nocount on
declare @i int
set @i = 0
begin tran
while @i < 10000
begin
insert #t (ord, total) values (@i, rand() * 100)
set @i = @i +1
end
commit
```
Test 1:
```
SELECT ord,total,
(SELECT SUM(total)
FROM #t b
WHERE b.ord <= a.ord) AS b
FROM #t a
-- CPU 11731, Reads 154934, Duration 11135
```
Test 2:
```
SELECT a.ord, a.total, SUM(b.total) AS RunningTotal
FROM #t a CROSS JOIN #t b
WHERE (b.ord <= a.ord)
GROUP BY a.ord,a.total
ORDER BY a.ord
-- CPU 16053, Reads 154935, Duration 4647
```
Test 3:
```
DECLARE @TotalTable table(ord int primary key, total int, running_total int)
DECLARE forward_cursor CURSOR FAST_FORWARD
FOR
SELECT ord, total
FROM #t
ORDER BY ord
OPEN forward_cursor
DECLARE @running_total int,
@ord int,
@total int
SET @running_total = 0
FETCH NEXT FROM forward_cursor INTO @ord, @total
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @running_total = @running_total + @total
INSERT @TotalTable VALUES(@ord, @total, @running_total)
FETCH NEXT FROM forward_cursor INTO @ord, @total
END
CLOSE forward_cursor
DEALLOCATE forward_cursor
SELECT * FROM @TotalTable
-- CPU 359, Reads 30392, Duration 496
```
Test 4:
```
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
-- CPU 0, Reads 58, Duration 139
``` | Assuming that windowing works on SQL Server 2008 like it does elsewhere (that I've tried), give this a go:
```
select testtable.*, sum(somevalue) over(order by somedate)
from testtable
order by somedate;
```
[MSDN](http://msdn.microsoft.com/en-us/library/ms189461.aspx) says it's available in SQL Server 2008 (and maybe 2005 as well?) but I don't have an instance to hand to try it.
EDIT: well, apparently SQL Server doesn't allow a window specification ("OVER(...)") without specifying "PARTITION BY" (dividing the result up into groups but not aggregating in quite the way GROUP BY does). Annoying-- the MSDN syntax reference suggests that its optional, but I only have SqlServer 2000 instances around at the moment.
The query I gave works in both Oracle 10.2.0.3.0 and PostgreSQL 8.4-beta. So tell MS to catch up ;) |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | ```
SELECT TOP 25 amount,
(SELECT SUM(amount)
FROM time_detail b
WHERE b.time_detail_id <= a.time_detail_id) AS Total FROM time_detail a
```
You can also use the ROW\_NUMBER() function and a temp table to create an arbitrary column to use in the comparison on the inner SELECT statement. | You can also denormalize - store running totals in the same table:
<http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/01/23/denormalizing-to-enforce-business-rules-running-totals.aspx>
Selects work much faster than any other solutions, but modifications may be slower |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | The APPLY operator in SQL 2005 and higher works for this:
```
select
t.id ,
t.somedate ,
t.somevalue ,
rt.runningTotal
from TestTable t
cross apply (select sum(somevalue) as runningTotal
from TestTable
where somedate <= t.somedate
) as rt
order by t.somedate
``` | Use a correlated sub-query. Very simple, here you go:
```
SELECT
somedate,
(SELECT SUM(somevalue) FROM TestTable t2 WHERE t2.somedate<=t1.somedate) AS running_total
FROM TestTable t1
GROUP BY somedate
ORDER BY somedate
```
The code might not be exactly correct, but I'm sure that the idea is.
The GROUP BY is in case a date appears more than once, you would only want to see it once in the result set.
If you don't mind seeing repeating dates, or you want to see the original value and id, then the following is what you want:
```
SELECT
id,
somedate,
somevalue,
(SELECT SUM(somevalue) FROM TestTable t2 WHERE t2.somedate<=t1.somedate) AS running_total
FROM TestTable t1
ORDER BY somedate
``` |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | If you are using Sql server 2008 R2 above. Then, It would be shortest way to do;
```
Select id
,somedate
,somevalue,
LAG(runningtotal) OVER (ORDER BY somedate) + somevalue AS runningtotal
From TestTable
```
[LAG](https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql) is use to get previous row value. You can do google for more info.
[1]: | The following will produce the required results.
```
SELECT a.SomeDate,
a.SomeValue,
SUM(b.SomeValue) AS RunningTotal
FROM TestTable a
CROSS JOIN TestTable b
WHERE (b.SomeDate <= a.SomeDate)
GROUP BY a.SomeDate,a.SomeValue
ORDER BY a.SomeDate,a.SomeValue
```
Having a clustered index on SomeDate will greatly improve the performance. |
860,966 | Imagine the following table (called `TestTable`):
```
id somedate somevalue
-- -------- ---------
45 01/Jan/09 3
23 08/Jan/09 5
12 02/Feb/09 0
77 14/Feb/09 7
39 20/Feb/09 34
33 02/Mar/09 6
```
I would like a query that returns a running total in date order, like:
```
id somedate somevalue runningtotal
-- -------- --------- ------------
45 01/Jan/09 3 3
23 08/Jan/09 5 8
12 02/Feb/09 0 8
77 14/Feb/09 7 15
39 20/Feb/09 34 49
33 02/Mar/09 6 55
```
I know there are [various ways of doing this](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) in SQL Server 2000 / 2005 / 2008.
I am particularly interested in this sort of method that uses the aggregating-set-statement trick:
```
INSERT INTO @AnotherTbl(id, somedate, somevalue, runningtotal)
SELECT id, somedate, somevalue, null
FROM TestTable
ORDER BY somedate
DECLARE @RunningTotal int
SET @RunningTotal = 0
UPDATE @AnotherTbl
SET @RunningTotal = runningtotal = @RunningTotal + somevalue
FROM @AnotherTbl
```
... this is very efficient but I have heard there are issues around this because you can't necessarily guarantee that the `UPDATE` statement will process the rows in the correct order. Maybe we can get some definitive answers about that issue.
But maybe there are other ways that people can suggest?
edit: Now with a [SqlFiddle](http://sqlfiddle.com/#!3/c8880/4) with the setup and the 'update trick' example above | 2009/05/13 | [
"https://Stackoverflow.com/questions/860966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22194/"
] | While Sam Saffron did great work on it, he still didn't provide **recursive common table expression** code for this problem. And for us who working with SQL Server 2008 R2 and not Denali, it's still fastest way to get running total, it's about 10 times faster than cursor on my work computer for 100000 rows, and it's also inline query.
So, here it is (I'm supposing that there's an `ord` column in the table and it's sequential number without gaps, for fast processing there also should be unique constraint on this number):
```
;with
CTE_RunningTotal
as
(
select T.ord, T.total, T.total as running_total
from #t as T
where T.ord = 0
union all
select T.ord, T.total, T.total + C.running_total as running_total
from CTE_RunningTotal as C
inner join #t as T on T.ord = C.ord + 1
)
select C.ord, C.total, C.running_total
from CTE_RunningTotal as C
option (maxrecursion 0)
-- CPU 140, Reads 110014, Duration 132
```
**`[sql fiddle demo](http://sqlfiddle.com/#!3/d41d8/6967)`**
**update**
I also was curious about this **update with variable** or **quirky update**. So usually it works ok, but how we can be sure that it works every time? well, here's a little trick (found it here - <http://www.sqlservercentral.com/Forums/Topic802558-203-21.aspx#bm981258>) - you just check current and previous `ord` and use `1/0` assignment in case they are different from what you expecting:
```
declare @total int, @ord int
select @total = 0, @ord = -1
update #t set
@total = @total + total,
@ord = case when ord <> @ord + 1 then 1/0 else ord end,
------------------------
running_total = @total
select * from #t
-- CPU 0, Reads 58, Duration 139
```
From what I've seen if you have proper clustered index/primary key on your table (in our case it would be index by `ord_id`) update will proceed in a linear way all the time (never encountered divide by zero). That said, it's up to you to decide if you want to use it in production code :)
**update 2** I'm linking this answer, cause it includes some useful info about unreliability of the quirky update - [nvarchar concatenation / index / nvarchar(max) inexplicable behavior](https://stackoverflow.com/a/15163136/1744834). | Assuming that windowing works on SQL Server 2008 like it does elsewhere (that I've tried), give this a go:
```
select testtable.*, sum(somevalue) over(order by somedate)
from testtable
order by somedate;
```
[MSDN](http://msdn.microsoft.com/en-us/library/ms189461.aspx) says it's available in SQL Server 2008 (and maybe 2005 as well?) but I don't have an instance to hand to try it.
EDIT: well, apparently SQL Server doesn't allow a window specification ("OVER(...)") without specifying "PARTITION BY" (dividing the result up into groups but not aggregating in quite the way GROUP BY does). Annoying-- the MSDN syntax reference suggests that its optional, but I only have SqlServer 2000 instances around at the moment.
The query I gave works in both Oracle 10.2.0.3.0 and PostgreSQL 8.4-beta. So tell MS to catch up ;) |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | ```
dict1={'a':1, 'b':'banana'}
```
To list the dictionary in Python 2.x:
```
for k,v in dict1.iteritems():
print k,v
```
In Python 3.x use:
```
for k,v in dict1.items():
print(k,v)
# a 1
# b banana
```
Finally, as others have indicated, if you want a running index, you can have that too:
```
for i in enumerate(dict1.items()):
print(i)
# (0, ('a', 1))
# (1, ('b', 'banana'))
```
But this defeats the purpose of a [dictionary (map, associative array)](https://en.wikipedia.org/wiki/Associative_array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) instead. | ```py
d = {0: 'zero', '0': 'ZERO', 1: 'one', '1': 'ONE'}
print("List of enumerated d= ", list(enumerate(d.items())))
```
output:
```
List of enumerated d= [(0, (0, 'zero')), (1, ('0', 'ZERO')), (2, (1, 'one')), (3, ('1', 'ONE'))]
``` |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | That sure must seem confusing. So this is what is going on. The first value of enumerate (in this case i) returns the next index value starting at 0 so 0, 1, 2, 3, ... It will always return these numbers regardless of what is in the dictionary. The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). What you really want to do is what roadrunner66 responded with. | ```py
d = {0: 'zero', '0': 'ZERO', 1: 'one', '1': 'ONE'}
print("List of enumerated d= ", list(enumerate(d.items())))
```
output:
```
List of enumerated d= [(0, (0, 'zero')), (1, ('0', 'ZERO')), (2, (1, 'one')), (3, ('1', 'ONE'))]
``` |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | Since you are using `enumerate` hence your `i` is actually the index of the key rather than the key itself.
So, you are getting `3` in the first column of the row `3 4`even though there is no key `3`.
`enumerate` iterates through a data structure(be it list or a dictionary) while also providing the current iteration number.
Hence, the columns here are the iteration number followed by the key in dictionary `enum`
Others Solutions have already shown how to iterate over key and value pair so I won't repeat the same in mine. | ```py
d = {0: 'zero', '0': 'ZERO', 1: 'one', '1': 'ONE'}
print("List of enumerated d= ", list(enumerate(d.items())))
```
output:
```
List of enumerated d= [(0, (0, 'zero')), (1, ('0', 'ZERO')), (2, (1, 'one')), (3, ('1', 'ONE'))]
``` |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | ```
dict1={'a':1, 'b':'banana'}
```
To list the dictionary in Python 2.x:
```
for k,v in dict1.iteritems():
print k,v
```
In Python 3.x use:
```
for k,v in dict1.items():
print(k,v)
# a 1
# b banana
```
Finally, as others have indicated, if you want a running index, you can have that too:
```
for i in enumerate(dict1.items()):
print(i)
# (0, ('a', 1))
# (1, ('b', 'banana'))
```
But this defeats the purpose of a [dictionary (map, associative array)](https://en.wikipedia.org/wiki/Associative_array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) instead. | `enumerate()` when working on list actually gives the index and the value of the items inside the list.
For example:
```
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i, j in enumerate(list):
print(i, j)
```
gives
```
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
```
where the first column denotes the index of the item and 2nd column denotes the items itself.
In a dictionary
```
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, j in enumerate(enumm):
print(i, j)
```
it gives the output
```
0 0
1 1
2 2
3 4
4 5
5 6
6 7
```
where the first column gives the index of the `key:value` pairs and the second column denotes the `keys` of the dictionary `enumm`.
So if you want the first column to be the `keys` and second columns as `values`, better try out `dict.iteritems()`[(Python 2)](https://stackoverflow.com/a/10458567/8881141) or `dict.items()` (Python 3)
```
for i, j in enumm.items():
print(i, j)
```
output
```
0 1
1 2
2 3
4 4
5 5
6 6
7 7
```
Voila |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | `enumerate()` when working on list actually gives the index and the value of the items inside the list.
For example:
```
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i, j in enumerate(list):
print(i, j)
```
gives
```
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
```
where the first column denotes the index of the item and 2nd column denotes the items itself.
In a dictionary
```
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, j in enumerate(enumm):
print(i, j)
```
it gives the output
```
0 0
1 1
2 2
3 4
4 5
5 6
6 7
```
where the first column gives the index of the `key:value` pairs and the second column denotes the `keys` of the dictionary `enumm`.
So if you want the first column to be the `keys` and second columns as `values`, better try out `dict.iteritems()`[(Python 2)](https://stackoverflow.com/a/10458567/8881141) or `dict.items()` (Python 3)
```
for i, j in enumm.items():
print(i, j)
```
output
```
0 1
1 2
2 3
4 4
5 5
6 6
7 7
```
Voila | 1. Iterating over a Python dict means to iterate over its keys exactly the same way as with `dict.keys()`
2. The order of the keys is determined by the implementation code and you cannot expect some specific order:
>
> Keys and values are iterated over in an arbitrary order which is
> non-random, varies across Python implementations, and depends on the
> dictionary’s history of insertions and deletions. If keys, values and
> items views are iterated over with no intervening modifications to the
> dictionary, the order of items will directly correspond.
>
>
>
That's why you see the indices 0 to 7 in the first column. They are produced by `enumerate` and are always in the correct order. Further you see the dict's keys 0 to 7 in the second column. They are not sorted. |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:
```
for index, (key, value) in enumerate(your_dict.items()):
print(index, key, value)
``` | ```
dict1={'a':1, 'b':'banana'}
```
To list the dictionary in Python 2.x:
```
for k,v in dict1.iteritems():
print k,v
```
In Python 3.x use:
```
for k,v in dict1.items():
print(k,v)
# a 1
# b banana
```
Finally, as others have indicated, if you want a running index, you can have that too:
```
for i in enumerate(dict1.items()):
print(i)
# (0, ('a', 1))
# (1, ('b', 'banana'))
```
But this defeats the purpose of a [dictionary (map, associative array)](https://en.wikipedia.org/wiki/Associative_array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) instead. |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | ```
dict1={'a':1, 'b':'banana'}
```
To list the dictionary in Python 2.x:
```
for k,v in dict1.iteritems():
print k,v
```
In Python 3.x use:
```
for k,v in dict1.items():
print(k,v)
# a 1
# b banana
```
Finally, as others have indicated, if you want a running index, you can have that too:
```
for i in enumerate(dict1.items()):
print(i)
# (0, ('a', 1))
# (1, ('b', 'banana'))
```
But this defeats the purpose of a [dictionary (map, associative array)](https://en.wikipedia.org/wiki/Associative_array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) instead. | Python3:
One solution:
```
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, k in enumerate(enumm):
print("{}) d.key={}, d.value={}".format(i, k, enumm[k]))
```
---
```
Output:
0) enumm.key=0, enumm.value=1
1) enumm.key=1, enumm.value=2
2) enumm.key=2, enumm.value=3
3) enumm.key=4, enumm.value=4
4) enumm.key=5, enumm.value=5
5) enumm.key=6, enumm.value=6
6) enumm.key=7, enumm.value=7
```
An another example:
```
d = {1 : {'a': 1, 'b' : 2, 'c' : 3},
2 : {'a': 10, 'b' : 20, 'c' : 30}
}
for i, k in enumerate(d):
print("{}) key={}, value={}".format(i, k, d[k])
```
---
```
Output:
0) key=1, value={'a': 1, 'b': 2, 'c': 3}
1) key=2, value={'a': 10, 'b': 20, 'c': 30}
``` |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:
```
for index, (key, value) in enumerate(your_dict.items()):
print(index, key, value)
``` | Since you are using `enumerate` hence your `i` is actually the index of the key rather than the key itself.
So, you are getting `3` in the first column of the row `3 4`even though there is no key `3`.
`enumerate` iterates through a data structure(be it list or a dictionary) while also providing the current iteration number.
Hence, the columns here are the iteration number followed by the key in dictionary `enum`
Others Solutions have already shown how to iterate over key and value pair so I won't repeat the same in mine. |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | The first column of output is the index of each item in `enumm` and the second one is its keys. If you want to iterate your dictionary then use .items():
```
for k, v in enumm.items():
print(k, v)
```
And the output should look like:
```
0 1
1 2
2 3
4 4
5 5
6 6
7 7
``` | You may find it useful to include index inside key:
```
d = {'a': 1, 'b': 2}
d = {(i, k): v for i, (k, v) in enumerate(d.items())}
```
Output:
```
{(0, 'a'): True, (1, 'b'): False}
``` |
36,244,384 | I'm trying to filter results on an HTML page by having the users select multiple options through dropdowns and text boxes.
One example is filtering results within a 10 mile radius of a user.
I have all the mechanics working but I'm not sure if I'm doing it right.
So I have something like:
<http://slickdeals.net/deals/tech/>
Where the filter options are on the left of the page, people can filter by price range, rating and so on.
So my first question is:
Using javascript how would I start tacking filter options to the URL parameters?
Right now I'm doing something like this:
```
$('#FilterLocation').on('change', function () {
window.location.replace("?lat=" + place.geometry.location.lat() + "&lng=" + place.geometry.location.lng());
});
$('#FilterPrice').on('change', function () {
window.location.replace("?price=" + #FilterPrice.val());
});
```
And the list goes on, as you can see if my filter list has 20 options, then my javascript code just starts growing and getting messy and ugly real quick.I know there has to be a better way to do this, how?
Also second question. Once we get past the part where the URL goes into my controller, I'm using PHP.. I'm returning results by just doing WHERE queries in MySQL.
So it looks like:
```
if ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal == '') {
$query = "select * from posts where ...";
} elseif (&& $State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State == '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County == 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} elseif ($State != '' && $County != 'null' && $isOnlineDeal != '') {
$query = "select * from posts where ...";
} else {
$query = "select * from posts";
}
```
As you can see, I'm just doing a bunch of elseif's to check if variables are not empty and doing queries based on that. Once my filter options start getting bigger, this also grows.
The specific data has been altered and isn't important, what I'm really trying to find out is:
1. What's the best way to tack on url params to the url with javascript/jquery.
2. Without having messy code, how do I filter those URL params in MySQL. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923236/"
] | Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:
```
for index, (key, value) in enumerate(your_dict.items()):
print(index, key, value)
``` | Python3:
One solution:
```
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, k in enumerate(enumm):
print("{}) d.key={}, d.value={}".format(i, k, enumm[k]))
```
---
```
Output:
0) enumm.key=0, enumm.value=1
1) enumm.key=1, enumm.value=2
2) enumm.key=2, enumm.value=3
3) enumm.key=4, enumm.value=4
4) enumm.key=5, enumm.value=5
5) enumm.key=6, enumm.value=6
6) enumm.key=7, enumm.value=7
```
An another example:
```
d = {1 : {'a': 1, 'b' : 2, 'c' : 3},
2 : {'a': 10, 'b' : 20, 'c' : 30}
}
for i, k in enumerate(d):
print("{}) key={}, value={}".format(i, k, d[k])
```
---
```
Output:
0) key=1, value={'a': 1, 'b': 2, 'c': 3}
1) key=2, value={'a': 10, 'b': 20, 'c': 30}
``` |
55,801,112 | I saw the following CSS code with what appears to be a triple greater than selector.
```
.b-table >>> .table-wrapper {
overflow-x: auto;
}
```
I know it's referencing a Buefy table component and applying a specific style to elements that have a `table-wrapper` class, but what does the `>>>`operator mean exactly? Based off [this answer](https://stackoverflow.com/questions/4459821/css-selector-what-is-it) I'm thinking it might be for applying styles to children of children of children, is that accurate? If so, why doesn't it seem to work with other amounts of `>`? | 2019/04/22 | [
"https://Stackoverflow.com/questions/55801112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7932229/"
] | `>>>` operator is Vue.js specific feature and called [**deep selector**](https://vue-loader.vuejs.org/guide/scoped-css.html#child-component-root-elements). In scoped CSS, you cannot apply CSS to child components without deep selector.
As your example, these two selector won't be applied.
```
<style scoped>
.table-wrapper {
overflow-x: auto !important; /* won't work */
}
.b-table .table-wrapper {
overflow-x: auto !important; /* won't work */
}
</style>
```
It needs deep selector.
```
<style scoped>
.b-table >>> .table-wrapper {
overflow-x: auto;
}
</style>
``` | It is **shadow-piercing descendant combinator**. In Angular, `>>>`, `/deep/` and `::ng-deep` are the same (source: <https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep>). It is deprecated and support has ben removed from major browsers. For example, it has been removed since Chrome version 63, around December 5 2017 (source: <https://www.chromestatus.com/feature/6750456638341120>) |
2,078,914 | Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?
```
Type k = typeof(double);
List<k> lst = new List<k>();
``` | 2010/01/16 | [
"https://Stackoverflow.com/questions/2078914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251985/"
] | Yes, there is:
```
var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);
``` | A cleaner way might be to use a generic method. Do something like this:
```
static void AddType<T>()
where T : DataObject
{
Indexes.Add(typeof(T), new Dictionary<int, T>());
}
``` |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | I'll try my shot.
---
EDIT:
After second though, to avoid global variable use it's better to do the following
```
$(document).ready(function() {
$("#toggle_value").click((function(){
var counter = 0;
return function()
{
$("#div" + counter).hide("fast");
counter = (counter % 3) + 1;
$("#div" + counter).show("fast");
}
})());
});
``` | The .toggle function in jQuery takes any number of argument functions, so the problem is already solved. See the docs under Events. |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | You should add a counter in the function.
```
$(document).ready(function() {
var count = 0;
$("#toggle_value").click(function(){
if (count == 0) {
$("#div1").show("fast");
$('#div2').hide();
count++;
}
else if (count == 1) {
$("#div2").show("fast");
...
count++;
}
else if (count == 2) {
$("#div3").show("fast");
....
count++;
}
else {
$('div').hide();
count=0;
}
});
});
``` | ```
<div id="div_<%=id>">
</div>
<div id="Hide_<%=id>" style="display:none;">
</div>
<div id="div_<%=id>">
</div>
<div id="Hide_<%=id>" style="display:none;">
</div>
<div id="div_<%=id>">
</div>
<div id="Hide_<%=id>" style="display:none;">
</div>
<div id="div_<%=id>">
</div>
<div id="Hide_<%=id>" style="display:none;">
</div>
<script>
var temp = 0;
var temp1 = 0;
$("#div_<%=id>").click(function(){
if (temp1 == 0) {
$('#' + temp).hide();
temp = 'Hide_<%=id>';
$('#Hide_<%=id>').show();
temp1 = 1;
}
else{
$('#' + temp).hide();
temp = 'Hide_<%=id>';
$('#Hide_<%=id>').show();
temp1 = 0;
}
});
</script>
``` |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | How about this
**[Working Example here](http://jsbin.com/ozape)** - add **/edit** to URL to edit the code
```
$('html').addClass('js'); // prevent hiding divs on DOM ready from 'flashing'
$(function() {
var counter = 1;
$('#toggle_value').click(function() {
$('div','#container')
// to stop current animations - clicking really fast could originally
// cause more than one div to show
.stop()
// hide all divs in the container
.hide()
// filter to only the div in question
.filter( function() { return this.id.match('div' + counter); })
// show the div
.show('fast');
// increment counter or reset to 1 if counter equals 3
counter == 3? counter = 1 : counter++;
// prevent default anchor click event
return false;
});
});
```
and HTML
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Div Example</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; }
.display { width:300px; height:200px; border: 2px solid #000; }
.js .display { display:none; }
</style>
</head>
<body>
<div class="toggle_button">
<a href="#" id="toggle_value">Toggle</a>
</div>
<br/>
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
div1
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
<div>
</body>
</html>
```
This could easily be wrapped up in a plugin | My solution is a little different - I'd do it dependant on the state of the divs at the current time (on click). See below for what I mean by this.
```
$(document).ready(function() {
$("#toggle_value").click(function(){
if ($("#div1).is(':visible')) { // Second click
// Hide all divs and show d2
$("#div1").hide();
$("#div2").show("fast");
$("#div3").hide();
$("#div4").hide();
} else if ($("#div2").is(':visible')) { // Third click
// follow above example for hiding all and showing div3
} else if ($("#div3").is(':visible')) { // Fouth click
// follow above example for hiding all and showing div1
} else { // first click
// All divs should be hidden first. Show div1 only.
$("#div1").show("fast");
}
});
});
```
Just to warn you - I have not tested this code :)
Based upon the following for determining visibility: <http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_determine_the_state_of_a_toggled_element.3F>
Hope it helps |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | I'll try my shot.
---
EDIT:
After second though, to avoid global variable use it's better to do the following
```
$(document).ready(function() {
$("#toggle_value").click((function(){
var counter = 0;
return function()
{
$("#div" + counter).hide("fast");
counter = (counter % 3) + 1;
$("#div" + counter).show("fast");
}
})());
});
``` | You should add a counter in the function.
```
$(document).ready(function() {
var count = 0;
$("#toggle_value").click(function(){
if (count == 0) {
$("#div1").show("fast");
$('#div2').hide();
count++;
}
else if (count == 1) {
$("#div2").show("fast");
...
count++;
}
else if (count == 2) {
$("#div3").show("fast");
....
count++;
}
else {
$('div').hide();
count=0;
}
});
});
``` |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | How about this
**[Working Example here](http://jsbin.com/ozape)** - add **/edit** to URL to edit the code
```
$('html').addClass('js'); // prevent hiding divs on DOM ready from 'flashing'
$(function() {
var counter = 1;
$('#toggle_value').click(function() {
$('div','#container')
// to stop current animations - clicking really fast could originally
// cause more than one div to show
.stop()
// hide all divs in the container
.hide()
// filter to only the div in question
.filter( function() { return this.id.match('div' + counter); })
// show the div
.show('fast');
// increment counter or reset to 1 if counter equals 3
counter == 3? counter = 1 : counter++;
// prevent default anchor click event
return false;
});
});
```
and HTML
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Div Example</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; }
.display { width:300px; height:200px; border: 2px solid #000; }
.js .display { display:none; }
</style>
</head>
<body>
<div class="toggle_button">
<a href="#" id="toggle_value">Toggle</a>
</div>
<br/>
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
div1
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
<div>
</body>
</html>
```
This could easily be wrapped up in a plugin | First You have to add query basic file:
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
```
Then you have to add the following code:
```
<script type="text/javascript">
$(document).ready(function () {
$("#hide").click(function(){
$(".slider_area").hide(1000);
$("#show").css("display","block");
$("#hide").css("display","none");
});
$("#show").click(function(){
$(".slider_area").show(1000);
$("#show").css("display","none");
$("#hide").css("display","block");
});
});
</script>
```
Add the code above into the header portion and the code below in the body portion.
```
<img src="images/hide-banner.png" id="hide" class="link right"/>
<img src="images/show-banner.png" id="show" class="link right dis" />
```
The code is ready for the different image click for show and hide div. |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | How about this
**[Working Example here](http://jsbin.com/ozape)** - add **/edit** to URL to edit the code
```
$('html').addClass('js'); // prevent hiding divs on DOM ready from 'flashing'
$(function() {
var counter = 1;
$('#toggle_value').click(function() {
$('div','#container')
// to stop current animations - clicking really fast could originally
// cause more than one div to show
.stop()
// hide all divs in the container
.hide()
// filter to only the div in question
.filter( function() { return this.id.match('div' + counter); })
// show the div
.show('fast');
// increment counter or reset to 1 if counter equals 3
counter == 3? counter = 1 : counter++;
// prevent default anchor click event
return false;
});
});
```
and HTML
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Div Example</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; }
.display { width:300px; height:200px; border: 2px solid #000; }
.js .display { display:none; }
</style>
</head>
<body>
<div class="toggle_button">
<a href="#" id="toggle_value">Toggle</a>
</div>
<br/>
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
div1
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
<div>
</body>
</html>
```
This could easily be wrapped up in a plugin | The .toggle function in jQuery takes any number of argument functions, so the problem is already solved. See the docs under Events. |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | I'll try my shot.
---
EDIT:
After second though, to avoid global variable use it's better to do the following
```
$(document).ready(function() {
$("#toggle_value").click((function(){
var counter = 0;
return function()
{
$("#div" + counter).hide("fast");
counter = (counter % 3) + 1;
$("#div" + counter).show("fast");
}
})());
});
``` | I would probably do something like: (The following assumes all your `<div>`s are in a container with id "container")
```
$(document).ready(function() {
var $allDivs = $("#container > div");
var counter = 0;
$("#container > div").click(function(){
counter = counter < $allDivs.length - 1 ? counter + 1 : 0;
$allDivs.not(":eq("+counter +")").hide("fast");
$allDivs.eq(counter).show("fast");
});
});
``` |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | How about this
**[Working Example here](http://jsbin.com/ozape)** - add **/edit** to URL to edit the code
```
$('html').addClass('js'); // prevent hiding divs on DOM ready from 'flashing'
$(function() {
var counter = 1;
$('#toggle_value').click(function() {
$('div','#container')
// to stop current animations - clicking really fast could originally
// cause more than one div to show
.stop()
// hide all divs in the container
.hide()
// filter to only the div in question
.filter( function() { return this.id.match('div' + counter); })
// show the div
.show('fast');
// increment counter or reset to 1 if counter equals 3
counter == 3? counter = 1 : counter++;
// prevent default anchor click event
return false;
});
});
```
and HTML
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Div Example</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; }
.display { width:300px; height:200px; border: 2px solid #000; }
.js .display { display:none; }
</style>
</head>
<body>
<div class="toggle_button">
<a href="#" id="toggle_value">Toggle</a>
</div>
<br/>
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
div1
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
<div>
</body>
</html>
```
This could easily be wrapped up in a plugin | ```
$("#toggle_value").click(function()
{
$("#div" + (++c) % 3).show().siblings().hide();
}
``` |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | I'll try my shot.
---
EDIT:
After second though, to avoid global variable use it's better to do the following
```
$(document).ready(function() {
$("#toggle_value").click((function(){
var counter = 0;
return function()
{
$("#div" + counter).hide("fast");
counter = (counter % 3) + 1;
$("#div" + counter).show("fast");
}
})());
});
``` | My solution is a little different - I'd do it dependant on the state of the divs at the current time (on click). See below for what I mean by this.
```
$(document).ready(function() {
$("#toggle_value").click(function(){
if ($("#div1).is(':visible')) { // Second click
// Hide all divs and show d2
$("#div1").hide();
$("#div2").show("fast");
$("#div3").hide();
$("#div4").hide();
} else if ($("#div2").is(':visible')) { // Third click
// follow above example for hiding all and showing div3
} else if ($("#div3").is(':visible')) { // Fouth click
// follow above example for hiding all and showing div1
} else { // first click
// All divs should be hidden first. Show div1 only.
$("#div1").show("fast");
}
});
});
```
Just to warn you - I have not tested this code :)
Based upon the following for determining visibility: <http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_determine_the_state_of_a_toggled_element.3F>
Hope it helps |
914,558 | I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
>
> ***Code Follows:***
>
>
>
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
>
> ***Jquery Code :***
>
>
>
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | 2009/05/27 | [
"https://Stackoverflow.com/questions/914558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98807/"
] | I'll try my shot.
---
EDIT:
After second though, to avoid global variable use it's better to do the following
```
$(document).ready(function() {
$("#toggle_value").click((function(){
var counter = 0;
return function()
{
$("#div" + counter).hide("fast");
counter = (counter % 3) + 1;
$("#div" + counter).show("fast");
}
})());
});
``` | ```
var c = 1;
$("#toggle_value").click(function()
{
$("#div" + c).hide("fast");
$("#div" + ++c).show("fast");
if (c > 3) c=1;
});
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.