qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
I do not know why this code ever worked. In no version of the C++ standard is a scalar stream object comparable to an integer *or* to `nullptr_t`. That being said, your question is not how to fix the code you've found but how to bypass the error. **I do not recommend doing what I'm about to say here in production code.** It's a hack, and it's only designed to get an unusual library like this working. The `==` operator can be defined outside of any class, as a standalone function. The library you're using compares `std::ofstream` to `long int`. Let's make that comparison valid. ``` bool operator==(const std::ofstream&, long int) { return false; } ``` Now your code will compile. But it will probably run incorrectly. You could try making the comparison smarter by having it check whether the `std::ofstream` is truthy. ``` bool operator==(const std::ofstream& out, long int n) { return (bool)out == (bool)n; } ``` Now it's a bit smarter. But there's no silver bullet here. The code you were given is *not working and not standard C++*, so there's no fullproof way to get it working without changing the actual library code. So my suggestion is to fork the repository and fix the broken line of code yourself.
Without knowing the rest of the code, you can just try to rephrase that line such as: if(!dFile) See what happens next.
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
My guess is this (`if(dFile==NULL){`) if condition is trying to check whether a file was open successfully for writing, if so you use function `is_open` which is available in c++. So simply replace the condition by `if (dFile.is_open())`. This should do the trick.
Without knowing the rest of the code, you can just try to rephrase that line such as: if(!dFile) See what happens next.
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
In C++ 98 the streams used to have an `operator void*()` to check the stream state. It returned a null pointer when the stream was in an error state. Turned out that this implicit conversion caused some unexpected results when accidentally invoked in odd places. So in C++11, which gained explicit operators, it was turned into an [`explicit operator bool()`](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool) instead. This returns `true` for a good state and `false` when the stream is in a failed state. Being `explicit` it can also only be used in places where a `bool` is expected. This removes most of the unexpected conversions from the old operator. So `if(dFile==NULL)`, testing for a non-good state of the stream, is now written `if (!dFile)`. And actually, the tests `if (dfile)` (good state) and `if (!dFile)` (non-good state) have always worked. The comparison against `NULL` has never been required, it just happened to work when the operator returned a `void*`.
Without knowing the rest of the code, you can just try to rephrase that line such as: if(!dFile) See what happens next.
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
In C++ 98 the streams used to have an `operator void*()` to check the stream state. It returned a null pointer when the stream was in an error state. Turned out that this implicit conversion caused some unexpected results when accidentally invoked in odd places. So in C++11, which gained explicit operators, it was turned into an [`explicit operator bool()`](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool) instead. This returns `true` for a good state and `false` when the stream is in a failed state. Being `explicit` it can also only be used in places where a `bool` is expected. This removes most of the unexpected conversions from the old operator. So `if(dFile==NULL)`, testing for a non-good state of the stream, is now written `if (!dFile)`. And actually, the tests `if (dfile)` (good state) and `if (!dFile)` (non-good state) have always worked. The comparison against `NULL` has never been required, it just happened to work when the operator returned a `void*`.
I do not know why this code ever worked. In no version of the C++ standard is a scalar stream object comparable to an integer *or* to `nullptr_t`. That being said, your question is not how to fix the code you've found but how to bypass the error. **I do not recommend doing what I'm about to say here in production code.** It's a hack, and it's only designed to get an unusual library like this working. The `==` operator can be defined outside of any class, as a standalone function. The library you're using compares `std::ofstream` to `long int`. Let's make that comparison valid. ``` bool operator==(const std::ofstream&, long int) { return false; } ``` Now your code will compile. But it will probably run incorrectly. You could try making the comparison smarter by having it check whether the `std::ofstream` is truthy. ``` bool operator==(const std::ofstream& out, long int n) { return (bool)out == (bool)n; } ``` Now it's a bit smarter. But there's no silver bullet here. The code you were given is *not working and not standard C++*, so there's no fullproof way to get it working without changing the actual library code. So my suggestion is to fork the repository and fix the broken line of code yourself.
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
In C++ 98 the streams used to have an `operator void*()` to check the stream state. It returned a null pointer when the stream was in an error state. Turned out that this implicit conversion caused some unexpected results when accidentally invoked in odd places. So in C++11, which gained explicit operators, it was turned into an [`explicit operator bool()`](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool) instead. This returns `true` for a good state and `false` when the stream is in a failed state. Being `explicit` it can also only be used in places where a `bool` is expected. This removes most of the unexpected conversions from the old operator. So `if(dFile==NULL)`, testing for a non-good state of the stream, is now written `if (!dFile)`. And actually, the tests `if (dfile)` (good state) and `if (!dFile)` (non-good state) have always worked. The comparison against `NULL` has never been required, it just happened to work when the operator returned a `void*`.
My guess is this (`if(dFile==NULL){`) if condition is trying to check whether a file was open successfully for writing, if so you use function `is_open` which is available in c++. So simply replace the condition by `if (dFile.is_open())`. This should do the trick.
3,698,733
> > **Theorem.** If two figures are similar and have the same orientation then there exists a homothecy that takes one of them into the other. > > > I see this result is being used pretty often in problems involving homothecy, but I don't know how to prove it. I know the reciprocal is true. If we have two figures and there exists a homothecy that takes one into the other, then the figures are similar and have the same orientation. Please help me with a proof of the theorem. I am a beginner in homothecy.
2020/05/30
[ "https://math.stackexchange.com/questions/3698733", "https://math.stackexchange.com", "https://math.stackexchange.com/users/463062/" ]
Let's assume that the two figures aren't congruent (the "center" of the homothety will be at infinity). Let's call the corresponding points on the two figures $A$ and $A'$. Firstly, let's prove the theorem is true for triangles. > > **Theorem:** If two triangles $ABC$ and $A'B'C'$ are similar with ratio $r$ with the same orientation, then there is a homothety from one to the other. > > > **Proof:** [![enter image description here](https://i.stack.imgur.com/B5rgp.png)](https://i.stack.imgur.com/B5rgp.png) Let $P$ be the intersection of $AA'$ and $BB'$, and consider the homothety $\varphi$ sending $A\to A'$ and $B\to B'$ (because $AB||A'B',\triangle PAB\sim \triangle PA'B'$ so the ratios $$\frac{PA}{PA'}=\frac{PB}{PB'}$$ are equal, and thus such a homothety exists. Let's consider where $\varphi(C)$ is. Because $\varphi$ sends $A\to A'$ and $AC||AC'$, we know that $\varphi(C)$ lies on ray $A'C'$. How far along this ray? Well, we know that $A'B'C'=rABC$ is the scaling up factor, and thus $C'$ lies at distance $rAC$ from $A'$. However, we also know that $\varphi$ takes $AB$ to $A'B'$ so $\varphi$ also scales everything up by $r$. Hence, $$|\varphi(AC)|=r|AC|=|A'C'|$$ and thus $$C\xrightarrow{\;\;\;\varphi\;\;\;}C'\;\;\square$$ How does this help with the general case? Well, consider two similar figures $\mathcal F$ and $\mathcal F'$. If each of these is a single point, then obviously there's a homothety between them. Otherwise, fix any $A,B\in\mathcal F$, find the corresponding $A',B'\in\mathcal F'$, and consider defining $P,\varphi$ as before. Then for any other $C\in\mathcal F$, we know by the triangle theorem that $\varphi(C)=C'$, the corresponding point on $\mathcal F'$. Hence the two figures are related by the homothety $\varphi$ centered at $P$.
You can just join two pairs of corresponding points. The obtained lines meet at the center of homothety. If they are parallel, your center is located at infinity.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
It doesn't make a difference in this case, because + is a special case that can apply to any number of arguments. Reduce is a way to apply a function that expects a fixed number of arguments (2) to an arbitrarily long list of arguments.
A bit late, but... In this case, there is not a big difference. But in general they are not equivalent. Further more reduce can be more performant. Why? reduce checks if a collection or type implements [IReduced](https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L6810) interface. That means a type knows how provide its values to the reducing function in the most performant why. reduce can be stopped prematurely by returning a Reduced value. Apply on the other hand, is invoked by [applyToHelper](https://github.com/clojure/clojure/blob/38bafca9e76cd6625d8dce5fb6d16b87845c8b9d/src/jvm/clojure/lang/AFn.java#L147). Which dispatches to the right arity by counting the args, unpacking the values from the collection. Is it a big performance impact? Probably not. My opinion is as others already pointed out. Use reduce if you want to semantically "reduce" a collection to a single value. Otherwise use apply.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
`reduce` and `apply` are of course only equivalent (in terms of the ultimate result returned) for associative functions which need to see all their arguments in the variable-arity case. When they are result-wise equivalent, I'd say that `apply` is always perfectly idiomatic, while `reduce` is equivalent -- and might shave off a fraction of a blink of an eye -- in a lot of the common cases. What follows is my rationale for believing this. `+` is itself implemented in terms of `reduce` for the variable-arity case (more than 2 arguments). Indeed, this seems like an immensely sensible "default" way to go for any variable-arity, associative function: `reduce` has the potential to perform some optimisations to speed things up -- perhaps through something like `internal-reduce`, a 1.2 novelty recently disabled in master, but hopefully to be reintroduced in the future -- which it would be silly to replicate in every function which might benefit from them in the vararg case. In such common cases, `apply` will just add a little overhead. (Note it's nothing to be really worried about.) On the other hand, a complex function might take advantage of some optimisation opportunities which aren't general enough to be built into `reduce`; then `apply` would let you take advantage of those while `reduce` might actually slow you down. A good example of the latter scenario occuring in practice is provided by `str`: it uses a `StringBuilder` internally and will benefit significantly from the use of `apply` rather than `reduce`. So, I'd say use `apply` when in doubt; and if you happen to know that it's not buying you anything over `reduce` (and that this is unlikely to change very soon), feel free to use `reduce` to shave off that diminutive unnecessary overhead if you feel like it.
For newbies looking at this answer, be careful, they are not the same: ``` (apply hash-map [:a 5 :b 6]) ;= {:a 5, :b 6} (reduce hash-map [:a 5 :b 6]) ;= {{{:a 5} :b} 6} ```
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
For newbies looking at this answer, be careful, they are not the same: ``` (apply hash-map [:a 5 :b 6]) ;= {:a 5, :b 6} (reduce hash-map [:a 5 :b 6]) ;= {{{:a 5} :b} 6} ```
Opinions vary- In the greater Lisp world, `reduce` is definitely considered more idiomatic. First, there is the variadic issues already discussed. Also, some Common Lisp compilers will actually fail when `apply` is applied against very long lists because of how they handle argument lists. Amongst Clojurists in my circle, though, using `apply` in this case seems more common. I find it easier to grok and prefer it also.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
I normally find myself preferring reduce when acting on any kind of collection - it performs well, and is a pretty useful function in general. The main reason I would use apply is if the parameters mean different things in different positions, or if you have a couple of initial parameters but want to get the rest from a collection, e.g. ``` (apply + 1 2 other-number-list) ```
When using a simple function like +, it really doesn't matter which one you use. In general, the idea is that `reduce` is an accumulating operation. You present the current accumulation value and one new value to your accumulating function The result of the function is the cumulative value for the next iteration. So, your iterations look like: ``` cum-val[i+1] = F( cum-val[i], input-val[i] ) ; please forgive the java-like syntax! ``` For apply, the idea is that you are attempting to call a function expecting a number of scalar arguments, but they are currently in a collection and need to be pulled out. So, instead of saying: ``` vals = [ val1 val2 val3 ] (some-fn (vals 0) (vals 1) (vals 2)) ``` we can say: ``` (apply some-fn vals) ``` and it is converted to be equivalent to: ``` (some-fn val1 val2 val3) ``` So, using "apply" is like "removing the parentheses" around the sequence.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
When using a simple function like +, it really doesn't matter which one you use. In general, the idea is that `reduce` is an accumulating operation. You present the current accumulation value and one new value to your accumulating function The result of the function is the cumulative value for the next iteration. So, your iterations look like: ``` cum-val[i+1] = F( cum-val[i], input-val[i] ) ; please forgive the java-like syntax! ``` For apply, the idea is that you are attempting to call a function expecting a number of scalar arguments, but they are currently in a collection and need to be pulled out. So, instead of saying: ``` vals = [ val1 val2 val3 ] (some-fn (vals 0) (vals 1) (vals 2)) ``` we can say: ``` (apply some-fn vals) ``` and it is converted to be equivalent to: ``` (some-fn val1 val2 val3) ``` So, using "apply" is like "removing the parentheses" around the sequence.
The beauty of apply is given function (+ in this case) can be applied to argument list formed by pre-pending intervening arguments with an ending collection. Reduce is an abstraction to process collection items applying the function for each and doesn't work with variable args case. ``` (apply + 1 2 3 [3 4]) => 13 (reduce + 1 2 3 [3 4]) ArityException Wrong number of args (5) passed to: core/reduce clojure.lang.AFn.throwArity (AFn.java:429) ```
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
Opinions vary- In the greater Lisp world, `reduce` is definitely considered more idiomatic. First, there is the variadic issues already discussed. Also, some Common Lisp compilers will actually fail when `apply` is applied against very long lists because of how they handle argument lists. Amongst Clojurists in my circle, though, using `apply` in this case seems more common. I find it easier to grok and prefer it also.
A bit late, but... In this case, there is not a big difference. But in general they are not equivalent. Further more reduce can be more performant. Why? reduce checks if a collection or type implements [IReduced](https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L6810) interface. That means a type knows how provide its values to the reducing function in the most performant why. reduce can be stopped prematurely by returning a Reduced value. Apply on the other hand, is invoked by [applyToHelper](https://github.com/clojure/clojure/blob/38bafca9e76cd6625d8dce5fb6d16b87845c8b9d/src/jvm/clojure/lang/AFn.java#L147). Which dispatches to the right arity by counting the args, unpacking the values from the collection. Is it a big performance impact? Probably not. My opinion is as others already pointed out. Use reduce if you want to semantically "reduce" a collection to a single value. Otherwise use apply.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
`reduce` and `apply` are of course only equivalent (in terms of the ultimate result returned) for associative functions which need to see all their arguments in the variable-arity case. When they are result-wise equivalent, I'd say that `apply` is always perfectly idiomatic, while `reduce` is equivalent -- and might shave off a fraction of a blink of an eye -- in a lot of the common cases. What follows is my rationale for believing this. `+` is itself implemented in terms of `reduce` for the variable-arity case (more than 2 arguments). Indeed, this seems like an immensely sensible "default" way to go for any variable-arity, associative function: `reduce` has the potential to perform some optimisations to speed things up -- perhaps through something like `internal-reduce`, a 1.2 novelty recently disabled in master, but hopefully to be reintroduced in the future -- which it would be silly to replicate in every function which might benefit from them in the vararg case. In such common cases, `apply` will just add a little overhead. (Note it's nothing to be really worried about.) On the other hand, a complex function might take advantage of some optimisation opportunities which aren't general enough to be built into `reduce`; then `apply` would let you take advantage of those while `reduce` might actually slow you down. A good example of the latter scenario occuring in practice is provided by `str`: it uses a `StringBuilder` internally and will benefit significantly from the use of `apply` rather than `reduce`. So, I'd say use `apply` when in doubt; and if you happen to know that it's not buying you anything over `reduce` (and that this is unlikely to change very soon), feel free to use `reduce` to shave off that diminutive unnecessary overhead if you feel like it.
I normally find myself preferring reduce when acting on any kind of collection - it performs well, and is a pretty useful function in general. The main reason I would use apply is if the parameters mean different things in different positions, or if you have a couple of initial parameters but want to get the rest from a collection, e.g. ``` (apply + 1 2 other-number-list) ```
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
`reduce` and `apply` are of course only equivalent (in terms of the ultimate result returned) for associative functions which need to see all their arguments in the variable-arity case. When they are result-wise equivalent, I'd say that `apply` is always perfectly idiomatic, while `reduce` is equivalent -- and might shave off a fraction of a blink of an eye -- in a lot of the common cases. What follows is my rationale for believing this. `+` is itself implemented in terms of `reduce` for the variable-arity case (more than 2 arguments). Indeed, this seems like an immensely sensible "default" way to go for any variable-arity, associative function: `reduce` has the potential to perform some optimisations to speed things up -- perhaps through something like `internal-reduce`, a 1.2 novelty recently disabled in master, but hopefully to be reintroduced in the future -- which it would be silly to replicate in every function which might benefit from them in the vararg case. In such common cases, `apply` will just add a little overhead. (Note it's nothing to be really worried about.) On the other hand, a complex function might take advantage of some optimisation opportunities which aren't general enough to be built into `reduce`; then `apply` would let you take advantage of those while `reduce` might actually slow you down. A good example of the latter scenario occuring in practice is provided by `str`: it uses a `StringBuilder` internally and will benefit significantly from the use of `apply` rather than `reduce`. So, I'd say use `apply` when in doubt; and if you happen to know that it's not buying you anything over `reduce` (and that this is unlikely to change very soon), feel free to use `reduce` to shave off that diminutive unnecessary overhead if you feel like it.
The beauty of apply is given function (+ in this case) can be applied to argument list formed by pre-pending intervening arguments with an ending collection. Reduce is an abstraction to process collection items applying the function for each and doesn't work with variable args case. ``` (apply + 1 2 3 [3 4]) => 13 (reduce + 1 2 3 [3 4]) ArityException Wrong number of args (5) passed to: core/reduce clojure.lang.AFn.throwArity (AFn.java:429) ```
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
For newbies looking at this answer, be careful, they are not the same: ``` (apply hash-map [:a 5 :b 6]) ;= {:a 5, :b 6} (reduce hash-map [:a 5 :b 6]) ;= {{{:a 5} :b} 6} ```
When using a simple function like +, it really doesn't matter which one you use. In general, the idea is that `reduce` is an accumulating operation. You present the current accumulation value and one new value to your accumulating function The result of the function is the cumulative value for the next iteration. So, your iterations look like: ``` cum-val[i+1] = F( cum-val[i], input-val[i] ) ; please forgive the java-like syntax! ``` For apply, the idea is that you are attempting to call a function expecting a number of scalar arguments, but they are currently in a collection and need to be pulled out. So, instead of saying: ``` vals = [ val1 val2 val3 ] (some-fn (vals 0) (vals 1) (vals 2)) ``` we can say: ``` (apply some-fn vals) ``` and it is converted to be equivalent to: ``` (some-fn val1 val2 val3) ``` So, using "apply" is like "removing the parentheses" around the sequence.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
In this specific case I prefer `reduce` because it's more **readable**: when I read ``` (reduce + some-numbers) ``` I know immediately that you're turning a sequence into a value. With `apply` I have to consider which function is being applied: "ah, it's the `+` function, so I'm getting... a single number". Slightly less straightforward.
When using a simple function like +, it really doesn't matter which one you use. In general, the idea is that `reduce` is an accumulating operation. You present the current accumulation value and one new value to your accumulating function The result of the function is the cumulative value for the next iteration. So, your iterations look like: ``` cum-val[i+1] = F( cum-val[i], input-val[i] ) ; please forgive the java-like syntax! ``` For apply, the idea is that you are attempting to call a function expecting a number of scalar arguments, but they are currently in a collection and need to be pulled out. So, instead of saying: ``` vals = [ val1 val2 val3 ] (some-fn (vals 0) (vals 1) (vals 2)) ``` we can say: ``` (apply some-fn vals) ``` and it is converted to be equivalent to: ``` (some-fn val1 val2 val3) ``` So, using "apply" is like "removing the parentheses" around the sequence.
22,932
I would like to include a file on every block but the last three. How can I accomplish this?
2017/11/22
[ "https://craftcms.stackexchange.com/questions/22932", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/7395/" ]
95% of the time you see a 400 Bad Request error, it's because it's a CSRF token validation error (or you're just missing the token all-together). Craft 3 has CSRF validation enabled by default. Here's how to pass the CSRF token to your JS in Craft 2: <https://craftcms.com/support/csrf-protection#updating-your-javascript> Here's the CSRF token changes in Craft 3 you'll need to change: <https://docs.craftcms.com/v3/changes-in-craft-3.html#csrf-token-params>
For Craft3 in JS you can use `var tokenInput = Craft.getCsrfInput();` to get the HTML input or `Craft.csrfTokenName` and `Craft.csrfTokenValue` for the Name and Value. Then your post url should be `<form method="post" action="actions/plugin/default/ajax-call" accept-charset="UTF-8">` And finally in the controller ``` public function actionAjaxCall() { $result = 'Welcome to the DefaultController actionAjaxCall() method'; return $result; } ``` That should be all you need
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
You don't have to export a file using the Excel format in order to get the data into Excel. It is generally much easier to export to `CSV`. `CSV` files should be associated with Excel by default, so it should have the Excel icon by it and everything. `XML` would work the same way, I think, but the `CSV` format is much lighter, and does the same job in this case. Converting `JSON` to `CSV` is simple: ``` var response = JSON.parse(responseJSON).response; var csv = arrayToCSV(response); function arrayToCSV(arr) { var columnNames = []; var rows = []; for (var i=0, len=arr.length; i<len; i++) { // Each obj represents a row in the table var obj = arr[i]; // row will collect data from obj var row = []; for (var key in obj) { // Don't iterate through prototype stuff if (!obj.hasOwnProperty(key)) continue; // Collect the column names only once if (i === 0) columnNames.push(prepareValueForCSV(key)); // Collect the data row.push(prepareValueForCSV(obj[key])); } // Push each row to the main collection as csv string rows.push(row.join(',')); } // Put the columnNames at the beginning of all the rows rows.unshift(columnNames.join(',')); // Return the csv string return rows.join('\n'); } // This function allows us to have commas, line breaks, and double // quotes in our value without breaking CSV format. function prepareValueForCSV(val) { val = '' + val; // Escape quotes to avoid ending the value prematurely. val = val.replace(/"/g, '""'); return '"' + val + '"'; } ```
I'm working with MOSS 2007 to export some lists(say 5 lists) to excel.My requirement is i need more than one lists to be exported to excel.I have added a CEWP in my page with a button so that by one click i can export more than one list datas to excel.nw i get a run time error when i use jquery if( $('#WebPartWPQ3').is(':visible') )--->object expected error. I dont find any div id to trace..so is anybody know the answer,pls be come out of it.. ans related to this issue is really really really appreciated..my code is as follows. ``` <button type="button" onclick=exportToExcel();>Click<br> </button><br> <script type="text/javascript"><br> function exportToExcel() <br> { <br> alert('Hi');<br> //alert($("#WebPartWPQ3").attr("visibility"));<br> if( $('#WebPartWPQ3').is(':visible') )<br> { <br> contentType = "application/vnd.ms-excel";<br> var oExcel = new ActiveXObject("Excel.Application");<br> var oBook = oExcel.Workbooks.Add;<br> var oSheet = oBook.Worksheets(1);<br> var VESSApplications =document.getElementById<br>('ctl00_m_g_e3f5d791_5651_40ca_a03a_1c511c7f2b28_ctl00_ctl00_toolBarTbl');<br> alert(document.getElementById('WebPartWPQ3'));<br> var OtherApplications =document.getElementById('tblOtherApplications');<br> // var MFGApplications =document.getElementById('tblMFGApplications');<br> var row=3;<br> var col=1;<br> //Define criteria - start<br> oSheet.Cells(row, col)="Business Function";<br> oSheet.Cells(row, col+1)="VESS";<br> oSheet.Cells(row, col+2)=selectedVESSBusinessFunction;<br> // oSheet.Cells(row, col+3)="Manufacturing";<br> // if(selectedMFGBusinessFunction != "-Select-")<br> // oSheet.Cells(row, col+4)=selectedMFGBusinessFunction;<br> row +=2;<br> oSheet.Cells(row, col)="Operating System";<br> oSheet.Cells(row, col+1)="First Choice";<br> if(selectedOperatingSystemFirstChoice != "-Select-")<br> oSheet.Cells(row, col+2)=selectedOperatingSystemFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedOperatingSystemSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedOperatingSystemSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Platform";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedPlatformFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedPlatformSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedPlatformSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Delivery Method";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedDeliveryFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedDeliverySecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedDeliverySecondChoice;<br> row +=2;<br> //alert(VESSApplications.rows.length);<br> if(VESSApplications.rows.length>0)<br> {<br> for (var y = 0; y < VESSApplications.rows.length; y++) <br> {<br> for (var x = 0; x < VESSApplications .rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> // oExcel.Visible = true;<br> // oExcel.UserControl = true;<br> }<br> else<br> {<br> alert("There is no VESS/Other Applications to Export!");<br> }<br> row +=2;<br> //Other Applications<br> /* for (var y = 0; y < OtherApplications.rows.length; y++) <br> {<br> for (var x = 0; x < OtherApplications.rows(y).cells.length; x++) <br> {<br> oSheet.Cells(row, x + 1) = OtherApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> row +=2;<br> //MFG Applications<br> for (var y = 0; y < MFGApplications.rows.length; y++) <br> {<br> for (var x = 0; x < MFGApplications.rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = MFGApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> */ oSheet.columns.autofit;<br> oExcel.Visible = true;<br> oExcel.UserControl = true;<br> }<br> else<br> {<br> alert('No VESS/Other applications available to export');<br> }<br> }<br> ```
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
You don't have to export a file using the Excel format in order to get the data into Excel. It is generally much easier to export to `CSV`. `CSV` files should be associated with Excel by default, so it should have the Excel icon by it and everything. `XML` would work the same way, I think, but the `CSV` format is much lighter, and does the same job in this case. Converting `JSON` to `CSV` is simple: ``` var response = JSON.parse(responseJSON).response; var csv = arrayToCSV(response); function arrayToCSV(arr) { var columnNames = []; var rows = []; for (var i=0, len=arr.length; i<len; i++) { // Each obj represents a row in the table var obj = arr[i]; // row will collect data from obj var row = []; for (var key in obj) { // Don't iterate through prototype stuff if (!obj.hasOwnProperty(key)) continue; // Collect the column names only once if (i === 0) columnNames.push(prepareValueForCSV(key)); // Collect the data row.push(prepareValueForCSV(obj[key])); } // Push each row to the main collection as csv string rows.push(row.join(',')); } // Put the columnNames at the beginning of all the rows rows.unshift(columnNames.join(',')); // Return the csv string return rows.join('\n'); } // This function allows us to have commas, line breaks, and double // quotes in our value without breaking CSV format. function prepareValueForCSV(val) { val = '' + val; // Escape quotes to avoid ending the value prematurely. val = val.replace(/"/g, '""'); return '"' + val + '"'; } ```
> > I have a jqGrid where I get data at once from server (java) in JSON > format. I want the data in the jqGrid to be exported into Excel > format. > > > Here's a nice article, showing you how to export from jqGrid to Excel... <http://www.codeproject.com/Articles/784342/Export-data-from-jqGrid-into-a-real-Excel-file>
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
You don't have to export a file using the Excel format in order to get the data into Excel. It is generally much easier to export to `CSV`. `CSV` files should be associated with Excel by default, so it should have the Excel icon by it and everything. `XML` would work the same way, I think, but the `CSV` format is much lighter, and does the same job in this case. Converting `JSON` to `CSV` is simple: ``` var response = JSON.parse(responseJSON).response; var csv = arrayToCSV(response); function arrayToCSV(arr) { var columnNames = []; var rows = []; for (var i=0, len=arr.length; i<len; i++) { // Each obj represents a row in the table var obj = arr[i]; // row will collect data from obj var row = []; for (var key in obj) { // Don't iterate through prototype stuff if (!obj.hasOwnProperty(key)) continue; // Collect the column names only once if (i === 0) columnNames.push(prepareValueForCSV(key)); // Collect the data row.push(prepareValueForCSV(obj[key])); } // Push each row to the main collection as csv string rows.push(row.join(',')); } // Put the columnNames at the beginning of all the rows rows.unshift(columnNames.join(',')); // Return the csv string return rows.join('\n'); } // This function allows us to have commas, line breaks, and double // quotes in our value without breaking CSV format. function prepareValueForCSV(val) { val = '' + val; // Escape quotes to avoid ending the value prematurely. val = val.replace(/"/g, '""'); return '"' + val + '"'; } ```
I solved this like this: 1. **Read** <https://w3lessons.info/2015/07/13/export-html-table-to-excel-csv-json-pdf-png-using-jquery/#Installation> 2. Here is **github** <https://github.com/kayalshri/tableExport.jquery.plugin> 3. Here is a **demo** <http://demos.w3lessons.info/jquery-table-export#> It works perfectly i tried the **Export Excel**. In my case i just used the id selector for the jqgrid table. **BTW** This will export only visible part so if you 100 pages it need server side because info is just not there !.
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
> > I have a jqGrid where I get data at once from server (java) in JSON > format. I want the data in the jqGrid to be exported into Excel > format. > > > Here's a nice article, showing you how to export from jqGrid to Excel... <http://www.codeproject.com/Articles/784342/Export-data-from-jqGrid-into-a-real-Excel-file>
I'm working with MOSS 2007 to export some lists(say 5 lists) to excel.My requirement is i need more than one lists to be exported to excel.I have added a CEWP in my page with a button so that by one click i can export more than one list datas to excel.nw i get a run time error when i use jquery if( $('#WebPartWPQ3').is(':visible') )--->object expected error. I dont find any div id to trace..so is anybody know the answer,pls be come out of it.. ans related to this issue is really really really appreciated..my code is as follows. ``` <button type="button" onclick=exportToExcel();>Click<br> </button><br> <script type="text/javascript"><br> function exportToExcel() <br> { <br> alert('Hi');<br> //alert($("#WebPartWPQ3").attr("visibility"));<br> if( $('#WebPartWPQ3').is(':visible') )<br> { <br> contentType = "application/vnd.ms-excel";<br> var oExcel = new ActiveXObject("Excel.Application");<br> var oBook = oExcel.Workbooks.Add;<br> var oSheet = oBook.Worksheets(1);<br> var VESSApplications =document.getElementById<br>('ctl00_m_g_e3f5d791_5651_40ca_a03a_1c511c7f2b28_ctl00_ctl00_toolBarTbl');<br> alert(document.getElementById('WebPartWPQ3'));<br> var OtherApplications =document.getElementById('tblOtherApplications');<br> // var MFGApplications =document.getElementById('tblMFGApplications');<br> var row=3;<br> var col=1;<br> //Define criteria - start<br> oSheet.Cells(row, col)="Business Function";<br> oSheet.Cells(row, col+1)="VESS";<br> oSheet.Cells(row, col+2)=selectedVESSBusinessFunction;<br> // oSheet.Cells(row, col+3)="Manufacturing";<br> // if(selectedMFGBusinessFunction != "-Select-")<br> // oSheet.Cells(row, col+4)=selectedMFGBusinessFunction;<br> row +=2;<br> oSheet.Cells(row, col)="Operating System";<br> oSheet.Cells(row, col+1)="First Choice";<br> if(selectedOperatingSystemFirstChoice != "-Select-")<br> oSheet.Cells(row, col+2)=selectedOperatingSystemFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedOperatingSystemSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedOperatingSystemSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Platform";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedPlatformFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedPlatformSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedPlatformSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Delivery Method";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedDeliveryFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedDeliverySecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedDeliverySecondChoice;<br> row +=2;<br> //alert(VESSApplications.rows.length);<br> if(VESSApplications.rows.length>0)<br> {<br> for (var y = 0; y < VESSApplications.rows.length; y++) <br> {<br> for (var x = 0; x < VESSApplications .rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> // oExcel.Visible = true;<br> // oExcel.UserControl = true;<br> }<br> else<br> {<br> alert("There is no VESS/Other Applications to Export!");<br> }<br> row +=2;<br> //Other Applications<br> /* for (var y = 0; y < OtherApplications.rows.length; y++) <br> {<br> for (var x = 0; x < OtherApplications.rows(y).cells.length; x++) <br> {<br> oSheet.Cells(row, x + 1) = OtherApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> row +=2;<br> //MFG Applications<br> for (var y = 0; y < MFGApplications.rows.length; y++) <br> {<br> for (var x = 0; x < MFGApplications.rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = MFGApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> */ oSheet.columns.autofit;<br> oExcel.Visible = true;<br> oExcel.UserControl = true;<br> }<br> else<br> {<br> alert('No VESS/Other applications available to export');<br> }<br> }<br> ```
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
I solved this like this: 1. **Read** <https://w3lessons.info/2015/07/13/export-html-table-to-excel-csv-json-pdf-png-using-jquery/#Installation> 2. Here is **github** <https://github.com/kayalshri/tableExport.jquery.plugin> 3. Here is a **demo** <http://demos.w3lessons.info/jquery-table-export#> It works perfectly i tried the **Export Excel**. In my case i just used the id selector for the jqgrid table. **BTW** This will export only visible part so if you 100 pages it need server side because info is just not there !.
I'm working with MOSS 2007 to export some lists(say 5 lists) to excel.My requirement is i need more than one lists to be exported to excel.I have added a CEWP in my page with a button so that by one click i can export more than one list datas to excel.nw i get a run time error when i use jquery if( $('#WebPartWPQ3').is(':visible') )--->object expected error. I dont find any div id to trace..so is anybody know the answer,pls be come out of it.. ans related to this issue is really really really appreciated..my code is as follows. ``` <button type="button" onclick=exportToExcel();>Click<br> </button><br> <script type="text/javascript"><br> function exportToExcel() <br> { <br> alert('Hi');<br> //alert($("#WebPartWPQ3").attr("visibility"));<br> if( $('#WebPartWPQ3').is(':visible') )<br> { <br> contentType = "application/vnd.ms-excel";<br> var oExcel = new ActiveXObject("Excel.Application");<br> var oBook = oExcel.Workbooks.Add;<br> var oSheet = oBook.Worksheets(1);<br> var VESSApplications =document.getElementById<br>('ctl00_m_g_e3f5d791_5651_40ca_a03a_1c511c7f2b28_ctl00_ctl00_toolBarTbl');<br> alert(document.getElementById('WebPartWPQ3'));<br> var OtherApplications =document.getElementById('tblOtherApplications');<br> // var MFGApplications =document.getElementById('tblMFGApplications');<br> var row=3;<br> var col=1;<br> //Define criteria - start<br> oSheet.Cells(row, col)="Business Function";<br> oSheet.Cells(row, col+1)="VESS";<br> oSheet.Cells(row, col+2)=selectedVESSBusinessFunction;<br> // oSheet.Cells(row, col+3)="Manufacturing";<br> // if(selectedMFGBusinessFunction != "-Select-")<br> // oSheet.Cells(row, col+4)=selectedMFGBusinessFunction;<br> row +=2;<br> oSheet.Cells(row, col)="Operating System";<br> oSheet.Cells(row, col+1)="First Choice";<br> if(selectedOperatingSystemFirstChoice != "-Select-")<br> oSheet.Cells(row, col+2)=selectedOperatingSystemFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedOperatingSystemSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedOperatingSystemSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Platform";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedPlatformFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedPlatformSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedPlatformSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Delivery Method";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedDeliveryFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedDeliverySecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedDeliverySecondChoice;<br> row +=2;<br> //alert(VESSApplications.rows.length);<br> if(VESSApplications.rows.length>0)<br> {<br> for (var y = 0; y < VESSApplications.rows.length; y++) <br> {<br> for (var x = 0; x < VESSApplications .rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> // oExcel.Visible = true;<br> // oExcel.UserControl = true;<br> }<br> else<br> {<br> alert("There is no VESS/Other Applications to Export!");<br> }<br> row +=2;<br> //Other Applications<br> /* for (var y = 0; y < OtherApplications.rows.length; y++) <br> {<br> for (var x = 0; x < OtherApplications.rows(y).cells.length; x++) <br> {<br> oSheet.Cells(row, x + 1) = OtherApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> row +=2;<br> //MFG Applications<br> for (var y = 0; y < MFGApplications.rows.length; y++) <br> {<br> for (var x = 0; x < MFGApplications.rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = MFGApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> */ oSheet.columns.autofit;<br> oExcel.Visible = true;<br> oExcel.UserControl = true;<br> }<br> else<br> {<br> alert('No VESS/Other applications available to export');<br> }<br> }<br> ```
10,393,457
I took out my arduino chip from my board and followed the instructions to put it on a breadboard here: <http://itp.nyu.edu/physcomp/uploads/arduinobb_09.jpg> Everything works fine but when I plug in an XBee, the code doesnt work the way it should. The code I was using was two simple statements in the `setup()` function 1. Starting the Serial port: `Serial.begin(9600);` 2. Printing a line: `Serial.println("Hello World");` The problem is that it repeatedly sends this message over the XBee and I can see from the receiver XBee that it rapidly sends `"Hello World"` over and over. Also, if I check the voltage supplied by the voltage regulator, it is only 3.7 volts rather than 5 volts. Why is this happening?
2012/05/01
[ "https://Stackoverflow.com/questions/10393457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986955/" ]
The likely explanation as to why `setup()` is being executed continually is that the chip is being repeatedly reset. This is likely to be related to the low voltage you are seeing.
Yea sorry about this guys. I finally figured out the problem. The batteries I was using were not delivering enough current and power to supply both the arduino and xbee. The thing is, since the batteries were cheap, they ran out really quick of charge and I thought that it was a problem. Better batteries were the solution however.
1,156,915
I have to find all the unit vectors that are orthogonal to the vectors $\overrightarrow{a}=(2, -4, 3), \overrightarrow{b}=(-4, 8, -6)$ . I calculated that the cross product $\overrightarrow{a} \times \overrightarrow{b}=0$. Does this mean that the vector $(0, 0, 0)$ is a unit vector that is perpendicular to $\overrightarrow{a}$ and $\overrightarrow{b}$ ??
2015/02/20
[ "https://math.stackexchange.com/questions/1156915", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
Given two sequences $x\_n$ and $y\_n$, we have the relation $$ x\_n\leq y\_n\Rightarrow \sum\_n x\_n\leq \sum\_n y\_n. $$ Therefore, if we set $x\_n=\sum^{\infty}\_{j=1}|I\_{n\_j}|$ and $y\_n=\frac{\epsilon }{2^n}$, applying the above gives $$ \sum\_n\sum^{\infty}\_{j=1}|I\_{n\_j}|<\sum\_n\frac{\epsilon}{2^n} $$
Equalities and inequalities with series of series are preserved under exchanging order of summation indices and also taking inner limits before outer limits, vs. summing all the terms in any order you want, so long as the series are either all positive or all negative terms. Thus you don't have to worry about the double summation and how it affects the inequality.
1,156,915
I have to find all the unit vectors that are orthogonal to the vectors $\overrightarrow{a}=(2, -4, 3), \overrightarrow{b}=(-4, 8, -6)$ . I calculated that the cross product $\overrightarrow{a} \times \overrightarrow{b}=0$. Does this mean that the vector $(0, 0, 0)$ is a unit vector that is perpendicular to $\overrightarrow{a}$ and $\overrightarrow{b}$ ??
2015/02/20
[ "https://math.stackexchange.com/questions/1156915", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
We're exploiting Zeno's Paradox. Since each set has measure $0$, we can cover it by intervals whose total length is less than any positive real number. Since the union is countable, we can enumerate our sets of measure $0$ as $\{I\_1, I\_2, I\_3, \ldots, \}$. Let $\mu(S) = (b-a)$ for $S=(a,b)$. Let $\epsilon > 0$. Let $I\_j$ be covered by an open covering so that $$\mu(A\_j) < \frac{\epsilon}{2^j}$$ $$I\_j \subset A\_j$$ Then, since $\mu$ is countably sub-additive, $$\mu\left(\bigcup\_{j=1}^{\infty} I\_j \right) \leq \sum\_{j=1}^{\infty} \mu(I\_j) \leq \sum\_{j=1}^{\infty} \mu(A\_j) = \sum\_{j=1}^{\infty} \frac{\epsilon}{2^j} = \epsilon.$$ Thus, our set has measure 0. This is nice because we're able to do a countable number of ''things'' with only an epsilon of room.
Equalities and inequalities with series of series are preserved under exchanging order of summation indices and also taking inner limits before outer limits, vs. summing all the terms in any order you want, so long as the series are either all positive or all negative terms. Thus you don't have to worry about the double summation and how it affects the inequality.
1,156,915
I have to find all the unit vectors that are orthogonal to the vectors $\overrightarrow{a}=(2, -4, 3), \overrightarrow{b}=(-4, 8, -6)$ . I calculated that the cross product $\overrightarrow{a} \times \overrightarrow{b}=0$. Does this mean that the vector $(0, 0, 0)$ is a unit vector that is perpendicular to $\overrightarrow{a}$ and $\overrightarrow{b}$ ??
2015/02/20
[ "https://math.stackexchange.com/questions/1156915", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
That's just how measures work. We start by defining that the measure of an open interval $(a,b)$ is $b-a$. Then we can attempt to define the (outer) measure of an arbitrary set $A$ as the infimum of all $\sum\_{i\in J}\mu(I\_i)$ where the $I\_j$ are open intervals and $A\subseteq \bigcup\_{i\in J}I\_i$. A few observations: * If more than countably many of the $\mu(I\_i)$ are nonzero, then certainly $\sum\_{i\in J}\mu(I\_i)=\infty$. Therefore and as any set $A\subseteq \mathbb R$ allows a countable cover, we nay restrict to the case that $J$ is countable. * With the extended definition, we still have $\mu((a,b))=b-a$. One shows by induction that $\sum\_{i\in J}\mu(I\_i)\ge b-a$ if $A\subseteq \bigcup\_{i\in J}I\_i$ with finite $J$, and then extends this to the case of countable $J$ (and larger $J$ need not be considered) Now given countably many $X\_k$, $k\in\mathbb N$, with $\mu(X\_k)=0$, and given $\epsilon>0$, by definition as infimum we find covers $X\_k\subseteq \bigcup\_{j\in J\_k}I\_{k,j}$ with $\sum\_{j\in J\_k}\mu(I\_{k,j})<2^{-k}\epsilon$. By the above we may assume that $J\_k=\mathbb N$. Then $$ X:=\bigcup\_{k\in\mathbb N}X\_k\subseteq\bigcup\_{k\in\mathbb N}\bigcup\_{j\in\mathbb N}I\_{k,j}=\bigcup\_{(k,j)\in\mathbb N\times\mathbb N}I\_{k,j}$$ with $$ \sum\_{(k,j)\in\mathbb N\times\mathbb N}\mu(I\_{k,j})=\sum\_{k\in\mathbb N}\sum\_{j\in\mathbb N}\mu(I\_{k,j})<\sum\_{k\in\mathbb N}2^{-k}\epsilon=\epsilon$$ so that $\mu(X)<\epsilon$. As $\epsilon$ was an arbitrary positive number, the infimum over all $\sum\_{i\in J}\mu(I\_i)$ for covers $X\subseteq \bigcup\_{i\in J}\mu(I\_j)$ is certainly $0$.
Equalities and inequalities with series of series are preserved under exchanging order of summation indices and also taking inner limits before outer limits, vs. summing all the terms in any order you want, so long as the series are either all positive or all negative terms. Thus you don't have to worry about the double summation and how it affects the inequality.
146,274
So I have a bunch of database users who should be able to execute a procedure with a call to xp\_cmdshell. They are not windows domain accounts, they are just sql-server logins. I want to do it using a proxy `##xp_cmdshell_proxy_account##`. I am aware of security threats that it may bring. I cannot use 'WITH EXECUTE AS admin' due to our company inner version control and I obviously do not want to grant all of the users rights to execute `xp_cmdshell`, that is why my only choice (am I right here?) is using the proxy account. I have a special windows-domain account for it, to whom I granted xp\_cmdshell execution rights. I can successfully execute cmdshell using this account. I created the proxy account using the following command: ``` EXEC sp_xp_cmdshell_proxy_account [my_domain\special_account],'SuperSecretPassword' ``` When I try to execute any xp\_cmdshell command as a database user with no xp\_cmdshell rights an error appears: ``` The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'. ``` My question is - can I execute a xp\_cmdshell command using an sql server login and I am simply missing something here or is it only possible using a domain account? Is there any other procedure to follow here to make it happen? If I fail to make the above work I will have to switch some logic to a CLR procedure, but I am determined to make it work. I am using sql-server 2012. Any help will be appreciated, thanks!
2016/08/09
[ "https://dba.stackexchange.com/questions/146274", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/88793/" ]
It appears you need to grant access to xp\_cmdshell for your sql server login. Once the user has permission to run xp\_cmdshell, it will use your proxy account to run it since it is a non-privileged user. Another alternative would be to use certificates to sign your stored procedures, allowing you to grant additional privileges for users executing that stored procedure. <https://msdn.microsoft.com/en-us/library/bb283630.aspx> The downside of certificates is that the procedure needs to be re-signed every time you make a change to it, which can be a pain.
The question is: what exactly are you using `xp_cmdshell` for? Is it to run a random program, or get a directory listing, or something else? You seem to be avoiding SQLCLR but you don't say why. In many cases, SQLCLR is more secure and more efficient. But it is not possible to be more specific unless additional details are provided regarding what the ultimate goal is. Outside of that, you can grant permissions in a highly targeted manner using signatures (@Shane also mentioned this). You can find an example of doing this in my answer to the following question, also here on DBA.StackExchange: [What minimum permissions do I need to provide to a user so that it can check the status of SQL Server Agent Service?](https://dba.stackexchange.com/questions/62230/what-minimum-permissions-do-i-need-to-provide-to-a-user-so-that-it-can-check-the/103275#103275) The basic concept is that you will: 1. Create a Certificate in the `master` Database 2. Create a Login based on this Certificate 3. Grant this Login the appropriate permission to run `xp_cmdshell` 4. Backup the Certificate 5. Restore the Certificate into the Database that has the Stored Procedure that is calling `xp_cmdshell` 6. Sign the Stored Procedure that is calling `xp_cmdshell` via [ADD SIGNATURE](https://msdn.microsoft.com/en-us/library/ms181700.aspx) Additional links to other variations of examples can be found in my answer to this question: [stored procedure can select and update tables in other databases - minimal permissions granted](https://dba.stackexchange.com/questions/131005/stored-procedure-can-select-and-update-tables-in-other-databases-minimal-permi/131026#131026)
146,274
So I have a bunch of database users who should be able to execute a procedure with a call to xp\_cmdshell. They are not windows domain accounts, they are just sql-server logins. I want to do it using a proxy `##xp_cmdshell_proxy_account##`. I am aware of security threats that it may bring. I cannot use 'WITH EXECUTE AS admin' due to our company inner version control and I obviously do not want to grant all of the users rights to execute `xp_cmdshell`, that is why my only choice (am I right here?) is using the proxy account. I have a special windows-domain account for it, to whom I granted xp\_cmdshell execution rights. I can successfully execute cmdshell using this account. I created the proxy account using the following command: ``` EXEC sp_xp_cmdshell_proxy_account [my_domain\special_account],'SuperSecretPassword' ``` When I try to execute any xp\_cmdshell command as a database user with no xp\_cmdshell rights an error appears: ``` The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'. ``` My question is - can I execute a xp\_cmdshell command using an sql server login and I am simply missing something here or is it only possible using a domain account? Is there any other procedure to follow here to make it happen? If I fail to make the above work I will have to switch some logic to a CLR procedure, but I am determined to make it work. I am using sql-server 2012. Any help will be appreciated, thanks!
2016/08/09
[ "https://dba.stackexchange.com/questions/146274", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/88793/" ]
You can use a SQL Server login. The following procedure is explained in [MSDN](https://msdn.microsoft.com/en-us/library/ms175046(v=sql.110).aspx): > > To allow non-administrators to use xp\_cmdshell, and allow SQL Server > to create child processes with the security token of a less-privileged > account, follow these steps: > > > 1. Create and customize a Windows local user account or a domain account with the least privileges that your processes require. > 2. Use the sp\_xp\_cmdshell\_proxy\_account system procedure to configure xp\_cmdshell to use that least-privileged account. > Note You can also configure this proxy account using SQL > Server Management Studio by right-clicking Properties on your server > name in Object Explorer, and looking on the Security tab for the > Server proxy account section. > 3. In Management Studio, using the master > database, execute the GRANT exec ON xp\_cmdshell TO '' > statement to give specific non-sysadmin users the ability to execute > xp\_cmdshell. The specified login must be mapped to a user in the > master database. > > >
The question is: what exactly are you using `xp_cmdshell` for? Is it to run a random program, or get a directory listing, or something else? You seem to be avoiding SQLCLR but you don't say why. In many cases, SQLCLR is more secure and more efficient. But it is not possible to be more specific unless additional details are provided regarding what the ultimate goal is. Outside of that, you can grant permissions in a highly targeted manner using signatures (@Shane also mentioned this). You can find an example of doing this in my answer to the following question, also here on DBA.StackExchange: [What minimum permissions do I need to provide to a user so that it can check the status of SQL Server Agent Service?](https://dba.stackexchange.com/questions/62230/what-minimum-permissions-do-i-need-to-provide-to-a-user-so-that-it-can-check-the/103275#103275) The basic concept is that you will: 1. Create a Certificate in the `master` Database 2. Create a Login based on this Certificate 3. Grant this Login the appropriate permission to run `xp_cmdshell` 4. Backup the Certificate 5. Restore the Certificate into the Database that has the Stored Procedure that is calling `xp_cmdshell` 6. Sign the Stored Procedure that is calling `xp_cmdshell` via [ADD SIGNATURE](https://msdn.microsoft.com/en-us/library/ms181700.aspx) Additional links to other variations of examples can be found in my answer to this question: [stored procedure can select and update tables in other databases - minimal permissions granted](https://dba.stackexchange.com/questions/131005/stored-procedure-can-select-and-update-tables-in-other-databases-minimal-permi/131026#131026)
2,581,664
I have two fields that need to multiply each other and fill a third form's value. Here's the HTML: ``` <input type="text" name="estimate[concrete][price]" value="" onBlur="calc_concreteprice(document.forms.mainform);" /> per SF <strong>times</strong> <input type="text" name="estimate[concrete][sqft]" value="" onBlur="calc_concreteprice(document.forms.mainform);" /> SF = <input type="text" name="estimate[concrete][quick_total]" value="" /> ``` Here's my JavaScript: ``` function calc_concreteprice(mainform) { var oprice; var ototal; oprice = ((mainform.estimate[concrete][sqft].value) * (mainform.estimate[concrete][price].value)); ototal = (oprice); mainform.estimate[concrete][quick_total].value = ototal; } ``` I want the first two forms to be multiplied together and output to the third. I think my problem may be within how I am referencing the input field names, with brackets (I'm taking results from this form as an array so I'm already used to working with the results as a multi-dimensional array).
2010/04/05
[ "https://Stackoverflow.com/questions/2581664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60318/" ]
When you write things like `mainform.estimate[concrete][quick_total].value`, it's attempting to access properties called `concrete` and `quick_total`. Try using this format instead to distinguish between a property and a string containing square brackets: `mainform['estimate[concrete][quick_total]'].value`
I'm pretty sure it's the square brackets. Try changing your names on your input fields. If you want definite separation between the names to show some sort of hierarchy, try using underscores like `<input type="text" name="estimate_concrete_price" />`. In your javascript change it to `mainform.estimate_concrete_price.value`..... Give that a shot. I'm pretty sure it will work.
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
You can use Outer APPLY or CROSS APPLY as per Below example, ``` SELECT C.Name_Client + ' - ' + V.Name_Country FROM Clients C OUTER APPLY( SELECT TOP 1 * FROM Countries CO WHERE CO.ID_Client = C.ID_Client ORDER BY ID_Country ) V ```
[SQL Fiddle](http://sqlfiddle.com/#!18/2ee07/7) **MS SQL Server 2017 Schema Setup**: ``` CREATE TABLE CLIENTS (ID_Client int,Name_Client varchar(255)) CREATE TABLE COUNTRIES(ID_Country int,ID_Client int,Name_Country varchar(255)) INSERT INTO CLIENTS(ID_Client,Name_Client)VALUES(1,'Mike'),(2,'Jon'),(3,'Ben') INSERT INTO COUNTRIES(ID_Country,ID_Client,Name_Country)VALUES(1,1,'France'), (2,1,'USA'),(3,1,'England'), (4,2,'Portugal'),(5,2,'Spain'), (6,3,'Germany') ``` **Query 1**: ``` with CTE as ( select c.Name_Client, ct.Name_Country, row_number() over(partition by c.ID_Client order by ct.ID_Country) as rn FROM CLIENTS c left join COUNTRIES ct on c.ID_Client=ct.ID_Client ) select CTE.Name_Client,CTE.Name_Country from CTE where rn=1 ``` **[Results](http://sqlfiddle.com/#!18/2ee07/7/0)**: ``` | Name_Client | Name_Country | |-------------|--------------| | Mike | France | | Jon | Portugal | | Ben | Germany | ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
Your sub-query isn't correlated, try to use `APPLY` : ``` SELECT c.Name_Client, cn.Name_Country FROM Clients C OUTER APPLY (SELECT TOP (1) cn.Name_Country From Countries CN WHERE cn.ID_Client = c.ID_Client ORDER BY cn.ID_Country ) cn; ```
use row\_number() ``` with cte as ( select c.Name_Client, cn.Name_Country, row_number() over(partition by c.ID_Client order by ID_Country) rn clients c join country cn on c.client_id=cn.client_id ) select * form cte where rn=1 ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
You can use Outer APPLY or CROSS APPLY as per Below example, ``` SELECT C.Name_Client + ' - ' + V.Name_Country FROM Clients C OUTER APPLY( SELECT TOP 1 * FROM Countries CO WHERE CO.ID_Client = C.ID_Client ORDER BY ID_Country ) V ```
use row\_number() ``` with cte as ( select c.Name_Client, cn.Name_Country, row_number() over(partition by c.ID_Client order by ID_Country) rn clients c join country cn on c.client_id=cn.client_id ) select * form cte where rn=1 ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
Your sub-query isn't correlated, try to use `APPLY` : ``` SELECT c.Name_Client, cn.Name_Country FROM Clients C OUTER APPLY (SELECT TOP (1) cn.Name_Country From Countries CN WHERE cn.ID_Client = c.ID_Client ORDER BY cn.ID_Country ) cn; ```
[SQL Fiddle](http://sqlfiddle.com/#!18/2ee07/7) **MS SQL Server 2017 Schema Setup**: ``` CREATE TABLE CLIENTS (ID_Client int,Name_Client varchar(255)) CREATE TABLE COUNTRIES(ID_Country int,ID_Client int,Name_Country varchar(255)) INSERT INTO CLIENTS(ID_Client,Name_Client)VALUES(1,'Mike'),(2,'Jon'),(3,'Ben') INSERT INTO COUNTRIES(ID_Country,ID_Client,Name_Country)VALUES(1,1,'France'), (2,1,'USA'),(3,1,'England'), (4,2,'Portugal'),(5,2,'Spain'), (6,3,'Germany') ``` **Query 1**: ``` with CTE as ( select c.Name_Client, ct.Name_Country, row_number() over(partition by c.ID_Client order by ct.ID_Country) as rn FROM CLIENTS c left join COUNTRIES ct on c.ID_Client=ct.ID_Client ) select CTE.Name_Client,CTE.Name_Country from CTE where rn=1 ``` **[Results](http://sqlfiddle.com/#!18/2ee07/7/0)**: ``` | Name_Client | Name_Country | |-------------|--------------| | Mike | France | | Jon | Portugal | | Ben | Germany | ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
[SQL Fiddle](http://sqlfiddle.com/#!18/2ee07/7) **MS SQL Server 2017 Schema Setup**: ``` CREATE TABLE CLIENTS (ID_Client int,Name_Client varchar(255)) CREATE TABLE COUNTRIES(ID_Country int,ID_Client int,Name_Country varchar(255)) INSERT INTO CLIENTS(ID_Client,Name_Client)VALUES(1,'Mike'),(2,'Jon'),(3,'Ben') INSERT INTO COUNTRIES(ID_Country,ID_Client,Name_Country)VALUES(1,1,'France'), (2,1,'USA'),(3,1,'England'), (4,2,'Portugal'),(5,2,'Spain'), (6,3,'Germany') ``` **Query 1**: ``` with CTE as ( select c.Name_Client, ct.Name_Country, row_number() over(partition by c.ID_Client order by ct.ID_Country) as rn FROM CLIENTS c left join COUNTRIES ct on c.ID_Client=ct.ID_Client ) select CTE.Name_Client,CTE.Name_Country from CTE where rn=1 ``` **[Results](http://sqlfiddle.com/#!18/2ee07/7/0)**: ``` | Name_Client | Name_Country | |-------------|--------------| | Mike | France | | Jon | Portugal | | Ben | Germany | ```
You can try this ``` SELECT * FROM ( SELECT Name_Client, Name_Country , RwNumbr = ROW_NUMBER() OVER(PARTITION by c.ID_Client order by cl.ID_Country) from CLIENTS c JOIN COUNTRIES cl ON cl.ID_Client = c.ID_Client ) as f WHERE f.RwNumbr = 1 ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
You can use Outer APPLY or CROSS APPLY as per Below example, ``` SELECT C.Name_Client + ' - ' + V.Name_Country FROM Clients C OUTER APPLY( SELECT TOP 1 * FROM Countries CO WHERE CO.ID_Client = C.ID_Client ORDER BY ID_Country ) V ```
You can use common table expression and filter on the row number partitioned by the id\_client. Like this the row\_number is incremented until a new id\_client is found. ``` WITH cte_countries AS( SELECT ROW_NUMBER() OVER (PARTITION BY ID_Client ORDER BY ID_Client) AS Row#, Countries.* FROM Countries) SELECT * FROM Clients cli JOIN cte_countries coun ON cli.ID_Client = coun.ID_Client WHERE coun.Row# = 1 ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
You can use Outer APPLY or CROSS APPLY as per Below example, ``` SELECT C.Name_Client + ' - ' + V.Name_Country FROM Clients C OUTER APPLY( SELECT TOP 1 * FROM Countries CO WHERE CO.ID_Client = C.ID_Client ORDER BY ID_Country ) V ```
You can try this ``` SELECT * FROM ( SELECT Name_Client, Name_Country , RwNumbr = ROW_NUMBER() OVER(PARTITION by c.ID_Client order by cl.ID_Country) from CLIENTS c JOIN COUNTRIES cl ON cl.ID_Client = c.ID_Client ) as f WHERE f.RwNumbr = 1 ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
[SQL Fiddle](http://sqlfiddle.com/#!18/2ee07/7) **MS SQL Server 2017 Schema Setup**: ``` CREATE TABLE CLIENTS (ID_Client int,Name_Client varchar(255)) CREATE TABLE COUNTRIES(ID_Country int,ID_Client int,Name_Country varchar(255)) INSERT INTO CLIENTS(ID_Client,Name_Client)VALUES(1,'Mike'),(2,'Jon'),(3,'Ben') INSERT INTO COUNTRIES(ID_Country,ID_Client,Name_Country)VALUES(1,1,'France'), (2,1,'USA'),(3,1,'England'), (4,2,'Portugal'),(5,2,'Spain'), (6,3,'Germany') ``` **Query 1**: ``` with CTE as ( select c.Name_Client, ct.Name_Country, row_number() over(partition by c.ID_Client order by ct.ID_Country) as rn FROM CLIENTS c left join COUNTRIES ct on c.ID_Client=ct.ID_Client ) select CTE.Name_Client,CTE.Name_Country from CTE where rn=1 ``` **[Results](http://sqlfiddle.com/#!18/2ee07/7/0)**: ``` | Name_Client | Name_Country | |-------------|--------------| | Mike | France | | Jon | Portugal | | Ben | Germany | ```
You can use common table expression and filter on the row number partitioned by the id\_client. Like this the row\_number is incremented until a new id\_client is found. ``` WITH cte_countries AS( SELECT ROW_NUMBER() OVER (PARTITION BY ID_Client ORDER BY ID_Client) AS Row#, Countries.* FROM Countries) SELECT * FROM Clients cli JOIN cte_countries coun ON cli.ID_Client = coun.ID_Client WHERE coun.Row# = 1 ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
Your sub-query isn't correlated, try to use `APPLY` : ``` SELECT c.Name_Client, cn.Name_Country FROM Clients C OUTER APPLY (SELECT TOP (1) cn.Name_Country From Countries CN WHERE cn.ID_Client = c.ID_Client ORDER BY cn.ID_Country ) cn; ```
You can use Outer APPLY or CROSS APPLY as per Below example, ``` SELECT C.Name_Client + ' - ' + V.Name_Country FROM Clients C OUTER APPLY( SELECT TOP 1 * FROM Countries CO WHERE CO.ID_Client = C.ID_Client ORDER BY ID_Country ) V ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
Your sub-query isn't correlated, try to use `APPLY` : ``` SELECT c.Name_Client, cn.Name_Country FROM Clients C OUTER APPLY (SELECT TOP (1) cn.Name_Country From Countries CN WHERE cn.ID_Client = c.ID_Client ORDER BY cn.ID_Country ) cn; ```
Rather than having a nested query like this try this instead. ``` SELECT clients.Name_Client, countries.Name_Country FROM Clients clients LEFT JOIN Countries countries on countries.ID_Client = clients.ID_Client ``` By performing the join you are matching the record and not having a subquery go off and get a bucket load of bad data.
2,890,172
I am planning to build a JS based twitter client. Information about libraries/clients is pretty old on other SO Questions. I was wondering if anyone has come across wrappers other than Spaz and TwitterHelper. Addition : Please note this will be client app which I also plan to run on mobiles using phonegap. Thanks :-)
2010/05/22
[ "https://Stackoverflow.com/questions/2890172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/304673/" ]
[SQLyog's](http://www.webyog.com) [HTTP Tunnel](http://gist.github.com/410502) is a very decent one. ![enter image description here](https://i.stack.imgur.com/GWsFJ.png)
try use HTTPtunnel GNU. here example [connection to MySQL using HTTPtunnel GNU.](http://mysql-tools.com/en/articles/http-tunnel/73-heidisql-a-http-tunnel.html)
2,890,172
I am planning to build a JS based twitter client. Information about libraries/clients is pretty old on other SO Questions. I was wondering if anyone has come across wrappers other than Spaz and TwitterHelper. Addition : Please note this will be client app which I also plan to run on mobiles using phonegap. Thanks :-)
2010/05/22
[ "https://Stackoverflow.com/questions/2890172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/304673/" ]
[SQLyog's](http://www.webyog.com) [HTTP Tunnel](http://gist.github.com/410502) is a very decent one. ![enter image description here](https://i.stack.imgur.com/GWsFJ.png)
You can use TCP/IP over SSH from within MySQL Workbench and SQLyog without the need for PHP tunnelling script if you have SSH access to you server. I have had customer sites on shared hosts where this doesn't work due to server configuration which is out of my control. I have overcome this restriction via SSH tunnelling which has the added benefit of being encrypted (Obviously this will only work if you have SSH access to the host however), although noted, the original post asked for a HTTP tunnel. To setup SSH Tunnelling in SQLyog, on the MySQL tab for your connection, enter you MySQL credentials as you normally would for a local user on the host (replace 'root' and password with something secure and sensible): ![MySQL Configuration](https://i.stack.imgur.com/aK5uV.png) And then under the SSH tab, enter your terminal login details (username, password and port# if not 22): ![SSH Configuration](https://i.stack.imgur.com/XlUeM.png) Then save your connection. The process is similar in MySQL workbench so shouldn't be hard to figure it out.
2,890,172
I am planning to build a JS based twitter client. Information about libraries/clients is pretty old on other SO Questions. I was wondering if anyone has come across wrappers other than Spaz and TwitterHelper. Addition : Please note this will be client app which I also plan to run on mobiles using phonegap. Thanks :-)
2010/05/22
[ "https://Stackoverflow.com/questions/2890172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/304673/" ]
[SQLyog's](http://www.webyog.com) [HTTP Tunnel](http://gist.github.com/410502) is a very decent one. ![enter image description here](https://i.stack.imgur.com/GWsFJ.png)
I have build a `MySQLTunnel` script in `PHP`, and put it in sourceforge. You can download it and try. It supports: > > * HTTP Tunneling to MySQL > * JSON Resultset > * On-demand compression to preserve bandwidth > * On-demand encryption using AES-128 or AES-256 to preserve secure data > and password > * Supports both http:// and https:// > * Written in PHP can be installed on any LAMP or WAMP stack > * Fast and secure communication > > > [Here](https://sourceforge.net/projects/mysqltunnel/?source=directory) you can find it Hope it helps
2,890,172
I am planning to build a JS based twitter client. Information about libraries/clients is pretty old on other SO Questions. I was wondering if anyone has come across wrappers other than Spaz and TwitterHelper. Addition : Please note this will be client app which I also plan to run on mobiles using phonegap. Thanks :-)
2010/05/22
[ "https://Stackoverflow.com/questions/2890172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/304673/" ]
You can use TCP/IP over SSH from within MySQL Workbench and SQLyog without the need for PHP tunnelling script if you have SSH access to you server. I have had customer sites on shared hosts where this doesn't work due to server configuration which is out of my control. I have overcome this restriction via SSH tunnelling which has the added benefit of being encrypted (Obviously this will only work if you have SSH access to the host however), although noted, the original post asked for a HTTP tunnel. To setup SSH Tunnelling in SQLyog, on the MySQL tab for your connection, enter you MySQL credentials as you normally would for a local user on the host (replace 'root' and password with something secure and sensible): ![MySQL Configuration](https://i.stack.imgur.com/aK5uV.png) And then under the SSH tab, enter your terminal login details (username, password and port# if not 22): ![SSH Configuration](https://i.stack.imgur.com/XlUeM.png) Then save your connection. The process is similar in MySQL workbench so shouldn't be hard to figure it out.
try use HTTPtunnel GNU. here example [connection to MySQL using HTTPtunnel GNU.](http://mysql-tools.com/en/articles/http-tunnel/73-heidisql-a-http-tunnel.html)
2,890,172
I am planning to build a JS based twitter client. Information about libraries/clients is pretty old on other SO Questions. I was wondering if anyone has come across wrappers other than Spaz and TwitterHelper. Addition : Please note this will be client app which I also plan to run on mobiles using phonegap. Thanks :-)
2010/05/22
[ "https://Stackoverflow.com/questions/2890172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/304673/" ]
try use HTTPtunnel GNU. here example [connection to MySQL using HTTPtunnel GNU.](http://mysql-tools.com/en/articles/http-tunnel/73-heidisql-a-http-tunnel.html)
I have build a `MySQLTunnel` script in `PHP`, and put it in sourceforge. You can download it and try. It supports: > > * HTTP Tunneling to MySQL > * JSON Resultset > * On-demand compression to preserve bandwidth > * On-demand encryption using AES-128 or AES-256 to preserve secure data > and password > * Supports both http:// and https:// > * Written in PHP can be installed on any LAMP or WAMP stack > * Fast and secure communication > > > [Here](https://sourceforge.net/projects/mysqltunnel/?source=directory) you can find it Hope it helps
2,890,172
I am planning to build a JS based twitter client. Information about libraries/clients is pretty old on other SO Questions. I was wondering if anyone has come across wrappers other than Spaz and TwitterHelper. Addition : Please note this will be client app which I also plan to run on mobiles using phonegap. Thanks :-)
2010/05/22
[ "https://Stackoverflow.com/questions/2890172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/304673/" ]
You can use TCP/IP over SSH from within MySQL Workbench and SQLyog without the need for PHP tunnelling script if you have SSH access to you server. I have had customer sites on shared hosts where this doesn't work due to server configuration which is out of my control. I have overcome this restriction via SSH tunnelling which has the added benefit of being encrypted (Obviously this will only work if you have SSH access to the host however), although noted, the original post asked for a HTTP tunnel. To setup SSH Tunnelling in SQLyog, on the MySQL tab for your connection, enter you MySQL credentials as you normally would for a local user on the host (replace 'root' and password with something secure and sensible): ![MySQL Configuration](https://i.stack.imgur.com/aK5uV.png) And then under the SSH tab, enter your terminal login details (username, password and port# if not 22): ![SSH Configuration](https://i.stack.imgur.com/XlUeM.png) Then save your connection. The process is similar in MySQL workbench so shouldn't be hard to figure it out.
I have build a `MySQLTunnel` script in `PHP`, and put it in sourceforge. You can download it and try. It supports: > > * HTTP Tunneling to MySQL > * JSON Resultset > * On-demand compression to preserve bandwidth > * On-demand encryption using AES-128 or AES-256 to preserve secure data > and password > * Supports both http:// and https:// > * Written in PHP can be installed on any LAMP or WAMP stack > * Fast and secure communication > > > [Here](https://sourceforge.net/projects/mysqltunnel/?source=directory) you can find it Hope it helps
68,059,041
I want make the same text of text1 appear in each line of text2 ``` <script type="text/javascript"> $("#btn").click(function(){ var text1 = $('#text1').val(); var text2 = $('#text2').val(); $('#text3').val(text2+text1); }); </script> ```
2021/06/20
[ "https://Stackoverflow.com/questions/68059041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16275160/" ]
Since these are the only numbers in the string, you can pull them out with a short regex: ``` import re s = 'mouse_position = "Point(x=535, y=415)"' [int(n) for n in re.findall(r'\d+', s)] # [535, 415] ``` This basically says, find all strings that are made of 1 or more digits. Note, that you will need to determine which is `x` and which is `y` by the order in the string. If it could be `Point(y=415, x=535)` you will need something a bit more sophisticated.
Another approach with `slicing`: ```py s = 'mouse_position = "Point(x=535, y=415)"' x_s=s.index('x=')+2 x_e=s.index(',') x = int(s[x_s:x_e]) y_s=s.index('y=')+2 y_e=s.index(')') y = int(s[y_s:y_e]) #print(f"{x=}, {y=}") print(x)#535 print(y)#415 ```
68,059,041
I want make the same text of text1 appear in each line of text2 ``` <script type="text/javascript"> $("#btn").click(function(){ var text1 = $('#text1').val(); var text2 = $('#text2').val(); $('#text3').val(text2+text1); }); </script> ```
2021/06/20
[ "https://Stackoverflow.com/questions/68059041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16275160/" ]
Since these are the only numbers in the string, you can pull them out with a short regex: ``` import re s = 'mouse_position = "Point(x=535, y=415)"' [int(n) for n in re.findall(r'\d+', s)] # [535, 415] ``` This basically says, find all strings that are made of 1 or more digits. Note, that you will need to determine which is `x` and which is `y` by the order in the string. If it could be `Point(y=415, x=535)` you will need something a bit more sophisticated.
This is probably the least python-like code, but it is easy to understand and works really well and extremally fast ``` import pyautogui import numpy as np while True: original_string = str(pyautogui.position()) #getting the position of mouse characters_to_remove = "Point()xy=,:[]''" #characters you want to remove new_string = original_string for character in characters_to_remove: new_string = new_string.replace(character, "") a = new_string.split() b = np.array_split(a, 2) c = str((a[0])) d = str((a[1])) for character in characters_to_remove: x = c.replace(character, "") y = d.replace(character, "") print(x + ", " + y) ```
68,059,041
I want make the same text of text1 appear in each line of text2 ``` <script type="text/javascript"> $("#btn").click(function(){ var text1 = $('#text1').val(); var text2 = $('#text2').val(); $('#text3').val(text2+text1); }); </script> ```
2021/06/20
[ "https://Stackoverflow.com/questions/68059041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16275160/" ]
You could always pull out the really big gun of text extraction. Regular expressions: ``` import re mouse_position = "Point(x=535, y=415)" d = re.match("Point\(x=(?P<x>\d+), y=(?P<y>\d+)\)",mouse_position).groupdict() ``` `d` is now : ``` {'x': '535', 'y': '415'} ```
Another approach with `slicing`: ```py s = 'mouse_position = "Point(x=535, y=415)"' x_s=s.index('x=')+2 x_e=s.index(',') x = int(s[x_s:x_e]) y_s=s.index('y=')+2 y_e=s.index(')') y = int(s[y_s:y_e]) #print(f"{x=}, {y=}") print(x)#535 print(y)#415 ```
68,059,041
I want make the same text of text1 appear in each line of text2 ``` <script type="text/javascript"> $("#btn").click(function(){ var text1 = $('#text1').val(); var text2 = $('#text2').val(); $('#text3').val(text2+text1); }); </script> ```
2021/06/20
[ "https://Stackoverflow.com/questions/68059041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16275160/" ]
You could always pull out the really big gun of text extraction. Regular expressions: ``` import re mouse_position = "Point(x=535, y=415)" d = re.match("Point\(x=(?P<x>\d+), y=(?P<y>\d+)\)",mouse_position).groupdict() ``` `d` is now : ``` {'x': '535', 'y': '415'} ```
This is probably the least python-like code, but it is easy to understand and works really well and extremally fast ``` import pyautogui import numpy as np while True: original_string = str(pyautogui.position()) #getting the position of mouse characters_to_remove = "Point()xy=,:[]''" #characters you want to remove new_string = original_string for character in characters_to_remove: new_string = new_string.replace(character, "") a = new_string.split() b = np.array_split(a, 2) c = str((a[0])) d = str((a[1])) for character in characters_to_remove: x = c.replace(character, "") y = d.replace(character, "") print(x + ", " + y) ```
1,772,652
I like the 'Recent Activity' effect on <http://foursquare.com/>. The top activity pushing all beneath. Is there a JQuery plugin or widget I can readily use which does the same? (I am a lazy developer so please no 'you can develop this yourself' responses)
2009/11/20
[ "https://Stackoverflow.com/questions/1772652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129001/" ]
Is there a reason you can't use [simplexml](http://www.php.net/manual/en/book.simplexml.php)? ``` $xml = simplexml_load_file('http://www.supashare.net/test.xml'); $result = $xml->xpath('/XML/RESULTS/LISTING/REDIRECT'); echo $result[0]; ```
``` $xml = stream_get_contents($fp); $xml = new SimpleXMLElement($xml); echo $xml->RESULTS->LISTING->REDIRECT; ```
1,772,652
I like the 'Recent Activity' effect on <http://foursquare.com/>. The top activity pushing all beneath. Is there a JQuery plugin or widget I can readily use which does the same? (I am a lazy developer so please no 'you can develop this yourself' responses)
2009/11/20
[ "https://Stackoverflow.com/questions/1772652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129001/" ]
Is there a reason you can't use [simplexml](http://www.php.net/manual/en/book.simplexml.php)? ``` $xml = simplexml_load_file('http://www.supashare.net/test.xml'); $result = $xml->xpath('/XML/RESULTS/LISTING/REDIRECT'); echo $result[0]; ```
``` $doc = new DomDocument(); $doc->load('http://www.supashare.net/test.xml'); $q = new DomXPath($doc); echo $q->query('//REDIRECT')->item(0)->nodeValue; ```
1,772,652
I like the 'Recent Activity' effect on <http://foursquare.com/>. The top activity pushing all beneath. Is there a JQuery plugin or widget I can readily use which does the same? (I am a lazy developer so please no 'you can develop this yourself' responses)
2009/11/20
[ "https://Stackoverflow.com/questions/1772652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129001/" ]
``` $xml = stream_get_contents($fp); $xml = new SimpleXMLElement($xml); echo $xml->RESULTS->LISTING->REDIRECT; ```
``` $doc = new DomDocument(); $doc->load('http://www.supashare.net/test.xml'); $q = new DomXPath($doc); echo $q->query('//REDIRECT')->item(0)->nodeValue; ```
31,552
I am using a linked datasource in MOSS to create a dynamic table of contents page based on a metadata associated with files in a document library. The library contains multilookup columns for the following: Audience, Category, Subcategory. Users get to the toc page by clicking from another page to pass the Audience in the query string. The toc page will filter the categories based on Audience. The categories are displayed using the categories list and then the subcategories are matched to the respective category based on the join. The original problem was that these were delimited strings. I broke the strings out using a recursive template. Now my problem is removing duplicates. I am able to remove the subcategory if it matches up exactly, but because of the multiple values this almost never happens. Is there a way to do this using xslt or will I need to look into some sort of jquery. ``` <xsl:stylesheet xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal"> <xsl:output method="html" indent="no"/> <xsl:decimal-format NaN=""/> <xsl:param name="dvt_apos">'</xsl:param> <xsl:param name="Audience" /> <xsl:param name="HelpURL" /> <xsl:variable name="dvt_1_automode">0</xsl:variable> <xsl:template match="/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:SharePoint="Microsoft.SharePoint.WebControls"> <xsl:call-template name="CategoryList"/> </xsl:template> <xsl:template name="CategoryList"> <xsl:variable name="dvt_StyleName">2ColCma</xsl:variable> <xsl:variable name="Rows" select="/dsQueryResponse/Categories/Rows/Row" /> <link rel="stylesheet" type="text/css" href="/_layouts/1033/styles/controls.css"/> <table border="0" width="100%"> <tr> <xsl:call-template name="CategoryList.body"> <xsl:with-param name="Rows" select="$Rows" /> </xsl:call-template> </tr> </table> </xsl:template> <xsl:template name="CategoryList.body"> <xsl:param name="Rows" /> <xsl:for-each select="$Rows"> <xsl:sort select="../../../Rows/Row/@Title" order="ascending" /> <xsl:call-template name="CategoryList.rowview" /> </xsl:for-each> </xsl:template> <xsl:template name="CategoryList.rowview"> <xsl:variable name="ParentCategory" select="@Title" /> <xsl:variable name="DocumentRows" select="../../../Documents/Rows/Row[contains(@Category, $ParentCategory) and contains(@Audience, $Audience)]" /> <xsl:variable name="RowCount" select="count($DocumentRows)" /> <xsl:variable name="dvt_IsEmpty" select="$RowCount = 0" /> <xsl:if test="$RowCount &gt; 0"> <td valign="top" width="50%"> <table border="0" cellspacing="0" width="100%"> <tr class="ms-WPHeader" > <td width="75%" class="ms-standardheader ms-WPTitle"> <xsl:value-of select="@Title" /></td> </tr> <xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1"> <tr> <td colspan="99" class="ms-vb"> <span ddwrt:amkeyfield="" ddwrt:amkeyvalue="string($XPath)" ddwrt:ammode="view" /> </td> </tr> </xsl:if> <tr> <td width="75%" class="ms-vb"> <xsl:call-template name="Documents" /> </td> </tr> </table> </td> <xsl:if test="position() mod 2 = 0" ddwrt:cf_ignore="1"> <xsl:text disable-output-escaping="yes">&lt;/tr&gt;</xsl:text> <xsl:if test="position() != last()" ddwrt:cf_ignore="1"> <xsl:text disable-output-escaping="yes">&lt;tr&gt;</xsl:text> </xsl:if> </xsl:if> </xsl:if> </xsl:template> <xsl:variable name="dvt_2_automode">0</xsl:variable> <xsl:template name="Documents"> <xsl:variable name="dvt_StyleName">Table</xsl:variable> <xsl:variable name="dvt_ParentRow" select="current()" /> <xsl:variable name="Rows" select="../../../Documents/Rows/Row[contains(@Category, $dvt_ParentRow/@Title) and contains(@Audience, $Audience)]" /> <xsl:variable name="dvt_RowCount" select="count($Rows)" /> <xsl:variable name="dvt_IsEmpty" select="$dvt_RowCount = 0" /> <xsl:choose> <xsl:when test="$dvt_IsEmpty"> <xsl:call-template name="dvt_1.empty" /> </xsl:when> <xsl:otherwise> <table border="0" width="100%" cellpadding="2" cellspacing="0"> <xsl:call-template name="Documents.body"> <xsl:with-param name="Rows" select="$Rows" /> <xsl:with-param name="dvt_ParentRow" select="$dvt_ParentRow" /> </xsl:call-template> </table> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="Documents.body"> <xsl:param name="Rows" /> <xsl:param name="dvt_ParentRow" /> <xsl:for-each select="$Rows"> <xsl:sort select="@Subcategory" /> <xsl:call-template name="Documents.rowview" > <xsl:with-param name="dvt_ParentRow" select="$dvt_ParentRow/@Title" /> </xsl:call-template> </xsl:for-each> </xsl:template> <xsl:template name="Documents.rowview"> <xsl:param name="dvt_ParentRow" /> <xsl:variable name="SubcatRow" select="ddwrt:NameChanged(string(@Subcategory), 0)" /> <xsl:if test="string-length($SubcatRow)"> <tr> <td class="ms-vb"> <xsl:call-template name="subcategoryLinks"> <xsl:with-param name="subcategory" select="@Subcategory" /> <xsl:with-param name="SingleCategory" select="$dvt_ParentRow" /> </xsl:call-template> </td> </tr> </xsl:if> </xsl:template> <!--Template used to determine subcategories --> <xsl:template name="subcategoryLinks"> <xsl:param name="SingleCategory" /> <xsl:param name="subcategory" /> <xsl:variable name="firstSubcat" select="substring-before($subcategory, ';')" /> <xsl:variable name="remainSubcat" select="substring-after($subcategory, ';')" /> <xsl:choose> <!--Tests to see if there are more than 1 subcategory--> <xsl:when test="not(contains(@Subcategory, ';'))"> <div id="subLink" class="bullet" style="font-size:10pt;"> <a href="{$HelpURL}{$Audience}&amp;Category={$SingleCategory}&amp;SubCategory={@Subcategory}"><xsl:value-of select="@Subcategory" /></a> </div> </xsl:when> <!--Runs if more than 1 subcategory--> <xsl:otherwise> <!--Creates subcategory row--> <div id="subLink" class="bullet" style="font-size:10pt;"> <a href="{$HelpURL}{$Audience}&amp;Category={$SingleCategory}&amp;SubCategory={$firstSubcat}"> <xsl:value-of select="$firstSubcat" /> </a> </div> <xsl:choose> <!--Tests to see if more than 1 subcategory remains, if so it will rerun the template--> <xsl:when test="contains($remainSubcat, ';')" > <xsl:call-template name="subcategoryLinks"> <xsl:with-param name="subcategory" select="$remainSubcat" /> <xsl:with-param name="SingleCategory" select="$SingleCategory" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <div id="subLink" class="bullet" style="font-size:10pt;"> <a href="{$HelpURL}{$Audience}&amp;Category={$SingleCategory}&amp;SubCategory={$remainSubcat}"><xsl:value-of select="$remainSubcat" /></a> </div> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="dvt_1.empty"> <xsl:variable name="dvt_ViewEmptyText">No items.</xsl:variable> <table border="0" width="100%"> <tr> <td class="ms-vb" style="height: 17px"> <xsl:value-of select="$dvt_ViewEmptyText" /> </td> </tr> </table> </xsl:template> ```
2012/03/14
[ "https://sharepoint.stackexchange.com/questions/31552", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/7057/" ]
You are missing the `ElementFile` element. From what you've described, your feature.xml should look something like this: ``` <?xml version="1.0" encoding="utf-8"?> <Feature Title="YourFeature" Description="YourFeature" Id="GUID" Scope="Site" Version="1.0.0.0" Hidden="FALSE" DefaultResourceFile="core" xmlns="http://schemas.microsoft.com/sharepoint/"> <ElementManifests> <ElementManifest Location="elements.xml" /> <ElementFile Location="YourFeature\schema.xml" /> </ElementManifests> </Feature> ``` The schema.xml should be in a folder named YourFeature. Also, the folder that contains schema.xml must be the same as the value of the Name attribute in your elements.xml.
I would check your ddf file. Here is the preview from one of my projects ``` ;.OPTION Explicit .Set CabinetNameTemplate="Test.wsp" .Set DiskDirectoryTemplate="..\TargetFolderForWsp(bin)" .Set CompressionType=MSZIP .Set UniqueFiles=Off .Set Cabinet=On ;******************************* manifest.xml %BuildPath%\Test.dll Test.dll .Set DestinationDir="FeatureName" 12\TEMPLATE\FEATURES\FeatureName\feature.xml feature.xml 12\TEMPLATE\FEATURES\FeatureName\SiteColumns.xml SiteColumns.xml 12\TEMPLATE\FEATURES\FeatureName\ContentTypes.xml ContentTypes.xml 12\TEMPLATE\FEATURES\FeatureName\ListTemplateName\ListDefinition.xml ListTemplateName\ListDefinition.xml 12\TEMPLATE\FEATURES\FeatureName\ListTemplateName\Schema.xml ListTemplateName\Schema.xml 12\TEMPLATE\FEATURES\FeatureName\ListTemplateName\AllItems.aspx ListTemplateName\AllItems.aspx 12\TEMPLATE\FEATURES\FeatureName\ListTemplateName\DispForm.aspx ListTemplateName\DispForm.aspx 12\TEMPLATE\FEATURES\FeatureName\ListTemplateName\EditForm.aspx ListTemplateName\EditForm.aspx 12\TEMPLATE\FEATURES\FeatureName\ListTemplateName\NewForm.aspx ListTemplateName\NewForm.aspx ``` The first path is path to file in project (Replace with you file path) The second path is the package location reltaive to the DestinationDir specified above
71,448,383
I need to dismiss an alert dialogue when a callback is being called. How can i achieve it?
2022/03/12
[ "https://Stackoverflow.com/questions/71448383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18445974/" ]
> > Some people say that this practice is adopted to avoid repeating declarations. > > > If some people say that then what they say is misleading. Header guards are used to avoid repeating *definitions* in order to conform to the One Definition Rule.
Repeating **declarations** is okay. Repeating **definitions** is not. ``` int func(); // declaration int func(); // declaration; repetition is okay class X; // declaration class X; // declaration; repetition is okay class Y {}; // definition class Y {}; // definition; repetition is not okay ``` If a header consists only of declarations it can be included multiple times. But that's inefficient: the compiler has to compile each declaration, determine that it's just a duplicate, and ignore it. And, of course, even if it consists only of declarations at the moment, some future maintainer (including you) will, at some point, change it.
71,448,383
I need to dismiss an alert dialogue when a callback is being called. How can i achieve it?
2022/03/12
[ "https://Stackoverflow.com/questions/71448383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18445974/" ]
> > Some people say that this practice is adopted to avoid repeating declarations. > > > If some people say that then what they say is misleading. Header guards are used to avoid repeating *definitions* in order to conform to the One Definition Rule.
> > So is it really necessary to avoid repeating declarations? > > > You can have multiple **declarations** for a given entity(name). That is you can repeat declarations in a given scope. > > is there another reason for using #ifndef? > > > The main reason for using **header guards** is to **ensure** that the second time a header file is `#included`, its contents are discarded, thereby **avoiding the duplicate definition** of a class, inline entity, template, and so on, that it may contain. In other words, so that the program conform to the **One Definition Rule**(aka ODR).
16,569,726
In this official doc they use 2.2-SNAPSHOT version. <http://doc.akka.io/docs/akka/snapshot/intro/getting-started.html> If try to resolve it - it does not work. If try to add typesafe repo: ``` <repositories> <repository> <id>java.net</id> <url>http://repo.typesafe.com/typesafe/releases/</url> </repository> </repositories> <dependencies> <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-actor_2.10</artifactId> <version>2.2-SNAPSHOT</version> </dependency> </dependencies> ``` It does not work neither. **Edit:** Even if I use snapshot repo in "< repository >" Is there some repo I can use to make official sample working? If I use previous version, then that example does not resolve some methods (like this: `Props.create`). So I need last one then.
2013/05/15
[ "https://Stackoverflow.com/questions/16569726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369759/" ]
Can't you use the M3? ``` <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-actor_2.10</artifactId> <version>2.2-M3</version> </dependency> ``` If so, please use the above. It's available on the standard Maven repo.
Normally people don't publish snapshots to the releases repository (there's almost always a snapshots repository), in Akka's case, it's: **repo.akka.io/snapshots/** And I definitely recommend to choose one of the timestamped ones and not the snapshot.
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
[Shavlik Netchk](http://www.shavlik.com/netchk-protect.aspx) can patch Windows and other programs - it is $40 (usd) per patched system.
You could run them on VMWare ESX/ESXi with vCenter and use vCenter Update Manager to get the updates and apply them to all your guest with a few clicks.
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
It seems from your question that the VMs are not always running (ie you manually start them). Is that so? If they are always running, then then the functionality you want (auto updates, being able to review updates etc) would mean stepping into the big leagues (WSUS server etc) [note that I don've have any experience with this :-) ] If they are not always running then I don't know how you can get around updating them without starting them. But still having a WSUS server would make downloading all the patches easier overall. I have a similar problem as I have multiple XP VMs on my laptop for testing software with different customers. Whenever I start a new project I manually start my base VM, update it and then clone it for the latest customer test. Its a pain to do, but I can't see any other way around it.
You could run them on VMWare ESX/ESXi with vCenter and use vCenter Update Manager to get the updates and apply them to all your guest with a few clicks.
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
Can you tell us what is your host OS? I think WSUS would be a good solution for you. You can review the updates and approve the ones you need. Also as the VMs are not always On, You may want to configure a simple startup script to run the WSUS Update command.
You could run them on VMWare ESX/ESXi with vCenter and use vCenter Update Manager to get the updates and apply them to all your guest with a few clicks.
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
[Shavlik Netchk](http://www.shavlik.com/netchk-protect.aspx) can patch Windows and other programs - it is $40 (usd) per patched system.
It sounds as though you want to be able to make lots of different changes to your virtual guests - whilst Update Manager will handle the patching/hotfix/update side of things, I don't think it will answer your queries around changing other system files/updating Java. Not forgetting, whilst ESXi may be free, VCenter isn't and that definitely seems like overkill for your requirements. If you're any good at vbscripting or powershell, I'd consider crafting something with them and automating as much of the process as you can.
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
[Shavlik Netchk](http://www.shavlik.com/netchk-protect.aspx) can patch Windows and other programs - it is $40 (usd) per patched system.
If your host OS is capable of hosting active directory or a Samba domain then you'll get a netlogon directory which you can use to script things to happen on login to your XP machines. You can use batch scripts, powershell or anything else you can make Windows support. It's maybe not the best way of doing things on a large scale, but on a pretty small scale like this you could get away with it quite nicely. As for what to run in those scripts, well it might be as simple as copying files or you could put the files you want synchronised in a Git or SVN repository. As for updates, provided you are being sensible and have the machines NATed then there's no reason to update them as soon as a patch comes out. You can simply allow Microsoft Update to do it's thing, likewise with Adobe Update and Java Update (though maybe you should be more proactive in keeping Adobe products up to date).
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
It seems from your question that the VMs are not always running (ie you manually start them). Is that so? If they are always running, then then the functionality you want (auto updates, being able to review updates etc) would mean stepping into the big leagues (WSUS server etc) [note that I don've have any experience with this :-) ] If they are not always running then I don't know how you can get around updating them without starting them. But still having a WSUS server would make downloading all the patches easier overall. I have a similar problem as I have multiple XP VMs on my laptop for testing software with different customers. Whenever I start a new project I manually start my base VM, update it and then clone it for the latest customer test. Its a pain to do, but I can't see any other way around it.
It sounds as though you want to be able to make lots of different changes to your virtual guests - whilst Update Manager will handle the patching/hotfix/update side of things, I don't think it will answer your queries around changing other system files/updating Java. Not forgetting, whilst ESXi may be free, VCenter isn't and that definitely seems like overkill for your requirements. If you're any good at vbscripting or powershell, I'd consider crafting something with them and automating as much of the process as you can.
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
Can you tell us what is your host OS? I think WSUS would be a good solution for you. You can review the updates and approve the ones you need. Also as the VMs are not always On, You may want to configure a simple startup script to run the WSUS Update command.
It sounds as though you want to be able to make lots of different changes to your virtual guests - whilst Update Manager will handle the patching/hotfix/update side of things, I don't think it will answer your queries around changing other system files/updating Java. Not forgetting, whilst ESXi may be free, VCenter isn't and that definitely seems like overkill for your requirements. If you're any good at vbscripting or powershell, I'd consider crafting something with them and automating as much of the process as you can.
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
It seems from your question that the VMs are not always running (ie you manually start them). Is that so? If they are always running, then then the functionality you want (auto updates, being able to review updates etc) would mean stepping into the big leagues (WSUS server etc) [note that I don've have any experience with this :-) ] If they are not always running then I don't know how you can get around updating them without starting them. But still having a WSUS server would make downloading all the patches easier overall. I have a similar problem as I have multiple XP VMs on my laptop for testing software with different customers. Whenever I start a new project I manually start my base VM, update it and then clone it for the latest customer test. Its a pain to do, but I can't see any other way around it.
If your host OS is capable of hosting active directory or a Samba domain then you'll get a netlogon directory which you can use to script things to happen on login to your XP machines. You can use batch scripts, powershell or anything else you can make Windows support. It's maybe not the best way of doing things on a large scale, but on a pretty small scale like this you could get away with it quite nicely. As for what to run in those scripts, well it might be as simple as copying files or you could put the files you want synchronised in a Git or SVN repository. As for updates, provided you are being sensible and have the machines NATed then there's no reason to update them as soon as a patch comes out. You can simply allow Microsoft Update to do it's thing, likewise with Adobe Update and Java Update (though maybe you should be more proactive in keeping Adobe products up to date).
127,260
I have a small set (currently 3, going to 6, not going to be more than 10) of (virtual, vmware workstation) Windows XP machines. They are similar but not exactly the same. I'm currently rolling out Windows updates, etc., by hand: start machine 1, update, close, etc; I'd like to review the updates first before the clients can install them. Incidentally there are also other updates to be performed: changes some files on all machines, install new Java versions, etc. What's a good way of doing this automatically? I tried to search for this but things like Active Directory seem overkill to me.
2010/03/29
[ "https://serverfault.com/questions/127260", "https://serverfault.com", "https://serverfault.com/users/39096/" ]
Can you tell us what is your host OS? I think WSUS would be a good solution for you. You can review the updates and approve the ones you need. Also as the VMs are not always On, You may want to configure a simple startup script to run the WSUS Update command.
If your host OS is capable of hosting active directory or a Samba domain then you'll get a netlogon directory which you can use to script things to happen on login to your XP machines. You can use batch scripts, powershell or anything else you can make Windows support. It's maybe not the best way of doing things on a large scale, but on a pretty small scale like this you could get away with it quite nicely. As for what to run in those scripts, well it might be as simple as copying files or you could put the files you want synchronised in a Git or SVN repository. As for updates, provided you are being sensible and have the machines NATed then there's no reason to update them as soon as a patch comes out. You can simply allow Microsoft Update to do it's thing, likewise with Adobe Update and Java Update (though maybe you should be more proactive in keeping Adobe products up to date).
3,940,888
Suppose $A,B$ are topological spaces, $B $ is a subspace of $A $ and $X\subseteq B $. If $X $ is compact in $ A$ then is $X $ compact in B? If an open covering of $X$ in $B$ is in fact an open covering in $A$ then by compactness of $A$ we would have a finite sub covering.
2020/12/09
[ "https://math.stackexchange.com/questions/3940888", "https://math.stackexchange.com", "https://math.stackexchange.com/users/617302/" ]
Yes, and you can prove it directly from the definitions. You are assuming we have a chain of subspaces $X \subseteq B \subseteq A$. If $\{O\_\beta \mid \beta \in I\}$ is an open cover of $X$ in $B$, then $O\_\beta = B \cap U\_\beta$ where $U\_\beta$ is open in $A$. Then $\{U\_\beta \mid \beta \in I\}$ is an open cover of $X$ in $A$, so this would reduce finitely by compactness. Now use the same finite number of $U\_\beta$'s to create a finite number of $O\_\beta$'s derived from the original cover.
Let $\bigcup U\_{i \in I} \supset X$ be a finite covering of $X$ in $A$. Since $B$ is a subspace of $A$ then $\tau\_B = \{B \bigcap U | U \in \tau\}$. This proves that there is a finite covering of $X$ in $B$.
3,940,888
Suppose $A,B$ are topological spaces, $B $ is a subspace of $A $ and $X\subseteq B $. If $X $ is compact in $ A$ then is $X $ compact in B? If an open covering of $X$ in $B$ is in fact an open covering in $A$ then by compactness of $A$ we would have a finite sub covering.
2020/12/09
[ "https://math.stackexchange.com/questions/3940888", "https://math.stackexchange.com", "https://math.stackexchange.com/users/617302/" ]
Yes, and you can prove it directly from the definitions. You are assuming we have a chain of subspaces $X \subseteq B \subseteq A$. If $\{O\_\beta \mid \beta \in I\}$ is an open cover of $X$ in $B$, then $O\_\beta = B \cap U\_\beta$ where $U\_\beta$ is open in $A$. Then $\{U\_\beta \mid \beta \in I\}$ is an open cover of $X$ in $A$, so this would reduce finitely by compactness. Now use the same finite number of $U\_\beta$'s to create a finite number of $O\_\beta$'s derived from the original cover.
Suppose $X$ is compact relative to $A$ and let $ \{O\}\_i$ be collection of open sets relative to $B$, such that $X\subset \bigcup\_i O\_i$. By definition of subspace topology, there exists $N\_i$ open in $A$, such that $O\_i=B\cap N\_i$, for all $i$. Since $X$ is compact in $A$. Therefore, $$X\subset N\_{i\_1}\cup\dots \cup N\_{i\_k}$$ for some choice of finitely many indices $i\_1,\dots,i\_k$. Since $X\subset B$, $\Longrightarrow$ $X\subset O\_{i\_1}\cup\dots \cup O\_{i\_k}$.
21,508,810
Looking at the code below I know that we have an array `$r`. The for loop evaluates to `true` and it goes to the `rand` function. The `rand` function generates a number between 0 and 100,000. Then the `if`-statement checks to see if the number generated is less than or equal to 10. The final part is what is confusing me, because I think if the number generated is less than 10 then it adds a 1 to it. Can someone please explain this code. Thank you. ``` <?php $r = array(0,0,0,0,0,0,0,0,0,0,0); for ($i=0;$i<1000000;$i++) { $n = rand(0,100000); if ($n<=10) { $r[$n]++; } } print_r($r); ?> ```
2014/02/02
[ "https://Stackoverflow.com/questions/21508810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009365/" ]
You could use `paste0`, e.g.: ``` grep(paste0("[Aa]ge: ", age, "$"), agr, value=TRUE)) ``` Or `sprintf`, e.g.: ``` grep(sprintf("[Aa]ge: %s$", age), agr, value=TRUE)) ``` Another way would be to use regular expressions (see `?regex`): ``` grep("[Aa]ge: [0-9]+$", agr, value=TRUE) ```
If you goal is to count the matches of the ages specified in `numb` in the strings in `agr`, you can use this approach: ``` # an example vector agr <- c("Age: 23", "age: 20", "age: 5", "Age: 20", "age: 3") numb <- c(20, 25, 3, 5) # create regex pattern pattern <- paste0("[Aa]ge: (", paste(numb, collapse = "|"), ")$") # [1] "[Aa]ge: (20|25|3|5)$" # count values table(factor(sub(".* (\\d+)$", "\\1", grep(pattern, agr, value = TRUE)), levels = numb)) # 20 25 3 5 # 2 0 1 1 ```
10,583
I love using Google map to give me direction. however, I would like it to provide "turn left, turn right" voice while I am driving. I heard Google map navigation able to provide such feature. I search from android market but cannot find one. is it only available to selected country? is there any workaround, or other software I can try out?
2011/06/18
[ "https://android.stackexchange.com/questions/10583", "https://android.stackexchange.com", "https://android.stackexchange.com/users/2999/" ]
It's limited to specific locations, and only available with a data connection. See [this question on the location limitations](https://android.stackexchange.com/questions/1854/does-android-come-with-free-navigation-in-non-us-contries) and [this question on alternatives](https://android.stackexchange.com/questions/227/what-replacements-are-available-for-google-maps).
Google's official list of countries with Google Maps Navigation (Beta) available is here: <http://www.google.com/support/mobile/bin/answer.py?answer=172221> Currently 29 countries are listed there. If your country is not in the list, the simplest workaround I found is [brut.all ownhere modified changepn Google Maps apps on XDADev](http://forum.xda-developers.com/showthread.php?t=1007132) .
23,607,059
I have seen this answer, [How to apply PostgreSQL UNLOGGED feature to an existing table?](https://stackoverflow.com/questions/7938610/how-to-apply-postgresql-9-1-unlogged-feature-to-an-existing-table/7938621#7938621), which basically suggests that the way to convert a table to unlogged is to run: ``` CREATE UNLOGGED TABLE your_table_unlogged AS SELECT * FROM your_table; ``` Is this still the case, because while this is an of obvious working solution, for a large table there are potential time and disk space factors that could come into play. And, if yes, could someone please explain briefly how the architecture of Postgres means you need to rewrite an entire table in order to make it unlogged?
2014/05/12
[ "https://Stackoverflow.com/questions/23607059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457052/" ]
*Update*: In PostgreSQL 9.5+ there is `ALTER TABLE ... SET LOGGED` and `... SET UNLOGGED` Converting from `UNLOGGED` to `LOGGED` requires that the whole table's data be written to xlogs if `wal_level` is > `minimal` so replicas get a copy. So it's not free, but it can still be worth creating a table unlogged, populating it then setting it logged if you have a bunch of cleanup and deletion and merging work to do on the table after initial load. --- Yes, that's still the case in 9.4. Converting from logged to `UNLOGGED` isn't theoretically hard AFAIK, but nobody's done the work to do it. The main thing is that all constraints and types etc referring to it must be re-checked to make sure there's no reference from another logged table to this table. Most attention has been paid to the other case, so if this feature is important to you, consider funding its development or getting involved in development yourself. Converting `UNLOGGED` to logged may become possible for nodes that aren't involved in streaming replication or using an `archive_command`. It's not simple otherwise because of the need to cope with the fact that the data for the table wasn't sent, but suddenly changes to it are - the replication protocol would need further enhancement to allow the table to be base-copied before continuing.
Apparently this (alter table ... set logged | unlogged) has been implemented in (the upcoming) postgresql 9.5.
46,306,596
My build.gradle: ``` // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.1.3-2' ext.realm_version = '3.7.2' repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath 'com.google.gms:google-services:3.1.0' classpath "io.realm:realm-gradle-plugin:$realm_version" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() maven { url "https://maven.google.com" } maven { url 'https://dl.bintray.com/jetbrains/anko' } } } task clean(type: Delete) { delete rootProject.buildDir } repositories { mavenCentral() } ``` My app/build.gradle ``` buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application' apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-android' apply plugin: 'io.fabric' apply plugin: 'realm-android' realm { syncEnabled = true; } repositories { maven { url 'https://maven.fabric.io/public' } mavenCentral() } android { compileSdkVersion 26 buildToolsVersion "25.0.3" dexOptions { jumboMode = true } defaultConfig { applicationId "com.my.project" minSdkVersion 15 targetSdkVersion 23 versionCode 54 versionName "1.3.54" multiDexEnabled true } } def AAVersion = '4.3.1' dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:26.1.0' compile('com.crashlytics.sdk.android:crashlytics:2.6.0@aar') { transitive = true; } compile('com.digits.sdk.android:digits:1.11.0@aar') { transitive = true; } compile 'com.android.support:multidex:1.0.1' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.android.volley:volley:1.0.0' compile 'com.baoyz.swipemenulistview:library:1.3.0' compile 'com.google.android.gms:play-services-gcm:11.0.4' compile 'com.google.code.gson:gson:2.7' compile 'com.miguelcatalan:materialsearchview:1.4.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.7.3' compile 'com.squareup.okhttp:okhttp:2.7.3' compile 'com.theartofdev.edmodo:android-image-cropper:2.2.5' compile 'commons-codec:commons-codec:1.9' compile 'commons-io:commons-io:2.4' compile 'io.realm:android-adapters:2.0.0' compile 'org.apache.commons:commons-lang3:3.4' compile 'org.apache.httpcomponents:httpcore:4.4.4' compile 'org.apache.httpcomponents:httpmime:4.3.6' compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile 'us.feras.mdv:markdownview:1.1.0' compile 'org.jetbrains.anko:anko-sdk15:0.9.1' compile "org.androidannotations:androidannotations-api:$AAVersion" // for annotaions kapt "io.realm:realm-android-library:$realm_version" kapt "org.androidannotations:androidannotations:$AAVersion" compile 'com.firebaseui:firebase-ui-auth:2.3.0' compile 'com.google.firebase:firebase-auth:11.0.4' compile "com.android.support:design:26.1.0" compile "com.android.support:customtabs:26.1.0" compile "com.android.support:cardview-v7:26.1.0" testCompile 'junit:junit:4.12' } apply plugin: 'com.google.gms.google-services' ``` When I build I get error: ``` Error:Execution failed for task ':app:processDevGoogleServices'. > File google-services.json is missing. The Google Services Plugin cannot function without it. Searched Location: com\my_project\app\src\dev\google-services.json com\my_project\\app\google-services.json ``` OK.In Android Studio select menu: **Tools**->**Friebase** 1. Firebase-> Authentification 2. Click on Email and password authentification 3. Connect to your app to Firebase and get error: [Could not parse the Android Application module](https://i.stack.imgur.com/cR3a6.png)
2017/09/19
[ "https://Stackoverflow.com/questions/46306596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8542613/" ]
I've just resolve this problem. I was upgrading the old GCM to FCM, and the Firebase Assistant shows the same error message as yours. Solved by: 1. Go to Firebase console, in the **Settings** of my project, download `google-servics.json` to `app/` folder. (Replace my old GCM's json file) 2. doing [Add Firebase to your app](https://firebase.google.com/docs/android/setup) again, Then I can use the Firebase Assistans of AndroidStudio, again.
You might want to try 'Sync Project with Gradle Files'. Sometimes I forget to sync the implementations after adding them to the gradle file.
46,306,596
My build.gradle: ``` // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.1.3-2' ext.realm_version = '3.7.2' repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath 'com.google.gms:google-services:3.1.0' classpath "io.realm:realm-gradle-plugin:$realm_version" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() maven { url "https://maven.google.com" } maven { url 'https://dl.bintray.com/jetbrains/anko' } } } task clean(type: Delete) { delete rootProject.buildDir } repositories { mavenCentral() } ``` My app/build.gradle ``` buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application' apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-android' apply plugin: 'io.fabric' apply plugin: 'realm-android' realm { syncEnabled = true; } repositories { maven { url 'https://maven.fabric.io/public' } mavenCentral() } android { compileSdkVersion 26 buildToolsVersion "25.0.3" dexOptions { jumboMode = true } defaultConfig { applicationId "com.my.project" minSdkVersion 15 targetSdkVersion 23 versionCode 54 versionName "1.3.54" multiDexEnabled true } } def AAVersion = '4.3.1' dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:26.1.0' compile('com.crashlytics.sdk.android:crashlytics:2.6.0@aar') { transitive = true; } compile('com.digits.sdk.android:digits:1.11.0@aar') { transitive = true; } compile 'com.android.support:multidex:1.0.1' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.android.volley:volley:1.0.0' compile 'com.baoyz.swipemenulistview:library:1.3.0' compile 'com.google.android.gms:play-services-gcm:11.0.4' compile 'com.google.code.gson:gson:2.7' compile 'com.miguelcatalan:materialsearchview:1.4.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.7.3' compile 'com.squareup.okhttp:okhttp:2.7.3' compile 'com.theartofdev.edmodo:android-image-cropper:2.2.5' compile 'commons-codec:commons-codec:1.9' compile 'commons-io:commons-io:2.4' compile 'io.realm:android-adapters:2.0.0' compile 'org.apache.commons:commons-lang3:3.4' compile 'org.apache.httpcomponents:httpcore:4.4.4' compile 'org.apache.httpcomponents:httpmime:4.3.6' compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile 'us.feras.mdv:markdownview:1.1.0' compile 'org.jetbrains.anko:anko-sdk15:0.9.1' compile "org.androidannotations:androidannotations-api:$AAVersion" // for annotaions kapt "io.realm:realm-android-library:$realm_version" kapt "org.androidannotations:androidannotations:$AAVersion" compile 'com.firebaseui:firebase-ui-auth:2.3.0' compile 'com.google.firebase:firebase-auth:11.0.4' compile "com.android.support:design:26.1.0" compile "com.android.support:customtabs:26.1.0" compile "com.android.support:cardview-v7:26.1.0" testCompile 'junit:junit:4.12' } apply plugin: 'com.google.gms.google-services' ``` When I build I get error: ``` Error:Execution failed for task ':app:processDevGoogleServices'. > File google-services.json is missing. The Google Services Plugin cannot function without it. Searched Location: com\my_project\app\src\dev\google-services.json com\my_project\\app\google-services.json ``` OK.In Android Studio select menu: **Tools**->**Friebase** 1. Firebase-> Authentification 2. Click on Email and password authentification 3. Connect to your app to Firebase and get error: [Could not parse the Android Application module](https://i.stack.imgur.com/cR3a6.png)
2017/09/19
[ "https://Stackoverflow.com/questions/46306596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8542613/" ]
For me, the issue was classpath 'com.google.gms:google-services:4.3.0' was giving error, then I changed to classpath 'com.google.gms:google-services:4.2.0', resync'd Project with Gradle Files', then pressed Connect to firebase, :D
You might want to try 'Sync Project with Gradle Files'. Sometimes I forget to sync the implementations after adding them to the gradle file.
5,776,299
Aloha everyone, I have another question. I have a SYDI script that retrieves WMI data from Windows computers, then appends a timestamp to the end of the file, and finally saves it to a share on a server. The PHP code I have to read and print out the filenames is shown below: ``` if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if ($file != "." && $file != "..") { $results[] = $file; echo $file . "<br />"; } } closedir($dh); } } ``` Everything is good and the filenames are returned as shown below: ``` sydiResult-24-Apr-11-18-59-52.xml sydiResult-24-Apr-11-19-00-32.xml sydiResult-24-Apr-11-19-01-17.xml ``` I've tried to use simplexml to call the files, in order, to see if I could even do it, with the following code: ``` for ($i = 0; $i < sizeof($results); $i++) { $xml = simplexml_load_file($results[$i]); } ``` but I get errors indicating that simplexml couldn't open external xml files. The php file is in my htdocs directory, and the xml files are in a directory in the htdocs directory, called sydiResults. I wanted to separate the sydi xml files, so I decided to make the sub-directory. Could that be the reason simple xml won't work? My plan is simple: open an the xml files and extract certain information from it, then loop to the next xml file, extract certain information from it, then ... so on and so on until I reach the last xml file in the directory. Does anyone have an idea of how I can use simplexml, or if I can use simplexml to open each xml file in turn? Thanks in advance for any and all responses.
2011/04/25
[ "https://Stackoverflow.com/questions/5776299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691694/" ]
try this : ``` for ($i = 0; $i < sizeof($results); $i++) { $file = 'sydiResults/'.$results[$i]; if (file_exists($file)) { $xml = simplexml_load_file($file); print_r($xml); } else { exit('Failed to open '.$file); } ```
As I put in the comment above, everything is resolved now! I tested my theory by reading a portion of the data within one of the tags. Here is the code that works: ``` // Open a known directory, and proceed to read its contents if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { // Check for the items not desired to be read into the $results array, then fill the array if ($file != "." && $file != ".." && $file != "syditest01.php" && $file != "sydi.bat" && $file != "sydi-server.vbs") { $results[] = $file; // Echo the filenames retrieved as they are read echo $file . "<br />"; } } echo "<br /> <br />"; for ($i = 0; $i < sizeof($results); $i++) { // Verify that only the desired filenames are actually in the array echo "Found file: $results[$i] <br />"; // Load the files using the simplexml_load_file() method $xml = simplexml_load_file($results[$i]); // Read each filename after it gets read by the method above echo $results[$i] . " should be loaded now. <br />"; // The foreach() loop extracts the data for the InventoryItems table,then the resulting data is // assigned a variable to use in the INSERT statemsnt for the database. foreach($xml->machineinfo[0]->attributes() as $a => $b) { // Fill the $info array with the attributes of the machineinfo xml tag $info[] = $b; } // Echo the attributes in the desired order for the INSERT statement for entry into the database echo $info[2], "<br />"; echo $info[0], "<br />"; echo $info[1], "<br />"; echo $info[3], "<br /><br />"; } closedir($dh); } } ``` This is the result: ``` sydiResult-24-Apr-11-18-59-52.xml sydiResult-24-Apr-11-19-00-32.xml sydiResult-24-Apr-11-19-01-17.xml sydiResult-25-Apr-11-13-08-52.xml sydiResult-25-Apr-11-13-10-47.xml sydiResult-25-Apr-11-13-12-01.xml Found file: sydiResult-24-Apr-11-18-59-52.xml sydiResult-24-Apr-11-18-59-52.xml should be loaded now. VMware-56 4d 96 72 5e ec d8 5d-e0 f3 b2 ba 2a 55 72 5b VMware, Inc. VMware Virtual Platform Other Found file: sydiResult-24-Apr-11-19-00-32.xml sydiResult-24-Apr-11-19-00-32.xml should be loaded now. VMware-56 4d 96 72 5e ec d8 5d-e0 f3 b2 ba 2a 55 72 5b VMware, Inc. VMware Virtual Platform Other Found file: sydiResult-24-Apr-11-19-01-17.xml sydiResult-24-Apr-11-19-01-17.xml should be loaded now. VMware-56 4d 96 72 5e ec d8 5d-e0 f3 b2 ba 2a 55 72 5b VMware, Inc. VMware Virtual Platform Other Found file: sydiResult-25-Apr-11-13-08-52.xml sydiResult-25-Apr-11-13-08-52.xml should be loaded now. VMware-56 4d 96 72 5e ec d8 5d-e0 f3 b2 ba 2a 55 72 5b VMware, Inc. VMware Virtual Platform Other ``` I'm running this on my Windows 7 virtual machine on my MacBook Pro, so the only differing information is the filename, but this at least proves that it is reading each file in turn, which is exactly the behavior I want to see!
9,074,342
When I try to get a month before last from today, I run “date --date ‘2 months ago’”. But I run this command on Jan 31st, it return December. I think it should return November. Would you know how to get a month before last with date command? Added at 17:30 (JST): If this date calculus written in Python, I will use dateutil and it's expression is natural as below: ``` from datetime import *; from dateutil.relativedelta import * today = date.today() twomonthago = today + relativedelta(months=-2) ``` So, I wonder how could I write same manner in bash shell. Added at 18:05 (JST): It seems that not only past month, but future month handling is same oddness. ``` $ date --date '+1 month' Fri Mar 2 17:42:37 JST 2012 $ date --date '+2 month' Sat Mar 31 17:42:56 JST 2012 $ date --date '+3 month' Tue May 1 17:42:59 JST 2012 ``` February and April are missing.
2012/01/31
[ "https://Stackoverflow.com/questions/9074342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/430349/" ]
You are not dreaming :) This is possible. > > Go to 'Test' menu >> 'Run' >> 'All Tests in Solution' > > > Keyboard Shortcut : Ctrl + R , A > > > This will run all the tests in the solution.
Go to the menu and choose: ``` Test -> Windows -> Test View ``` In that view you just mark them all by pressing `Ctrl + A` and then press the `Run` button
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
No error check for null lists, but here it is. ``` List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); for (List<Integer> l : list) { Collections.sort(l); } Collections.sort(list, new Comparator<List<Integer>>() { public int compare(List<Integer> o1, List<Integer> o2) { return o1.get(0).compareTo(o2.get(0)); } }); System.out.println(list); ``` With Java 8 it gets even more concise: ``` List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); list.forEach(Collections::sort); Collections.sort(list, (l1, l2) -> l1.get(0).compareTo(l2.get(0))); System.out.println(list); ```
You could just sort each list individually. The `Collections.sort(collection)` will sort the Integers in ascending order automatically.
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
No error check for null lists, but here it is. ``` List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); for (List<Integer> l : list) { Collections.sort(l); } Collections.sort(list, new Comparator<List<Integer>>() { public int compare(List<Integer> o1, List<Integer> o2) { return o1.get(0).compareTo(o2.get(0)); } }); System.out.println(list); ``` With Java 8 it gets even more concise: ``` List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); list.forEach(Collections::sort); Collections.sort(list, (l1, l2) -> l1.get(0).compareTo(l2.get(0))); System.out.println(list); ```
if sort doesnt have what u need you can try this algorithm: ``` package drawFramePackage; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.ListIterator; import java.util.Random; public class QuicksortAlgorithm { ArrayList<AffineTransform> affs; ListIterator<AffineTransform> li; Integer count, count2; /** * @param args */ public static void main(String[] args) { new QuicksortAlgorithm(); } public QuicksortAlgorithm(){ count = new Integer(0); count2 = new Integer(1); affs = new ArrayList<AffineTransform>(); for (int i = 0; i <= 128; i++){ affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0)); } affs = arrangeNumbers(affs); printNumbers(); } public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){ while (list.size() > 1 && count != list.size() - 1){ if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){ list.add(count, list.get(count2)); list.remove(count2 + 1); } if (count2 == list.size() - 1){ count++; count2 = count + 1; } else{ count2++; } } return list; } public void printNumbers(){ li = affs.listIterator(); while (li.hasNext()){ System.out.println(li.next()); } } } ```
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
No error check for null lists, but here it is. ``` List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); for (List<Integer> l : list) { Collections.sort(l); } Collections.sort(list, new Comparator<List<Integer>>() { public int compare(List<Integer> o1, List<Integer> o2) { return o1.get(0).compareTo(o2.get(0)); } }); System.out.println(list); ``` With Java 8 it gets even more concise: ``` List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); list.forEach(Collections::sort); Collections.sort(list, (l1, l2) -> l1.get(0).compareTo(l2.get(0))); System.out.println(list); ```
This works for me ``` Collections.sort(list, new Comparator<List<Integer>>() { public int compare(List<Integer> o1, List<Integer> o2) { int min = Math.min(o1.size(),o2.size()); for(int i=0;i<min;i++) { if(o1.get(i)!=o2.get(i)) { return o1.get(i).compareTo(o2.get(i)); } } return (o1.size()<=o2.size())? -1:1; } }); ```
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
No error check for null lists, but here it is. ``` List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); for (List<Integer> l : list) { Collections.sort(l); } Collections.sort(list, new Comparator<List<Integer>>() { public int compare(List<Integer> o1, List<Integer> o2) { return o1.get(0).compareTo(o2.get(0)); } }); System.out.println(list); ``` With Java 8 it gets even more concise: ``` List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); list.forEach(Collections::sort); Collections.sort(list, (l1, l2) -> l1.get(0).compareTo(l2.get(0))); System.out.println(list); ```
It will check up to last element of the list and sort them according to the requirement. ``` Collections.sort(res, new MIN()); ``` //method ``` static class MIN implements Comparator<ArrayList<Integer>> { public int compare(ArrayList<Integer> a,ArrayList<Integer> b) { for(int i=0;i<Math.min(a.size(),b.size());i++) { if(a.get(i)>b.get(i)) return 1; else if(a.get(i)<b.get(i)) return -1; else continue; } return a.size()-b.size(); } } ```
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
You could just sort each list individually. The `Collections.sort(collection)` will sort the Integers in ascending order automatically.
if sort doesnt have what u need you can try this algorithm: ``` package drawFramePackage; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.ListIterator; import java.util.Random; public class QuicksortAlgorithm { ArrayList<AffineTransform> affs; ListIterator<AffineTransform> li; Integer count, count2; /** * @param args */ public static void main(String[] args) { new QuicksortAlgorithm(); } public QuicksortAlgorithm(){ count = new Integer(0); count2 = new Integer(1); affs = new ArrayList<AffineTransform>(); for (int i = 0; i <= 128; i++){ affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0)); } affs = arrangeNumbers(affs); printNumbers(); } public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){ while (list.size() > 1 && count != list.size() - 1){ if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){ list.add(count, list.get(count2)); list.remove(count2 + 1); } if (count2 == list.size() - 1){ count++; count2 = count + 1; } else{ count2++; } } return list; } public void printNumbers(){ li = affs.listIterator(); while (li.hasNext()){ System.out.println(li.next()); } } } ```
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
You could just sort each list individually. The `Collections.sort(collection)` will sort the Integers in ascending order automatically.
This works for me ``` Collections.sort(list, new Comparator<List<Integer>>() { public int compare(List<Integer> o1, List<Integer> o2) { int min = Math.min(o1.size(),o2.size()); for(int i=0;i<min;i++) { if(o1.get(i)!=o2.get(i)) { return o1.get(i).compareTo(o2.get(i)); } } return (o1.size()<=o2.size())? -1:1; } }); ```
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
You could just sort each list individually. The `Collections.sort(collection)` will sort the Integers in ascending order automatically.
It will check up to last element of the list and sort them according to the requirement. ``` Collections.sort(res, new MIN()); ``` //method ``` static class MIN implements Comparator<ArrayList<Integer>> { public int compare(ArrayList<Integer> a,ArrayList<Integer> b) { for(int i=0;i<Math.min(a.size(),b.size());i++) { if(a.get(i)>b.get(i)) return 1; else if(a.get(i)<b.get(i)) return -1; else continue; } return a.size()-b.size(); } } ```
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
if sort doesnt have what u need you can try this algorithm: ``` package drawFramePackage; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.ListIterator; import java.util.Random; public class QuicksortAlgorithm { ArrayList<AffineTransform> affs; ListIterator<AffineTransform> li; Integer count, count2; /** * @param args */ public static void main(String[] args) { new QuicksortAlgorithm(); } public QuicksortAlgorithm(){ count = new Integer(0); count2 = new Integer(1); affs = new ArrayList<AffineTransform>(); for (int i = 0; i <= 128; i++){ affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0)); } affs = arrangeNumbers(affs); printNumbers(); } public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){ while (list.size() > 1 && count != list.size() - 1){ if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){ list.add(count, list.get(count2)); list.remove(count2 + 1); } if (count2 == list.size() - 1){ count++; count2 = count + 1; } else{ count2++; } } return list; } public void printNumbers(){ li = affs.listIterator(); while (li.hasNext()){ System.out.println(li.next()); } } } ```
This works for me ``` Collections.sort(list, new Comparator<List<Integer>>() { public int compare(List<Integer> o1, List<Integer> o2) { int min = Math.min(o1.size(),o2.size()); for(int i=0;i<min;i++) { if(o1.get(i)!=o2.get(i)) { return o1.get(i).compareTo(o2.get(i)); } } return (o1.size()<=o2.size())? -1:1; } }); ```
10,794,148
I am looking to sort an arraylist of arraylist of integers and I require help? I was informed that I need to implement comparator or comparable and then use the collection.sort to sort the list of list in order... ``` ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 ```
2012/05/29
[ "https://Stackoverflow.com/questions/10794148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127574/" ]
if sort doesnt have what u need you can try this algorithm: ``` package drawFramePackage; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.ListIterator; import java.util.Random; public class QuicksortAlgorithm { ArrayList<AffineTransform> affs; ListIterator<AffineTransform> li; Integer count, count2; /** * @param args */ public static void main(String[] args) { new QuicksortAlgorithm(); } public QuicksortAlgorithm(){ count = new Integer(0); count2 = new Integer(1); affs = new ArrayList<AffineTransform>(); for (int i = 0; i <= 128; i++){ affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0)); } affs = arrangeNumbers(affs); printNumbers(); } public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){ while (list.size() > 1 && count != list.size() - 1){ if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){ list.add(count, list.get(count2)); list.remove(count2 + 1); } if (count2 == list.size() - 1){ count++; count2 = count + 1; } else{ count2++; } } return list; } public void printNumbers(){ li = affs.listIterator(); while (li.hasNext()){ System.out.println(li.next()); } } } ```
It will check up to last element of the list and sort them according to the requirement. ``` Collections.sort(res, new MIN()); ``` //method ``` static class MIN implements Comparator<ArrayList<Integer>> { public int compare(ArrayList<Integer> a,ArrayList<Integer> b) { for(int i=0;i<Math.min(a.size(),b.size());i++) { if(a.get(i)>b.get(i)) return 1; else if(a.get(i)<b.get(i)) return -1; else continue; } return a.size()-b.size(); } } ```
28,289,256
I installed the latest (2015-02-03) MASShortcut as CocoaPod together with a correct bridging header for a very basic OS X Swift Application. I ended up with the following code and I do not know what I am doing wrong?: ``` import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func callback() { NSLog("callback") } func applicationDidFinishLaunching(aNotification: NSNotification) { let keyMask = NSEventModifierFlags.CommandKeyMask | NSEventModifierFlags.AlternateKeyMask let shortcut = MASShortcut.shortcutWithKeyCode(kVK_Space, modifierFlags: UInt(keyMask.rawValue)) MASShortcut.addGlobalHotkeyMonitorWithShortcut(shortcut, handler: callback) } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } } ``` Thanks in advance!
2015/02/03
[ "https://Stackoverflow.com/questions/28289256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4522072/" ]
There are a few issues here. Before fixing them you should make sure that you have `MASShortcut` 2.1.2 installed (you can see this in your `Podfile.lock`). If you don't you should run `pod update` to get the newest version. Another potential issue with you testing this is your shortcut conflicting with OS X default shortcuts. In your current example `Command`+`Option`+`Space` is bound to opening a Finder window and selecting the search field. If you have this disabled that's fine, otherwise I would recommend adding `Control` to your test case. So there are a few issues with your code so far. First off I would recommend changing your `keyMask` declaration a bit to: ``` let keyMask: NSEventModifierFlags = .CommandKeyMask | .ControlKeyMask | .AlternateKeyMask ``` This way Swift can infer the type and you only have to have `NSEventModifierFlags` once (notice that I added the `.ControlKeyMask` here for my comment above). A cool part about enums in Swift is that you can call `rawValue` on them. In this case the `rawValue` of `NSEventModifierFlags` is a `UInt` which will fix your type problem when creating your shortcut. Now your `keyCode` argument must be a `UInt` as well. So you can pull this out into a temporary value: ``` let keyCode = UInt(kVK_Space) ``` In Swift, methods that look like class level initializers are actually turned in to Swift initializers. So in this case, you're trying to call a class method called `shortcutWithKeyCode:modifierFlags:` when Swift has actually turned this into an initializer. So you can create your shortcut like this: ``` let shortcut = MASShortcut(keyCode: keyCode, modifierFlags: keyMask.rawValue) ``` Note the `rawValue` call to convert our modifier flags into a `UInt`. Finally, the API to register this shortcut globally is actually a method on `MASShortcutMonitor`. In your bridging header where you have: ``` #import <MASShortcut/MASShortcut.h> ``` You'll have to add a new import to get this API. The new one is: ``` #import <MASShortcut/MASShortcutMonitor.h> ``` Now you can register your shortcut: ``` MASShortcutMonitor.sharedMonitor().registerShortcut(shortcut, withAction: callback) ``` And your all set. Your callback function was already setup correctly! One last thing. I would recommend removing your shortcut in `applicationWillTerminate:` like this: ``` MASShortcutMonitor.sharedMonitor().unregisterAllShortcuts() ```
Wow, that is a great answer. Thank you so much! I realized that I should have studied the basics of Swift a little bit longer. Your solution works perfectly! However, one little detail is superfluous. You do not have to add the bridging header ``` #import <MASShortcut/MASShortcutMonitor.h> ``` if you create the bridging header file like it is shown in the documentation. My bridging header file contains ``` #import <Cocoa/Cocoa.h> #import <MASShortcut/Shortcut.h> ``` and Shortcut.h already refers to the MASShortcutMonitor.h. Again: Thanks a lot!!
30,506,502
I want to consume the API messages in c#.net and the response it may come continuously/frequently. Team suggest me to use Web sockets. But I consume the API thru HTTP. Can any one give idea which is better and advantages of Web-socket in continuous receiving the messages as well as in HTTP
2015/05/28
[ "https://Stackoverflow.com/questions/30506502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516583/" ]
HTTP normally uses a request/response model. It does not allow the server to send data to the client, unless the client first requested it. This can be worked around by letting the client regularly poll the server, or by using the long polling technique where the server delays the response until data is available. In both cases, the client will need to regularly make a new request (though less often with long polling). Web sockets remove these limitations so that polling or long polling is no longer needed.
You may try with ASP.NET SignalR which able to send and receive messages via HTTP. You can achieve real-time web functionality to your messaging application. It's able to have server code push content to connected clients instantly, rather than having the server wait for a client to request new data. Have a look at these samples -> <http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr>
61,354,248
Having trouble trying to change where Django looks for the default image in the ImageField. I am trying to store a default image within a folder in my "media" file. Code from models.py below: ``` from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') ``` When I load the page I get a 404 error: Not Found: /media/default.jpg [21/Apr/2020 18:11:48] "GET /media/default.jpg HTTP/1.1" 404 1795 Any ideas on how to add the "profile\_pics" piece to the path?
2020/04/21
[ "https://Stackoverflow.com/questions/61354248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12090552/" ]
Map function basically loops and returns result of each loop as an array. So basically all you need is an array of components in the end. There are just different routes to achieve it. Converting HashMap to an array and running a map on it is slower. Please avoid that. Below code will loop through just once. ``` function getComponents(myHashMap) { const comps = []; myHashMap.forEach((value, key) => comps.push(<MyComponent myKey={key} myValue={value} />)); return comps; } ``` Hope it helps.
You can derive an array of keys using the built-in `Map.prototype.forEach` and then use it for `.map` in your render <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach> ``` let myKeys = []; myHashMap.forEach((value, key) => myKeys.push(key); return ( { myKeys.map((item) => <MyComponent myKey={item} myValue={myHashMap.get(key)}/>) } ) ```
61,354,248
Having trouble trying to change where Django looks for the default image in the ImageField. I am trying to store a default image within a folder in my "media" file. Code from models.py below: ``` from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') ``` When I load the page I get a 404 error: Not Found: /media/default.jpg [21/Apr/2020 18:11:48] "GET /media/default.jpg HTTP/1.1" 404 1795 Any ideas on how to add the "profile\_pics" piece to the path?
2020/04/21
[ "https://Stackoverflow.com/questions/61354248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12090552/" ]
You guys gave great answers, but I found the simplest syntax: ```js Array.from(myHashMap.entries()).map((entry) => { const [key, value] = entry; return (<MyComponent myKey={key} myValue={value} />); } ```
You can derive an array of keys using the built-in `Map.prototype.forEach` and then use it for `.map` in your render <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach> ``` let myKeys = []; myHashMap.forEach((value, key) => myKeys.push(key); return ( { myKeys.map((item) => <MyComponent myKey={item} myValue={myHashMap.get(key)}/>) } ) ```
65,770,316
I'm trying to get the second to last non-null column per row, where the null could be in any column. Solutions such as this don't work due to where the null can be anywhere: [Pandas select the second to last column which is also not nan](https://stackoverflow.com/questions/37955900/pandas-select-the-second-to-last-column-which-is-also-not-nan) **Not Ideal Solution:** I was able to solve it with the following code, but there has to be a more concise way to write this. Any feedback would be appreciated. ``` data = [[1, 10, np.nan, np.nan], [2, 15, 13, np.nan], [9, 14, np.nan, np.nan]] df = pd.DataFrame(data, columns = ['a', 'b', 'c', 'd']) df['count_nulls'] = len(df.columns) - df.apply(lambda x: x.count(), axis=1) df['count_nonnull'] = df.apply(lambda x: x.count(), axis=1)-1 df['new_index'] = np.where(df['count_nonnull']==1, 1, np.where(df['count_nonnull']==0,0, df['count_nonnull'] - 1)) df['value'] = df.values[np.arange(len(df)), df['new_index']-1] df ```
2021/01/18
[ "https://Stackoverflow.com/questions/65770316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6545542/" ]
You can check for `notna` and do a reverse `cumsum` on `axis=1` , then get the first column that returns 2. and get its value using `df.lookup`: ``` u = df.notna().iloc[:,::-1].cumsum(axis=1) df['value'] = df.lookup(df.index,u.eq(2).dot(u.columns+',').str.split(',').str[0]) ``` --- ``` print(df) a b c d value 0 1 10 NaN NaN 1 1 2 15 13.0 NaN 15 2 9 14 NaN NaN 9 ``` Following comments since `lookup` is deprecated, one can use: ``` u = df.notna().iloc[:,::-1].cumsum(axis=1) v = u.eq(2).dot(u.columns+',').str.split(',').str[0] df['value'] = df.stack().loc[pd.MultiIndex.from_arrays((v.index,v))].to_numpy() ``` The other parts can be solved without resorting to apply, or the nested `np.where` ``` df.assign( count_nulls=df.isna().sum(1), count_non_null=df.notna().sum(1), new_index=lambda df: np.select( [df.count_non_null == 1, df.count_non_null == 0], [1, 0], df.count_non_null - 1)) ```
You can use [`pandas.DataFrame.apply`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html) and [`pandas.Series.shift`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html): ``` df.apply(lambda x: x.shift(x.isnull().sum())[-2], axis = 1) #0 1.0 #1 15.0 #2 9.0 ``` The idea is to shift the rows "number of `NaN`s" times, so the second to last that is not `NaN` will be always in the second to last position.
65,770,316
I'm trying to get the second to last non-null column per row, where the null could be in any column. Solutions such as this don't work due to where the null can be anywhere: [Pandas select the second to last column which is also not nan](https://stackoverflow.com/questions/37955900/pandas-select-the-second-to-last-column-which-is-also-not-nan) **Not Ideal Solution:** I was able to solve it with the following code, but there has to be a more concise way to write this. Any feedback would be appreciated. ``` data = [[1, 10, np.nan, np.nan], [2, 15, 13, np.nan], [9, 14, np.nan, np.nan]] df = pd.DataFrame(data, columns = ['a', 'b', 'c', 'd']) df['count_nulls'] = len(df.columns) - df.apply(lambda x: x.count(), axis=1) df['count_nonnull'] = df.apply(lambda x: x.count(), axis=1)-1 df['new_index'] = np.where(df['count_nonnull']==1, 1, np.where(df['count_nonnull']==0,0, df['count_nonnull'] - 1)) df['value'] = df.values[np.arange(len(df)), df['new_index']-1] df ```
2021/01/18
[ "https://Stackoverflow.com/questions/65770316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6545542/" ]
You can check for `notna` and do a reverse `cumsum` on `axis=1` , then get the first column that returns 2. and get its value using `df.lookup`: ``` u = df.notna().iloc[:,::-1].cumsum(axis=1) df['value'] = df.lookup(df.index,u.eq(2).dot(u.columns+',').str.split(',').str[0]) ``` --- ``` print(df) a b c d value 0 1 10 NaN NaN 1 1 2 15 13.0 NaN 15 2 9 14 NaN NaN 9 ``` Following comments since `lookup` is deprecated, one can use: ``` u = df.notna().iloc[:,::-1].cumsum(axis=1) v = u.eq(2).dot(u.columns+',').str.split(',').str[0] df['value'] = df.stack().loc[pd.MultiIndex.from_arrays((v.index,v))].to_numpy() ``` The other parts can be solved without resorting to apply, or the nested `np.where` ``` df.assign( count_nulls=df.isna().sum(1), count_non_null=df.notna().sum(1), new_index=lambda df: np.select( [df.count_non_null == 1, df.count_non_null == 0], [1, 0], df.count_non_null - 1)) ```
You can [`pandas.DataFrame.apply`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html), [`pandas.DataFrame.dropna`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html) and access the second last element. ``` >>> df.apply(lambda x:x.dropna().iloc[-2], axis=1) 0 1.0 1 15.0 2 9.0 ```
67,869,203
I have a json object as below in Azure Dashboard: {...,'Signal':'0.0',...} where the Signal can take on the values of 0.0 for No and 1.0 for Yes. I wish to convert these values to "yes" and "no" using Kusto. I tried to do the following but it doesn't work: | extend signal = tostring(replace(@"0.0",@"No",object['Signal'])) How do I fix this?
2021/06/07
[ "https://Stackoverflow.com/questions/67869203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9205507/" ]
This is done by AJAX, here are the steps 1. create a new view that checks the user status e.g is\_verified\_user and return True/False 2. write a JS function that will call the view and check response, it shall be something like this ``` function check_user_status(){ $.ajax({"url":"{%url 'is_verified_user'%}", success:function(data){ if (data == "True") { //change the colors} else setTimeout("check_user_status",3000) // Check again in 3 seconds } }) } ``` 3. Once the user clicks on 'verify your mobile number', call the `check_user_status` function to start checking. P.S you need JQuery for that.
Check the api response and use the ternary operator Example in React JS const [state, setState] = useState(false) useEffect( () => { // call api let response = axios.get('/') let result = response.verified ? true : false setState(result) },[state]) return ( )
18,030,990
I would like to retrieve all schemas in oracle and display in a combobox. I have been researching and knew that I can retrieve through GetSchema(). ``` DataTable table = connection.GetSchema(); ``` I don't know how to include the schemas in the list. ``` List<string> list = new List<string>(); return list; ``` Please help!
2013/08/03
[ "https://Stackoverflow.com/questions/18030990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136827/" ]
This code creates serial queue: ``` dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", NULL); ``` therefore each task IN QUEUE is performed in the same thread successive. Therefore your single work thread is sustained by sleep for each task of loading that slow down all process of loading. Use asynchronous CONCURRENT queue by using something like that: ``` dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", DISPATCH_QUEUE_CONCURRENT); ```
Use Lazy Load File for your requirement. [LazyLoad.h](https://gist.github.com/ipreencekmr/6146285) [LazyLoad.m](https://gist.github.com/ipreencekmr/6146286) Use them like this ``` - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; [cell addSubview:[self addViewWithURL:@"http://openwalls.com/image/399/explosion_of_colors_1920x1200.jpg" NFrame:CGRectMake(0, 0, 50, 50)]]; cell.backgroundColor=[UIColor blueColor]; return cell; } -(UIView*)addViewWithURL:(NSString*)urlStr NFrame:(CGRect)rect { LazyLoad *lazyLoading; lazyLoading = [[LazyLoad alloc] init]; [lazyLoading setBackgroundColor:[UIColor grayColor]]; [lazyLoading setFrame:rect]; [lazyLoading loadImageFromURL:[NSURL URLWithString:urlStr]]; return lazyLoading; } ``` [Download Demo Here](http://ge.tt/83goHmn/v/0)
18,030,990
I would like to retrieve all schemas in oracle and display in a combobox. I have been researching and knew that I can retrieve through GetSchema(). ``` DataTable table = connection.GetSchema(); ``` I don't know how to include the schemas in the list. ``` List<string> list = new List<string>(); return list; ``` Please help!
2013/08/03
[ "https://Stackoverflow.com/questions/18030990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136827/" ]
Trying to answer your main question "How can i load images to a `UICollectionview` asynchronously?" I would suggest solution offered by "*Natasha Murashev*" [here](http://natashatherobot.com/ios-how-to-download-images-asynchronously-make-uitableview-scroll-fast/), which worked nicely for me and it's simple. If here `imgURL = [allImage objectAtIndex:k];` in `allImage` property you keep array of URLs, then update your `collectionView:cellForItemAtIndexPath:` method like this: ``` - (PSTCollectionViewCell *)collectionView:(PSTCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { NSURL *url = [NSURL URLWithString:[allImage objectAtIndex:indexPath]]; [self downloadImageWithURL:url completionBlock:^(BOOL succeeded, NSData *data) { if (succeeded) { cell.grid_image.image = [[UIImage alloc] initWithData:data]; } }]; } ``` And add method `downloadImageWithURL:completionBlock:` to your class, which will load images asynchronously and update cells in CollectionView automatically when images are successfully downloaded. ``` - (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (!error) { completionBlock(YES, data); } else { completionBlock(NO, nil); } }]; } ``` I see you try to preload images before view appears so maybe my solution isn't what you what, but from your question it's hard to say. Any how, you can achieve what you want with this as well. **Swift 2.2** Solution in Swift. ``` public typealias ImageFetchCompletionClosure = (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void extension String { func fetchImage(completionHandler: (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void) { if let imageURL = NSURL(string: self) { NSURLSession.sharedSession().dataTaskWithURL(imageURL) { data, response, error in guard let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200, let mimeType = response?.MIMEType where mimeType.hasPrefix("image"), let data = data where error == nil, let image = UIImage(data: data) else { if error != nil { completionHandler(image: nil, error: error, imageURL: imageURL) } return } dispatch_sync(dispatch_get_main_queue()) { () -> Void in completionHandler(image: image, error: nil, imageURL: imageURL) } }.resume() } } } ``` Usage sample: ``` "url_string".fetchImage { (image, error, imageURL) in // handle different results, either image was downloaded or error received } ```
This code creates serial queue: ``` dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", NULL); ``` therefore each task IN QUEUE is performed in the same thread successive. Therefore your single work thread is sustained by sleep for each task of loading that slow down all process of loading. Use asynchronous CONCURRENT queue by using something like that: ``` dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", DISPATCH_QUEUE_CONCURRENT); ```
18,030,990
I would like to retrieve all schemas in oracle and display in a combobox. I have been researching and knew that I can retrieve through GetSchema(). ``` DataTable table = connection.GetSchema(); ``` I don't know how to include the schemas in the list. ``` List<string> list = new List<string>(); return list; ``` Please help!
2013/08/03
[ "https://Stackoverflow.com/questions/18030990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136827/" ]
Trying to answer your main question "How can i load images to a `UICollectionview` asynchronously?" I would suggest solution offered by "*Natasha Murashev*" [here](http://natashatherobot.com/ios-how-to-download-images-asynchronously-make-uitableview-scroll-fast/), which worked nicely for me and it's simple. If here `imgURL = [allImage objectAtIndex:k];` in `allImage` property you keep array of URLs, then update your `collectionView:cellForItemAtIndexPath:` method like this: ``` - (PSTCollectionViewCell *)collectionView:(PSTCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { NSURL *url = [NSURL URLWithString:[allImage objectAtIndex:indexPath]]; [self downloadImageWithURL:url completionBlock:^(BOOL succeeded, NSData *data) { if (succeeded) { cell.grid_image.image = [[UIImage alloc] initWithData:data]; } }]; } ``` And add method `downloadImageWithURL:completionBlock:` to your class, which will load images asynchronously and update cells in CollectionView automatically when images are successfully downloaded. ``` - (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (!error) { completionBlock(YES, data); } else { completionBlock(NO, nil); } }]; } ``` I see you try to preload images before view appears so maybe my solution isn't what you what, but from your question it's hard to say. Any how, you can achieve what you want with this as well. **Swift 2.2** Solution in Swift. ``` public typealias ImageFetchCompletionClosure = (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void extension String { func fetchImage(completionHandler: (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void) { if let imageURL = NSURL(string: self) { NSURLSession.sharedSession().dataTaskWithURL(imageURL) { data, response, error in guard let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200, let mimeType = response?.MIMEType where mimeType.hasPrefix("image"), let data = data where error == nil, let image = UIImage(data: data) else { if error != nil { completionHandler(image: nil, error: error, imageURL: imageURL) } return } dispatch_sync(dispatch_get_main_queue()) { () -> Void in completionHandler(image: image, error: nil, imageURL: imageURL) } }.resume() } } } ``` Usage sample: ``` "url_string".fetchImage { (image, error, imageURL) in // handle different results, either image was downloaded or error received } ```
Use Lazy Load File for your requirement. [LazyLoad.h](https://gist.github.com/ipreencekmr/6146285) [LazyLoad.m](https://gist.github.com/ipreencekmr/6146286) Use them like this ``` - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; [cell addSubview:[self addViewWithURL:@"http://openwalls.com/image/399/explosion_of_colors_1920x1200.jpg" NFrame:CGRectMake(0, 0, 50, 50)]]; cell.backgroundColor=[UIColor blueColor]; return cell; } -(UIView*)addViewWithURL:(NSString*)urlStr NFrame:(CGRect)rect { LazyLoad *lazyLoading; lazyLoading = [[LazyLoad alloc] init]; [lazyLoading setBackgroundColor:[UIColor grayColor]]; [lazyLoading setFrame:rect]; [lazyLoading loadImageFromURL:[NSURL URLWithString:urlStr]]; return lazyLoading; } ``` [Download Demo Here](http://ge.tt/83goHmn/v/0)
18,113,429
> > Notice: Undefined index: myusername in C:\xampp\htdocs\login\_in2.php on line 14 > Wrong Username or Password > > > ``` <?php $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="test"; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> ```
2013/08/07
[ "https://Stackoverflow.com/questions/18113429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2654476/" ]
The data is not being submitted, the error is related to trying to access the variable at `$_POST['']`. Some simple error checking should fix it: ``` <?php [..] if ( isset( $_POST['myusername'] ) && isset( $_POST['mypassword'] ) ) { // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; [...] } ?> ```
Could it be that you are mixing your quote marks? Instead of ``` $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'" ``` You might try ``` $sql="SELECT * FROM $tbl_name WHERE username='".$myusername."' and password='".$mypassword."'"; ```
18,113,429
> > Notice: Undefined index: myusername in C:\xampp\htdocs\login\_in2.php on line 14 > Wrong Username or Password > > > ``` <?php $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="test"; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> ```
2013/08/07
[ "https://Stackoverflow.com/questions/18113429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2654476/" ]
The data is not being submitted, the error is related to trying to access the variable at `$_POST['']`. Some simple error checking should fix it: ``` <?php [..] if ( isset( $_POST['myusername'] ) && isset( $_POST['mypassword'] ) ) { // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; [...] } ?> ```
Probably input form name has a typo. Replace ``` $myusername=$_POST['myusername']; with $myusername=$_POST['username']; ``` and ``` $mypassword=$_POST['mypassword']; with $mypassword=$_POST['password']; ``` in all instances.
18,113,429
> > Notice: Undefined index: myusername in C:\xampp\htdocs\login\_in2.php on line 14 > Wrong Username or Password > > > ``` <?php $host="localhost"; // Host name $username="root"; // Mysql username $password=""; // Mysql password $db_name="test"; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> ```
2013/08/07
[ "https://Stackoverflow.com/questions/18113429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2654476/" ]
The data is not being submitted, the error is related to trying to access the variable at `$_POST['']`. Some simple error checking should fix it: ``` <?php [..] if ( isset( $_POST['myusername'] ) && isset( $_POST['mypassword'] ) ) { // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; [...] } ?> ```
It's the html part you may check. you must name your username input "myusername" since you try to access it by using ``` $myusername=$_POST['myusername']; ``` you must have this on the html code ``` <input type="text" name="myusername" > ```
11,680,774
I tried to find another question with the answer to this but I've had no luck. My question is basically...will this work? ``` $insert_tweets = "INSERT INTO tweets ( 'id', 'created_at', 'from_user_id', 'profile_image', 'from_user', 'from_user_name', 'text' ) VALUES ( {$user_data[$i]["id"]}, {$user_data[$i]["created_at"]}, {$user_data[$i]["from_user_id"]}, {$user_data[$i]["profile_image"]}, {$user_data[$i]["from_user"]}, {$user_data[$i]["from_user_name"]}, {$user_data[$i]["text"]} )" for($i=0;$i<count($user_data);$i++){ mysqli_query($mysqli,$insert_tweets); } ``` $user\_data is a multi-dimensional array, the first level of which is numeric, the subsequent level is associative. Also, what would be the best way to "database prepare"/sanitize the associative array variables prior to insertion? I don't anticipate any malicious data but it is always possible.
2012/07/27
[ "https://Stackoverflow.com/questions/11680774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738201/" ]
``` for($i=0;$i<count($user_data);$i++){ $insert_tweets = "INSERT INTO tweets ('id','created_at','from_user_id','profile_image','from_user','from_user_name','text') VALUES ({$user_data[$i]["id"]},{$user_data[$i]["created_at"]},{$user_data[$i]["from_user_id"]},{$user_data[$i]["profile_image"]},{$user_data[$i]["from_user"]},{$user_data[$i]["from_user_name"]},{$user_data[$i]["text"]})"; mysqli_query($mysqli,$insert_tweets); } ``` This should work
Yes, it will work, but the best way to do this would be to use PDO. You can create nameless parameters in your prepare statement and then just pass in a array to bind values to those params. ``` $data = array('val1', 'val2'); $query = $db->prepare("INSERT INTO table (col1, col2) VALUES (? , ?)"); $query->execute($data); ``` PDO will escape the input values for you. Here's a tutorial on PDO to get you started <http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/>
11,680,774
I tried to find another question with the answer to this but I've had no luck. My question is basically...will this work? ``` $insert_tweets = "INSERT INTO tweets ( 'id', 'created_at', 'from_user_id', 'profile_image', 'from_user', 'from_user_name', 'text' ) VALUES ( {$user_data[$i]["id"]}, {$user_data[$i]["created_at"]}, {$user_data[$i]["from_user_id"]}, {$user_data[$i]["profile_image"]}, {$user_data[$i]["from_user"]}, {$user_data[$i]["from_user_name"]}, {$user_data[$i]["text"]} )" for($i=0;$i<count($user_data);$i++){ mysqli_query($mysqli,$insert_tweets); } ``` $user\_data is a multi-dimensional array, the first level of which is numeric, the subsequent level is associative. Also, what would be the best way to "database prepare"/sanitize the associative array variables prior to insertion? I don't anticipate any malicious data but it is always possible.
2012/07/27
[ "https://Stackoverflow.com/questions/11680774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738201/" ]
``` for($i=0;$i<count($user_data);$i++){ $insert_tweets = "INSERT INTO tweets ('id','created_at','from_user_id','profile_image','from_user','from_user_name','text') VALUES ({$user_data[$i]["id"]},{$user_data[$i]["created_at"]},{$user_data[$i]["from_user_id"]},{$user_data[$i]["profile_image"]},{$user_data[$i]["from_user"]},{$user_data[$i]["from_user_name"]},{$user_data[$i]["text"]})"; mysqli_query($mysqli,$insert_tweets); } ``` This should work
Here is my suggestion on sanitizing your array: What i do is create a basic function for sanitizing data: ``` function array_sanitize(&$item){ $item = mysql_real_escape_string($item); } ``` Then you can use the `array_walk()` to sanitize your array with your new function. ([php manual refrence](http://php.net/manual/en/function.array-walk.php)) and sanitize by passing in your array like this: ``` array_walk($user_data, 'array_sanitize'); ```
11,680,774
I tried to find another question with the answer to this but I've had no luck. My question is basically...will this work? ``` $insert_tweets = "INSERT INTO tweets ( 'id', 'created_at', 'from_user_id', 'profile_image', 'from_user', 'from_user_name', 'text' ) VALUES ( {$user_data[$i]["id"]}, {$user_data[$i]["created_at"]}, {$user_data[$i]["from_user_id"]}, {$user_data[$i]["profile_image"]}, {$user_data[$i]["from_user"]}, {$user_data[$i]["from_user_name"]}, {$user_data[$i]["text"]} )" for($i=0;$i<count($user_data);$i++){ mysqli_query($mysqli,$insert_tweets); } ``` $user\_data is a multi-dimensional array, the first level of which is numeric, the subsequent level is associative. Also, what would be the best way to "database prepare"/sanitize the associative array variables prior to insertion? I don't anticipate any malicious data but it is always possible.
2012/07/27
[ "https://Stackoverflow.com/questions/11680774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738201/" ]
Yes, it will work, but the best way to do this would be to use PDO. You can create nameless parameters in your prepare statement and then just pass in a array to bind values to those params. ``` $data = array('val1', 'val2'); $query = $db->prepare("INSERT INTO table (col1, col2) VALUES (? , ?)"); $query->execute($data); ``` PDO will escape the input values for you. Here's a tutorial on PDO to get you started <http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/>
Here is my suggestion on sanitizing your array: What i do is create a basic function for sanitizing data: ``` function array_sanitize(&$item){ $item = mysql_real_escape_string($item); } ``` Then you can use the `array_walk()` to sanitize your array with your new function. ([php manual refrence](http://php.net/manual/en/function.array-walk.php)) and sanitize by passing in your array like this: ``` array_walk($user_data, 'array_sanitize'); ```
23,208,700
I'm doing an app using Laravel, and I'm doing a login system. In login I don't have any problem, but in logout the browser gets an error ``` Whoops, looks like something went wrong. ``` My login function ``` public function postSignin() { if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))) { return Redirect::to('users/dashboard')->with('message', 'You are now logged in!'); } else { return Redirect::to('users/login') ->with('message', 'Your username/password combination was incorrect') ->withInput(); } } ``` My logout function ``` public function getLogout() { Auth::logout(); return Redirect::to('users/login')->with('message', 'Your are now logged out!'); } ``` If I remove the line `Auth::logout();` the page is redirected but I can't use the `Auth::check()` to verify the if the user is logged in. After having the error `Whoops, looks like something went wrong.` if I refresh the page the redirect is done properly. Any clue what the problem is? **Edited:** The error is just that ![enter image description here](https://i.stack.imgur.com/ZowKH.png)
2014/04/22
[ "https://Stackoverflow.com/questions/23208700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329124/" ]
If you are using Laravel version > 4.1.25 you may be missing the remember\_token field on the users table. see: <http://laravel.com/docs/upgrade#upgrade-4.1.26> Laravel requires "nullable remember\_token of VARCHAR(100), TEXT, or equivalent to your users table."
i hope to be helpful giving you this link to a package with build-in authentication signup and admin panel with permission handling. Fully customizable: <https://github.com/intrip/laravel-authentication-acl>