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
|
---|---|---|---|---|---|
3,910,625 | I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria?
I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete.
Any suggestions/ideas will be grately appreciated. | 2010/10/11 | [
"https://Stackoverflow.com/questions/3910625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472777/"
] | The problem with Java is that since it does the garbage collection automatically, and you can only induce it to happen, you cannot free resources at the exact moment you want them to be freed. The advantage is that you do not have to worry about objects being left behind, because they won't affect your memory in the long run (as long as you don't keep a reference to them, of course).
For optimal memory management, I would recommend C or C++, even though between those two, I would say C++ because of the high number of features it has. As for particular arguments regarding the memory management between C and C++, I do not know.
In any case, the fact that they allow you to treat things in a much more controlled and customized way, means that you must not relax and forget to do that management yourself.
Hope that helps. | Programmer managed memory in c and c++ is the root cause of many software bugs in programs written in those languages. This is one of the main reasons modern languages like Java and C# have garbage collection. |
3,910,625 | I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria?
I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete.
Any suggestions/ideas will be grately appreciated. | 2010/10/11 | [
"https://Stackoverflow.com/questions/3910625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472777/"
] | As for internal memory management, Java has the best of the three, since it automates disposing of objects.
If your question aims at performance, C or C++ would be a better bet. You would have to do all of the memory management yourself, but at the same time wouldn't have to wait for a Garbage Collector to do it's job.
IMO it all depends on your approach:
If you want to optimize your Application for Performance, go C or C++.
If you don't want to worry about memory management yourself, use Java. | Programmer managed memory in c and c++ is the root cause of many software bugs in programs written in those languages. This is one of the main reasons modern languages like Java and C# have garbage collection. |
3,910,625 | I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria?
I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete.
Any suggestions/ideas will be grately appreciated. | 2010/10/11 | [
"https://Stackoverflow.com/questions/3910625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472777/"
] | Java has memory management. C and C++ don't, so it's memory management is a function of the programmer. | The problem with Java is that since it does the garbage collection automatically, and you can only induce it to happen, you cannot free resources at the exact moment you want them to be freed. The advantage is that you do not have to worry about objects being left behind, because they won't affect your memory in the long run (as long as you don't keep a reference to them, of course).
For optimal memory management, I would recommend C or C++, even though between those two, I would say C++ because of the high number of features it has. As for particular arguments regarding the memory management between C and C++, I do not know.
In any case, the fact that they allow you to treat things in a much more controlled and customized way, means that you must not relax and forget to do that management yourself.
Hope that helps. |
3,910,625 | I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria?
I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete.
Any suggestions/ideas will be grately appreciated. | 2010/10/11 | [
"https://Stackoverflow.com/questions/3910625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472777/"
] | Java has memory management. C and C++ don't, so it's memory management is a function of the programmer. | As for internal memory management, Java has the best of the three, since it automates disposing of objects.
If your question aims at performance, C or C++ would be a better bet. You would have to do all of the memory management yourself, but at the same time wouldn't have to wait for a Garbage Collector to do it's job.
IMO it all depends on your approach:
If you want to optimize your Application for Performance, go C or C++.
If you don't want to worry about memory management yourself, use Java. |
3,910,625 | I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria?
I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete.
Any suggestions/ideas will be grately appreciated. | 2010/10/11 | [
"https://Stackoverflow.com/questions/3910625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472777/"
] | Thats a apples to oranges question in my book. C/c++ don't have memory management at least not in the language thats your job. That being said java will allocate and destroy memory for you all the live long day but at the cost of control. For the standard business app this is not at issue. You are going to load some bloated 3rd party code either way, but when it counts you have more power in c/c++. You also have more power to shoot yourself in the foot. | Java and C# have both garbage collection. This is a good thing because the programmer has less problems with memory management, and can concentrate on other problems. In C and C++ you must manually manage memory - for this you need much time and patience and experience.
JVM's garbage collector is fast enough, hence you almost don't feel the difference between time execution of C++ programs vs Java programs(C++ is supposed to be faster than java). |
3,910,625 | I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria?
I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete.
Any suggestions/ideas will be grately appreciated. | 2010/10/11 | [
"https://Stackoverflow.com/questions/3910625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472777/"
] | Thats a apples to oranges question in my book. C/c++ don't have memory management at least not in the language thats your job. That being said java will allocate and destroy memory for you all the live long day but at the cost of control. For the standard business app this is not at issue. You are going to load some bloated 3rd party code either way, but when it counts you have more power in c/c++. You also have more power to shoot yourself in the foot. | Programmer managed memory in c and c++ is the root cause of many software bugs in programs written in those languages. This is one of the main reasons modern languages like Java and C# have garbage collection. |
3,910,625 | I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria?
I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete.
Any suggestions/ideas will be grately appreciated. | 2010/10/11 | [
"https://Stackoverflow.com/questions/3910625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472777/"
] | The problem with Java is that since it does the garbage collection automatically, and you can only induce it to happen, you cannot free resources at the exact moment you want them to be freed. The advantage is that you do not have to worry about objects being left behind, because they won't affect your memory in the long run (as long as you don't keep a reference to them, of course).
For optimal memory management, I would recommend C or C++, even though between those two, I would say C++ because of the high number of features it has. As for particular arguments regarding the memory management between C and C++, I do not know.
In any case, the fact that they allow you to treat things in a much more controlled and customized way, means that you must not relax and forget to do that management yourself.
Hope that helps. | Java and C# have both garbage collection. This is a good thing because the programmer has less problems with memory management, and can concentrate on other problems. In C and C++ you must manually manage memory - for this you need much time and patience and experience.
JVM's garbage collector is fast enough, hence you almost don't feel the difference between time execution of C++ programs vs Java programs(C++ is supposed to be faster than java). |
3,910,625 | I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria?
I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete.
Any suggestions/ideas will be grately appreciated. | 2010/10/11 | [
"https://Stackoverflow.com/questions/3910625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472777/"
] | Java has memory management. C and C++ don't, so it's memory management is a function of the programmer. | Java and C# have both garbage collection. This is a good thing because the programmer has less problems with memory management, and can concentrate on other problems. In C and C++ you must manually manage memory - for this you need much time and patience and experience.
JVM's garbage collector is fast enough, hence you almost don't feel the difference between time execution of C++ programs vs Java programs(C++ is supposed to be faster than java). |
134,478 | I would like to attach an eyebolt to the ridgeline of my metal roof. I can then attach a rope to that when I need to work on the roof. I am a climber and have the knowledge and gear to secure myself. The rope is mainly to allow me to get up the 10/12 central part of the roof (the ridgeline of which I'll mount the eye-bolt), and not slide off the adjacent 5/12 portions of the roof. It will not be subject to dynamic loading (catching falls); the biggest loads it will sustain are when I haul on it to get up the 10/12 roof (it's impossible otherwise, very slippery).
Since the ridge cap is just a fairly flimsy piece of galvalume, the eyebolt must be secured without reliance on it (and RTV silicon caulked to it). My plan is to drill a hole through the ridge cap, the eyebolt will come through that, and then be attached to the rafters with two u-bolts. Since this is the ridge, it's where the rafters meet. So additionally, I will reinforce the rafters with two triangular shaped steel plates (one on each side of the area where the rafters meet); these will be bolted through the rafter with 2-3 bolts, and then the u-bolts will go through them as well.
This picture shows the detail.
[](https://i.stack.imgur.com/PLNdV.jpg) | 2018/03/13 | [
"https://diy.stackexchange.com/questions/134478",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/34111/"
] | If I may suggest an alternative since putting a hole in any roof is better avoided.
I have a 10/12 pitched roof and I use an extension ladder with a stand-off stabilizer to reach the peak.
[](https://i.stack.imgur.com/gLCUR.jpg)
The ladder is laid flat on the roof with the stabilizer pointing skyward. Extend the section and slide upward towards the peak and then flip the ladder so the stabilizer hooks over the peak.
Climb up the rungs which offer both hand and footholds. Once you’re at the peak, tie off your safety line, hoist a plank to lay on the opposite side of the peak and insert through the top rung. Lash it off or use pipe clamps and you’ve reinforced the setup. I have used it to rebuild chimneys, antenna work, placing hundreds of pounds of brick, etc... on it. | Here's what I ended up doing:
1. I mounted a piece of 6x6 oak between two rafters, just down from the ridgeline, butted flat against the roof underlayment, and secured with three anodized 4" timber screws through the rafters at each end. I did two of these, one of each side of the ridgeline.
2. I sourced some 1/2" by 4+" stainless steel shoulder lag eye bolts.
[](https://i.stack.imgur.com/2LKH7.png)
... and screwed them through the roofing metal and into the oak 6x6 pieces. I obtained some nylon washers (called a company that manufactures them and asked for samples) to use where the bolts penetrated the roof, to forestall galvanic corrosion between the SS and the galvalume. I sealed the penetration throughly with RTV silicon.
3. I sourced some 3/16" wire rope and hardware to make loops at each end, and used this to tie the two eyebolts together (outside, on top of the roof). I covered the wire rope with UV resistant plastic tubing where it lays over the galvalume ridge cap, again to avoid galvanic corrosion. The purpose of this is to create redundancy in my anchors: if the one I'm secured to should fail, the wire rope will keep me secured to the other. This will fail if the circular eye of the bolt fails, but this seems an unlikely failure point - the whole thing seems extremely secure, including the way I mounted the eye bolts to the 6x6 pieces. The only part that worries me a little is where the shoulder of the eye is attached to the threaded shaft of the bolt.
As far as using, some of this will only make sense to climbers:
1. I attach a piece of climbing rope to a 'biner with a retraced-figure8. Standing up through a "roof window" openable skylight in the loft, I use a stick clip to attach the 'biner to the near-side eyebolt.
2. I attach the rope to my harness with a grigri, with a safety knot below the grigri. I adjust the rope length as I move about the roof. I could move the 'biner to the other eyebolt when I go over the ridgeline to the other side of the roof.
3. When done, I do a procedure somewhat like cleaning a sport climb. I secure myself to the near-side eyebolt with a sling. Then I detach the rope and 'biner from the eyebolt. I thread the rope through the eyebolt and tie it to my harness.
4. Then I rappel down from the eyebolt to the roof window, using the grigri. |
134,478 | I would like to attach an eyebolt to the ridgeline of my metal roof. I can then attach a rope to that when I need to work on the roof. I am a climber and have the knowledge and gear to secure myself. The rope is mainly to allow me to get up the 10/12 central part of the roof (the ridgeline of which I'll mount the eye-bolt), and not slide off the adjacent 5/12 portions of the roof. It will not be subject to dynamic loading (catching falls); the biggest loads it will sustain are when I haul on it to get up the 10/12 roof (it's impossible otherwise, very slippery).
Since the ridge cap is just a fairly flimsy piece of galvalume, the eyebolt must be secured without reliance on it (and RTV silicon caulked to it). My plan is to drill a hole through the ridge cap, the eyebolt will come through that, and then be attached to the rafters with two u-bolts. Since this is the ridge, it's where the rafters meet. So additionally, I will reinforce the rafters with two triangular shaped steel plates (one on each side of the area where the rafters meet); these will be bolted through the rafter with 2-3 bolts, and then the u-bolts will go through them as well.
This picture shows the detail.
[](https://i.stack.imgur.com/PLNdV.jpg) | 2018/03/13 | [
"https://diy.stackexchange.com/questions/134478",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/34111/"
] | It may not look the best, but if you're going to install a fall arrest system on your roof this seems like a cheaper and tested solution. It's best not to try to MacGyver solutions when life safety is involved. I'd suggest covering the fasteners with a waterproofing tape once the system is installed to prevent as much water damage as possible.
[](https://i.stack.imgur.com/3NjhQ.png) | Here's what I ended up doing:
1. I mounted a piece of 6x6 oak between two rafters, just down from the ridgeline, butted flat against the roof underlayment, and secured with three anodized 4" timber screws through the rafters at each end. I did two of these, one of each side of the ridgeline.
2. I sourced some 1/2" by 4+" stainless steel shoulder lag eye bolts.
[](https://i.stack.imgur.com/2LKH7.png)
... and screwed them through the roofing metal and into the oak 6x6 pieces. I obtained some nylon washers (called a company that manufactures them and asked for samples) to use where the bolts penetrated the roof, to forestall galvanic corrosion between the SS and the galvalume. I sealed the penetration throughly with RTV silicon.
3. I sourced some 3/16" wire rope and hardware to make loops at each end, and used this to tie the two eyebolts together (outside, on top of the roof). I covered the wire rope with UV resistant plastic tubing where it lays over the galvalume ridge cap, again to avoid galvanic corrosion. The purpose of this is to create redundancy in my anchors: if the one I'm secured to should fail, the wire rope will keep me secured to the other. This will fail if the circular eye of the bolt fails, but this seems an unlikely failure point - the whole thing seems extremely secure, including the way I mounted the eye bolts to the 6x6 pieces. The only part that worries me a little is where the shoulder of the eye is attached to the threaded shaft of the bolt.
As far as using, some of this will only make sense to climbers:
1. I attach a piece of climbing rope to a 'biner with a retraced-figure8. Standing up through a "roof window" openable skylight in the loft, I use a stick clip to attach the 'biner to the near-side eyebolt.
2. I attach the rope to my harness with a grigri, with a safety knot below the grigri. I adjust the rope length as I move about the roof. I could move the 'biner to the other eyebolt when I go over the ridgeline to the other side of the roof.
3. When done, I do a procedure somewhat like cleaning a sport climb. I secure myself to the near-side eyebolt with a sling. Then I detach the rope and 'biner from the eyebolt. I thread the rope through the eyebolt and tie it to my harness.
4. Then I rappel down from the eyebolt to the roof window, using the grigri. |
17,220,607 | I have a stored procedure like this:
```
create proc calcaulateavaerage
@studentid int
as
begin
-- some complicated business and query
return @result -- single decimal value
end
```
and then I want to
create proc the whole result
```
select * , ................................ from X where X.value > (calculateaverage X.Id)
```
It always gives an error that reads like "multi-part identifier calculateaverage couldn't be bound." Any idea how to solve that? | 2013/06/20 | [
"https://Stackoverflow.com/questions/17220607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/712104/"
] | You don't want a stored procedure. You want a function. | Use Output variables to output the data out of stored procedure:
```
create proc calcaulateavaerage
@studentid int, @result int
as
begin
-- some complecated business and query
select @result = id from sometable;
end
-- Declaring output variable named result;
declare @result int;
-- Passing output variable to stored procedure.
exec calculateaverage 1, @result;
-- Now you can display the result or do whatever you like.
print @result
``` |
11,242,592 | I am facing a problem for several days and after many research I couldn't find anything that fit with my case.
Here's the thing :
I'm working with Visual Studio 2010 on a solution that contains several projects and a Setup Project. I want the setup project to create a MSI file to update the product from version 1.5 to version 1.6.
I followed this tutorial <http://www.simple-talk.com/dotnet/visual-studio/updates-to-setup-projects/> and updated also the assembly version and file version numbers of each project of the solution.
The settings of my Setup Project are :
DetectNewerInstalledVersion : **True**
InstallAllUsers : **True**
RemovePreviousVersions : **True**
Version : **1.6.3**
The ProductCode is different from the ProductCode of the previous version
and UpgradeCode is the same than the UpgradeCode of the previous version.
I read that normally the MSI should remove the files which version is newer than the existing ones and replace with the new ones. And when I run the previous MSI (those which updates the product from 1.4 to 1.5) it works just fine as described. (I'm not sure with which version of visual studio it was compiled but I guess it's with VS2008).
Now when I run my MSI, it seems that it first runs the "installation sequence" that replace the old .exe with the new ones, and then it runs the "uninstall sequence" that erase the .exe. And when the install is "finished" there is no more .exe in my application directory. (However in the "Add/Remove Programs" Panel the product apppears as installed in version 1.6).
(NB : I can notice when the "install" part or "uninstall" part of the MSI is running because both have Custom Actions that open a Console Application in which I can have a trace).
After more research I compared the old MSI with mine whith ORCA and I noticed differences in the table InstallExecuteSequence :
With the old MSI, the sequence number of RemoveExistingProducts is **1525** that is between InstallInitialize (1500) and AllocateRegistrySpace (1550).
With my MSI, the sequence number of RemoveExistingProducts is **6550** that is between InstallExecute (6500) and InstallFinalize (6600).
I can't see any other differencies in the table.
I even tried to edit manually with ORCA the MSI and put the sequence number of RemoveExistingProduct to 1525. At the execution the "uninstall part" ran correctly but then I got a 2356 Error (after a few research I guess this is because editing manually the MSI corrupted it).
If anyone have an idea that explains the behaviour of my MSI and how to fix it?
Thanks | 2012/06/28 | [
"https://Stackoverflow.com/questions/11242592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1488053/"
] | This appears to be a bug with the plugin
"Microsoft Visual Studio 2017 Installer Projects".
The msi file gets built with an incorrect sequence number (too high). The uninstall of older products happens *after* the install of new files, so new files get incorrectly deleted.
Manual fix: Change the sequence so that uninstall of old products happens before the install of new items.
* open the msi with orca.exe (or whatever editor works for you)
* go to the InstallExecuteSequence table
* change the RemoveExistingProducts
sequence number so that it is between InstallValidate and
InstallInitialize. For example, I changed it from 6550 to 1450.
I ended up creating a simple script to do this fix automatically as a post build step. You can get on github it here...
[InstallerStuff](https://github.com/DigitalCoastSoftware/InstallerStuff) | That article is just out of date in two respects:
1. It doesn't explain that the upgrade in later versions of Visual Studio setup projects was changed to be "on top" of the existing files, after which the older product is removed. This is not a bug, it's a feature. Example: If you installed a product with a database that was then populated by the customer with a million database entries, then the old upgrade removed it before installing the new version of the product.
2. Because the new version is installed over the older version the file replacement update rules are applied, such as newer versions replace older versions (based on file version) and files modified after first install are not removed (so preserving our hypothetical database).
<https://learn.microsoft.com/en-us/windows/desktop/msi/default-file-versioning>
Having said that, this doesn't appear to be the cause of the problem. If you upgraded from VS 2008 to VS 2010 it sounds like you have this issue:
<https://support.microsoft.com/en-us/help/2418919/fix-files-and-registry-keys-for-the-installation-path-disappear-unexpe> |
4,529,129 | We have the following recursive definition of a set
1. The number 1 belongs to set S
2. if x belongs to set S, then so does x+x
3. Only those elements defined by above rules belong to set S
Now, suppose x and y are two elements of set S. Prove that x\*y also belongs to set S.
I realize that the set defined by three rules is the set of powers of 2 i.e. {1, 2, 4, 8, 16, 32,.....}
and for any two powers of 2, we can use algebra to prove that their product is also a power of 2. But in this case, I need to prove that x\*y belongs to set S only by using the recursive definition of set S. | 2022/09/11 | [
"https://math.stackexchange.com/questions/4529129",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1093790/"
] | Since only the elements defined in this way are in the set, if $x\in S$ and $x\neq 1$, then $x/2\in S$. Suppose that $x\in S$ is the smallest element such that there exists $y\in S$ with $xy\not \in S$. We can't have $x$ or $y$ equal to $1$, so $x/2 \in S$. Then $(x/2)\*(2y)=xy\not \in S$, contradicting minimality of $x$. | Fix $x \in S$ and use induction on the recursive definition of the assertion that $y \in S$. In the base case, $y = 1$ and $x \times y = x \in S$, by assumption. In the inductive step $y = y' + y'$ where $y' \in S$ and the inductive hypothesis gives us that $x \times y' \in S$, but then $x\times y = (x \times y') + (x \times y')$ is also in $S$. |
24,207,428 | For my current project, I need to drop some pins on a image(NOT a map), and also should be able to click the pin to add some comments to this pin. I wonder if I can use MKAnnotation/MKAnnotationView to do this. I have searched on Internet for a while. I only find tutorials about how to customize MKAnnotation with other images.
If I cannot use MKAnnotation, what should I use? Any tutorials about this will be great helpful.
Thanks. | 2014/06/13 | [
"https://Stackoverflow.com/questions/24207428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3727706/"
] | Finally I found that when I want to read attribute user.MYATTR, i have to use name MYATTR.
I just wanna mention what interesting behaviour I found, that may lead to mystakes and i wanna warn you :)
My file has these two attributes:
user.MYATTR1
user.somethingElse.MYATTR2
When I was listing attributes using view.list() method I saw only this one (without user.):
MYATTR1
when i wanna read attribute value, i have to use name of attribute without 'user.', so for mentioned attributes it is:
MYATTR1
or
somethingElse.MYATTR2 | Did you read the [docs](http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/UserDefinedFileAttributeView.html) to the class `UserDefinedFileAttributeView`?
Reading carefully gives a few hints, why your code doesn't work properly.
For example you can check that:
>
> ... This *FileAttributeView* is not intended for use where the size of an
> attribute value is larger than [Integer.MAX\_VALUE](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE) ...
>
>
>
or check, if you have a security manager installed:
>
> ... in the case of the default provider at least, all methods that
> access user-defined attributes require the
> *RuntimePermission("accessUserDefinedAttributes")* permission when a
> security manager is installed. ...
>
>
>
Or try out another method to get an attribute:
>
> ... Where dynamic access to file attributes is required, the
> [getAttribute](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#getAttribute%28java.nio.file.Path,%20java.lang.String,%20java.nio.file.LinkOption...%29) method may be used to read the attribute value. The attribute value is returned as a byte array (byte[]). ...
>
>
>
Maybe any of the hints helps you, good luck! :-)
**EDIT**
Here's an example code, which checks, if your file system provides user defined file attributes and prints them (on succes):
```
Path file = Paths.get("filename.ext");
// check that user defined attributes are supported by the file system
FileStore store = file.getFileStore();
if (!store.supportsFileAttributeView("xattr")) {
System.err.format("UserDefinedFileAttributeView not supported on %s\n", store);
System.exit(-1);
}
UserDefinedFileAttributeView view = file.getFileAttributeView(UserDefinedFileAttributeView.class);
// list user defined attributes
if (args.length == 1) {
System.out.println(" Size Name");
System.out.println("-------- --------------------------------------");
for (String name: view.list()) {
System.out.format("%8d %s\n", view.size(name), name);
}
}
```
Full source code [here](http://www-inf.int-evry.fr/cours/java/javatutorial/essential/io/examples/Xdd.java) linked from [this page](http://www-inf.int-evry.fr/cours/java/javatutorial/essential/io/fileAttr.html#user) your question code is from ;-) |
5,248,028 | jQuery 1.4 added [a shorthand way for constructing new DOM Elements](http://api.jquery.com/jQuery/#jQuery2) and filling in some of their attributes:
>
> `jQuery( html, props )`
>
>
> `html`: A string defining a single, standalone, HTML element (e.g. or ).
>
>
> `props`: A map of attributes, events, and methods to call on the newly-created element.
>
>
>
But, I just noticed this strangeness (with jQuery 1.5.1):
```
>>> $("<img />", { height: 4 })[0].height
0
>>> $("<img />").attr({ height: 4 })[0].height
4
```
So, they are some differences between the shorthand and the longer way..! Is this a bug or is it intentional? Are there any other ones with similar behaviour which I should watch out for? | 2011/03/09 | [
"https://Stackoverflow.com/questions/5248028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | From the [docs](http://api.jquery.com/jQuery/#jQuery2):
>
> As of jQuery 1.4, the second argument
> can accept a map consisting of a
> superset of the properties that can be
> passed to the `.attr()` method.
> Furthermore, any event type can be
> passed in, and the following jQuery
> methods can be called: val, css, html,
> text, data, width, height, or offset.
>
>
>
So basically the snippet is not equivalent to `$("<img />").attr({ height: 4 })` but to `$("<img />").height(4)` and the html it evaluates to is `<img style="height: 4px" />` - hence the returned `0`. | The short way should be :
```
$("<img />", { height: 4 }).height();
``` |
5,248,028 | jQuery 1.4 added [a shorthand way for constructing new DOM Elements](http://api.jquery.com/jQuery/#jQuery2) and filling in some of their attributes:
>
> `jQuery( html, props )`
>
>
> `html`: A string defining a single, standalone, HTML element (e.g. or ).
>
>
> `props`: A map of attributes, events, and methods to call on the newly-created element.
>
>
>
But, I just noticed this strangeness (with jQuery 1.5.1):
```
>>> $("<img />", { height: 4 })[0].height
0
>>> $("<img />").attr({ height: 4 })[0].height
4
```
So, they are some differences between the shorthand and the longer way..! Is this a bug or is it intentional? Are there any other ones with similar behaviour which I should watch out for? | 2011/03/09 | [
"https://Stackoverflow.com/questions/5248028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | From the [docs](http://api.jquery.com/jQuery/#jQuery2):
>
> As of jQuery 1.4, the second argument
> can accept a map consisting of a
> superset of the properties that can be
> passed to the `.attr()` method.
> Furthermore, any event type can be
> passed in, and the following jQuery
> methods can be called: val, css, html,
> text, data, width, height, or offset.
>
>
>
So basically the snippet is not equivalent to `$("<img />").attr({ height: 4 })` but to `$("<img />").height(4)` and the html it evaluates to is `<img style="height: 4px" />` - hence the returned `0`. | The difference is setting the attr will add a height attribute, the other forms set the height style property. So the shorthand version sets the style rather than the `height` attribute:
```
$("<img />", { height: 4 });
// creates <img style="height:4px;">
$("<img />").height(4);
// creates <img style="height:4px;">
$("<img />").attr({height: 4});
// creates <img height="4">
```
This is the case whether you append the element into the DOM or not (with jquery 1.4.4 and 1.5.1). Apologies if I'm restating something already covered in the comments. |
753,813 | I'm trying to lay out some images in code using addSubview, and they are not showing up.
I created a class (myUIView) that subclasses UIView, and then changed the class of the nib file in IB to be myUIView.
Then I put in the following code, but am still getting a blank grey screen.
```
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
[self setupSubviews];
}
return self;
}
- (void)setupSubviews
{
self.backgroundColor = [UIColor blackColor];
UIImageView *black = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"black.png"]];
black.center = self.center;
black.opaque = YES;
[self addSubview:black];
[black release];
}
``` | 2009/04/15 | [
"https://Stackoverflow.com/questions/753813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82780/"
] | yes, just implement initWithCoder.
initWithFrame is called when a UIView is created dynamically, from code.
a view that is loaded from a .nib file is always instantiated using initWithCoder, the coder takes care of reading the settings from the .nib file
i took the habit to do the initialization in a separate method, implementing both initWithCode and initWithFrame (and my own initialization methods when required) | try implementing `initWithCoder:` sometimes I've had trouble with IB and `initWithFrame:`
or at least add a logging call to see if your init method is executed |
1,738,022 | Assume M has only a countable or finite number of points and M is connected. Prove that every continuous function f:M->R is a constant function on all of M.
Here is what I have so far:
If f: M->R is continuous and M is connected then f(M) is connected in R. Hence f(M) is an interval because it is a connected subset of R. Since M has only a finite number of points, the only interval it can be mapped to is a single point, hence f is a constant function.
I am confused how to go from f(M) being an interval to that actually meaning it is only a single point to prove that it is a constant function. | 2016/04/11 | [
"https://math.stackexchange.com/questions/1738022",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/317811/"
] | The cardinality of $f(M)$ is at most the cardinality of $M$, thus countable or finite. The only nonempty intervals of $\mathbb R$ that are countable or finite are singletons. | $M$ finite implies $|f(M)|< \infty$. Since $f(M)$ is connected then it can't be a union of singletons because that is a disconnected space. Therefore, $|f(M)| = 1$ i.e $f$ is constant. |
32,179,545 | I have 2 input boxes for first name and last name of passengers travelling.
There could be maximum 9 number of passengers.
It is not allowed to have two passengers with same name(first and last combined)
How can I check if none of the passenger have same names(first and last name combined)
```
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;">
```
Thanks.
**Edit:**
I am not using a database to store the passenger names and the passengers are all entered on the same page. | 2015/08/24 | [
"https://Stackoverflow.com/questions/32179545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4895885/"
] | You can add a verification javascript function , but first u need to have specific names for all input boxes .
U can try something like this :
```
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;" OnClick="Verify();">
.
.
.
<input type="text" name="adultFirstName10" id="adultFirstName10" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;" OnClick="Verify(id);">
```
then you'll need to verify at every change of value of a boxe . | Are there 2 input boxes for each passenger? If so, try something like this:
```
$(document).ready(function(){
$("button").click(function(){
if($("#adultFirstName1").val() == $("#adultFirstName2").val()
&& $("#adultLastName1").val() == $("#adultLastName2").val()) {
//Names are the same
}
});
});
```
Or are you needing to check against the names of other passengers already in a database somewhere? |
32,179,545 | I have 2 input boxes for first name and last name of passengers travelling.
There could be maximum 9 number of passengers.
It is not allowed to have two passengers with same name(first and last combined)
How can I check if none of the passenger have same names(first and last name combined)
```
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;">
```
Thanks.
**Edit:**
I am not using a database to store the passenger names and the passengers are all entered on the same page. | 2015/08/24 | [
"https://Stackoverflow.com/questions/32179545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4895885/"
] | ```
var name=[];
var sameName=false;
for(var i=1;i<=<%=detailsModel.getNumberOfAdult()%>;i++)
{
var fullName = document.getElementById("adultFirstName"+i).value+" "+document.getElementById("adultLastName"+i).value
name.push(fullName);
}
for(var i=1;i<=<%=detailsModel.getNumberOfChild()%>;i++)
{
var fullName = document.getElementById("childFirstName"+i).value+" "+document.getElementById("childLastName"+i).value
name.push(fullName);
}
for(var i=1;i<=<%=detailsModel.getNumberOfInfant()%>;i++)
{
var fullName = document.getElementById("infantFirstName"+i).value+" "+document.getElementById("infantLastName"+i).value
name.push(fullName);
}
for(var i=0;i<name.length;i++)
{
for(var j=i+1;j<name.length;j++)
{
if(name[i]==name[j])
{
var sameName=true
valid= false;
}
}
}
if(sameName==true)
{
$('#sameNameError').html('2 Passengers Cannot Have Same Name');
}
else
{
$('#sameNameError').html('');
}
``` | Are there 2 input boxes for each passenger? If so, try something like this:
```
$(document).ready(function(){
$("button").click(function(){
if($("#adultFirstName1").val() == $("#adultFirstName2").val()
&& $("#adultLastName1").val() == $("#adultLastName2").val()) {
//Names are the same
}
});
});
```
Or are you needing to check against the names of other passengers already in a database somewhere? |
32,179,545 | I have 2 input boxes for first name and last name of passengers travelling.
There could be maximum 9 number of passengers.
It is not allowed to have two passengers with same name(first and last combined)
How can I check if none of the passenger have same names(first and last name combined)
```
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;">
```
Thanks.
**Edit:**
I am not using a database to store the passenger names and the passengers are all entered on the same page. | 2015/08/24 | [
"https://Stackoverflow.com/questions/32179545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4895885/"
] | ```
var name=[];
var sameName=false;
for(var i=1;i<=<%=detailsModel.getNumberOfAdult()%>;i++)
{
var fullName = document.getElementById("adultFirstName"+i).value+" "+document.getElementById("adultLastName"+i).value
name.push(fullName);
}
for(var i=1;i<=<%=detailsModel.getNumberOfChild()%>;i++)
{
var fullName = document.getElementById("childFirstName"+i).value+" "+document.getElementById("childLastName"+i).value
name.push(fullName);
}
for(var i=1;i<=<%=detailsModel.getNumberOfInfant()%>;i++)
{
var fullName = document.getElementById("infantFirstName"+i).value+" "+document.getElementById("infantLastName"+i).value
name.push(fullName);
}
for(var i=0;i<name.length;i++)
{
for(var j=i+1;j<name.length;j++)
{
if(name[i]==name[j])
{
var sameName=true
valid= false;
}
}
}
if(sameName==true)
{
$('#sameNameError').html('2 Passengers Cannot Have Same Name');
}
else
{
$('#sameNameError').html('');
}
``` | You can add a verification javascript function , but first u need to have specific names for all input boxes .
U can try something like this :
```
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;" OnClick="Verify();">
.
.
.
<input type="text" name="adultFirstName10" id="adultFirstName10" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;" OnClick="Verify(id);">
```
then you'll need to verify at every change of value of a boxe . |
13,080,956 | I have seen that it is possible but not easy to configure cross-compiling with Free Pascal, as there have to be libraries of the target OS on the system.
But I only need a quick syntax-check to verify that the project can be compiled, linking an executable is not required.
So: are there compiler options which I can use to do a **cross-platform test compile** (only) with Free Pascal?
In my case, before checking in the project in source control, I would like to verify on a Windows workstation if the compiler can compile for a Linux or OSX target. | 2012/10/26 | [
"https://Stackoverflow.com/questions/13080956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80901/"
] | Do you ever call init for any instance of that class ?
somewhere in your code you should have :
```
untitled *myObj = [[untitled alloc] init];
```
If not, then this is the reason why it is not called. | I apologize to all who wasted time looking at the result of my bonehead errors.
Several combined, but mainly I realized that those authors were using an NSView class with initWithFrame, which runs at startup like it should with no additions to UntitledAppDelegate.
I still haven't figured out why a simple init in an NSObject class doesn't run at startup.
```
- (id)init {
if (self = [super init]) {
NSLog(@"Foo");
}
return self;
}
``` |
13,080,956 | I have seen that it is possible but not easy to configure cross-compiling with Free Pascal, as there have to be libraries of the target OS on the system.
But I only need a quick syntax-check to verify that the project can be compiled, linking an executable is not required.
So: are there compiler options which I can use to do a **cross-platform test compile** (only) with Free Pascal?
In my case, before checking in the project in source control, I would like to verify on a Windows workstation if the compiler can compile for a Linux or OSX target. | 2012/10/26 | [
"https://Stackoverflow.com/questions/13080956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80901/"
] | Do you ever call init for any instance of that class ?
somewhere in your code you should have :
```
untitled *myObj = [[untitled alloc] init];
```
If not, then this is the reason why it is not called. | ```
untitled *object = [untitled new];
``` |
41,922,466 | I would like to automatically route to a login page if the user is not logged in.
app.module.ts
=============
```
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { DashBoardComponent} from './dashboard/dashboard.component';
import { NotFoundComponent } from './not-found/not-found.component';
const APPROUTES: Routes = [
{path: 'home', component: AppComponent},
{path: 'login', component: LoginComponent},
{path: 'dashboard', component: DashboardComponent},
{path: '**', component: NotFoundComponent}
];
@NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent
NotFoundComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule.forRoot(),
RouterModule.forRoot(APPROUTES)
],
providers: [],
bootstrap: [AppComponent]
})
```
If the user isn't logged in, the `LoginComponent` should load, otherwise the `DashboardComponent`. | 2017/01/29 | [
"https://Stackoverflow.com/questions/41922466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6865232/"
] | Here are 3 ways to do what you asked, from least preferred to favorite:
**Option 1. Imperatively redirect the user in `AppComponent`**
```ts
@Component({
selector: 'app-root',
template: `...`
})
export class AppComponent {
constructor(authService: AuthService, router: Router) {
if (authService.isLoggedIn()) {
router.navigate(['dashboard']);
}
}
}
```
Not very good. It's better to keep the "login required" information in the route declaration where it belongs.
**Option 2. Use a `CanActivate` guard**
Add a `CanActivate` guard to all the routes that require the user to be logged in:
```ts
const APPROUTES: Routes = [
{path: 'home', component: AppComponent, canActivate:[LoginActivate]},
{path: 'dashboard', component: DashBoardComponent, canActivate:[LoginActivate]},
{path: 'login', component: LoginComponent},
{path: '**', component: NotFoundComponent}
];
```
My guard is called `LoginActivate`.
For it to work I must add the guard to my module's `providers`.
And then I need to implement it. In this example I'll use the guard to redirect the user if they're not logged in:
```ts
@Injectable()
export class LoginActivate implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['login']);
}
return true;
}
}
```
Check out the doc about route guards if this doesn't make sense: <https://angular.io/docs/ts/latest/guide/router.html#guards>
This option is better but not super flexible. What if we need to check for other conditions than "logged in" such as the user permissions? What if we need to pass some parameter to the guard, like the name of a role "admin", "editor"...?
**Option 3. Use the route `data` property**
The best solution IMHO is to **add some metadata in the routes declaration** to indicate "this route requires that the user be logged in".
We can use the route `data` property for that. It can hold arbitrary data and in this case I chose to include a `requiresLogin` flag that's either `true` or `false` (`false` will be the default if the flag is not defined):
```ts
const APPROUTES: Routes = [
{path: 'home', component: AppComponent, data:{requiresLogin: true}},
{path: 'dashboard', component: DashBoardComponent, data:{requiresLogin: true}}
];
```
Now the `data` property in itself doesn't do anything. But I can use it to enforce my "login required" logic. For that I need a `CanActivate` guard again.
Too bad, you say. Now I need to add 2 things to each protected route: the metadata AND the guard...
BUT:
* You can attach the `CanActivate` guard to a top-level route and *it will be executed for all of its children routes* [TO BE CONFIRMED]. That way you only need to use the guard once. Of course, it only works if the routes to protect are all children of a parent route (that's not the case in Rafael Moura's example).
* The `data` property allows us pass all kinds of parameters to the guard, e.g. the name of a specific role or permission to check, a number of points or credits that the user needs to possess to access the page, etc.
Taking these remarks into account, it's best to rename the guard to something more generic like `AccessGuard`.
I'll only show the piece of code where the guard retrieves the `data` attached to the route, as what you do inside the guard really depends on your situation:
```ts
@Injectable()
export class AccessGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot): Observable<boolean>|Promise<boolean>|boolean {
const requiresLogin = route.data.requiresLogin || false;
if (requiresLogin) {
// Check that the user is logged in...
}
}
}
```
For the above code to be executed, you need to have a route similar to:
```ts
{
path: 'home',
component: AppComponent,
data: { requiresLogin: true },
canActivate: [ AccessGuard ]
}
```
NB. Don't forget to add `AccessGuard` to your module's `providers`. | You can also do something like this:
```
{
path: 'home',
component: getHomeComponent(),
data: { requiresLogin: true },
canActivate: [ AccessGuard ]
}
```
And then:
```
export function getHomeComponent(): Type<Component> {
if (User.isLoggedIn) {
return <Type<Component>>HomeComponent;
}
else{
return <Type<Component>>LoginComponent;
}
}
``` |
28,470,591 | I am trying to upload images to DB using below code,
MyJsp.jsp
```
<form action="ImageUploadToDB" method="post" enctype="multipart/form-data">
<div>
<img alt="Image1" id="Image11" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files11" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image2" id="Image12" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files12" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image3" id="Image13" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files13" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image4" id="Image14" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files14" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image5" id="Image15" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files15" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
</div>
</form>
```
I am inserting all uploaded images from above form by using servlet like below,
```
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
fileMap.put(item.getName(), item.getInputStream());
//System.out.println("uploaded images here:"+item.getName());
}
}
}
}
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
String sql ="INSERT INTO contacts2 (images) values (?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setBlob(1, fileMap.get(fileName));
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
```
If i uploading such as images1.jpg, images2.jpg, images3.jpg, images4.jpg, images5.jpg then my output is :
```
inserted successfully:
inserted successfully:
inserted successfully:
inserted successfully:
inserted successfully:
```
But if i uploading such as images1.jpg, images2.jpg, images1.jpg, images4.jpg, images2.jpg then my output is :
```
inserted successfully:
inserted successfully:
inserted successfully:
```
when i check my DB there is image1.jpg, image2.jpg, image4.jpg only.I have no idea why that same name of images not inserting to DB.
Someone tell me where i am wrong?
Updated :
This is for Mr.Keval's answer
```
fileMap.put((item.getName() + "" + new Date().getTime()), item.getInputStream());
int count2 =5;
for (int
k=0;k<5;k++) {
System.out.println("for successfully:");
String sql ="INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setString(1, clas);
statement.setString(2, subject);
statement.setString(3, uid);
System.out.println("Qimg name is:"+listGet.get(k));
statement.setString(4, listGet.get(k));
System.out.println("Qimg is:"+fileMap.values().toArray()[k]);
Object bb = fileMap.values().toArray()[k];
// System.out.println("Qimg is:"+listGet2.get(listgetcount));
// System.out.println("finallyyyy:"+fileMap.get("files1"));
statement.setBinaryStream(5, (InputStream) bb);
// System.out.println("Aimg name is:"+listGet.get(count2));
statement.setString(6, listGet.get(count2));
//System.out.println("Aimg is:"+fileMap.values().toArray()[count2]);
Object bb2 = fileMap.values().toArray()[count2];
//System.out.println("Qimg is:"+fileMap.get("files2"));
//String getval2 = listGet2.get(count2);
statement.setBinaryStream(7, (InputStream) bb2);
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
count2=count2+1;
}
```
If i upload same images then shows like
```
for successfully:
Qimg name is:image1.jpg
Qimg is:java.io.FileInputStream@f747c0
inserted successfully:
for successfully:
Qimg name is:image4.jpg
Qimg is:java.io.FileInputStream@fd4f30
inserted successfully:
for successfully:
Qimg name is:image5.jpg
Qimg is:java.io.FileInputStream@1b654b9
inserted successfully:
for successfully:
Qimg name is:image7.jpg
Qimg is:java.io.FileInputStream@1303c07
inserted successfully:
for successfully:
Qimg name is:image9.jpg
Qimg is:java.io.FileInputStream@110b3f6
java.lang.ArrayIndexOutOfBoundsException: 9
``` | 2015/02/12 | [
"https://Stackoverflow.com/questions/28470591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3766129/"
] | Since you are using `LinkedHashMap` with the names of files as keys, when you add two files of the same name (two entries with the same key), the latter will replace the former. This is causing the entries with duplicate names to be replaced. Consider using an ArrayList of a class (that you create) containing the file name and the `InputStream` to store this data.
Edit: my suggestion in code (untested)
```
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
ArrayList<FileWithStream> fileMap = new ArrayList<FileWithStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
fileMap.add(new FileWithStream(item.getName(), item.getInputStream()));
//System.out.println("uploaded images here:"+item.getName());
}
}
}
}
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
for (FileWithStream file : fileMap) {
String sql ="INSERT INTO contacts2 (images) values (?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setBlob(1, file.getStream());
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
```
with a class like:
```
public class FileWithStream {
private String name;
private InputStream stream;
public FileWithStream(String name, InputStream stream) {
this.name = name;
this.stream = stream;
}
public String getName() {
return name;
}
public InputStream getStream() {
return stream;
}
}
``` | Finally i got answer using below code,
```
Connection con1 =null;
Statement stmt=null;
int GetUniqueId=0;
System.out.println("Entered successfully 1:");
try
{
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
String sql1 ="select contact_id from contacts order by contact_id desc limit 1" ;
stmt = con1.createStatement();
ResultSet rst = stmt.executeQuery(sql1);
if(rst.next())
{
//String newone = rst.getString("contact_id");
GetUniqueId = Integer.parseInt(rst.getString("AutoIncrementValue"));
System.out.println("Ifffffffffffff"+GetUniqueId);
}
else
{
GetUniqueId = 0;
System.out.println("elseeeeeeeeeeee"+GetUniqueId);
}
}
catch(Exception ex)
{
System.out.println(ex);
}
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
// item.getName() - gives file name
GetUniqueId = GetUniqueId+1;
String getfirst = item.getName();
String [] get = getfirst.split("\\.");
System.out.println("splited :"+get[0]);
System.out.println("splited :"+get[1]);
getchange = get[0];
getchange = getchange+""+ GetUniqueId;
String addjpg =getchange+"."+get[1];
System.out.println("splited finally :"+addjpg);
fileMap.put(addjpg, item.getInputStream());
listGetImgName.add(addjpg);
}
}
}
}
```
Its working fine now. Thanks to Mr.Keval and Mr.colavitam |
28,470,591 | I am trying to upload images to DB using below code,
MyJsp.jsp
```
<form action="ImageUploadToDB" method="post" enctype="multipart/form-data">
<div>
<img alt="Image1" id="Image11" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files11" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image2" id="Image12" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files12" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image3" id="Image13" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files13" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image4" id="Image14" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files14" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image5" id="Image15" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files15" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
</div>
</form>
```
I am inserting all uploaded images from above form by using servlet like below,
```
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
fileMap.put(item.getName(), item.getInputStream());
//System.out.println("uploaded images here:"+item.getName());
}
}
}
}
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
String sql ="INSERT INTO contacts2 (images) values (?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setBlob(1, fileMap.get(fileName));
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
```
If i uploading such as images1.jpg, images2.jpg, images3.jpg, images4.jpg, images5.jpg then my output is :
```
inserted successfully:
inserted successfully:
inserted successfully:
inserted successfully:
inserted successfully:
```
But if i uploading such as images1.jpg, images2.jpg, images1.jpg, images4.jpg, images2.jpg then my output is :
```
inserted successfully:
inserted successfully:
inserted successfully:
```
when i check my DB there is image1.jpg, image2.jpg, image4.jpg only.I have no idea why that same name of images not inserting to DB.
Someone tell me where i am wrong?
Updated :
This is for Mr.Keval's answer
```
fileMap.put((item.getName() + "" + new Date().getTime()), item.getInputStream());
int count2 =5;
for (int
k=0;k<5;k++) {
System.out.println("for successfully:");
String sql ="INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setString(1, clas);
statement.setString(2, subject);
statement.setString(3, uid);
System.out.println("Qimg name is:"+listGet.get(k));
statement.setString(4, listGet.get(k));
System.out.println("Qimg is:"+fileMap.values().toArray()[k]);
Object bb = fileMap.values().toArray()[k];
// System.out.println("Qimg is:"+listGet2.get(listgetcount));
// System.out.println("finallyyyy:"+fileMap.get("files1"));
statement.setBinaryStream(5, (InputStream) bb);
// System.out.println("Aimg name is:"+listGet.get(count2));
statement.setString(6, listGet.get(count2));
//System.out.println("Aimg is:"+fileMap.values().toArray()[count2]);
Object bb2 = fileMap.values().toArray()[count2];
//System.out.println("Qimg is:"+fileMap.get("files2"));
//String getval2 = listGet2.get(count2);
statement.setBinaryStream(7, (InputStream) bb2);
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
count2=count2+1;
}
```
If i upload same images then shows like
```
for successfully:
Qimg name is:image1.jpg
Qimg is:java.io.FileInputStream@f747c0
inserted successfully:
for successfully:
Qimg name is:image4.jpg
Qimg is:java.io.FileInputStream@fd4f30
inserted successfully:
for successfully:
Qimg name is:image5.jpg
Qimg is:java.io.FileInputStream@1b654b9
inserted successfully:
for successfully:
Qimg name is:image7.jpg
Qimg is:java.io.FileInputStream@1303c07
inserted successfully:
for successfully:
Qimg name is:image9.jpg
Qimg is:java.io.FileInputStream@110b3f6
java.lang.ArrayIndexOutOfBoundsException: 9
``` | 2015/02/12 | [
"https://Stackoverflow.com/questions/28470591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3766129/"
] | While putting values in map
>
> ...
>
>
> fileMap.put(item.getName(), item.getInputStream());
>
>
> ....
>
>
>
You have kept "File Name" as key and map keep only last added value, in case of duplicate key.
So, I suggest you to replace your file Name with a unique key. | Finally i got answer using below code,
```
Connection con1 =null;
Statement stmt=null;
int GetUniqueId=0;
System.out.println("Entered successfully 1:");
try
{
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
String sql1 ="select contact_id from contacts order by contact_id desc limit 1" ;
stmt = con1.createStatement();
ResultSet rst = stmt.executeQuery(sql1);
if(rst.next())
{
//String newone = rst.getString("contact_id");
GetUniqueId = Integer.parseInt(rst.getString("AutoIncrementValue"));
System.out.println("Ifffffffffffff"+GetUniqueId);
}
else
{
GetUniqueId = 0;
System.out.println("elseeeeeeeeeeee"+GetUniqueId);
}
}
catch(Exception ex)
{
System.out.println(ex);
}
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
// item.getName() - gives file name
GetUniqueId = GetUniqueId+1;
String getfirst = item.getName();
String [] get = getfirst.split("\\.");
System.out.println("splited :"+get[0]);
System.out.println("splited :"+get[1]);
getchange = get[0];
getchange = getchange+""+ GetUniqueId;
String addjpg =getchange+"."+get[1];
System.out.println("splited finally :"+addjpg);
fileMap.put(addjpg, item.getInputStream());
listGetImgName.add(addjpg);
}
}
}
}
```
Its working fine now. Thanks to Mr.Keval and Mr.colavitam |
28,470,591 | I am trying to upload images to DB using below code,
MyJsp.jsp
```
<form action="ImageUploadToDB" method="post" enctype="multipart/form-data">
<div>
<img alt="Image1" id="Image11" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files11" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image2" id="Image12" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files12" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image3" id="Image13" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files13" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image4" id="Image14" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files14" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
<img alt="Image5" id="Image15" src="" width="130px" height="90px" class="imgtotxt"><br><br>
<input type="file" id="files15" class="fileUploadimgtotxt" name="files3[]" style="" value="Select Image">
</div>
</form>
```
I am inserting all uploaded images from above form by using servlet like below,
```
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
fileMap.put(item.getName(), item.getInputStream());
//System.out.println("uploaded images here:"+item.getName());
}
}
}
}
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
String sql ="INSERT INTO contacts2 (images) values (?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setBlob(1, fileMap.get(fileName));
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
```
If i uploading such as images1.jpg, images2.jpg, images3.jpg, images4.jpg, images5.jpg then my output is :
```
inserted successfully:
inserted successfully:
inserted successfully:
inserted successfully:
inserted successfully:
```
But if i uploading such as images1.jpg, images2.jpg, images1.jpg, images4.jpg, images2.jpg then my output is :
```
inserted successfully:
inserted successfully:
inserted successfully:
```
when i check my DB there is image1.jpg, image2.jpg, image4.jpg only.I have no idea why that same name of images not inserting to DB.
Someone tell me where i am wrong?
Updated :
This is for Mr.Keval's answer
```
fileMap.put((item.getName() + "" + new Date().getTime()), item.getInputStream());
int count2 =5;
for (int
k=0;k<5;k++) {
System.out.println("for successfully:");
String sql ="INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setString(1, clas);
statement.setString(2, subject);
statement.setString(3, uid);
System.out.println("Qimg name is:"+listGet.get(k));
statement.setString(4, listGet.get(k));
System.out.println("Qimg is:"+fileMap.values().toArray()[k]);
Object bb = fileMap.values().toArray()[k];
// System.out.println("Qimg is:"+listGet2.get(listgetcount));
// System.out.println("finallyyyy:"+fileMap.get("files1"));
statement.setBinaryStream(5, (InputStream) bb);
// System.out.println("Aimg name is:"+listGet.get(count2));
statement.setString(6, listGet.get(count2));
//System.out.println("Aimg is:"+fileMap.values().toArray()[count2]);
Object bb2 = fileMap.values().toArray()[count2];
//System.out.println("Qimg is:"+fileMap.get("files2"));
//String getval2 = listGet2.get(count2);
statement.setBinaryStream(7, (InputStream) bb2);
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
count2=count2+1;
}
```
If i upload same images then shows like
```
for successfully:
Qimg name is:image1.jpg
Qimg is:java.io.FileInputStream@f747c0
inserted successfully:
for successfully:
Qimg name is:image4.jpg
Qimg is:java.io.FileInputStream@fd4f30
inserted successfully:
for successfully:
Qimg name is:image5.jpg
Qimg is:java.io.FileInputStream@1b654b9
inserted successfully:
for successfully:
Qimg name is:image7.jpg
Qimg is:java.io.FileInputStream@1303c07
inserted successfully:
for successfully:
Qimg name is:image9.jpg
Qimg is:java.io.FileInputStream@110b3f6
java.lang.ArrayIndexOutOfBoundsException: 9
``` | 2015/02/12 | [
"https://Stackoverflow.com/questions/28470591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3766129/"
] | You need uniqe image name for each image other wise image with same name will overwrite value of old image in your map as keys are unique in map
```
fileMap.put(item.getName(), item.getInputStream());
```
one solution is you can append current time with your file name to make them unique
```
fileMap.put((item.getName() + "" + new Date().getTime()), item.getInputStream());
``` | Finally i got answer using below code,
```
Connection con1 =null;
Statement stmt=null;
int GetUniqueId=0;
System.out.println("Entered successfully 1:");
try
{
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
String sql1 ="select contact_id from contacts order by contact_id desc limit 1" ;
stmt = con1.createStatement();
ResultSet rst = stmt.executeQuery(sql1);
if(rst.next())
{
//String newone = rst.getString("contact_id");
GetUniqueId = Integer.parseInt(rst.getString("AutoIncrementValue"));
System.out.println("Ifffffffffffff"+GetUniqueId);
}
else
{
GetUniqueId = 0;
System.out.println("elseeeeeeeeeeee"+GetUniqueId);
}
}
catch(Exception ex)
{
System.out.println(ex);
}
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
LinkedHashMap<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
// item.getName() - gives file name
GetUniqueId = GetUniqueId+1;
String getfirst = item.getName();
String [] get = getfirst.split("\\.");
System.out.println("splited :"+get[0]);
System.out.println("splited :"+get[1]);
getchange = get[0];
getchange = getchange+""+ GetUniqueId;
String addjpg =getchange+"."+get[1];
System.out.println("splited finally :"+addjpg);
fileMap.put(addjpg, item.getInputStream());
listGetImgName.add(addjpg);
}
}
}
}
```
Its working fine now. Thanks to Mr.Keval and Mr.colavitam |
29,533 | I need to have a special class for example for body element which will be showing me on which site from multisite installation I am in.
Here is a [solution](https://drupal.stackexchange.com/questions/17009/load-domain-specific-css-file-on-a-multisite) loading different css files but is there a way to have a simple class? | 2012/04/27 | [
"https://drupal.stackexchange.com/questions/29533",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/5551/"
] | Well i decided to use different .css files with this code:
```
// Allow a site-specific user defined CSS file (useful for multisite installations):
// If a CSS file "local-[SITE].css" is residing in the "css" directory (beside "local.css"),
// it will be loaded after "local.css". SITE is the site's host name, without leading "www".
// For example, for the site http://www.mydomain.tld/ the file must be called called "local-[mydomain.tld].css"
global $base_url;
$site = preg_replace("/^[^\/]+[\/]+/", '', $base_url);
$site = preg_replace("/[\/].+/", '', $site);
$site = preg_replace("/^www[^.]*[.]/", '', $site);
drupal_add_css(path_to_theme() . '/css/local-[' . $site . '].css', 'theme', 'all');
``` | I would recommend you to create a custom module where you can store individual settings for each domain. Create for example a simple textfield where you can enter the class you would like to have in your body tag from this site. Use these settings then in your template preprocessor to add for example a class to the body. |
26,463,915 | I have e.g. following `Lists`:
```
List<tst> listx; // tst object has properties: year, A, B, C, D
year A B C D
------------
2013 5 0 0 0 // list1
2014 3 0 0 0
2013 0 8 0 0 // list2
2014 0 1 0 0
2013 0 0 2 0 // list3
2014 0 0 3 0
2013 0 0 0 1 // list4
2014 0 0 0 5
```
if I use `addAll` method, the `listTotal` will be:
```
year A B C D
------------
2013 5 0 0 0 // listTotal
2014 3 0 0 0
2013 0 8 0 0
2014 0 1 0 0
2013 0 0 2 0
2014 0 0 3 0
2013 0 0 0 1
2014 0 0 0 5
```
How to merge them to the `listRequired` which would be like this?
```
year A B C D
------------
2013 5 8 2 1 // listRequired
2014 3 1 3 5
``` | 2014/10/20 | [
"https://Stackoverflow.com/questions/26463915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731696/"
] | Use a `Map<Integer, Tst>` containing, for each year (the key of the map) the `Tst` you want for this year as a result.
Iterate through your `listTotal` and, for each Tst:
* if the year of the `Tst` isn't in the map yet, then store the `Tst` for this year
* else, get the Tst from the map and merge it with the current Tst
In the end, the `values()` of the map is what you want in your `listRequired`.
Code:
```
Map<Integer, Tst> resultPerYear = new HashMap<>();
for (Tst tst : listTotal) {
Tst resultForYear = resultPerYear.get(tst.getYear());
if (resultForYear == null) {
resultPerYear.put(tst.getYear(), tst);
}
else {
resultForYear.merge(tst);
}
}
Set<Tst> result = resultPerYear.values();
``` | use a map to maintain a mapping from year to the TST structure.
iterate each item of the lists, retrieve the corresponding TST structure and update the A/B/C/D attributes manually |
26,463,915 | I have e.g. following `Lists`:
```
List<tst> listx; // tst object has properties: year, A, B, C, D
year A B C D
------------
2013 5 0 0 0 // list1
2014 3 0 0 0
2013 0 8 0 0 // list2
2014 0 1 0 0
2013 0 0 2 0 // list3
2014 0 0 3 0
2013 0 0 0 1 // list4
2014 0 0 0 5
```
if I use `addAll` method, the `listTotal` will be:
```
year A B C D
------------
2013 5 0 0 0 // listTotal
2014 3 0 0 0
2013 0 8 0 0
2014 0 1 0 0
2013 0 0 2 0
2014 0 0 3 0
2013 0 0 0 1
2014 0 0 0 5
```
How to merge them to the `listRequired` which would be like this?
```
year A B C D
------------
2013 5 8 2 1 // listRequired
2014 3 1 3 5
``` | 2014/10/20 | [
"https://Stackoverflow.com/questions/26463915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731696/"
] | Use a `Map<Integer, Tst>` containing, for each year (the key of the map) the `Tst` you want for this year as a result.
Iterate through your `listTotal` and, for each Tst:
* if the year of the `Tst` isn't in the map yet, then store the `Tst` for this year
* else, get the Tst from the map and merge it with the current Tst
In the end, the `values()` of the map is what you want in your `listRequired`.
Code:
```
Map<Integer, Tst> resultPerYear = new HashMap<>();
for (Tst tst : listTotal) {
Tst resultForYear = resultPerYear.get(tst.getYear());
if (resultForYear == null) {
resultPerYear.put(tst.getYear(), tst);
}
else {
resultForYear.merge(tst);
}
}
Set<Tst> result = resultPerYear.values();
``` | You should be able to do it by defining a custom merge method:
```
List<tst> merge (List<tst> listA, List<tst> listB)
```
which merges the properties of each element in listA with the element of the same index in listB.
Call this method iteratively on list1, ...list4 to get listRequired. |
34,847,380 | I'm using `AWS VPC` with `ELB` in-front. As far as i understand, only the `Network Access Control List (ACL)` can do the Inbound **Blocking**, by IPs. But again the problem there is:
* The limitation of the number of Rules inside ACL. Which is only 40 max total.
Again the Security Groups can not do "blocking". So what i do now is, to block the certain IPs by the Apache Virtual Hosts (handle the `x-forwarded-for` ips), which is not the clean approach.
Then what is the proper approach to this please? | 2016/01/18 | [
"https://Stackoverflow.com/questions/34847380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775856/"
] | Your success function is overwriting the whole `$scope` variable instead of placing values in it. You need to do the latter in order for anything to actually be accessible to your view:
```
success: function(results) {
$scope.price = results.price;
$scope.priceDescription = results.priceDescription;
console.log($scope.price);
console.log($scope.priceDescription);
},
``` | From what I can tell, you are overwriting the entire `$scope` object, which has certain properties you need to maintain to keep your Angular application running correctly and keep the bindings intact.
What you will want to do is store the returned values as properties on the `$scope` object. Instead of `$scope = results;` you should do a few separate declarations:
```
$scope.price = results.price;
$scope.priceDescription = results.priceDescription;
```
...and so on for any properties you want to reference in your HTML template.
Remember that `$scope` is not just a store of values, but an object that is built to play nicely within the context of the rest of the Angular framework. If you want to see it's unique properties, `console.log($scope)` before you overwrite it (or after you fix you declarations to the pattern described above). |
34,847,380 | I'm using `AWS VPC` with `ELB` in-front. As far as i understand, only the `Network Access Control List (ACL)` can do the Inbound **Blocking**, by IPs. But again the problem there is:
* The limitation of the number of Rules inside ACL. Which is only 40 max total.
Again the Security Groups can not do "blocking". So what i do now is, to block the certain IPs by the Apache Virtual Hosts (handle the `x-forwarded-for` ips), which is not the clean approach.
Then what is the proper approach to this please? | 2016/01/18 | [
"https://Stackoverflow.com/questions/34847380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775856/"
] | Your success function is overwriting the whole `$scope` variable instead of placing values in it. You need to do the latter in order for anything to actually be accessible to your view:
```
success: function(results) {
$scope.price = results.price;
$scope.priceDescription = results.priceDescription;
console.log($scope.price);
console.log($scope.priceDescription);
},
``` | Several problems are:
Parse is not part of angular core so you need to tell angular to update the view when making scope changes.
You should assign the data to properties of scope, not overwrite the scope object. A simple way to do that is `angular.extend()` which will update `$scope` with the same properties and values as in your `results` object
```
query.first({
success: function(results) {
angular.extend($scope,results);// merge results into scope
$scope.$digest();//notify angular to run digests
console.log($scope.priceDescription);// check one of the new properties added
}
``` |
34,847,380 | I'm using `AWS VPC` with `ELB` in-front. As far as i understand, only the `Network Access Control List (ACL)` can do the Inbound **Blocking**, by IPs. But again the problem there is:
* The limitation of the number of Rules inside ACL. Which is only 40 max total.
Again the Security Groups can not do "blocking". So what i do now is, to block the certain IPs by the Apache Virtual Hosts (handle the `x-forwarded-for` ips), which is not the clean approach.
Then what is the proper approach to this please? | 2016/01/18 | [
"https://Stackoverflow.com/questions/34847380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775856/"
] | UPDATE: Find working version of your fiddle here: <https://jsfiddle.net/h4od21fs/1/>
So you have number of issues here:
* as others have said Parse and angular doesn't know about each other without angular plugin, so in your case you need to call `$scope.$apply()` after you got data
* you have handlebars plugged in together with angular and have total mess with layout
* you can't just use object that parse returns you, it returns you active record so you need to call methods to get actual data from it , i.e. :
vm.results.price = results.get('price')
* and in your fiddle you did not include angular.js, but included a lot of other stuff , like bootstrap, handlebars and jquery.
* also don't forget to change key in parse.com so no one would use your quotas.
Resulting code:
```
var app = angular.module('myApp',[]);
app.run(function() {
Parse.initialize("Clfupzjbt9iWIdezPCZuBJqajuxHJ8okP5nteViS", "sakt1qjwM4duTAo3ZCvWWBM32Tv3ZdL13PQ0Eea4");
});
var currentTime = new Date();
currentTime = new Date(currentTime.getTime() - 25200000);
app.controller('membershipCtrl', ['$scope', function($scope) {
var vm = this;
vm.results = null;
var membership = Parse.Object.extend("Membership");
var query = new Parse.Query(membership);
//query.ascending("priceDate").greaterThan('priceDate', currentTime).limit(1);
// i commented it out as it was not returning any data with those conditions
query.first({
success: function(results) {
vm.results = {
price : results.get('price'),
priceDescription: results.get('priceDescription')
};
$scope.$apply();
console.log(vm);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}]);
```
When you are doing `$scope = smooth` inside controller you are not changing scope, but rather changing variable assigned to `$scope` argument of your controller function. As it is passed as reference, it would not affect `$scope` object that was passed into controller.
You should add property on the scope instead, or to controller itself if you are using `ControllerAs` syntax, i.e. for $scope:
```
$scope.results = results // inside your success callback
```
For `controllerAs` syntax:
```
app.controller('membershipCtrl', ['$scope', function($scope) {
var vm = this;
var membership = Parse.Object.extend("Membership");
var query = new Parse.Query(membership);
query.ascending("priceDate").greaterThan('priceDate', currentTime).limit(1);
query.first({
success: function(results) {
vm.results = results;
console.log(vm);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}]);
```
And in html:
```
<div ng-app="myApp" ng-controller="membershipCtrl as vm">
{{vm.results.price}}{{vm.results.priceDescription}}
</div>
``` | From what I can tell, you are overwriting the entire `$scope` object, which has certain properties you need to maintain to keep your Angular application running correctly and keep the bindings intact.
What you will want to do is store the returned values as properties on the `$scope` object. Instead of `$scope = results;` you should do a few separate declarations:
```
$scope.price = results.price;
$scope.priceDescription = results.priceDescription;
```
...and so on for any properties you want to reference in your HTML template.
Remember that `$scope` is not just a store of values, but an object that is built to play nicely within the context of the rest of the Angular framework. If you want to see it's unique properties, `console.log($scope)` before you overwrite it (or after you fix you declarations to the pattern described above). |
34,847,380 | I'm using `AWS VPC` with `ELB` in-front. As far as i understand, only the `Network Access Control List (ACL)` can do the Inbound **Blocking**, by IPs. But again the problem there is:
* The limitation of the number of Rules inside ACL. Which is only 40 max total.
Again the Security Groups can not do "blocking". So what i do now is, to block the certain IPs by the Apache Virtual Hosts (handle the `x-forwarded-for` ips), which is not the clean approach.
Then what is the proper approach to this please? | 2016/01/18 | [
"https://Stackoverflow.com/questions/34847380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775856/"
] | UPDATE: Find working version of your fiddle here: <https://jsfiddle.net/h4od21fs/1/>
So you have number of issues here:
* as others have said Parse and angular doesn't know about each other without angular plugin, so in your case you need to call `$scope.$apply()` after you got data
* you have handlebars plugged in together with angular and have total mess with layout
* you can't just use object that parse returns you, it returns you active record so you need to call methods to get actual data from it , i.e. :
vm.results.price = results.get('price')
* and in your fiddle you did not include angular.js, but included a lot of other stuff , like bootstrap, handlebars and jquery.
* also don't forget to change key in parse.com so no one would use your quotas.
Resulting code:
```
var app = angular.module('myApp',[]);
app.run(function() {
Parse.initialize("Clfupzjbt9iWIdezPCZuBJqajuxHJ8okP5nteViS", "sakt1qjwM4duTAo3ZCvWWBM32Tv3ZdL13PQ0Eea4");
});
var currentTime = new Date();
currentTime = new Date(currentTime.getTime() - 25200000);
app.controller('membershipCtrl', ['$scope', function($scope) {
var vm = this;
vm.results = null;
var membership = Parse.Object.extend("Membership");
var query = new Parse.Query(membership);
//query.ascending("priceDate").greaterThan('priceDate', currentTime).limit(1);
// i commented it out as it was not returning any data with those conditions
query.first({
success: function(results) {
vm.results = {
price : results.get('price'),
priceDescription: results.get('priceDescription')
};
$scope.$apply();
console.log(vm);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}]);
```
When you are doing `$scope = smooth` inside controller you are not changing scope, but rather changing variable assigned to `$scope` argument of your controller function. As it is passed as reference, it would not affect `$scope` object that was passed into controller.
You should add property on the scope instead, or to controller itself if you are using `ControllerAs` syntax, i.e. for $scope:
```
$scope.results = results // inside your success callback
```
For `controllerAs` syntax:
```
app.controller('membershipCtrl', ['$scope', function($scope) {
var vm = this;
var membership = Parse.Object.extend("Membership");
var query = new Parse.Query(membership);
query.ascending("priceDate").greaterThan('priceDate', currentTime).limit(1);
query.first({
success: function(results) {
vm.results = results;
console.log(vm);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}]);
```
And in html:
```
<div ng-app="myApp" ng-controller="membershipCtrl as vm">
{{vm.results.price}}{{vm.results.priceDescription}}
</div>
``` | Several problems are:
Parse is not part of angular core so you need to tell angular to update the view when making scope changes.
You should assign the data to properties of scope, not overwrite the scope object. A simple way to do that is `angular.extend()` which will update `$scope` with the same properties and values as in your `results` object
```
query.first({
success: function(results) {
angular.extend($scope,results);// merge results into scope
$scope.$digest();//notify angular to run digests
console.log($scope.priceDescription);// check one of the new properties added
}
``` |
25,887,511 | Volley gives us better efficiency, however it uses the "url"
```
JsonObjectRequest j = new JsonObjectRequest((int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener);
```
But if I have to use HttpPost or HttpGet object as I have to set Header and Entity etc. How can I do it while still using Volley.
```
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("String", "something" );
httpGet.setHeader("Content-Type","application/json");
...
httpPost.setEntity(new StringEntity("whatever"));
```
basically after these lines of code I get HttpPost / HttpGet object; is there a way to use this object in volley instead of using HttpClient to execute the request.
Or is there a some different way to set header etc and then use it with Volley. | 2014/09/17 | [
"https://Stackoverflow.com/questions/25887511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3174460/"
] | Create an ErrorController - this allows you to tailor your end-user error pages and status codes. Each action result accepts an exception which you can add to your route data in your application\_error method in your global.asax. It doesn't have to be the exception object, it can be anything you like - just add it to the routedata in your application\_error.
```
[AllowAnonymous]
public class ErrorController : Controller
{
public ActionResult PageNotFound(Exception ex)
{
Response.StatusCode = 404;
return View("Error", ex);
}
public ActionResult ServerError(Exception ex)
{
Response.StatusCode = 500;
return View("Error", ex);
}
public ActionResult UnauthorisedRequest(Exception ex)
{
Response.StatusCode = 403;
return View("Error", ex);
}
//Any other errors you want to specifically handle here.
public ActionResult CatchAllUrls()
{
//throwing an exception here pushes the error through the Application_Error method for centralised handling/logging
throw new HttpException(404, "The requested url " + Request.Url.ToString() + " was not found");
}
}
```
Your Error View:
```
@model Exception
@{
ViewBag.Title = "Error";
}
<h2>Error</h2>
@Model.Message
```
Add a route to catch all urls to the end of your route config - this captures all 404's that are not already caught by matching existing routes:
```
routes.MapRoute("CatchAllUrls", "{*url}", new { controller = "Error", action = "CatchAllUrls" });
```
In your global.asax:
```
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
//Error logging omitted
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
IController errorController = new Controllers.ErrorController();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("area", "");
routeData.Values.Add("ex", exception);
if (httpException != null)
{
//this is a basic example of how you can choose to handle your errors based on http status codes.
switch (httpException.GetHttpCode())
{
case 404:
Response.Clear();
// page not found
routeData.Values.Add("action", "PageNotFound");
Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
break;
case 500:
// server error
routeData.Values.Add("action", "ServerError");
Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
break;
case 403:
// server error
routeData.Values.Add("action", "UnauthorisedRequest");
Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
break;
//add cases for other http errors you want to handle, otherwise HTTP500 will be returned as the default.
default:
// server error
routeData.Values.Add("action", "ServerError");
Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
break;
}
}
//All other exceptions should result in a 500 error as they are issues with unhandled exceptions in the code
else
{
routeData.Values.Add("action", "ServerError");
Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}
```
Then when you throw
```
throw new HttpException(404, "Invoice 5 does not exist");
```
your message will be carried through and displayed to the user. You can specify at this point which status code you want to use, and extend the switch statement in the application\_error. | BaseController :
```
using System.Web;
using System.Web.Mvc;
namespace YourNamespace.Controllers
{
public class BaseController : Controller
{
public BaseController()
{
ViewBag.MetaDescription = Settings.metaDescription;
ViewBag.MetaKeywords = Settings.metaKeywords;
}
protected new HttpNotFoundResult HttpNotFound(string statusDescription = null)
{
return new HttpNotFoundResult(statusDescription);
}
protected HttpUnauthorizedResult HttpUnauthorized(string statusDescription = null)
{
return new HttpUnauthorizedResult(statusDescription);
}
protected class HttpNotFoundResult : HttpStatusCodeResult
{
public HttpNotFoundResult() : this(null) { }
public HttpNotFoundResult(string statusDescription) : base(404, statusDescription) { }
}
protected class HttpUnauthorizedResult : HttpStatusCodeResult
{
public HttpUnauthorizedResult(string statusDescription) : base(401, statusDescription) { }
}
protected class HttpStatusCodeResult : ViewResult
{
public int StatusCode { get; private set; }
public string StatusDescription { get; private set; }
public HttpStatusCodeResult(int statusCode) : this(statusCode, null) { }
public HttpStatusCodeResult(int statusCode, string statusDescription)
{
this.StatusCode = statusCode;
this.StatusDescription = statusDescription;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.HttpContext.Response.StatusCode = this.StatusCode;
if (this.StatusDescription != null)
{
context.HttpContext.Response.StatusDescription = this.StatusDescription;
}
// 1. Uncomment this to use the existing Error.ascx / Error.cshtml to view as an error or
// 2. Uncomment this and change to any custom view and set the name here or simply
// 3. (Recommended) Let it commented and the ViewName will be the current controller view action and on your view (or layout view even better) show the @ViewBag.Message to produce an inline message that tell the Not Found or Unauthorized
//this.ViewName = "Error";
this.ViewBag.Message = context.HttpContext.Response.StatusDescription;
base.ExecuteResult(context);
}
}
}
}
```
To use in your action like this:
```
public ActionResult Index()
{
// Some processing
if (...)
return HttpNotFound();
// Other processing
}
``` |
27,026,866 | I want to convert an image to 2D array with 5 columns where each row is of the form `[r, g, b, x, y]`. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python?
```
import Image
import numpy as np
im = Image.open("farm.jpg")
col,row = im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
for j in range(col):
r,g,b = pixels[i,j]
data[i*col + j,:] = r,g,b,i,j
``` | 2014/11/19 | [
"https://Stackoverflow.com/questions/27026866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344013/"
] | I had to write this recently and ended up with
```
indices = np.dstack(np.indices(im.shape[:2]))
data = np.concatenate((im, indices), axis=-1)
```
Where `im` is a numpy array. You are probably better off reading the images straight into numpy arrays with
```
from scipy.misc import imread
im = imread("farm.jpg")
```
Or, better still if you have Scikit Image installed
```
from skimage.io import imread
im = imread("farm.jpg")
``` | I am not sure if this is the very efficient. But here you go, say `arr = np.array(im)`; then you can do something like this.
```
>>> arr = np.arange(150).reshape(5, 10, 3)
>>> x, y, z = arr.shape
>>> indices = np.vstack(np.unravel_index(np.arange(x*y), (y, x))).T
#or indices = np.hstack((np.repeat(np.arange(y), x)[:,np.newaxis], np.tile(np.arange(x), y)[:,np.newaxis]))
>>> np.hstack((arr.reshape(x*y, z), indices))
array([[ 0, 1, 2, 0, 0],
[ 3, 4, 5, 0, 1],
[ 6, 7, 8, 0, 2],
[ 9, 10, 11, 0, 3],
[ 12, 13, 14, 0, 4],
[ 15, 16, 17, 1, 0],
[ 18, 19, 20, 1, 1],
[ 21, 22, 23, 1, 2],
[ 24, 25, 26, 1, 3],
[ 27, 28, 29, 1, 4],
[ 30, 31, 32, 2, 0],
[ 33, 34, 35, 2, 1],
[ 36, 37, 38, 2, 2],
...
[129, 130, 131, 8, 3],
[132, 133, 134, 8, 4],
[135, 136, 137, 9, 0],
[138, 139, 140, 9, 1],
[141, 142, 143, 9, 2],
[144, 145, 146, 9, 3],
[147, 148, 149, 9, 4]])
``` |
27,026,866 | I want to convert an image to 2D array with 5 columns where each row is of the form `[r, g, b, x, y]`. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python?
```
import Image
import numpy as np
im = Image.open("farm.jpg")
col,row = im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
for j in range(col):
r,g,b = pixels[i,j]
data[i*col + j,:] = r,g,b,i,j
``` | 2014/11/19 | [
"https://Stackoverflow.com/questions/27026866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344013/"
] | I am not sure if this is the very efficient. But here you go, say `arr = np.array(im)`; then you can do something like this.
```
>>> arr = np.arange(150).reshape(5, 10, 3)
>>> x, y, z = arr.shape
>>> indices = np.vstack(np.unravel_index(np.arange(x*y), (y, x))).T
#or indices = np.hstack((np.repeat(np.arange(y), x)[:,np.newaxis], np.tile(np.arange(x), y)[:,np.newaxis]))
>>> np.hstack((arr.reshape(x*y, z), indices))
array([[ 0, 1, 2, 0, 0],
[ 3, 4, 5, 0, 1],
[ 6, 7, 8, 0, 2],
[ 9, 10, 11, 0, 3],
[ 12, 13, 14, 0, 4],
[ 15, 16, 17, 1, 0],
[ 18, 19, 20, 1, 1],
[ 21, 22, 23, 1, 2],
[ 24, 25, 26, 1, 3],
[ 27, 28, 29, 1, 4],
[ 30, 31, 32, 2, 0],
[ 33, 34, 35, 2, 1],
[ 36, 37, 38, 2, 2],
...
[129, 130, 131, 8, 3],
[132, 133, 134, 8, 4],
[135, 136, 137, 9, 0],
[138, 139, 140, 9, 1],
[141, 142, 143, 9, 2],
[144, 145, 146, 9, 3],
[147, 148, 149, 9, 4]])
``` | I used "+" to combine two tuple, and use `.append()` to make "data" list.No need to use Numpy here.
```
row,col = im.size
data=[] #r,g,b,i,j
pixels=im.load()
for i in range(row):
for j in range(col):
data.append(pixels[i,j]+(i,j))
``` |
27,026,866 | I want to convert an image to 2D array with 5 columns where each row is of the form `[r, g, b, x, y]`. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python?
```
import Image
import numpy as np
im = Image.open("farm.jpg")
col,row = im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
for j in range(col):
r,g,b = pixels[i,j]
data[i*col + j,:] = r,g,b,i,j
``` | 2014/11/19 | [
"https://Stackoverflow.com/questions/27026866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344013/"
] | I am not sure if this is the very efficient. But here you go, say `arr = np.array(im)`; then you can do something like this.
```
>>> arr = np.arange(150).reshape(5, 10, 3)
>>> x, y, z = arr.shape
>>> indices = np.vstack(np.unravel_index(np.arange(x*y), (y, x))).T
#or indices = np.hstack((np.repeat(np.arange(y), x)[:,np.newaxis], np.tile(np.arange(x), y)[:,np.newaxis]))
>>> np.hstack((arr.reshape(x*y, z), indices))
array([[ 0, 1, 2, 0, 0],
[ 3, 4, 5, 0, 1],
[ 6, 7, 8, 0, 2],
[ 9, 10, 11, 0, 3],
[ 12, 13, 14, 0, 4],
[ 15, 16, 17, 1, 0],
[ 18, 19, 20, 1, 1],
[ 21, 22, 23, 1, 2],
[ 24, 25, 26, 1, 3],
[ 27, 28, 29, 1, 4],
[ 30, 31, 32, 2, 0],
[ 33, 34, 35, 2, 1],
[ 36, 37, 38, 2, 2],
...
[129, 130, 131, 8, 3],
[132, 133, 134, 8, 4],
[135, 136, 137, 9, 0],
[138, 139, 140, 9, 1],
[141, 142, 143, 9, 2],
[144, 145, 146, 9, 3],
[147, 148, 149, 9, 4]])
``` | steps are :
1. convert images to grayscale (opencv)
2. convert grayscale to binary image (opencv)
3. convert to binary 2D matrix (scipy , pillow, numpy)
```py
from scipy.ndimage import zoom
from PIL import Image
import numpy as np
srcImage = Image.open("image_in_binary_color.jpg")
grayImage = srcImage.convert('L')
array = np.array(grayImage)
array = zoom(array, 310/174)
np.savetxt("binarized.txt", array<128, fmt="%d")
print("\n\n Output Stored to binarized.txt.......#")
```
4. store it in a file named binarized.txt
This is how i did it : <https://github.com/jithi22/Imagery.git> |
27,026,866 | I want to convert an image to 2D array with 5 columns where each row is of the form `[r, g, b, x, y]`. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python?
```
import Image
import numpy as np
im = Image.open("farm.jpg")
col,row = im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
for j in range(col):
r,g,b = pixels[i,j]
data[i*col + j,:] = r,g,b,i,j
``` | 2014/11/19 | [
"https://Stackoverflow.com/questions/27026866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344013/"
] | I had to write this recently and ended up with
```
indices = np.dstack(np.indices(im.shape[:2]))
data = np.concatenate((im, indices), axis=-1)
```
Where `im` is a numpy array. You are probably better off reading the images straight into numpy arrays with
```
from scipy.misc import imread
im = imread("farm.jpg")
```
Or, better still if you have Scikit Image installed
```
from skimage.io import imread
im = imread("farm.jpg")
``` | I used "+" to combine two tuple, and use `.append()` to make "data" list.No need to use Numpy here.
```
row,col = im.size
data=[] #r,g,b,i,j
pixels=im.load()
for i in range(row):
for j in range(col):
data.append(pixels[i,j]+(i,j))
``` |
27,026,866 | I want to convert an image to 2D array with 5 columns where each row is of the form `[r, g, b, x, y]`. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python?
```
import Image
import numpy as np
im = Image.open("farm.jpg")
col,row = im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
for j in range(col):
r,g,b = pixels[i,j]
data[i*col + j,:] = r,g,b,i,j
``` | 2014/11/19 | [
"https://Stackoverflow.com/questions/27026866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344013/"
] | I had to write this recently and ended up with
```
indices = np.dstack(np.indices(im.shape[:2]))
data = np.concatenate((im, indices), axis=-1)
```
Where `im` is a numpy array. You are probably better off reading the images straight into numpy arrays with
```
from scipy.misc import imread
im = imread("farm.jpg")
```
Or, better still if you have Scikit Image installed
```
from skimage.io import imread
im = imread("farm.jpg")
``` | steps are :
1. convert images to grayscale (opencv)
2. convert grayscale to binary image (opencv)
3. convert to binary 2D matrix (scipy , pillow, numpy)
```py
from scipy.ndimage import zoom
from PIL import Image
import numpy as np
srcImage = Image.open("image_in_binary_color.jpg")
grayImage = srcImage.convert('L')
array = np.array(grayImage)
array = zoom(array, 310/174)
np.savetxt("binarized.txt", array<128, fmt="%d")
print("\n\n Output Stored to binarized.txt.......#")
```
4. store it in a file named binarized.txt
This is how i did it : <https://github.com/jithi22/Imagery.git> |
27,026,866 | I want to convert an image to 2D array with 5 columns where each row is of the form `[r, g, b, x, y]`. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python?
```
import Image
import numpy as np
im = Image.open("farm.jpg")
col,row = im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
for j in range(col):
r,g,b = pixels[i,j]
data[i*col + j,:] = r,g,b,i,j
``` | 2014/11/19 | [
"https://Stackoverflow.com/questions/27026866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344013/"
] | I used "+" to combine two tuple, and use `.append()` to make "data" list.No need to use Numpy here.
```
row,col = im.size
data=[] #r,g,b,i,j
pixels=im.load()
for i in range(row):
for j in range(col):
data.append(pixels[i,j]+(i,j))
``` | steps are :
1. convert images to grayscale (opencv)
2. convert grayscale to binary image (opencv)
3. convert to binary 2D matrix (scipy , pillow, numpy)
```py
from scipy.ndimage import zoom
from PIL import Image
import numpy as np
srcImage = Image.open("image_in_binary_color.jpg")
grayImage = srcImage.convert('L')
array = np.array(grayImage)
array = zoom(array, 310/174)
np.savetxt("binarized.txt", array<128, fmt="%d")
print("\n\n Output Stored to binarized.txt.......#")
```
4. store it in a file named binarized.txt
This is how i did it : <https://github.com/jithi22/Imagery.git> |
15,072,038 | Good morning everyone,
I have a macro that I want to sort data. A button in my workbook calls a small userform with 10 checkboxes. The user should pick those categories that he wants to review and click sort. The result I want is for only the categories he chose to be displayed but I am getting an all or nothing result out of the attached macro. Below is that macro that supports the form/button to sort the categories. I have searched through Google and several other forums and can't find an answer relevant to my problem! Any help you could offer would be greatly appreciated.
Thanks!
```
Private Sub cmdSort_Click()
LastRow = Range("A" & Rows.Count).End(xlUp).Row
If chkFE = True Then
For Each cell In Range("BC4:BC" & LastRow)
If UCase(cell.Value) <> "Fire Extinguishers" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkChem = True Then
For Each cell In Range("BD4:BD" & LastRow)
If UCase(cell.Value) <> "Chem" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkFL = True Then
For Each cell In Range("BE4:BE" & LastRow)
If UCase(cell.Value) <> "FL" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkElec = True Then
For Each cell In Range("BF4:BF" & LastRow)
If UCase(cell.Value) <> "Elec" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkFP = True Then
For Each cell In Range("BG4:BG" & LastRow)
If UCase(cell.Value) <> "FP" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkLift = True Then
For Each cell In Range("BH4:BH" & LastRow)
If UCase(cell.Value) <> "Lift" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkPPE = True Then
For Each cell In Range("BI4:BI" & LastRow)
If UCase(cell.Value) <> "PPE" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkPS = True Then
For Each cell In Range("BJ4:BJ" & LastRow)
If UCase(cell.Value) <> "PS" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkSTF = True Then
For Each cell In Range("BK4:BK" & LastRow)
If UCase(cell.Value) <> "STF" Then
cell.EntireRow.Hidden = True
End If
Next
End If
If chkErgonomics = True Then
For Each cell In Range("BL4:BL" & LastRow)
If UCase(cell.Value) <> "Ergonomics" Then
cell.EntireRow.Hidden = True
End If
Next
End If
Unload frmSort
End Sub
``` | 2013/02/25 | [
"https://Stackoverflow.com/questions/15072038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2030282/"
] | You are actually filtering, not sorting. Which raises the question, why not just let the user the Excel's `Filter` button and dialog?
To answer your question, your code will only ever work if one `Checkbox` is checked. For every Checkbox that's checked your code is hiding the rows for all other categories. So only the category for the last Checkbox will have rows showing
You could try reversing your logic. Start with all rows hidden, and set `Hidden = False` for any rows whose category is clicked. | I wanted to share the solution that @AlphaFrog provided me with, it works perfectly:
```
Private Sub cmdSort_Click()
Dim i As Long, rng As Range, arrCriteria As Variant
Set rng = Rows(3) 'Headers
arrCriteria = Array("Fire Extinguishers", "Chem", "FL", "Elec", "FP", _
"Lift", "PPE", "PS", "STF", "Ergonomics")
Application.ScreenUpdating = False
Rows.Hidden = False
With Range("BC3:BL" & Range("A" & Rows.Count).End(xlUp).Row)
For i = 1 To 10
If Me.Controls("CheckBox" & i) Then
.AutoFilter i, arrCriteria(i - 1)
Set rng = Union(rng, .SpecialCells(xlCellTypeVisible).EntireRow)
.AutoFilter
End If
Next i
.Parent.AutoFilterMode = False
.EntireRow.Hidden = True
rng.EntireRow.Hidden = False
End With
Application.ScreenUpdating = True
Unload frmSort
End Sub
```
Link to the original answer:
<http://www.ozgrid.com/forum/showthread.php?t=175539> |
45,294,027 | I'm trying to select a specific sheet (by name or index) with my excel Add-In with no avail.
My addin file `ThisAddIn.cs` has:
```
public Excel.Workbook GetActiveWorkbook()
{
return (Excel.Workbook)Application.ActiveWorkbook;
}
```
And my `Ribbon1.cs` has:
```
namespace Test3
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
Debug.WriteLine("Hello");
Workbook currentwb = Globals.ThisAddIn.GetActiveWorkbook();
Worksheet scratch = currentwb.Worksheets.Item[1] as Worksheet; // Error blocks here
if (scratch == null)
return;
// Worksheet scratch = currentwb.Worksheets["Sheets1"];
scratch.Range["A1"].Value = "Hello";
}
}
}
```
But I get a `System.NullReferenceException: 'Object reference not set to an instance of an object.'`
I'm new to c# (come from Python) and am very confused why this doesn't work. Any help would be greatly appreciated. | 2017/07/25 | [
"https://Stackoverflow.com/questions/45294027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3478500/"
] | It all has to do with what is in the accumulator (`high`). If you don't provide the second argument to `reduce`, the accumulator starts off as the first object, and the current element is the second element. In your first iteration, you treat the accumulator as the object, fetching the grade using `high.grade`; but then you return a number (`94`), and not an object, to be your next accumulator. In the next iteration of the loop, `high` is not an object any more but `94`, and `(94).grade` makes no sense.
When you remove the third element, there is no second iteration, and there is no time for the bug to occur, and you get the value of the current accumulator (`94`). If there were only one element, you'd get the initial accumulator (`{name: 'Leah', grade: 94}`). This is, obviously, not ideal, as you can't reliably predict the shape of the result of your calculation (object, number or error).
You need to decide whether you want the number or the object, one or the other.
```
let highest = students.reduce(
(high, current) => Math.max(high, current.grade),
Number.NEGATIVE_INFINITY
)
```
This variant keeps the accumulator as a number, and will return `94`. We can't rely on the default starting accumulator, as it needs to be a number, so we set it artificially at `-INF`.
```
let highest = students.reduce(
(high, current) => high.grade > current.grade ? high : current,
)
```
This is the object version, where `highest` ends up with `{name: 'Leah', grade: 94}`. | The issue here is the accumulator (high) after the first pass is a number (what gets returned by math.max), yet each pass requires that high be an object with grade as a number property. So by the second call you're calling `Math.max(undefined, 73)` - which will return `NaN`. Instead I'd recommend initializing the accumulator with `-Infinity` and only supplying `high`:
`let highest = students.reduce(
(high, current) => Math.max(high, current.grade)
, -Infinity)` |
10,422,174 | I used ctrl-6 to jump between two files and compare these two files page by page, But each time when I switch back, the page content is changed. That is, a new page with previous cursor line in the middle of screen now is shown instead.
Is there a way to keep the page position in the screen unchanged when I switched back.
Thanks a lot! | 2012/05/02 | [
"https://Stackoverflow.com/questions/10422174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/724472/"
] | May I suggest using tabs (`C-PgUp` and `C-PgDn` to switch)?
You can always start by doing `C-w``s``C-^``C-w``T`
Otherwise see this odler answer of mine for hints on restoring cursor positions:
* [After a :windo, how do I get the cursor back where it was?](https://stackoverflow.com/questions/9984032/after-a-windo-how-do-i-get-the-cursor-back-where-it-was/9989348#9989348)
* [Vim buffer position change on window split (annoyance)](https://stackoverflow.com/questions/9625028/vim-buffer-position-change-on-window-split-annoyance/9626591#9626591) | This might not be what you're looking for, but just in case: For a different approach to the task you're doing (visually comparing two files), see `:help scrollbind`. You would do `:set scrollbind` in two side-by-side windows and open one file in each, then scroll through them together, linked. See also `vimdiff` for even more functionality. |
54,840,020 | I'm trying to display the info of the user when I get the id using `$routeParams.id`, I already displayed the user's info using texts only but how can I display the user's image using `img src`?
**In my controller I did this to get the selected user.**
```
.controller('editbloodrequestCtrl', function($scope,$routeParams, Bloodrequest) {
var app = this;
Bloodrequest.getBloodrequest($routeParams.id).then(function(data) {
if (data.data.success) {
$scope.newLastname = data.data.bloodrequest.lastname;
$scope.newFirstname = data.data.bloodrequest.firstname;
$scope.newImg = data.data.bloodrequest.img;
app.currentUser = data.data.bloodrequest._id;
} else {
app.errorMsg = data.data.message;
}
});
});
```
**Now that I get the users info, I displayed this in my frontend**
```
<label>Lastname:</label>
<input class="form-control" type="text" name="lastname" ng-model="newLastname">
<label>Firstname:</label>
<input class="form-control" type="text" name="firstname" ng-model="newFirstname">
<label>Image:</label>
<img src ="" name="img" ng-model="newImg"> //how can I display the image here?
```
**Sample Documents:**
```
{firstname:"James",lastname:"Reid",img:"random.jpg"}
```
**My output:**
[](https://i.stack.imgur.com/EuXt2.png) | 2019/02/23 | [
"https://Stackoverflow.com/questions/54840020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7294541/"
] | No need to bind ng-model to your image, just use the src with the absolute path of the image
```
<img src ="{{newImg}}" name="img">
``` | No need to bind ng-model to your image, just use the src with the absolute path of the image..ng-model using only input tags.
```
<img ng-src ="newImg" name="newimg" />
``` |
16,480,300 | at the moment I have script which prints out numeric values into bits so for example
```
print((short) 1);
```
I get a value of `00000001`, but how can I get for this a value like `00000001 00000000` and in case if I print `print((int) 1);` I get a value of `00000001 00000000 00000000 00000000`.
Here is my code:
```
void printbyte(unsigned char x)
{
for (int i = 0; i < 8; i++)
{
if (x & 0x80) cout << 1;
else cout << 0;
x = x << 1;
}
cout << endl;
}
template <typename T>
void print (T A)
{
unsigned char *p = (unsigned char *) &A;
printbyte(*p);
}
int main()
{
print((short) 1);
system("pause");
return 0;
}
``` | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2363241/"
] | You can just use `sizeof(T)` within `print` to determine how many bytes to process and then call `printbyte` for each byte, e.g.
```
#include <iostream>
#include <climits>
using namespace std;
void printbyte(unsigned char x)
{
for (int i = 0; i < CHAR_BIT; i++)
{
cout << ((x & 0x80) != 0);
x <<= 1;
}
}
template <typename T>
void print (T A)
{
for (size_t i = 0; i < sizeof(T); ++i)
{
unsigned char b = A >> ((sizeof(T) - i - 1) * CHAR_BIT);
//unsigned char b = A >> (i * CHAR_BIT); // use this for little endian output
printbyte(b);
cout << " ";
}
cout << endl;
}
int main()
{
print((short) 1);
print((long long) 42);
return 0;
}
``` | You can use bitset, it's the easiest way. Here's an example:
```
#include <iostream>
#include <bitset>
using namespace std;
int main ()
{
int number;
cin>>number;
bitset <16> end (number);
cout<<number<<" --> "<<end<<'\n';
return 0;
}
```
Or reference: <http://www.cplusplus.com/reference/bitset/bitset/>
If you not want to use standard solutions, it can also look like this:
```
#include <iostream>
#include <climits>
using namespace std;
template <typename Type>
void bprint(Type in)
{
unsigned char* p = (reinterpret_cast<unsigned char*>(&in))+(sizeof(Type)-1); //x86
for(unsigned int n = sizeof(Type);n--;--p, std::cout<<' ')
for(unsigned int i = CHAR_BIT;i--;)
std::cout<<((*p&char(1<<i))!=0);
std::cout<<'\n';
}
int main(void)
{
int number;
cin>>number;
bprint(number);
bprint(short(number));
bprint(char(number));
return 0;
}
```
"unsigned" before "char\*" is required, if it isn't set by default. Access to variable's memory has only a pointer of variable's type or unsigned char, according to standard.
The most interesting option is the use of mathematics, described, inter alia, by Gynvael Coldwind, here: <http://gynvael.coldwind.pl/n/c_cpp_number_to_binary_string_01011010> . |
16,480,300 | at the moment I have script which prints out numeric values into bits so for example
```
print((short) 1);
```
I get a value of `00000001`, but how can I get for this a value like `00000001 00000000` and in case if I print `print((int) 1);` I get a value of `00000001 00000000 00000000 00000000`.
Here is my code:
```
void printbyte(unsigned char x)
{
for (int i = 0; i < 8; i++)
{
if (x & 0x80) cout << 1;
else cout << 0;
x = x << 1;
}
cout << endl;
}
template <typename T>
void print (T A)
{
unsigned char *p = (unsigned char *) &A;
printbyte(*p);
}
int main()
{
print((short) 1);
system("pause");
return 0;
}
``` | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2363241/"
] | You can just use `sizeof(T)` within `print` to determine how many bytes to process and then call `printbyte` for each byte, e.g.
```
#include <iostream>
#include <climits>
using namespace std;
void printbyte(unsigned char x)
{
for (int i = 0; i < CHAR_BIT; i++)
{
cout << ((x & 0x80) != 0);
x <<= 1;
}
}
template <typename T>
void print (T A)
{
for (size_t i = 0; i < sizeof(T); ++i)
{
unsigned char b = A >> ((sizeof(T) - i - 1) * CHAR_BIT);
//unsigned char b = A >> (i * CHAR_BIT); // use this for little endian output
printbyte(b);
cout << " ";
}
cout << endl;
}
int main()
{
print((short) 1);
print((long long) 42);
return 0;
}
``` | I think you should use [std::bitset](http://www.cplusplus.com/reference/bitset/bitset/), but you always have to specify the size at compile time.
To avoid that, you can use a template function like this (note that this is C++11):
```
#include <iostream>
#include <bitset>
#include <limits>
template <class T> void PrintBits (const T &Number) {
std::bitset<std::numeric_limits<T>::digits> Bit_Number(Number);
std::cout << Bit_Number << std::endl;
}
``` |
16,480,300 | at the moment I have script which prints out numeric values into bits so for example
```
print((short) 1);
```
I get a value of `00000001`, but how can I get for this a value like `00000001 00000000` and in case if I print `print((int) 1);` I get a value of `00000001 00000000 00000000 00000000`.
Here is my code:
```
void printbyte(unsigned char x)
{
for (int i = 0; i < 8; i++)
{
if (x & 0x80) cout << 1;
else cout << 0;
x = x << 1;
}
cout << endl;
}
template <typename T>
void print (T A)
{
unsigned char *p = (unsigned char *) &A;
printbyte(*p);
}
int main()
{
print((short) 1);
system("pause");
return 0;
}
``` | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2363241/"
] | You can use bitset, it's the easiest way. Here's an example:
```
#include <iostream>
#include <bitset>
using namespace std;
int main ()
{
int number;
cin>>number;
bitset <16> end (number);
cout<<number<<" --> "<<end<<'\n';
return 0;
}
```
Or reference: <http://www.cplusplus.com/reference/bitset/bitset/>
If you not want to use standard solutions, it can also look like this:
```
#include <iostream>
#include <climits>
using namespace std;
template <typename Type>
void bprint(Type in)
{
unsigned char* p = (reinterpret_cast<unsigned char*>(&in))+(sizeof(Type)-1); //x86
for(unsigned int n = sizeof(Type);n--;--p, std::cout<<' ')
for(unsigned int i = CHAR_BIT;i--;)
std::cout<<((*p&char(1<<i))!=0);
std::cout<<'\n';
}
int main(void)
{
int number;
cin>>number;
bprint(number);
bprint(short(number));
bprint(char(number));
return 0;
}
```
"unsigned" before "char\*" is required, if it isn't set by default. Access to variable's memory has only a pointer of variable's type or unsigned char, according to standard.
The most interesting option is the use of mathematics, described, inter alia, by Gynvael Coldwind, here: <http://gynvael.coldwind.pl/n/c_cpp_number_to_binary_string_01011010> . | I think you should use [std::bitset](http://www.cplusplus.com/reference/bitset/bitset/), but you always have to specify the size at compile time.
To avoid that, you can use a template function like this (note that this is C++11):
```
#include <iostream>
#include <bitset>
#include <limits>
template <class T> void PrintBits (const T &Number) {
std::bitset<std::numeric_limits<T>::digits> Bit_Number(Number);
std::cout << Bit_Number << std::endl;
}
``` |
12,511,202 | I have Python 2.7.3 installed on RHEL 6, and when I tried to install pysvn-1.7.6, I got an error. What should I do?
```
/search/python/pysvn-1.7.6/Import/pycxx-6.2.4/CXX/Python2/Objects.hxx:2912: warning: deprecated conversion from string constant to 'char*'
Compile: pysvn_svnenv.cpp into pysvn_svnenv.o
Compile: pysvn_profile.cpp into pysvn_profile.o
Compile: /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/Src/cxxsupport.cxx into cxxsupport.o
Compile: /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/Src/cxx_extensions.cxx into cxx_extensions.o
Compile: /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/Src/cxxextensions.c into cxxextensions.o
Compile: /search/python/pysvn-1.7.6/Import/pycxx-6.2.4/Src/IndirectPythonInterface.cxx into IndirectPythonInterface.o
Link pysvn/_pysvn_2_7.so
make: *** No rule to make target `egg'. Stop.
error: Not a URL, existing file, or requirement spec: 'dist/pysvn-1.7.6-py2.7-linux-x86_64.egg'
``` | 2012/09/20 | [
"https://Stackoverflow.com/questions/12511202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1685704/"
] | I solved this problem, the reason is that i have made a mistake.
i just executed the following command, it is not in the instruction.
```
python setup.py install
```
the installation steps are (**the Source is the dir name in pysvn directory**):
```
cd Source
python setup.py configure
make
cd ../Tests
make
cd Source
mkdir [YOUR PYTHON LIBDIR]/site-packages/pysvn
cp pysvn/__init__.py [YOUR PYTHON LIBDIR]/site-packages/pysvn
cp pysvn/_pysvn*.so [YOUR PYTHON LIBDIR]/site-packages/pysvn
``` | I had a same problem. and I find this solution and it is working.
Download the latest epel-release rpm from
<http://dl.fedoraproject.org/pub/epel/6/x86_64/>
for now :
`wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm`
Install epel-release rpm:
`rpm -Uvh epel-release*rpm`
Install pysvn rpm package:
`yum install pysvn` |
4,244,321 | in my application i am using array of button and i need to get the specified button which was pressed in the array. how to get.
Note: not in table view | 2010/11/22 | [
"https://Stackoverflow.com/questions/4244321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/489687/"
] | All UIViews have a integer `tag` property you can use to identify them. So in your button click handler (assuming it is the same function for all your buttons) you can get that tag and use it to differentiate between your buttons, e.g.:
```
-(void) myButtonClicked:(UIButton*)sender{
switch(sender.tag){
//Perform an action depending on button's tag
...
}
}
``` | Two ways:
Either set up a diffrent selector/method for each button.
or
You could set the .tag property and detect on that in your method |
111,749 | How might I implement a local HTTP server using either Java, C#, C or purely Mathematica?
It should be able to respond with Mathematica input to GET and POST requests ideally on W7.
This is related although [doesn't really work.](https://mathematica.stackexchange.com/questions/72551/reading-from-a-socket-stream) If you would like you can read the license [here](https://mathematica.stackexchange.com/questions/27785/implementing-a-100-mathematica-http-server) | 2016/04/03 | [
"https://mathematica.stackexchange.com/questions/111749",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5615/"
] | The following guide shows how to conduct communication between [nanohttpd](https://github.com/NanoHttpd/nanohttpd), an http server for Java, and *Mathematica*. The result is a server that, if you go to its address in a web browser, displays the result of `SessionTime[]`, i.e. the time since the *Mathematica* kernel associated to the server started.
I'm going to write as if the reader was using OS X with Maven installed because that is the operating system I am using, but this solution works on all operating systems with the proper, obvious, modifications. Directories and so on. On OS X Maven can be installed with [Brew](http://brew.sh/) using
```
brew -install maven
```
Getting up and running with nanohttpd:
1. Download the latest version of nanohttpd from [Github](https://github.com/NanoHttpd/nanohttpd/releases).
2. Follow the steps listed under "quickstart" on [nanohttpd.org](http://www.nanohttpd.org/)
Add this to the top of the sample app among the other imports:
```
import com.wolfram.jlink.*;
```
Locate JLink.jar on your harddrive. On OS X it is located at
```
/Applications/Mathematica.app/SystemFiles/Links/JLink
```
Navigate to the app's directory and run the following command to include JLink.jar in the Maven project (with the appropriate modifications):
```
mvn install:install-file -Dfile=/Applications/Mathematica.app/Contents/SystemFiles/Links/JLink/JLink.jar -DgroupId=com.wolfram.jlink -DartifactId=JLink -Dversion=1.0 -Dpackaging=jar
```
And modify the app's pom.xml by adding the file as a dependency:
```
<dependency>
<groupId>com.wolfram.jlink</groupId>
<artifactId>JLink</artifactId>
<version>1.0</version>
</dependency>
```
Check that you can still compile the application and that it still works. Now if that's true, replace the code in App.java with this (see the sample program [here](https://reference.wolfram.com/language/JLink/tutorial/WritingJavaProgramsThatUseTheWolframLanguage.html)):
```
import java.io.IOException;
import java.util.Map;
import com.wolfram.jlink.*;
import fi.iki.elonen.NanoHTTPD;
public class App extends NanoHTTPD {
KernelLink ml;
public App() throws IOException {
super(8888);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
try {
String jLinkDir = "/Applications/Mathematica.app/SystemFiles/Links/JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir); // http://forums.wolfram.com/mathgroup/archive/2008/Aug/msg00664.html
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname '\"/Applications/Mathematica.app/Contents/MacOS/MathKernel\" -mathlink'");
// Get rid of the initial InputNamePacket the kernel will send
// when it is launched.
ml.discardAnswer();
} catch (MathLinkException e) {
throw new IOException("Fatal error opening link: " + e.getMessage());
}
System.out.println("\nRunning! Point your browers to http://localhost:8888/ \n");
}
public static void main(String[] args) {
try {
new App();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
}
}
@Override
public Response serve(IHTTPSession session) {
String msg = "<html><body><p>";
try {
ml.evaluate("SessionTime[]");
ml.waitForAnswer();
double result = ml.getDouble();
msg = msg + Double.toString(result);
} catch (MathLinkException e) {
msg = msg + "MathLinkException occurred: " + e.getMessage();
}
msg = msg + "</p></body></html>";
return newFixedLengthResponse(msg);
}
}
```
Look up the line with `String jLinkDir =` and confirm that the directory is right. If you are using another operating system than OS X you also have to configure the line with `MathLinkFactory` in it. Information about that is available [here](https://reference.wolfram.com/language/JLink/tutorial/WritingJavaProgramsThatUseTheWolframLanguage.html).
Compile the code and run it by (as you did before to run the sample app), navigating to the project's directory and executing the following commands:
```
mvcompile
mvn exec:java -Dexec.mainClass="com.stackexchange.mathematica.App"
```
where you have edited mainClass appropriately. You now have an HTTP server on the address <http://localhost:8888/> that calls on a *Mathematica* kernel and uses its response to answer requests. | Starting in Mathematica 12, there is a built-in function [`SocketListen`](https://reference.wolfram.com/language/ref/SocketListen.html) that can start a web server and respond to HTTP requests.
`SocketListen` is also available in Mathematica 11.2, but only on an experimental basis.
Further reading: [Network Programming Guide](https://reference.wolfram.com/language/guide/NetworkProgramming.html). |
111,749 | How might I implement a local HTTP server using either Java, C#, C or purely Mathematica?
It should be able to respond with Mathematica input to GET and POST requests ideally on W7.
This is related although [doesn't really work.](https://mathematica.stackexchange.com/questions/72551/reading-from-a-socket-stream) If you would like you can read the license [here](https://mathematica.stackexchange.com/questions/27785/implementing-a-100-mathematica-http-server) | 2016/04/03 | [
"https://mathematica.stackexchange.com/questions/111749",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5615/"
] | The following guide shows how to conduct communication between [nanohttpd](https://github.com/NanoHttpd/nanohttpd), an http server for Java, and *Mathematica*. The result is a server that, if you go to its address in a web browser, displays the result of `SessionTime[]`, i.e. the time since the *Mathematica* kernel associated to the server started.
I'm going to write as if the reader was using OS X with Maven installed because that is the operating system I am using, but this solution works on all operating systems with the proper, obvious, modifications. Directories and so on. On OS X Maven can be installed with [Brew](http://brew.sh/) using
```
brew -install maven
```
Getting up and running with nanohttpd:
1. Download the latest version of nanohttpd from [Github](https://github.com/NanoHttpd/nanohttpd/releases).
2. Follow the steps listed under "quickstart" on [nanohttpd.org](http://www.nanohttpd.org/)
Add this to the top of the sample app among the other imports:
```
import com.wolfram.jlink.*;
```
Locate JLink.jar on your harddrive. On OS X it is located at
```
/Applications/Mathematica.app/SystemFiles/Links/JLink
```
Navigate to the app's directory and run the following command to include JLink.jar in the Maven project (with the appropriate modifications):
```
mvn install:install-file -Dfile=/Applications/Mathematica.app/Contents/SystemFiles/Links/JLink/JLink.jar -DgroupId=com.wolfram.jlink -DartifactId=JLink -Dversion=1.0 -Dpackaging=jar
```
And modify the app's pom.xml by adding the file as a dependency:
```
<dependency>
<groupId>com.wolfram.jlink</groupId>
<artifactId>JLink</artifactId>
<version>1.0</version>
</dependency>
```
Check that you can still compile the application and that it still works. Now if that's true, replace the code in App.java with this (see the sample program [here](https://reference.wolfram.com/language/JLink/tutorial/WritingJavaProgramsThatUseTheWolframLanguage.html)):
```
import java.io.IOException;
import java.util.Map;
import com.wolfram.jlink.*;
import fi.iki.elonen.NanoHTTPD;
public class App extends NanoHTTPD {
KernelLink ml;
public App() throws IOException {
super(8888);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
try {
String jLinkDir = "/Applications/Mathematica.app/SystemFiles/Links/JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir); // http://forums.wolfram.com/mathgroup/archive/2008/Aug/msg00664.html
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname '\"/Applications/Mathematica.app/Contents/MacOS/MathKernel\" -mathlink'");
// Get rid of the initial InputNamePacket the kernel will send
// when it is launched.
ml.discardAnswer();
} catch (MathLinkException e) {
throw new IOException("Fatal error opening link: " + e.getMessage());
}
System.out.println("\nRunning! Point your browers to http://localhost:8888/ \n");
}
public static void main(String[] args) {
try {
new App();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
}
}
@Override
public Response serve(IHTTPSession session) {
String msg = "<html><body><p>";
try {
ml.evaluate("SessionTime[]");
ml.waitForAnswer();
double result = ml.getDouble();
msg = msg + Double.toString(result);
} catch (MathLinkException e) {
msg = msg + "MathLinkException occurred: " + e.getMessage();
}
msg = msg + "</p></body></html>";
return newFixedLengthResponse(msg);
}
}
```
Look up the line with `String jLinkDir =` and confirm that the directory is right. If you are using another operating system than OS X you also have to configure the line with `MathLinkFactory` in it. Information about that is available [here](https://reference.wolfram.com/language/JLink/tutorial/WritingJavaProgramsThatUseTheWolframLanguage.html).
Compile the code and run it by (as you did before to run the sample app), navigating to the project's directory and executing the following commands:
```
mvcompile
mvn exec:java -Dexec.mainClass="com.stackexchange.mathematica.App"
```
where you have edited mainClass appropriately. You now have an HTTP server on the address <http://localhost:8888/> that calls on a *Mathematica* kernel and uses its response to answer requests. | The following is a sample implementation of a simple HTTP server in Wolfram Language code only:
<https://github.com/arnoudbuzing/wolfram-server>
You send it a POST request where the body data of the HTTP request contains the Wolfram Language code you wish to evaluate.
The (running) wolframserver.wls script processes the request by evaluating the code string and returning the result as [ExpressionJSON](https://reference.wolfram.com/language/ref/format/ExpressionJSON.html) which should be generic enough to parse and process in most programming languages (including javascript for web browsers).
It's a new and evolving project for me, so please give it a star if this is useful to you because that will tell me how much interest there is in this (and how much time to spend on it for making improvements). |
111,749 | How might I implement a local HTTP server using either Java, C#, C or purely Mathematica?
It should be able to respond with Mathematica input to GET and POST requests ideally on W7.
This is related although [doesn't really work.](https://mathematica.stackexchange.com/questions/72551/reading-from-a-socket-stream) If you would like you can read the license [here](https://mathematica.stackexchange.com/questions/27785/implementing-a-100-mathematica-http-server) | 2016/04/03 | [
"https://mathematica.stackexchange.com/questions/111749",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5615/"
] | The following guide shows how to conduct communication between [nanohttpd](https://github.com/NanoHttpd/nanohttpd), an http server for Java, and *Mathematica*. The result is a server that, if you go to its address in a web browser, displays the result of `SessionTime[]`, i.e. the time since the *Mathematica* kernel associated to the server started.
I'm going to write as if the reader was using OS X with Maven installed because that is the operating system I am using, but this solution works on all operating systems with the proper, obvious, modifications. Directories and so on. On OS X Maven can be installed with [Brew](http://brew.sh/) using
```
brew -install maven
```
Getting up and running with nanohttpd:
1. Download the latest version of nanohttpd from [Github](https://github.com/NanoHttpd/nanohttpd/releases).
2. Follow the steps listed under "quickstart" on [nanohttpd.org](http://www.nanohttpd.org/)
Add this to the top of the sample app among the other imports:
```
import com.wolfram.jlink.*;
```
Locate JLink.jar on your harddrive. On OS X it is located at
```
/Applications/Mathematica.app/SystemFiles/Links/JLink
```
Navigate to the app's directory and run the following command to include JLink.jar in the Maven project (with the appropriate modifications):
```
mvn install:install-file -Dfile=/Applications/Mathematica.app/Contents/SystemFiles/Links/JLink/JLink.jar -DgroupId=com.wolfram.jlink -DartifactId=JLink -Dversion=1.0 -Dpackaging=jar
```
And modify the app's pom.xml by adding the file as a dependency:
```
<dependency>
<groupId>com.wolfram.jlink</groupId>
<artifactId>JLink</artifactId>
<version>1.0</version>
</dependency>
```
Check that you can still compile the application and that it still works. Now if that's true, replace the code in App.java with this (see the sample program [here](https://reference.wolfram.com/language/JLink/tutorial/WritingJavaProgramsThatUseTheWolframLanguage.html)):
```
import java.io.IOException;
import java.util.Map;
import com.wolfram.jlink.*;
import fi.iki.elonen.NanoHTTPD;
public class App extends NanoHTTPD {
KernelLink ml;
public App() throws IOException {
super(8888);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
try {
String jLinkDir = "/Applications/Mathematica.app/SystemFiles/Links/JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir); // http://forums.wolfram.com/mathgroup/archive/2008/Aug/msg00664.html
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname '\"/Applications/Mathematica.app/Contents/MacOS/MathKernel\" -mathlink'");
// Get rid of the initial InputNamePacket the kernel will send
// when it is launched.
ml.discardAnswer();
} catch (MathLinkException e) {
throw new IOException("Fatal error opening link: " + e.getMessage());
}
System.out.println("\nRunning! Point your browers to http://localhost:8888/ \n");
}
public static void main(String[] args) {
try {
new App();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
}
}
@Override
public Response serve(IHTTPSession session) {
String msg = "<html><body><p>";
try {
ml.evaluate("SessionTime[]");
ml.waitForAnswer();
double result = ml.getDouble();
msg = msg + Double.toString(result);
} catch (MathLinkException e) {
msg = msg + "MathLinkException occurred: " + e.getMessage();
}
msg = msg + "</p></body></html>";
return newFixedLengthResponse(msg);
}
}
```
Look up the line with `String jLinkDir =` and confirm that the directory is right. If you are using another operating system than OS X you also have to configure the line with `MathLinkFactory` in it. Information about that is available [here](https://reference.wolfram.com/language/JLink/tutorial/WritingJavaProgramsThatUseTheWolframLanguage.html).
Compile the code and run it by (as you did before to run the sample app), navigating to the project's directory and executing the following commands:
```
mvcompile
mvn exec:java -Dexec.mainClass="com.stackexchange.mathematica.App"
```
where you have edited mainClass appropriately. You now have an HTTP server on the address <http://localhost:8888/> that calls on a *Mathematica* kernel and uses its response to answer requests. | Yes (and using pure Mathematica or WolframEngine)
<https://jerryi.github.io/tinyweb-mathematica/> |
111,749 | How might I implement a local HTTP server using either Java, C#, C or purely Mathematica?
It should be able to respond with Mathematica input to GET and POST requests ideally on W7.
This is related although [doesn't really work.](https://mathematica.stackexchange.com/questions/72551/reading-from-a-socket-stream) If you would like you can read the license [here](https://mathematica.stackexchange.com/questions/27785/implementing-a-100-mathematica-http-server) | 2016/04/03 | [
"https://mathematica.stackexchange.com/questions/111749",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5615/"
] | The following is a sample implementation of a simple HTTP server in Wolfram Language code only:
<https://github.com/arnoudbuzing/wolfram-server>
You send it a POST request where the body data of the HTTP request contains the Wolfram Language code you wish to evaluate.
The (running) wolframserver.wls script processes the request by evaluating the code string and returning the result as [ExpressionJSON](https://reference.wolfram.com/language/ref/format/ExpressionJSON.html) which should be generic enough to parse and process in most programming languages (including javascript for web browsers).
It's a new and evolving project for me, so please give it a star if this is useful to you because that will tell me how much interest there is in this (and how much time to spend on it for making improvements). | Starting in Mathematica 12, there is a built-in function [`SocketListen`](https://reference.wolfram.com/language/ref/SocketListen.html) that can start a web server and respond to HTTP requests.
`SocketListen` is also available in Mathematica 11.2, but only on an experimental basis.
Further reading: [Network Programming Guide](https://reference.wolfram.com/language/guide/NetworkProgramming.html). |
111,749 | How might I implement a local HTTP server using either Java, C#, C or purely Mathematica?
It should be able to respond with Mathematica input to GET and POST requests ideally on W7.
This is related although [doesn't really work.](https://mathematica.stackexchange.com/questions/72551/reading-from-a-socket-stream) If you would like you can read the license [here](https://mathematica.stackexchange.com/questions/27785/implementing-a-100-mathematica-http-server) | 2016/04/03 | [
"https://mathematica.stackexchange.com/questions/111749",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5615/"
] | Starting in Mathematica 12, there is a built-in function [`SocketListen`](https://reference.wolfram.com/language/ref/SocketListen.html) that can start a web server and respond to HTTP requests.
`SocketListen` is also available in Mathematica 11.2, but only on an experimental basis.
Further reading: [Network Programming Guide](https://reference.wolfram.com/language/guide/NetworkProgramming.html). | Yes (and using pure Mathematica or WolframEngine)
<https://jerryi.github.io/tinyweb-mathematica/> |
111,749 | How might I implement a local HTTP server using either Java, C#, C or purely Mathematica?
It should be able to respond with Mathematica input to GET and POST requests ideally on W7.
This is related although [doesn't really work.](https://mathematica.stackexchange.com/questions/72551/reading-from-a-socket-stream) If you would like you can read the license [here](https://mathematica.stackexchange.com/questions/27785/implementing-a-100-mathematica-http-server) | 2016/04/03 | [
"https://mathematica.stackexchange.com/questions/111749",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5615/"
] | The following is a sample implementation of a simple HTTP server in Wolfram Language code only:
<https://github.com/arnoudbuzing/wolfram-server>
You send it a POST request where the body data of the HTTP request contains the Wolfram Language code you wish to evaluate.
The (running) wolframserver.wls script processes the request by evaluating the code string and returning the result as [ExpressionJSON](https://reference.wolfram.com/language/ref/format/ExpressionJSON.html) which should be generic enough to parse and process in most programming languages (including javascript for web browsers).
It's a new and evolving project for me, so please give it a star if this is useful to you because that will tell me how much interest there is in this (and how much time to spend on it for making improvements). | Yes (and using pure Mathematica or WolframEngine)
<https://jerryi.github.io/tinyweb-mathematica/> |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | >
> Are these valid statements?
>
>
>
Yes ... taken as Java expressions in the context of a normal Java program.
In the context of an Eclipse debugger's expression evaluator, I'm not sure.
>
> If so, why am I getting an exception?
>
>
>
I don't know for sure, but I suspect that it is something to do with the debugger itself.
* One possibility is that you are using the expression evaluation functionality incorrectly.
* Another possibility is that this is a bug in the Eclipse debugger, or a mismatch between the Eclipse debugger and the debug agent in the JVM.
The one thing that I do know is that the `parseInt` and `parseLong` methods themselves don't throw `UnsupportedOperationException`. (In theory, they could because it is an unchecked exception. But I checked the source code for those 2 methods, and there's no way that the code could do that ... if executed in the normal way.)
---
The Google query - "site:eclipse.org +UnsupportedOperationException JDI" - shows a lot of hits in the Eclipse issues database and newsgroups / mailing lists.
In some cases, it looks like the problem is that the JDI / JNDI implementation for the target platform is incomplete. Could this be your problem? You mention you are doing Android development ... | I do not think it is related to parseInt or parseLong.
The exception clearly specifies "Exception processing async thread queue"
Older versions of Eclipse has been known to throw similar exceptions, when it is being used in Debug mode. But I think these were fixed in the newer version.
I know that your code is ok, because it would have thrown "NumberFormatException" if there was anything wrong.
I even tried an example just to make sure.
```
Long lVal = Long.parseLong("5");
System.out.println("lVal = " + lVal );
```
Output was
>
> lVal = 5
>
>
>
With no exceptions |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | >
> Are these valid statements?
>
>
>
Yes ... taken as Java expressions in the context of a normal Java program.
In the context of an Eclipse debugger's expression evaluator, I'm not sure.
>
> If so, why am I getting an exception?
>
>
>
I don't know for sure, but I suspect that it is something to do with the debugger itself.
* One possibility is that you are using the expression evaluation functionality incorrectly.
* Another possibility is that this is a bug in the Eclipse debugger, or a mismatch between the Eclipse debugger and the debug agent in the JVM.
The one thing that I do know is that the `parseInt` and `parseLong` methods themselves don't throw `UnsupportedOperationException`. (In theory, they could because it is an unchecked exception. But I checked the source code for those 2 methods, and there's no way that the code could do that ... if executed in the normal way.)
---
The Google query - "site:eclipse.org +UnsupportedOperationException JDI" - shows a lot of hits in the Eclipse issues database and newsgroups / mailing lists.
In some cases, it looks like the problem is that the JDI / JNDI implementation for the target platform is incomplete. Could this be your problem? You mention you are doing Android development ... | Exception is the declared type of `e` and that is what is normally displayed in the tooltip in Java perspective. If eclipse doesn't tell you more, first make sure you are in debug perspective (not in Java perspective).
I guess you have a problem with the configuration of eclipse tooltips. You should see more information about the exception in the variable view (if it's not open, try Window/Show View/Variables).
Also, when debugging stops at your breakpoint, you can mark `e` in source and hit CTRL+I (inspect). You should get a popup telling you more about e.
EDIT: This is about finding out more about e. I agree with the earlier posters you cannot normally get an UnsupportedOperationException from your code. Seems like the problem is that debugging is not working correctly. |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | I do not think it is related to parseInt or parseLong.
The exception clearly specifies "Exception processing async thread queue"
Older versions of Eclipse has been known to throw similar exceptions, when it is being used in Debug mode. But I think these were fixed in the newer version.
I know that your code is ok, because it would have thrown "NumberFormatException" if there was anything wrong.
I even tried an example just to make sure.
```
Long lVal = Long.parseLong("5");
System.out.println("lVal = " + lVal );
```
Output was
>
> lVal = 5
>
>
>
With no exceptions | I think you should first try to parse the text variable and put it in another long variable and print. So that you can know whether the parsing is done or not. So that you will know where the problem is. |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | I do not think it is related to parseInt or parseLong.
The exception clearly specifies "Exception processing async thread queue"
Older versions of Eclipse has been known to throw similar exceptions, when it is being used in Debug mode. But I think these were fixed in the newer version.
I know that your code is ok, because it would have thrown "NumberFormatException" if there was anything wrong.
I even tried an example just to make sure.
```
Long lVal = Long.parseLong("5");
System.out.println("lVal = " + lVal );
```
Output was
>
> lVal = 5
>
>
>
With no exceptions | Exception is the declared type of `e` and that is what is normally displayed in the tooltip in Java perspective. If eclipse doesn't tell you more, first make sure you are in debug perspective (not in Java perspective).
I guess you have a problem with the configuration of eclipse tooltips. You should see more information about the exception in the variable view (if it's not open, try Window/Show View/Variables).
Also, when debugging stops at your breakpoint, you can mark `e` in source and hit CTRL+I (inspect). You should get a popup telling you more about e.
EDIT: This is about finding out more about e. I agree with the earlier posters you cannot normally get an UnsupportedOperationException from your code. Seems like the problem is that debugging is not working correctly. |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | According to [java docs](http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29) parseInt can throw only NumberFormatException,it means UnsupportedException comes from different place in your code.
**parseInt**
```
public static int parseInt(String s)
throws NumberFormatException
```
>
> Parses the string argument as a signed decimal integer. The characters
> in the string must all be decimal
> digits, except that the first
> character may be an ASCII minus sign
> '-' ('\u002D') to indicate a negative
> value. The resulting integer value is
> returned, exactly as if the argument
> and the radix 10 were given as
> arguments to the
> parseInt(java.lang.String, int)
> method.
>
>
> | Exception is the declared type of `e` and that is what is normally displayed in the tooltip in Java perspective. If eclipse doesn't tell you more, first make sure you are in debug perspective (not in Java perspective).
I guess you have a problem with the configuration of eclipse tooltips. You should see more information about the exception in the variable view (if it's not open, try Window/Show View/Variables).
Also, when debugging stops at your breakpoint, you can mark `e` in source and hit CTRL+I (inspect). You should get a popup telling you more about e.
EDIT: This is about finding out more about e. I agree with the earlier posters you cannot normally get an UnsupportedOperationException from your code. Seems like the problem is that debugging is not working correctly. |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | I do not think it is related to parseInt or parseLong.
The exception clearly specifies "Exception processing async thread queue"
Older versions of Eclipse has been known to throw similar exceptions, when it is being used in Debug mode. But I think these were fixed in the newer version.
I know that your code is ok, because it would have thrown "NumberFormatException" if there was anything wrong.
I even tried an example just to make sure.
```
Long lVal = Long.parseLong("5");
System.out.println("lVal = " + lVal );
```
Output was
>
> lVal = 5
>
>
>
With no exceptions | try to put sysout in catch block which shows the type of the exception.
```
System.out.println(e);
```
and moreover as suresh mention it can throw only NumberFormatException |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | >
> Are these valid statements?
>
>
>
Yes ... taken as Java expressions in the context of a normal Java program.
In the context of an Eclipse debugger's expression evaluator, I'm not sure.
>
> If so, why am I getting an exception?
>
>
>
I don't know for sure, but I suspect that it is something to do with the debugger itself.
* One possibility is that you are using the expression evaluation functionality incorrectly.
* Another possibility is that this is a bug in the Eclipse debugger, or a mismatch between the Eclipse debugger and the debug agent in the JVM.
The one thing that I do know is that the `parseInt` and `parseLong` methods themselves don't throw `UnsupportedOperationException`. (In theory, they could because it is an unchecked exception. But I checked the source code for those 2 methods, and there's no way that the code could do that ... if executed in the normal way.)
---
The Google query - "site:eclipse.org +UnsupportedOperationException JDI" - shows a lot of hits in the Eclipse issues database and newsgroups / mailing lists.
In some cases, it looks like the problem is that the JDI / JNDI implementation for the target platform is incomplete. Could this be your problem? You mention you are doing Android development ... | try to put sysout in catch block which shows the type of the exception.
```
System.out.println(e);
```
and moreover as suresh mention it can throw only NumberFormatException |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | According to [java docs](http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29) parseInt can throw only NumberFormatException,it means UnsupportedException comes from different place in your code.
**parseInt**
```
public static int parseInt(String s)
throws NumberFormatException
```
>
> Parses the string argument as a signed decimal integer. The characters
> in the string must all be decimal
> digits, except that the first
> character may be an ASCII minus sign
> '-' ('\u002D') to indicate a negative
> value. The resulting integer value is
> returned, exactly as if the argument
> and the radix 10 were given as
> arguments to the
> parseInt(java.lang.String, int)
> method.
>
>
> | try to put sysout in catch block which shows the type of the exception.
```
System.out.println(e);
```
and moreover as suresh mention it can throw only NumberFormatException |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | According to [java docs](http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29) parseInt can throw only NumberFormatException,it means UnsupportedException comes from different place in your code.
**parseInt**
```
public static int parseInt(String s)
throws NumberFormatException
```
>
> Parses the string argument as a signed decimal integer. The characters
> in the string must all be decimal
> digits, except that the first
> character may be an ASCII minus sign
> '-' ('\u002D') to indicate a negative
> value. The resulting integer value is
> returned, exactly as if the argument
> and the radix 10 were given as
> arguments to the
> parseInt(java.lang.String, int)
> method.
>
>
> | I think you should first try to parse the text variable and put it in another long variable and print. So that you can know whether the parsing is done or not. So that you will know where the problem is. |
5,509,793 | `Integer.parseInt("5")` and `Long.parseLong("5")` are throwing an `UnsupportedOperationException` in the Eclipse Expressions Window.

I think this is also the Exception I'm getting at runtime, but being new to Eclipse, I'm not sure how to find the type of `e` within a debug session:
```
public static long longTryParse(String text, long fallbackValue) {
try {
return Long.parseLong(text);
} catch (Exception e) {
return fallbackValue; // When stopping at a breakpoint here, Eclipse says that e is of type 'Exception'. Well, that's informative.
}
}
```
So ...
1. Are these valid statements?
2. If so, why am I getting an exception?
3. (Of lesser importance) Why won't Eclipse say that e is of type UnsupportedOperationException rather than Exception during my debug session?
Thanks! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] | >
> Are these valid statements?
>
>
>
Yes ... taken as Java expressions in the context of a normal Java program.
In the context of an Eclipse debugger's expression evaluator, I'm not sure.
>
> If so, why am I getting an exception?
>
>
>
I don't know for sure, but I suspect that it is something to do with the debugger itself.
* One possibility is that you are using the expression evaluation functionality incorrectly.
* Another possibility is that this is a bug in the Eclipse debugger, or a mismatch between the Eclipse debugger and the debug agent in the JVM.
The one thing that I do know is that the `parseInt` and `parseLong` methods themselves don't throw `UnsupportedOperationException`. (In theory, they could because it is an unchecked exception. But I checked the source code for those 2 methods, and there's no way that the code could do that ... if executed in the normal way.)
---
The Google query - "site:eclipse.org +UnsupportedOperationException JDI" - shows a lot of hits in the Eclipse issues database and newsgroups / mailing lists.
In some cases, it looks like the problem is that the JDI / JNDI implementation for the target platform is incomplete. Could this be your problem? You mention you are doing Android development ... | I think you should first try to parse the text variable and put it in another long variable and print. So that you can know whether the parsing is done or not. So that you will know where the problem is. |
123,318 | I have a list 'choiceOpt' which contains a choice field 'choiceOptions' having Yes ad No as options.
I want to retrieve this Yes and No programmatically (javascript) .
Kindly help. | 2014/12/05 | [
"https://sharepoint.stackexchange.com/questions/123318",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/35506/"
] | After the first query that creates `Folder` object you could perform the `second` REST request:
```
http://<sitecollection>/<site>/_api/web/folders/getbyurl(folderrelativeurl)/listItemAllFields
```
to retrieve the associated `List Item` with a `Folder`.
The following JavaScript example demonstrates that approach:
```
function executeJson(url,method,additionalHeaders,payload)
{
var headers = {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
if (typeof additionalHeaders != 'undefined') {
for(var key in additionalHeaders){
headers[key] = additionalHeaders[key];
}
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if(method == "POST") {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
function createFolder(webUrl,folderUrl)
{
var url = webUrl + "/_api/web/folders";
var folderPayload = { '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': folderUrl};
return executeJson(url,'POST',null,folderPayload).then(function(data){
var url = webUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/ListItemAllFields";
return executeJson(url,'GET');
});
}
```
Usage
```
createFolder(_spPageContextInfo.webAbsoluteUrl,'/Shared Documents/Archive')
.done(function(data)
{
var folderItem = data.d;
console.log(folderItem.Id); //print ListItem.Id property
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
``` | I've found using the following GetByUrl or GetFolderByServerRelativeUrl with a number of folders can lead to the below.
"The length of the URL for this request exceeds the configured maxUrlLength value."
By using GetFolderById('guid')/listItemAllFields I was able to accomplish my task of assigning permissions and updating a field. |
1,647,927 | For the sake of education, and programming practice, I'd like to write a simple library that can handle raw keyboard input, and output to the terminal in 'real time'.
I'd like to stick with ansi C as much as possible, I just have no idea where to start something like this. I've done several google searches, and 99% of the results use libraries, or are for C++.
I'd really like to get it working in windows, then port it to OSX when I have the time. | 2009/10/30 | [
"https://Stackoverflow.com/questions/1647927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101946/"
] | Sticking with Standard C as much as possible is a good idea, but you are not going to get very far with your adopted task using just Standard C. The mechanisms to obtain characters from the terminal one at a time are inherently platform specific. For POSIX systems (MacOS X), look at the [`<termios.h>`](http://www.opengroup.org/onlinepubs/9699919799/basedefs/termios.h.html#tag_13_74) header. Older systems use a vast variety of headers and system calls to achieve similar effects. You'll have to decide whether you are going to do any special character handling, remembering that things like 'line kill' can appear at the end of the line and zap all the characters entered so far.
For Windows, you'll need to delve into the WIN32 API - there is going to be essentially no commonality in the code between Unix and Windows, at least where you put the 'terminal' into character-by-character mode. Once you've got a mechanism to read single characters, you can manage common code - probably.
Also, you'll need to worry about the differences between characters and the keys pressed. For example, to enter 'ï' on MacOS X, you type `option-u` and `i`. That's three key presses. | This is not possible using only standard ISO C. However, you can try using the following:
```
#include <stdio.h>
void setbuf(FILE * restrict stream, char * restrict buf);
```
and related functions.
Your best bet though is to use the `ncurses` library. |
1,647,927 | For the sake of education, and programming practice, I'd like to write a simple library that can handle raw keyboard input, and output to the terminal in 'real time'.
I'd like to stick with ansi C as much as possible, I just have no idea where to start something like this. I've done several google searches, and 99% of the results use libraries, or are for C++.
I'd really like to get it working in windows, then port it to OSX when I have the time. | 2009/10/30 | [
"https://Stackoverflow.com/questions/1647927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101946/"
] | To set an open stream to be non-buffered using ANSI C, you can do this:
```
#include <stdio.h>
if (setvbuf(fd, NULL, _IONBF, 0) == 0)
printf("Set stream to unbuffered mode\n");
```
(Reference: C89 4.9.5.6)
However, after that you're on your own. :-) | This is not possible using only standard ISO C. However, you can try using the following:
```
#include <stdio.h>
void setbuf(FILE * restrict stream, char * restrict buf);
```
and related functions.
Your best bet though is to use the `ncurses` library. |
1,647,927 | For the sake of education, and programming practice, I'd like to write a simple library that can handle raw keyboard input, and output to the terminal in 'real time'.
I'd like to stick with ansi C as much as possible, I just have no idea where to start something like this. I've done several google searches, and 99% of the results use libraries, or are for C++.
I'd really like to get it working in windows, then port it to OSX when I have the time. | 2009/10/30 | [
"https://Stackoverflow.com/questions/1647927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101946/"
] | Sticking with Standard C as much as possible is a good idea, but you are not going to get very far with your adopted task using just Standard C. The mechanisms to obtain characters from the terminal one at a time are inherently platform specific. For POSIX systems (MacOS X), look at the [`<termios.h>`](http://www.opengroup.org/onlinepubs/9699919799/basedefs/termios.h.html#tag_13_74) header. Older systems use a vast variety of headers and system calls to achieve similar effects. You'll have to decide whether you are going to do any special character handling, remembering that things like 'line kill' can appear at the end of the line and zap all the characters entered so far.
For Windows, you'll need to delve into the WIN32 API - there is going to be essentially no commonality in the code between Unix and Windows, at least where you put the 'terminal' into character-by-character mode. Once you've got a mechanism to read single characters, you can manage common code - probably.
Also, you'll need to worry about the differences between characters and the keys pressed. For example, to enter 'ï' on MacOS X, you type `option-u` and `i`. That's three key presses. | To set an open stream to be non-buffered using ANSI C, you can do this:
```
#include <stdio.h>
if (setvbuf(fd, NULL, _IONBF, 0) == 0)
printf("Set stream to unbuffered mode\n");
```
(Reference: C89 4.9.5.6)
However, after that you're on your own. :-) |
43,314 | Is there a difference when the adverbs '*always, continually,forever,etc..*' are used with past simple and past progressive?
For example :
1. He **always/ continually** worked there.
2. He was **always/ continually** working there.
(What is the difference between the above two sentences?) | 2014/12/17 | [
"https://ell.stackexchange.com/questions/43314",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/10435/"
] | Let's say that a colleague mistakenly believes that Joe is a new hire. We might say:
*Joe has always worked here.*
to mean nothing more than the fact that Joe is not a new employee. He has been here for some while.
If we want to say that Joe never slacked off when he was working at Acme Widgets, but always took his job seriously and gave it his best effort:
*Joe was always working when he was at Acme Widgets.* | /simple past/ means **perfect** or done. /always/ can be used in past form when we want to **emphasize** the event.
past progressive follows simple past.
for ex:
*I was reading a novel* when *he knocked the door*.
you could also say:
He knocked the door while I was reading a novel.
as long as I know, adverb of freq /always/ is not good to place in past prog. tense |
43,314 | Is there a difference when the adverbs '*always, continually,forever,etc..*' are used with past simple and past progressive?
For example :
1. He **always/ continually** worked there.
2. He was **always/ continually** working there.
(What is the difference between the above two sentences?) | 2014/12/17 | [
"https://ell.stackexchange.com/questions/43314",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/10435/"
] | Sometimes, we use the past continuous as an alternative to the past simple for repeated or routine actions, with a little difference in meaning.
He always/continually worked there.
He was always/continually working there.
The first sentence literally implies that he always worked there, whereas, the second sentence does not literally mean so. It conveys the sense that he appeared to be always working there. In other words, it implies that he was seen to be working there very often. | /simple past/ means **perfect** or done. /always/ can be used in past form when we want to **emphasize** the event.
past progressive follows simple past.
for ex:
*I was reading a novel* when *he knocked the door*.
you could also say:
He knocked the door while I was reading a novel.
as long as I know, adverb of freq /always/ is not good to place in past prog. tense |
43,314 | Is there a difference when the adverbs '*always, continually,forever,etc..*' are used with past simple and past progressive?
For example :
1. He **always/ continually** worked there.
2. He was **always/ continually** working there.
(What is the difference between the above two sentences?) | 2014/12/17 | [
"https://ell.stackexchange.com/questions/43314",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/10435/"
] | Let's say that a colleague mistakenly believes that Joe is a new hire. We might say:
*Joe has always worked here.*
to mean nothing more than the fact that Joe is not a new employee. He has been here for some while.
If we want to say that Joe never slacked off when he was working at Acme Widgets, but always took his job seriously and gave it his best effort:
*Joe was always working when he was at Acme Widgets.* | Sometimes, we use the past continuous as an alternative to the past simple for repeated or routine actions, with a little difference in meaning.
He always/continually worked there.
He was always/continually working there.
The first sentence literally implies that he always worked there, whereas, the second sentence does not literally mean so. It conveys the sense that he appeared to be always working there. In other words, it implies that he was seen to be working there very often. |
5,764,693 | Only info I found was this:
<http://forrst.com/posts/Node_js_Jade_Import_Jade_File-CZW>
I replicated the suggested folder structure (views/partials) But it didn't work, as soon as I put
```
!=partial('header', {})
!=partial('menu', {})
```
into index.jade, I get a blank screen, the error message I receive from jade is:
>
> ReferenceError: ./views/index.jade:3
> 1. 'p index'
>
> 2. ''
>
> 3. '!=partial(\'header', {})'
>
>
> partial is not defined
>
>
>
I'd be very grateful for any help ! (I strongly prefer not to use express.js) | 2011/04/23 | [
"https://Stackoverflow.com/questions/5764693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335355/"
] | Jade has a command called include. Just use
```
include _form
```
given that the filename of the partial is \*\_form.jade\*, and is in the same directory | I think partial rendering is done in express, so you will have to snag that code or write your own.
I have my own helper class for jade rendering with partials that you can use or get some ideas from [here](https://gist.github.com/938647), (it's using [Joose](http://joose.it) and [Cactus](https://github.com/Raevel/Cactus)) |
5,764,693 | Only info I found was this:
<http://forrst.com/posts/Node_js_Jade_Import_Jade_File-CZW>
I replicated the suggested folder structure (views/partials) But it didn't work, as soon as I put
```
!=partial('header', {})
!=partial('menu', {})
```
into index.jade, I get a blank screen, the error message I receive from jade is:
>
> ReferenceError: ./views/index.jade:3
> 1. 'p index'
>
> 2. ''
>
> 3. '!=partial(\'header', {})'
>
>
> partial is not defined
>
>
>
I'd be very grateful for any help ! (I strongly prefer not to use express.js) | 2011/04/23 | [
"https://Stackoverflow.com/questions/5764693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335355/"
] | As of August 2012 (possibly earlier) Partials have been removed from Express.
A lot of tutorials are now out of date. It seems that you can replicate much of the partial functionality with include.
Eg.
movies.jade
```
div(id='movies')
- each movie in movies
include movie
```
movie.jade
```
h2= movie.title
.description= movie.description
```
HTH | I think partial rendering is done in express, so you will have to snag that code or write your own.
I have my own helper class for jade rendering with partials that you can use or get some ideas from [here](https://gist.github.com/938647), (it's using [Joose](http://joose.it) and [Cactus](https://github.com/Raevel/Cactus)) |
5,764,693 | Only info I found was this:
<http://forrst.com/posts/Node_js_Jade_Import_Jade_File-CZW>
I replicated the suggested folder structure (views/partials) But it didn't work, as soon as I put
```
!=partial('header', {})
!=partial('menu', {})
```
into index.jade, I get a blank screen, the error message I receive from jade is:
>
> ReferenceError: ./views/index.jade:3
> 1. 'p index'
>
> 2. ''
>
> 3. '!=partial(\'header', {})'
>
>
> partial is not defined
>
>
>
I'd be very grateful for any help ! (I strongly prefer not to use express.js) | 2011/04/23 | [
"https://Stackoverflow.com/questions/5764693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335355/"
] | Jade has a command called include. Just use
```
include _form
```
given that the filename of the partial is \*\_form.jade\*, and is in the same directory | With the latest node/express I get the following movies.jade template to call partials:
```
div(id='movies')
- each movie in movies
!=partial('movie', movie)
```
where I have movie.jade in the views directory alongside movies.jade.
movies.jade is called from app.js with:
`res.render('movies', { movies: [{ title: 'Jaws' }, { title: 'Un Chien Andalou' }] });` |
5,764,693 | Only info I found was this:
<http://forrst.com/posts/Node_js_Jade_Import_Jade_File-CZW>
I replicated the suggested folder structure (views/partials) But it didn't work, as soon as I put
```
!=partial('header', {})
!=partial('menu', {})
```
into index.jade, I get a blank screen, the error message I receive from jade is:
>
> ReferenceError: ./views/index.jade:3
> 1. 'p index'
>
> 2. ''
>
> 3. '!=partial(\'header', {})'
>
>
> partial is not defined
>
>
>
I'd be very grateful for any help ! (I strongly prefer not to use express.js) | 2011/04/23 | [
"https://Stackoverflow.com/questions/5764693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335355/"
] | As of August 2012 (possibly earlier) Partials have been removed from Express.
A lot of tutorials are now out of date. It seems that you can replicate much of the partial functionality with include.
Eg.
movies.jade
```
div(id='movies')
- each movie in movies
include movie
```
movie.jade
```
h2= movie.title
.description= movie.description
```
HTH | With the latest node/express I get the following movies.jade template to call partials:
```
div(id='movies')
- each movie in movies
!=partial('movie', movie)
```
where I have movie.jade in the views directory alongside movies.jade.
movies.jade is called from app.js with:
`res.render('movies', { movies: [{ title: 'Jaws' }, { title: 'Un Chien Andalou' }] });` |
5,764,693 | Only info I found was this:
<http://forrst.com/posts/Node_js_Jade_Import_Jade_File-CZW>
I replicated the suggested folder structure (views/partials) But it didn't work, as soon as I put
```
!=partial('header', {})
!=partial('menu', {})
```
into index.jade, I get a blank screen, the error message I receive from jade is:
>
> ReferenceError: ./views/index.jade:3
> 1. 'p index'
>
> 2. ''
>
> 3. '!=partial(\'header', {})'
>
>
> partial is not defined
>
>
>
I'd be very grateful for any help ! (I strongly prefer not to use express.js) | 2011/04/23 | [
"https://Stackoverflow.com/questions/5764693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335355/"
] | Jade has a command called include. Just use
```
include _form
```
given that the filename of the partial is \*\_form.jade\*, and is in the same directory | As of August 2012 (possibly earlier) Partials have been removed from Express.
A lot of tutorials are now out of date. It seems that you can replicate much of the partial functionality with include.
Eg.
movies.jade
```
div(id='movies')
- each movie in movies
include movie
```
movie.jade
```
h2= movie.title
.description= movie.description
```
HTH |
49,288,411 | I have a map with a lot of sprites. I could add a material to the sprite with diffuse shading and than add lots of lights. But that won't give me the result I want. And is performance heavy.
---
Examples
--------
In the first image you can see that light is generated by torches. It's expanding its light at its best through 'open spaces' and it is stopped by blocks fairly quickly.
[](https://i.stack.imgur.com/8Sm4g.jpg)
---
Here is a great example of the top layer. We can see some kind of 2D directional light? Please note that the lighting inside the house is generated by torches again. The cave on the right side shows a better example of how light is handled. Also, note the hole in the background, this is generating some extra light into the cave. As if the light is really shining through the background there.
[](https://i.stack.imgur.com/ibtqE.jpg)
---
What I have
-----------
You can clearly see the issue here. Lights increase their intensity. And light creates a squared edge around some of the tiles for some reason. Also, lots of lights will cause performance issues very quickly.
[](https://i.stack.imgur.com/OZWtH.jpg)
---
Raycasting?
-----------
I read that you can somehow use raycasting? To target 'open space' or something? I have no experience with shaders or with lighting in games at all. I'd love a well-explained answer with how to achieve this Terraria/Starbound lighting effect. This does not mean I'm saying that raycasting is the solution.
---
Minecraft
---------
In Minecraft, light can travel for a certain amount of air blocks. It gradually fades to completely dark. In the Graphic settings you can enable `Smooth Lightning`, which will (obviously) smooth the lightning on the blocks.
I guess this is done with shaders, but I'm not sure. My guess is that this is performance heavy. But I'm thinking about air blocks (which are gameobjects) and maybe I have the wrong logic.
---
**Note:** I love a helpful answer, but please provide a link with a detailed explanation. Or provide an explanation with source code or links to the Unity docs in your answer. I wouldn't like to see theories worked out or something. I'd love to get an answer on how to implement this kind of lighting in Unity.
I'd also like to know if it's possible to *NOT* use a package from the Unity Marketplace.
---
Similar, but no good
--------------------
Take a look at similar posts with links to articles that cover the basics of raycasting. But no explanation on how to implement this in Unity and not the Terraria/Starbound effect I'd like to achieve:
[Make pixel lighting like terraria and starbound](https://stackoverflow.com/questions/41443130/make-pixel-lighting-like-terraria-and-starbound)
[How to achieve Terraria/Starbound 2d lighting?](https://stackoverflow.com/questions/31736654/how-to-achieve-terraria-starbound-2d-lighting)
---
Video impression
----------------
For example, take a look at this video for a really good impression on how 2d light works in Starbound:
<https://www.youtube.com/watch?v=F5d-USf69SU>
I know this is a bit more advanced, but also the point light generated by the player's flash light is stopped by blocks and let through by the open spaces.
---
Other help forums
-----------------
Also posted by me.
**Gamedev Exchange:** <https://gamedev.stackexchange.com/questions/155440/unity-2d-shader-lighting-like-terraria-or-starbound>
**Unity Forum:** <https://answers.unity.com/questions/1480518/2d-shader-lighting-like-terraria-or-starbound.html>
--- | 2018/03/14 | [
"https://Stackoverflow.com/questions/49288411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6086226/"
] | I can mention 2 main elements about 2d Dynamic Lighting for unity.
1. One of the main asset used for 2d lighting in unity essentials is [DDL light](https://assetstore.unity.com/packages/tools/particles-effects/2ddl-pro-2d-dynamic-lights-and-shadows-25933), with an official tutorial [here](https://learn.unity.com/tutorial/recorded-video-session-2d-essentials-pack).
2. Most importantly Unity itself is working on a Dynamic lighting system, currently in beta (for 2019.2). Unity introduced the package Lightweight RP for 2d lights [here](https://forum.unity.com/threads/experimental-2d-lights-and-shader-graph-support-in-lwrp.683623/) and there's a tutorial [here](https://www.youtube.com/watch?v=nkgGyO9VG54). | Apparently, there are several packages on [the Unity Asset Store](https://assetstore.unity.com/). Search for "2d lighting" or "2d shader". You can easily import the source code of these packages and test it in Unity yourself. If you like a package after testing, you can use it.
I highly advise you not to import it directly into an existing project. For your own sake, test it in a test environment (or a copy of your project) before including it into your project. |
18,059,797 | Hi I am currently working with a report in Visual Studio 2008. I use the query below to create a data set. This works correctly in SQL / SMSS and in the dataset when I test the query.
```
SELECT
CASE WHEN Make LIKE 'FO%' THEN 'Ford'
WHEN Make LIKE 'HON%' THEN 'Honda'
END Make,
CASE WHEN model LIKE 'CIV%' THEN 'Civic'
WHEN model LIKE '%AC%' THEN 'Accord'
ELSE model
END model,
year, AVG(Fuel.MPG) as AVGMPG
From cars, Fuel
Where Fuel.ID=cars.ID
AND year > 2003
AND Make is not NULL
AND model is not NULL
AND year is not NULL
Group by Make, model, year
```
When I have a report reference the dataset it generates the following error;
>
> An error has occurred during report processing. Exception has been
> thrown by the target of an invocation. Failed to enable constraints.
> One or more rows contain values violating non-null, unique, or
> foreign-key constraints.
>
>
>
Since the actual SQL statement is larger and involves several CASE statements, all of which work, I have narrowed it down to the else portion of the statement.
For background, I am trying to pull all the data from model but group certain values that are similar, but still pull the rest of the data as well. | 2013/08/05 | [
"https://Stackoverflow.com/questions/18059797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902937/"
] | The WHATWG (the organization who specifies browser behavior, alongside the W3C) has a [list of known script MIME types](http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#scriptingLanguages) and some blacklisted MIME types that must not be treated as scripting languages:
>
> The following lists the MIME type strings that user agents must recognize, and the languages to which they refer:
>
>
> * `"application/ecmascript"`
> * `"application/javascript"`
> * `"application/x-ecmascript"`
> * ...
>
>
> The following MIME types (with or without parameters) must not be interpreted as scripting languages:
>
>
> * `"text/plain"`
> * `"text/xml"`
> * `"application/octet-stream"`
> * `"application/xml"`
>
>
> Note: These types are explicitly listed here because they are poorly-defined types that are nonetheless likely to be used as formats for data blocks, and it would be problematic if they were suddenly to be interpreted as script by a user agent.
>
>
>
What the WHATWG spec calls "data blocks" here are **non-scripts** enclosed in `<script>` tags:
>
> In this example, two script elements are used. One embeds an external script, and the other includes some data.
>
>
>
```
<script src="game-engine.js"></script>
<script type="text/x-game-map">`
........U.........e
o............A....e
.....A.....AAA....e
.A..AAA...AAAAA...e
</script>
```
The components of the WHATWG spec that specify `load` events for `<script>` tags explicitly state that they fire for *scripts* referred to by `<script>` tags, not to non-script data blocks. A `<script>` element is a data block if its `type` is not recognized as a MIME type corresponding to a scripting language supported by the browser. This means that blacklisted types like `text/plain` will never be recognized as scripts, whereas type values in neither the must-support nor must-not-support list, like `application/dart` (for Google's Dart language) might be supported by some browsers.
Furthermore, including a non-script `type` alongside a `src` is not spec-compliant. Data blocks are legal only when specified inline:
>
> When used to include data blocks (as opposed to scripts), the **data must be embedded inline**, the format of the data must be given using the `type` attribute, the **`src` attribute must not be specified**, and the contents of the script element must conform to the requirements defined for the format used.
>
>
> | If you specify your script as "text/plain" the browser wont do anything with it.
You must specify it as "script/javascript" to have it execute as JavaScript. |
49,953,590 | Quick Context: I have a basic excel Spreadsheet with three fields: Client\_URL, Client\_Name and AHREFs\_Rank. When a URL is entered into Client\_URL I want to:
1. Login to AHREFs;
2. Paste and enter the client URL into a web form field using the value of cell Client\_URL;
3. Pull the AHREF's Rank number for the inner text of a link.
**I'm having trouble with step 3.**
Here's the **full** code for Step 3 used so far, I'm experiencing "Compile Error: Object Required" issues.
```
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row = Range("Client_URL").Row And _
Target.Column = Range("Client_URL").Column Then
Dim HTMLDoc As HTMLDocument
Dim MyBrowser As InternetExplorer
Dim MyHTML_Element As IHTMLElement
Dim MyURL As String
MyURL = "https://ahrefs.com/user/login"
Set MyBrowser = New InternetExplorer
MyBrowser.navigate MyURL
MyBrowser.Visible = True
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
HTMLDoc.all.Email.Value = "[email protected]"
HTMLDoc.all.Password.Value = "password123"
For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input")
If MyHTML_Element.Type = "submit" Then MyHTML_Element.Click: Exit For
Next
MyURL = "https://ahrefs.com/dashboard/metrics"
MyBrowser.navigate MyURL
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
HTMLDoc.activeElement.Value = Range("Client_URL").Value
HTMLDoc.getElementById("dashboard_start_analysing").Click
Do
DoEvents
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
Dim rankInnertext As Object
rankInnertext = HTMLDoc.getElementById("topAhrefsRank").innerText
MsgBox rankInnertext
End If
End Sub
```
If I remove the "Set" from "rankInnertext =" i then get a Runtime Error 91 "Object Variable Not Set".
To break it down, in Step 3 I've: Submitted a field on a previous page and am waiting for the current page to finish loading. I'm then attempting to pull the inner text of a link with the ID "topAhrefsRank" and set the value of the cell "AHREFs\_Rank" to equal the value of the inner text as a string.
>
> Very new to visual basic so any help is appreciated.
>
>
> Update: Changed code as per suggestions. Have changed rankInnertext from String to Object. Now receiving "Run Time Error 91: Object Variable or With block variable not set"
>
>
> | 2018/04/21 | [
"https://Stackoverflow.com/questions/49953590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2613371/"
] | This helped me:
```
.fa {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}
``` | Use `transform` css to achieve this:
```
.fa {
transform: rotateZ(180deg);
}
``` |
49,953,590 | Quick Context: I have a basic excel Spreadsheet with three fields: Client\_URL, Client\_Name and AHREFs\_Rank. When a URL is entered into Client\_URL I want to:
1. Login to AHREFs;
2. Paste and enter the client URL into a web form field using the value of cell Client\_URL;
3. Pull the AHREF's Rank number for the inner text of a link.
**I'm having trouble with step 3.**
Here's the **full** code for Step 3 used so far, I'm experiencing "Compile Error: Object Required" issues.
```
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row = Range("Client_URL").Row And _
Target.Column = Range("Client_URL").Column Then
Dim HTMLDoc As HTMLDocument
Dim MyBrowser As InternetExplorer
Dim MyHTML_Element As IHTMLElement
Dim MyURL As String
MyURL = "https://ahrefs.com/user/login"
Set MyBrowser = New InternetExplorer
MyBrowser.navigate MyURL
MyBrowser.Visible = True
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
HTMLDoc.all.Email.Value = "[email protected]"
HTMLDoc.all.Password.Value = "password123"
For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input")
If MyHTML_Element.Type = "submit" Then MyHTML_Element.Click: Exit For
Next
MyURL = "https://ahrefs.com/dashboard/metrics"
MyBrowser.navigate MyURL
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
HTMLDoc.activeElement.Value = Range("Client_URL").Value
HTMLDoc.getElementById("dashboard_start_analysing").Click
Do
DoEvents
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
Dim rankInnertext As Object
rankInnertext = HTMLDoc.getElementById("topAhrefsRank").innerText
MsgBox rankInnertext
End If
End Sub
```
If I remove the "Set" from "rankInnertext =" i then get a Runtime Error 91 "Object Variable Not Set".
To break it down, in Step 3 I've: Submitted a field on a previous page and am waiting for the current page to finish loading. I'm then attempting to pull the inner text of a link with the ID "topAhrefsRank" and set the value of the cell "AHREFs\_Rank" to equal the value of the inner text as a string.
>
> Very new to visual basic so any help is appreciated.
>
>
> Update: Changed code as per suggestions. Have changed rankInnertext from String to Object. Now receiving "Run Time Error 91: Object Variable or With block variable not set"
>
>
> | 2018/04/21 | [
"https://Stackoverflow.com/questions/49953590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2613371/"
] | Use `transform` css to achieve this:
```
.fa {
transform: rotateZ(180deg);
}
``` | >
> You can use the `transform` css option combine it with `rotate()` function.
> [See it in action](https://jsfiddle.net/Roland1993/4zrnghpq/4/)
>
>
> |
49,953,590 | Quick Context: I have a basic excel Spreadsheet with three fields: Client\_URL, Client\_Name and AHREFs\_Rank. When a URL is entered into Client\_URL I want to:
1. Login to AHREFs;
2. Paste and enter the client URL into a web form field using the value of cell Client\_URL;
3. Pull the AHREF's Rank number for the inner text of a link.
**I'm having trouble with step 3.**
Here's the **full** code for Step 3 used so far, I'm experiencing "Compile Error: Object Required" issues.
```
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row = Range("Client_URL").Row And _
Target.Column = Range("Client_URL").Column Then
Dim HTMLDoc As HTMLDocument
Dim MyBrowser As InternetExplorer
Dim MyHTML_Element As IHTMLElement
Dim MyURL As String
MyURL = "https://ahrefs.com/user/login"
Set MyBrowser = New InternetExplorer
MyBrowser.navigate MyURL
MyBrowser.Visible = True
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
HTMLDoc.all.Email.Value = "[email protected]"
HTMLDoc.all.Password.Value = "password123"
For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input")
If MyHTML_Element.Type = "submit" Then MyHTML_Element.Click: Exit For
Next
MyURL = "https://ahrefs.com/dashboard/metrics"
MyBrowser.navigate MyURL
Do
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
HTMLDoc.activeElement.Value = Range("Client_URL").Value
HTMLDoc.getElementById("dashboard_start_analysing").Click
Do
DoEvents
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = MyBrowser.document
Dim rankInnertext As Object
rankInnertext = HTMLDoc.getElementById("topAhrefsRank").innerText
MsgBox rankInnertext
End If
End Sub
```
If I remove the "Set" from "rankInnertext =" i then get a Runtime Error 91 "Object Variable Not Set".
To break it down, in Step 3 I've: Submitted a field on a previous page and am waiting for the current page to finish loading. I'm then attempting to pull the inner text of a link with the ID "topAhrefsRank" and set the value of the cell "AHREFs\_Rank" to equal the value of the inner text as a string.
>
> Very new to visual basic so any help is appreciated.
>
>
> Update: Changed code as per suggestions. Have changed rankInnertext from String to Object. Now receiving "Run Time Error 91: Object Variable or With block variable not set"
>
>
> | 2018/04/21 | [
"https://Stackoverflow.com/questions/49953590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2613371/"
] | This helped me:
```
.fa {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}
``` | >
> You can use the `transform` css option combine it with `rotate()` function.
> [See it in action](https://jsfiddle.net/Roland1993/4zrnghpq/4/)
>
>
> |
33,010,655 | I just wanted to append `td` in the `tr`
**Table**
```
<table class="u-full-width" id="result">
<thead>
<tr>
<th>Project Name</th>
<th>Id</th>
<th>Event</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dave Gamache</td>
<td>26</td>
<td>Male</td>
</tr>
</tbody>
</table>
```
**Script**
```
// Receive Message
socket.on('message', function(data){
console.log(data);
var Project = data.project;
var Id = data.id;
var Event = data.event;
var tr = document.createElement("tr");
var td1 = tr.appendChild(document.createElement('td'));
var td2 = tr.appendChild(document.createElement('td'));
var td3 = tr.appendChild(document.createElement('td'));
td1.innerHTML = Project;
td2.innerHTML = Id;
td3.innerHTML = Event;
document.getElementById("result").appendChild(td1, td2, td3);
});
```
I come up with this above code but this is not working means see the image...
[](https://i.stack.imgur.com/1yOoJ.png) | 2015/10/08 | [
"https://Stackoverflow.com/questions/33010655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The last line is wrong. You should append the `tr` to the table, not all the `td`s.
```
document.getElementById("result").appendChild(tr);
``` | document.getElementById("result").appendChild(td1, td2, td3);
seems you are appending your tds directly to the table, not a tr in the tbody. |
33,010,655 | I just wanted to append `td` in the `tr`
**Table**
```
<table class="u-full-width" id="result">
<thead>
<tr>
<th>Project Name</th>
<th>Id</th>
<th>Event</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dave Gamache</td>
<td>26</td>
<td>Male</td>
</tr>
</tbody>
</table>
```
**Script**
```
// Receive Message
socket.on('message', function(data){
console.log(data);
var Project = data.project;
var Id = data.id;
var Event = data.event;
var tr = document.createElement("tr");
var td1 = tr.appendChild(document.createElement('td'));
var td2 = tr.appendChild(document.createElement('td'));
var td3 = tr.appendChild(document.createElement('td'));
td1.innerHTML = Project;
td2.innerHTML = Id;
td3.innerHTML = Event;
document.getElementById("result").appendChild(td1, td2, td3);
});
```
I come up with this above code but this is not working means see the image...
[](https://i.stack.imgur.com/1yOoJ.png) | 2015/10/08 | [
"https://Stackoverflow.com/questions/33010655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The last line is wrong. You should append the `tr` to the table, not all the `td`s.
```
document.getElementById("result").appendChild(tr);
``` | Try this way to bind your data
```
<table class="u-full-width" id="result">
<thead>
<tr>
<th>Project Name</th>
<th>Id</th>
<th>Event</th>
</tr>
</thead>
<tbody id="bodytable">
</tbody>
</table>
socket.on('message', function(data){
console.log(data);
var _html='';
html +='<tr>'
html +='<td>'+data.project+'</td>';
html +='<td>'+data.id+'</td>';
html +='<td>'+data.event+'</td></tr>';
$('#bodytable').append(_html);
});
``` |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | Since you don't want to define a custom struct or class, I assume that you want the return value to be only point. So, I suggest you to use an optional pointer argument, it's default value is NULL, and if it is not NULL you store the distance in the variable pointed by it.
```
point3D findIntersect(const vec3 &v1, const vec3 &v2, double *dist = NULL) {
// ...
if (dist) {
// find the distance and store in *dist
}
return ... ;
}
``` | Straustrup and Sutter are recommending using `tuple/tie` for this: [F.41: Prefer to return tuples to multiple out-parameters](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f41-prefer-to-return-tuples-to-multiple-out-parameters)
```
Point3D point3D;
double distance;
std::tie(point3D, distance) = findIntersect(/*..params..*/);
```
Where:
```
std::tuple<Point3D, double> findIntersect(/*..params..*/)
{
Point3D point3D;
double distance;
// calculate point3D & distance
return std::make_tuple(point3D, distance);
}
``` |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | You sure can use [pairs](http://www.cplusplus.com/reference/utility/pair/).
```
std::pair<point3D, double> findIntersect(const vec3& vector1, const vec3& vector2);
``` | I still think that you can and should create the struct for your code (if your code is not a real time..) Stucts are very common and gives you robastics and flexibility in case you would need to expend your code. To be depends on on these key value pair in you code and then realize after few months that you need to change it in 10 places... :) |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | Since you don't want to define a custom struct or class, I assume that you want the return value to be only point. So, I suggest you to use an optional pointer argument, it's default value is NULL, and if it is not NULL you store the distance in the variable pointed by it.
```
point3D findIntersect(const vec3 &v1, const vec3 &v2, double *dist = NULL) {
// ...
if (dist) {
// find the distance and store in *dist
}
return ... ;
}
``` | C++ lets you overload the function, i.e. use the same name, but different parameter types. You can return `point3D` as the return value, and make the `length` reference parameter appear "optional" by providing a separate overload:
```
point3D findIntersect(const vec3& vector1, const vec3& vector2) {
double ignore;
return findIntersect(vector1, vector2, ignore);
}
point3D findIntersect(const vec3& vector1, const vec3& vector2, double &length) {
... // Implementation goes here
}
```
Callers who don't want to get the length back would call the two-argument overload, while the callers who want the length would call the three-argument one. In both cases the implementation is going to be the same, with the two-argument call providing a reference to an ignored variable for the length. |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | C++ lets you overload the function, i.e. use the same name, but different parameter types. You can return `point3D` as the return value, and make the `length` reference parameter appear "optional" by providing a separate overload:
```
point3D findIntersect(const vec3& vector1, const vec3& vector2) {
double ignore;
return findIntersect(vector1, vector2, ignore);
}
point3D findIntersect(const vec3& vector1, const vec3& vector2, double &length) {
... // Implementation goes here
}
```
Callers who don't want to get the length back would call the two-argument overload, while the callers who want the length would call the three-argument one. In both cases the implementation is going to be the same, with the two-argument call providing a reference to an ignored variable for the length. | You sure can use [pairs](http://www.cplusplus.com/reference/utility/pair/).
```
std::pair<point3D, double> findIntersect(const vec3& vector1, const vec3& vector2);
``` |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | Straustrup and Sutter are recommending using `tuple/tie` for this: [F.41: Prefer to return tuples to multiple out-parameters](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f41-prefer-to-return-tuples-to-multiple-out-parameters)
```
Point3D point3D;
double distance;
std::tie(point3D, distance) = findIntersect(/*..params..*/);
```
Where:
```
std::tuple<Point3D, double> findIntersect(/*..params..*/)
{
Point3D point3D;
double distance;
// calculate point3D & distance
return std::make_tuple(point3D, distance);
}
``` | You could use a `std::pair<point3D, double>`. There is also a `std::tuple`, when you need to return more than two values. (Notice there is no such thing as same type for the pair or tuple values, as you mentioned.) |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | C++ lets you overload the function, i.e. use the same name, but different parameter types. You can return `point3D` as the return value, and make the `length` reference parameter appear "optional" by providing a separate overload:
```
point3D findIntersect(const vec3& vector1, const vec3& vector2) {
double ignore;
return findIntersect(vector1, vector2, ignore);
}
point3D findIntersect(const vec3& vector1, const vec3& vector2, double &length) {
... // Implementation goes here
}
```
Callers who don't want to get the length back would call the two-argument overload, while the callers who want the length would call the three-argument one. In both cases the implementation is going to be the same, with the two-argument call providing a reference to an ignored variable for the length. | I still think that you can and should create the struct for your code (if your code is not a real time..) Stucts are very common and gives you robastics and flexibility in case you would need to expend your code. To be depends on on these key value pair in you code and then realize after few months that you need to change it in 10 places... :) |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | You could use a `std::pair<point3D, double>`. There is also a `std::tuple`, when you need to return more than two values. (Notice there is no such thing as same type for the pair or tuple values, as you mentioned.) | I still think that you can and should create the struct for your code (if your code is not a real time..) Stucts are very common and gives you robastics and flexibility in case you would need to expend your code. To be depends on on these key value pair in you code and then realize after few months that you need to change it in 10 places... :) |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | C++ lets you overload the function, i.e. use the same name, but different parameter types. You can return `point3D` as the return value, and make the `length` reference parameter appear "optional" by providing a separate overload:
```
point3D findIntersect(const vec3& vector1, const vec3& vector2) {
double ignore;
return findIntersect(vector1, vector2, ignore);
}
point3D findIntersect(const vec3& vector1, const vec3& vector2, double &length) {
... // Implementation goes here
}
```
Callers who don't want to get the length back would call the two-argument overload, while the callers who want the length would call the three-argument one. In both cases the implementation is going to be the same, with the two-argument call providing a reference to an ignored variable for the length. | You could use a `std::pair<point3D, double>`. There is also a `std::tuple`, when you need to return more than two values. (Notice there is no such thing as same type for the pair or tuple values, as you mentioned.) |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | Straustrup and Sutter are recommending using `tuple/tie` for this: [F.41: Prefer to return tuples to multiple out-parameters](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f41-prefer-to-return-tuples-to-multiple-out-parameters)
```
Point3D point3D;
double distance;
std::tie(point3D, distance) = findIntersect(/*..params..*/);
```
Where:
```
std::tuple<Point3D, double> findIntersect(/*..params..*/)
{
Point3D point3D;
double distance;
// calculate point3D & distance
return std::make_tuple(point3D, distance);
}
``` | You sure can use [pairs](http://www.cplusplus.com/reference/utility/pair/).
```
std::pair<point3D, double> findIntersect(const vec3& vector1, const vec3& vector2);
``` |
32,801,983 | The backstory.
In VBA in Excel I created a function that calculate the shortest distance between two lines (vectors). This function returns the apparent intersection point, and the actual distance between them.
To make this work I ended up passing out an array, then sorting out what went where afterwards. It works, but is clunky to read and work with.
In C++ i have made a similar function that returns the point in question.
```
struct point3D
{
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}
```
The problem:
I want to return the length as well, since it uses parts of the original calculation. However most of the time I only want the point.
Possible solutions I have looked at are:
Write a separate function for the distance. A lot of extra work for when I want both of them.
* Create a custom struct for this one function. *Seems a bit overkill.*
* Return an array like the VBA function did. *Resulting code is not very intuitive, and requires care when using.*
* Using an optional argument as a reference to a variable to store the distance. *Does not work. The compiler does not allow me to change an optional argument.*
* Using an argument list like this `function(const argin1, const argin2, argout&, argout2&)`. *Just ugh! Would require the user to always expect every variable out.*
I have seen examples with pairs, but the they look like they have to be the same data type. I essentially want to return a `point3D`, and a `double`.
Does anyone have a more elegant solution to returning multiple values from a function? | 2015/09/26 | [
"https://Stackoverflow.com/questions/32801983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380126/"
] | Straustrup and Sutter are recommending using `tuple/tie` for this: [F.41: Prefer to return tuples to multiple out-parameters](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f41-prefer-to-return-tuples-to-multiple-out-parameters)
```
Point3D point3D;
double distance;
std::tie(point3D, distance) = findIntersect(/*..params..*/);
```
Where:
```
std::tuple<Point3D, double> findIntersect(/*..params..*/)
{
Point3D point3D;
double distance;
// calculate point3D & distance
return std::make_tuple(point3D, distance);
}
``` | I still think that you can and should create the struct for your code (if your code is not a real time..) Stucts are very common and gives you robastics and flexibility in case you would need to expend your code. To be depends on on these key value pair in you code and then realize after few months that you need to change it in 10 places... :) |
4,354,341 | Could someone please help with the following jQuery
***I need all jQuery UI buttons that are not children of two tables #id1 and #id2 and not of classid=x***
What I have come up with so far is
```
$(":button(.ui-button .ui-widget):not(#table1 #table2):not(.MyCustomClass)")
```
but this doesnt seem to work...
What am I missing? | 2010/12/04 | [
"https://Stackoverflow.com/questions/4354341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314661/"
] | I think you want:
```
$(':button.ui-button, :button.ui-widget').not('#table1 *, #table2 *').not('.MyCustomClass')
```
It's usually faster to break the qualifiers out of the selector. | Try ([demo](http://jsfiddle.net/Mottie/63Nrx/)):
```
$('table:not(#table1, #table2) .ui-button:not(.MyCustomClass)')
``` |
4,253,815 | i try to deserialize a json string with the help of gson. While gson.fromJson I get the following error:
>
> No-args constructor for class xyz; does not exist. Register an InstanceCreator with Gson for this type to fix this problem
>
>
>
I tried to work with an InstanceCreate but I didn't get this running.
I hope you can help me.
JSON String
```
[
{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
},
{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 12:38:12"
}
```
]
according to gson I have to cut the first and last chars ("[" and "]")
according to <http://www.jsonlint.com/> the string is with the chars correct... :?:
the code looks like that:
```
public class License {
public String prog;
public String name;
public String computername;
public String date;
public License() {
this.computername = "";
this.date = "";
this.name = "";
this.prog = "";
// no-args constructor
}
}
```
---
```
String JSONSerializedResources = "json_string_from_above"
try
{
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
License[] lic = null;
j = new JSONObject(JSONSerializedResources);
lic = gson.fromJson(j.toString(), License[].class);
for (License license : lic) {
Toast.makeText(getApplicationContext(), license.name + " - " + license.date, Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
```
regards Chris | 2010/11/23 | [
"https://Stackoverflow.com/questions/4253815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517123/"
] | Try making your constructor public, so that gson can actually access it.
```
public License() {
this.computername = "";
this.date = "";
this.name = "";
this.prog = "";
// no-args constructor
}
```
but since Java creates a default constructor, you could just use:
```
public class License {
public String prog = "";
public String name = "";
public String computername = "";
public String date = "";
}
```
**Update:**
It's really quite trivial: `JSONObject` expects a Json object "{..}". You should use `JSONArray` which expects "[...]".
I tried it and it works. You should still change `License` class as noted above. | it is unbelievable...
now I tried it not so
```
j = new JSONObject(JSONSerializedResources);
lic = gson.fromJson(j.toString(), License[].class);
```
but directly so
```
lic = gson.fromJson(JSONSerializedResources, License[].class);
```
with my old original json string with starting and ending "[" & "]"
and it works |
4,253,815 | i try to deserialize a json string with the help of gson. While gson.fromJson I get the following error:
>
> No-args constructor for class xyz; does not exist. Register an InstanceCreator with Gson for this type to fix this problem
>
>
>
I tried to work with an InstanceCreate but I didn't get this running.
I hope you can help me.
JSON String
```
[
{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
},
{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 12:38:12"
}
```
]
according to gson I have to cut the first and last chars ("[" and "]")
according to <http://www.jsonlint.com/> the string is with the chars correct... :?:
the code looks like that:
```
public class License {
public String prog;
public String name;
public String computername;
public String date;
public License() {
this.computername = "";
this.date = "";
this.name = "";
this.prog = "";
// no-args constructor
}
}
```
---
```
String JSONSerializedResources = "json_string_from_above"
try
{
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
License[] lic = null;
j = new JSONObject(JSONSerializedResources);
lic = gson.fromJson(j.toString(), License[].class);
for (License license : lic) {
Toast.makeText(getApplicationContext(), license.name + " - " + license.date, Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
```
regards Chris | 2010/11/23 | [
"https://Stackoverflow.com/questions/4253815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517123/"
] | Try making your constructor public, so that gson can actually access it.
```
public License() {
this.computername = "";
this.date = "";
this.name = "";
this.prog = "";
// no-args constructor
}
```
but since Java creates a default constructor, you could just use:
```
public class License {
public String prog = "";
public String name = "";
public String computername = "";
public String date = "";
}
```
**Update:**
It's really quite trivial: `JSONObject` expects a Json object "{..}". You should use `JSONArray` which expects "[...]".
I tried it and it works. You should still change `License` class as noted above. | Try removing the constructors if you don't need
I tried using two classes
Class A having list of Class B
Removed all the constructors and just worked fine for me. |
4,253,815 | i try to deserialize a json string with the help of gson. While gson.fromJson I get the following error:
>
> No-args constructor for class xyz; does not exist. Register an InstanceCreator with Gson for this type to fix this problem
>
>
>
I tried to work with an InstanceCreate but I didn't get this running.
I hope you can help me.
JSON String
```
[
{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
},
{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 12:38:12"
}
```
]
according to gson I have to cut the first and last chars ("[" and "]")
according to <http://www.jsonlint.com/> the string is with the chars correct... :?:
the code looks like that:
```
public class License {
public String prog;
public String name;
public String computername;
public String date;
public License() {
this.computername = "";
this.date = "";
this.name = "";
this.prog = "";
// no-args constructor
}
}
```
---
```
String JSONSerializedResources = "json_string_from_above"
try
{
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
License[] lic = null;
j = new JSONObject(JSONSerializedResources);
lic = gson.fromJson(j.toString(), License[].class);
for (License license : lic) {
Toast.makeText(getApplicationContext(), license.name + " - " + license.date, Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
```
regards Chris | 2010/11/23 | [
"https://Stackoverflow.com/questions/4253815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517123/"
] | it is unbelievable...
now I tried it not so
```
j = new JSONObject(JSONSerializedResources);
lic = gson.fromJson(j.toString(), License[].class);
```
but directly so
```
lic = gson.fromJson(JSONSerializedResources, License[].class);
```
with my old original json string with starting and ending "[" & "]"
and it works | Try removing the constructors if you don't need
I tried using two classes
Class A having list of Class B
Removed all the constructors and just worked fine for me. |
52,324,863 | For example, turn this:
```
const enums = { ip: 'ip', er: 'er' };
const obj = {
somethingNotNeeded: {...},
er: [
{ a: 1},
{ b: 2}
],
somethingElseNotNeeded: {...},
ip: [
{ a: 1},
{ b: 2}
]
}
```
Into this:
```
[
{ a: 1},
{ b: 2},
{ a: 1},
{ b: 2}
]
```
I'm already doing this in a roundabout way by declaring an enum object of the types i want (er, ip) then doing a forEach (lodash) loop on obj checking if the keys aren't in the enum and delete them off the original obj. Then having just the objects I want, I do two nested forEach loops concatenating the results to a new object using object rest spread...
I'm almost entirely sure there's a better way of doing this but I didn't think of it today. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52324863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391600/"
] | Get the `enums` properties with [`Object.values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values) (or [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) if they are always identical). Use [`Array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to iterate the array of property names, and extract their values from `obj`. Flatten the array of arrays by [spreading](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) it into [`Array.concat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat):
```js
const enums = { ip: 'ip', er: 'er' };
const obj = {
somethingNotNeeded: {},
er: [
{ a: 1},
{ b: 2}
],
somethingElseNotNeeded: {},
ip: [
{ a: 1},
{ b: 2}
]
};
const result = [].concat(...Object.values(enums).map(p => obj[p]));
console.log(result);
``` | ```js
const props = ['ip', 'er']; // An array of the properties you are interested in
const obj = {
somethingNotNeeded: {},
er: [
{ a: 1},
{ b: 2}
],
somethingElseNotNeeded: {},
ip: [
{ a: 1},
{ b: 2}
]
}
const flatten = (array) => array ? array.reduce((output, array) => [...output, ...array], []) : array; // Take an array of arrays and flatten it into a single array
const result = flatten(props.map(p => obj[p])); //Run the flattern over an array that has been created by mapping the property names
console.log(result)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.